C++ I cant upload file to FTP server - c++

I want to upload a file to my FTP server using C++ code and I'm able to FTP my server with FileZilla.
When I run my C++ code, it throws me an output "3" error ( GetLastError() function returned this value to the FtpPutFile() function
#pragma comment (lib,"wininet.lib")
#include <windows.h>
#include <wininet.h> //for uploadFile function
#include <iostream>
using namespace std;
int main()
{
HINTERNET hint, hftp;
hint = InternetOpen("FTP", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_ASYNC);
hftp = InternetConnect(hint, "MY IP ADRESS", INTERNET_DEFAULT_FTP_PORT, "MY NAME", "MY PASS", INTERNET_SERVICE_FTP, 0, 0);
if (!FtpPutFile(hftp, "C://Users//Elliot//Desktop//log.txt", "//log.txt", FTP_TRANSFER_TYPE_BINARY, 0))
{
cout << "FAIL !" << endl;
cout << GetLastError() << endl;
}
else {
cout << "file sended !";
};
InternetCloseHandle(hftp);
InternetCloseHandle(hint);
system("PAUSE");
}
things i have tried :
Changing server ( i made new server but still same result )
Controlling firewall
Running as adminstrator
break points ( the ftpputfile is giving the error )

The error message is clear. File is not there, there is nothing to send. You can easily check the file's path using std::ifstream before continuing with internet functions.
Use FtpSetCurrentDirectory to set a target directory. In this example I used "public_html", maybe your server is different.
#include <windows.h>
#include <wininet.h>
#include <iostream>
#include <string>
#include <fstream>
#pragma comment (lib,"wininet.lib")
using namespace std;
int main()
{
string file = "C:\\path.txt";
string site = "www.site.com";
string user = "username";
string pass = "password";
if (!ifstream(file))
{
cout << "no file\n";
return 0;
}
HINTERNET hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
HINTERNET hftp = InternetConnect(hint, site.c_str(), INTERNET_DEFAULT_FTP_PORT,
user.c_str(), pass.c_str(), INTERNET_SERVICE_FTP, 0, 0);
if (FtpSetCurrentDirectory(hftp, "public_html"))
{
if (!FtpPutFile(hftp, file.c_str(), "log.txt", FTP_TRANSFER_TYPE_BINARY, 0))
{
cout << "FAIL!" << endl;
cout << GetLastError() << endl;
}
else
{
cout << "file sended !";
}
}
InternetCloseHandle(hftp);
InternetCloseHandle(hint);
return 0;
}

Related

InternetOpenUrl does not work from a virtual machine

Setup:
Oracle Virtual Box 6.1
Windows 7 Home Premium x86 and x64
I have the following code running from a Virtual Machine in both versions of win7 32 and 64 bit:
#include <iostream>
#include <Windows.h>
#include <WinInet.h>
#include <thread>
#pragma comment(lib, "wininet.lib")
using namespace std;
bool isURL_Redirected(wstring url)
{
HINTERNET hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hInternet)
{
hInternet = InternetOpenUrl(hInternet, url.c_str(), 0, 0, INTERNET_FLAG_NO_AUTO_REDIRECT, 0);
WCHAR lpvData[1000];
DWORD size = sizeof(lpvData);
if (hInternet)
{
if (HttpQueryInfo(hInternet, HTTP_QUERY_LOCATION, lpvData, &size, NULL))
{
InternetCloseHandle(hInternet);
return true;
}
}
else
{
cout << "line 30: " << GetLastError() << endl;
}
}
else
{
cout << "line 35: " << GetLastError() << endl;
}
InternetCloseHandle(hInternet);
return false;
}
int main()
{
if (isURL_Redirected(L"https://download.visualstudio.microsoft.com/download/pr/8e396c75-4d0d-41d3-aea8-848babc2736a/80b431456d8866ebe053eb8b81a168b3/ndp462-kb3151800-x86-x64-allos-enu.exe"))
cout << "It does redirect." << endl;
else
cout << "It does not redirect." << endl;
system("pause"); // Win only.
}
Outputs:
line 30: 12157
Why it does not work from a Virtual Machine? It works fine in a real machine though. I noticed that if I change the URL to https://www.google.com it works fine, so I truly believe there's something to do with the URL and the Virtual Machine. Is there a workaround for this?
EDIT
12157 is an internal WinInet error, usually when it can't load its SSL/TLS library. It has nothing to do with sending keys to the HTTPS server.

C++ windows.h WriteFile function

I am trying to display in console a list of running processes and the current time and save them to a text file using the WriteFile and windows.h functions. How to effectively redirect the output stream and "My data..." to a text file without using "freopen" in C ++?
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
char temp;
HANDLE h = CreateFile("process.txt", // name of the file
GENERIC_WRITE, // open for writing
0, // sharing mode, none in this case
0, // use default security descriptor
CREATE_ALWAYS, // overwrite if exists
FILE_ATTRIBUTE_NORMAL,
0);
if (h)
{
std::cout << "CreateFile() succeeded\n";
CloseHandle(h);
}
else
{
std::cerr << "CreateFile() failed:" << GetLastError() << "\n";
}
time_t actualTime = chrono::system_clock::to_time_t(chrono::system_clock::now());
cout << ctime(&actualTime);
cout << "My data..." << endl;
PROCESSENTRY32 proc32;
HANDLE hSnapshot;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
proc32.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hSnapshot, &proc32))
{
cout << proc32.szExeFile << endl;
while(Process32Next(hSnapshot, &proc32))
cout << proc32.szExeFile << endl;
}
WriteFile(HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
);
CloseHandle(hSnapshot);
system ("pause >nul");
return 0;
}
Use OPEN_ALWAYS instead of CREATE_ALWAYS and then use SetFilePointer to move the file pointer to the end of file.

Simple ifstream not opening any file

Newb here. I have spent the last 4 hours trying to solve this problem.
ifstream is suddenly not opening files.
ofstream has no problems writing to the file.
The file exists, it's contents are, ThisIsText, and it is in the reference directory, which I confirmed with system("dir & pause")
I tried Code::Blocks and Dev C++, but I think they're using the same compiler(GNU GCC Compiler).
I tried using the full filename path with double backslashes.
I see people mentioning permissions, but I don't know how to tinker with that.
I'm on Windows 10.
Edit: I just found a new compiler(Embarcadero 10.1 AKA Borland) and the code works with it. I still want to know what the problem is with GNU GCC
The following code skips to the else statement:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string message;
ifstream inputFile;
inputFile.open("File.txt");
if (inputFile.good())
{
inputFile >> message;
cout << message;
system("dir & pause");
}
else
{
cout << "failed to open input file\n";
system("dir & pause");
} return 0;
}
If it helps, I found the following code online and it outputs, "Error code = 2"
from winerror.h, that is: ERROR_FILE_NOT_FOUND
#include <windows.h>
#include <iostream>
int main()
{
HANDLE hFile = CreateFile(
"one.txt", // Windows does not case about case
GENERIC_READ,
0, // no sharing
NULL, // default security
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL ); // no file template
if(INVALID_HANDLE_VALUE == hFile)
{
DWORD errCode = GetLastError(); // see winerror.h for meanings
std::cout << "File wouldn't open :-(" << std::endl;
std::cout << "Error code = " << errCode << std::endl;
}
else
{
std::cout << "File opened OK :-)" << std::endl;
CloseHandle(hFile);
}
return 0;
}
PS. I know using namespace std; is bad practice

Named Pipes Issue

I am trying to learn how named pipes work, and created 2 consoles to test the connectivity between server and client. Client will send a message to the server and the server will display the message, but instead of the message, it returns a value of "nullptr" as shown in the error exception break from VS.
below are my codes, do enlighten me if you found any problem with my code, and I am still learning..
Server.cpp
#include "cust_ostream.hpp"
#include <Windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
LPVOID buffer = NULL;
DWORD readbyte;
cout << "---Named Pipe Server Test---" << endl << endl;
cout << "Creating named pipe: \\\\.\\pipe\\mypipe" << endl;
HANDLE hPipe = CreateNamedPipeA("\\\\.\\pipe\\mypipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, NULL);
if (!hPipe || hPipe == INVALID_HANDLE_VALUE)
{
cout << "Pipe creation failed." << endl;
return 0;
}
cout << "Connecting pipe to client..." << endl;
BOOL connect = ConnectNamedPipe(hPipe, NULL);
if (!connect)
{
cout << "Connect named pipe failed" << endl;
}
cout << "Success! Reading pipe message from client..." << endl;
ReadFile(hPipe, buffer, sizeof(buffer), &readbyte, NULL);
c_cout << "Pipe message = " << *(int *)buffer << endl;
_getch();
return 0;
}
cust_ostream.hpp
#include <Windows.h>
#include <iostream>
#include <sstream>
using namespace std;
#define endl "\n"
class cust_ostream
{
public:
~cust_ostream()
{
cout << m_buffer.str();
}
template <typename T>
cust_ostream &operator<<(T const &value)
{
m_buffer << value;
return *this;
}
private:
ostringstream m_buffer;
};
#define c_cout cust_ostream()
and my client
#include <Windows.h>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
LPVOID data;
DWORD writebyte;
int i = 2;
cout << "---Named Pipe Client---" << endl << endl;
cout << "Creating pipe file: \\\\.\\pipe\\mypipe" << endl;
HANDLE pipe = CreateFileA("\\\\.\\pipe\\mypipe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (!pipe || pipe == INVALID_HANDLE_VALUE)
{
cout << "Pipe client failed." << endl;
return 0;
}
cout << "Pipe connected to server, sending data..." << endl;
WriteFile(pipe, &i, sizeof(i), &writebyte, NULL);
_getch();
return 0;
}
You need to wait for the NamedPipe to have a ConnectPipeReady event on it. As it stands, you are trying to create the pipe without actually seeing if it was succesfull. See the MSDN documentation for Named Pipes here: https://msdn.microsoft.com/en-ca/library/windows/desktop/aa365592(v=vs.85).aspx
Specifically, this block:
while (1)
{
hPipe = CreateFile(
lpszPipename, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
// Break if the pipe handle is valid.
if (hPipe != INVALID_HANDLE_VALUE)
break;
// Exit if an error other than ERROR_PIPE_BUSY occurs.
if (GetLastError() != ERROR_PIPE_BUSY)
{
_tprintf( TEXT("Could not open pipe. GLE=%d\n"), GetLastError() );
return -1;
}
// All pipe instances are busy, so wait for 20 seconds.
if ( ! WaitNamedPipe(lpszPipename, 20000))
{
printf("Could not open pipe: 20 second wait timed out.");
return -1;
}
}
Also you shouldn't use #define endl "\n", use std::endl
You have initialized your buffer as NULL which means that by default its length is zero. Now when you use the sizeof operator in your read function in server (to retrieve the message received by server from client), what happens is that you are asking the sizeof operator in Read function to read 0 bytes! which means that nothing will be read.
To solve this, you can declare a char array of size 100 or a size of a message which you are sure that won't be exceeded by client. Like if you are assuming that message by client is not going to be longer than lets say 60 characters, then you can create your char buffer to be of size 100 just to make sure that you do accommodate all the message by client.
And one more thing, if problem still persists, instead of using sizeof in read, use 100 or whatever the size of of your char buffer array. This should solve your problem.

How to Enumerate Names of All Named Pipes in a Process?

I need to open a certain named pipe so I can fuzz test it, however my test code does not have access to the same data used to generate the name of the named pipe. However I can recognize the name of the pipe and then use that name to open up the pipe for fuzzing.
I used this forum post to start enumerating names of the handles on the system:
http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html
However it seems that won't work with named pipes for some reason.
TL;DR: What API(s) do I need to use to list the names of all named pipes in the current process on Windows?
This will enumerate all named pipes in the system, or at the very least put you a step in the right direction.
This works in MinGW when built with -fpermissive. It should work with similar settings in MSVC.
#ifndef _WIN32_WINNT
// Windows XP
#define _WIN32_WINNT 0x0501
#endif
#include <Windows.h>
#include <Psapi.h>
// mycreatepipeex.c is at http://www.davehart.net/remote/PipeEx.c
// I created a simple header based on that.
#include "mycreatepipeex.h"
#include <iostream>
#include <cstdio>
#include <errno.h>
void EnumeratePipes()
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
#define TARGET_PREFIX "//./pipe/"
const char *target = TARGET_PREFIX "*";
memset(&FindFileData, 0, sizeof(FindFileData));
hFind = FindFirstFileA(target, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
std::cerr << "FindFirstFileA() failed: " << GetLastError() << std::endl;
return;
}
else
{
do
{
std::cout << "Pipe: " << TARGET_PREFIX << FindFileData.cFileName << std::endl;
}
while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
#undef TARGET_PREFIX
return;
}
int main(int argc, char**argv)
{
HANDLE read = INVALID_HANDLE_VALUE;
HANDLE write = INVALID_HANDLE_VALUE;
unsigned char pipe_name[MAX_PATH+1];
BOOL success = MyCreatePipeEx(&read, &write, NULL, 0, 0, 0, pipe_name);
EnumeratePipes();
if ( success == FALSE )
{
std::cerr << "MyCreatePipeEx() failed: " << GetLastError() << std::endl;
return 1;
}
FILE *f = fopen((const char*)pipe_name, "rwb");
if ( f == NULL )
{
std::cerr << "fopen(\"" << pipe_name << "\") failed: " << (int)errno << std::endl;
}
CloseHandle(read);
CloseHandle(write);
return 0;
}