How-to: Send text from webpage and send to external application - c++

i'm writing a program for my algorithm class that is supposed to be able to traverse a webpage, find a random address, and then using a browser extension(Firefox/Chrome), it should do a Google Maps search for that address. I literally just thought that maybe trying to use the extension to capture text and put it into a text file and then make my program read that text file would be a good idea, but i have no clue as to how that would be implemented.
My code so far (Don't worry, after a Window UI, it will get longer. This is just a test console app):
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <windows.h>
using namespace std;
int main ()
{
string address;
cout << "Please input address: ";
//cin >> address;
getline(cin, address);
//word_list = getRecursiveURLs(url, DEPTH)
//return cleaner(word_list)
//string address = "Houston, Tx ";
std::string str = "http://mapof.it/" + address;
//cout << mapSearch;
const char * c = str.c_str();
ShellExecute(NULL, "open", c, NULL, NULL, SW_SHOWNORMAL);
}
Right now, my code takes in an address and adds it to the end of a "Mapof.it" url that basically initiates a GMaps search.

It look like user is interact with your C++ program. It doesn't need to communicate with browser progress.
You can send http request from C++ program, fetch the reponse text, then parse it.
First, you try to find whether the website provide a api url which return json/xml format, because json/xml is easier to parse. For example, Google Map does provide api.
If not, try to use regular expression to parse html, or find some DOM handle library to parse it with DOM.
If your result text can't not extract from raw, it create by JavaScript dynamically, you can find some "headless browser" library to help you.
If you need a full feature browser, use QT, it provide QtWebkit widget.

Related

c++ password storage .txt file + masking input

I'm pretty new to programming - just starting out with C++. So I wanted to make an application - just for fun - which would mask user input with asterisks. I did some research and found exactly what I was looking for. As you can see inside the code below it works fine but only checks password from a char I put - "correct_password". I thought it'd be more challenging to extend options. The program would write two options out: 1. register - just put your login and password (without asterisks), then store it into a file (fstream I guess), 2. login - after putting login and password (with asterisks just the way it is in getpass) it would check the file for data if user is actually registered. Even thought maybe about encrypting data in that file, although I have no idea how to proceed. Well, it's just made up thing to learn some new stuff, I know it's not really a THING and there's no really a purpose to write such code - just messing around with C++. Maybe you got some ideas how to snap that? After I wrote this asterisk thing i don't really see where I should put those other options, storing in file and so on. Would love to go through some ideas and appreciate the input from more experienced coders :)
I tried using fstream inside getpass but didn't work out. Generally I'd like to extend this program with login and password input, storing them into .txt file and then program would check if user is registered and while logging with this data input would be masked with asterisks - just like my first idea of that program which is only masking password input. I don't really know how to split unmasked input with that inside getpass.
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
string getpass(const char *dat, bool s_asterisk=true)
{
const char BACKSPACE=8;
const char RETURN=13;
string password;
unsigned char ch=0;
cout << dat;
DWORD con_mode;
DWORD dwRead;
HANDLE hIn=GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode( hIn, &con_mode );
SetConsoleMode( hIn, con_mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT) );
while(ReadConsoleA( hIn, &ch, 1, &dwRead, NULL) && ch !=RETURN)
{
if(ch==BACKSPACE)
{
if(password.length()!=0)
{
if(s_asterisk)
cout <<"\b \b";
password.resize(password.length()-1);
}
}
else
{
password+=ch;
if(s_asterisk)
cout <<'*';
}
}
cout << endl;
return password;
}
int main()
{
const char *correct_password="fdsidfjsijdsf21128321873";
START:
string password=getpass("Enter the password: ",true);
if(password==correct_password){
cout <<"\nCorrect password."<<endl;
exit(1);
}else{
cout <<"\nIncorrect password. Try again.\n"<<endl;
goto START;
}
return 0;
}
Usually you don't want to store actual passwords in a file. Although encrypting them would help security (to at least some degree), it's still generally pretty insecure and better avoided.
What you usually want to do instead is salt the password, then hash the salted password with a cryptographic hash. Then you store the salt and the hash, rather than the password itself.
Then (for the simplest case) when the user wants to log in, you repeat the same process: retrieve the salt for their password, apply the salt to the password they enter, hash the result, and finally compare that result to the value you stored. If they match, you assume the user entered the correct password. If they don't match, you know they didn't.
Note that this is only reasonable for the user logging into your application locally (or at least over a secure connection). If they might log in over an insecure connection, you need to get considerably more sophisticated still.
Another major point though: nearly all of this should happen outside getpass. getpass should do exactly one thing: read in a password from the user. Salting, hashing, storing, and so on, should all happen separately from that.

How to make a C++ program that works with a .txt file without showing it

My program needs to use a hidden text file to keep track of user's name.
But when the program starts, if it can't find the 'Name.txt' file in the same directory, it generates one that is visible to the user.
The user can view it, edit it, and so on. How can I prevent this from happening, so that only my program can modify the file?
Also, is there a better way to keep knowledge of the name of the user (keep in mind I'm new to programming in general, not only to C++)?
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <Windows.h>
using std::string;
using std::cout;
using std::cin;
using std::ifstream;
using std::ofstream;
int main()
{
string line;
ifstream example;
example.open("Name.txt");
getline(example, line);
if (line.compare("") == 0)
{
example.close();
string con;
cout << "Welcome to this program!\n";
cout << "Do you want to register? (y/n) ";
cin >> con;
con[0] = tolower(con[0]);
if (con.compare("n") != 0)
{
string name;
ofstream one;
one.open("Name.txt");
cout << "What's your name? ";
cin >> name;
one << name;
one.close();
cout << "See you later " << name << ".";
Sleep(4000);
}
}
else
{
cout << "Welcome back " << line << ".";
example.close();
Sleep(4000);
}
}
EDIT : I just realised I said 'to keep track of the user'. Now I realized why you guys thought I wanted to do something bad with this program. I corrected it now, what I meant was 'to keep track of the user’s name'.
I understand that you want to maintain a file that contains the names of all the registered users, or some other kind of current-user-independent data.
The problem
Your code tries to open the file in the current working directory of the program. Unfortunately, it depends on the way the user has launched your program.
It also ignores possible errors during the opening when reading the file. So if the file isn't there, your code will open the file as ofstream for writing (which will create the file if it doesn't exist).
How to solve it ?
To fulfill your requirements, you should open the file in a predetermined location (for example fixed during the installation process, or in the program's configuration). See this article, on where to ideally store data and configuration files on windows platform.
If you want to make sure that the program only opens the file if it already exists, you should verify the result of the open on the ifstream and issue an error message if this failed:
example.open("Name.txt");
if (!example) {
cout << "OUCH ! Fatal error: the registration file couldn't be opened !" <<endl;
exit (1);
}
How to protect the file against users ?
Note however that if your program reads and writes data from the file, the user could find it also and edit it manually. This will be difficult to prevent.
Alternatively you could consider using the windows registry, which is less trivial for the user to edit (although not impossible). The major inconvenience of this approach is that it's system dependent and it will make the porting of your code to other platforms much more difficult.
If you want to fully protect your file, you could as suggested by Chris in the comment, encrypt the file. Encryption is complex business; Consider using a library such as openssl or a proven algorithm.
This will protect you against ordinary users. But you'd still be exposed to hackers able to reverse engineer your code and to find the encryption key that must be somehow embedded in your code to decrypt the file.

How do I address a very specific web url?

I am writing code in C++ (using the Poco net libraries) to try to create a program for fun which will email me every few hours with updates to the TwitchPlaysPokemon stream (stupid, I know). Here is my code:
#include <iostream>
#include "Poco/Net/SocketAddress.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/SocketStream.h"
#include "Poco/StreamCopier.h"
using namespace std;
using namespace Poco::Net;
using namespace Poco;
int main(int argc, char *argv[])
{
string url = "www.reddit.com";
string fullPage;
SocketAddress sa(url, 80);
StreamSocket socket(sa);
SocketStream str(socket);
str << "GET / HTTP/1.1\r\n"
"Host: " << url << "\r\n"
"\r\n";
str.flush();
StreamCopier::copyStream(str, cout);
}
This exact code works perfectly fine. It grabs the raw html of www.reddit.com and prints it to the console. However, I'm trying to get information from one of two places for my program:
Either:
Here (url = "http://www.reddit.com/live/sw7bubeycai6hey4ciytwamw3a")
or
Here (url = "https://sites.google.com/site/twitchplayspokemonstatus/")
Either of these will be fine for my purposes. The problem is that when I plug these values in as the url in my program, the program has no idea what I'm talking about. Specifically, I get the following:
so clearly it cannot find the host. This is where I am stuck, as I know very little about internet protocol, hosts, etc. I tried to see if there was a specific IP address for this website (using cmd prompt ping), but it couldn't figure it out either ( it says "Ping request could not find the host www.reddit.com/live/sw7bubeycai6hey4ciytwamw3a"). The Poco library accepts written out urls (www.reddit.com), IPv4, and IPv6 addresses as the host input to SocketAddress (where I use the variable url, the other variable is the port which I've been told should basically always be 80?)
Question: I need help figuring out how I should be identifying the host to the Poco library. In other words, how do I properly refer to the host for either of those two sites listed above in such a way that my code can recognize it and grab the HTML from the page.
It sounds as though you may not understand HTTP correctly. Here's a brief refresher.
To get the contents of the URL http://www.example.com/path/page.html, the corresponding HTTP request would be sent to www.example.com on port 80, and would have the contents:
GET /path/page.html HTTP/1.1\r\n
Host: www.example.com\r\n
\r\n
The critical part that it doesn't look like you're doing correctly here is splitting the URL into the hostname and path components. Having a single url variable won't work (unless you manually split it on the first slash).

Extra Characters Reading from Serial Port Using libserial on Linux

I have a very basic device with which I am trying to interact via a serial connection on Linux. I am on the steep part of the learning curve here, still, so please be gentle!
Anyhow, I am able to control the device via Hyperterminal in Windows, or via cu, screen, or minicom in Linux. I am connected via a built-in serial port on a PC at 19200, 8N1. The interface for the device is very simple:
Type "H", and the device echoes back "H".
Type "V", and the device echoes back a string containing its software version, "ADD111C".
Type "S", and the device returns "0", "1", or "?", depending on its printer status.
Type "Q", and it returns a five-line response with details on the last transaction processed.
Each response is followed by a new-line, perhaps a CR, too, I am not certain.
There's more, but that's a good start. When I connect to the device using screen, it works fine:
root#dc5000:~# screen /dev/ttyS0 19200,cs8,-ixon,-ixoff
V
ADD111C
Once I had that working manually, I tried to write a simple program using C++ and libserial to interact with the device. It looks like this:
#include <SerialStream.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
using namespace LibSerial;
int main(){
char next_char[100];
int i;
SerialStream my_serial_stream;
my_serial_stream.Open("/dev/ttyS0") ;
my_serial_stream.SetBaudRate( SerialStreamBuf::BAUD_19200 ) ;
my_serial_stream.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ;
my_serial_stream.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_NONE ) ;
my_serial_stream.SetParity( SerialStreamBuf::PARITY_NONE ) ;
my_serial_stream.SetNumOfStopBits(1) ;
my_serial_stream.SetVTime(1);
my_serial_stream.SetVMin(100);
cout<<"Sending Command:\n";
my_serial_stream << "V";
my_serial_stream.read(next_char,100);
cout<<"Result: "<<next_char<<"\n";
my_serial_stream.Close();
return 0;
}
This is successfully able to send the "V" to the serial port, but when I read it back, I get a number of non-printing characters back after the valid data:
root#dc5000:~# g++ -o serialtest serialtest.cpp -lserial
root#dc5000:~# ./serialtest
Sending Command:
Result:
V
ADD111C
��se�Xw��AN��ƿ,�
root#dc5000:~#
What am I missing to only grab the response to my query? I'm guessing that I need to flush a buffer on the port or something, but I have reached the end of my limited knowledge here.
Ideally I would like to just get the "ADD111C", but I don't want to paint myself into a corner by grabbing a specific length of data (in case it changes in the future), and the garbage at the end of the read does not always seem to be the same length, or the same data.
Many thanks for taking a look,
Tom
Zack & keshlam: Thank you for the help. Zack's suggestion to write a NULL to the end of the string resolved the problem, but I actually stumbled across a simpler method while working with another string (trying to grab a substring of the output).
Rather than define the C string like this:
char next_char[100];
I did it like this:
char next_char[100] = "";
It seems that assigning a value to the char before reading from the serial port properly null terminated it. I can now remove the memset command from my code and it now works fine:
root#dc5000:~# ./serialtest
Sending Command:
Result:
V
ADD111C
Thanks for the help!

Program that modifes string inside its exe

I looking for example of program, that modifies a string inside its exe.
I work with C++, Visual Studio under Windows.
I searched working examples in Windows, but I can't find any working code.
I need simple code, that will ask user for string:
string strTest = "";
(if strTest != "")
{
cout << "Modified: " << strTest << endl;
}
cin >> strText;
And code should rewrite:
string strTest = "";
To string that typed user:
string strTest = "SomeStringFromUser";
How, in C++, do you modify a string (from string strTest = ""), to string, what a user typed? (for example to strTest = "foo")?
When an EXE is running on a Windows machine, the exe file is held open as a CreateFileMapping object with pages marked either as READONLY or COPY_ON_WRITE.
So when the exe writes to itself, the file is not modified. It just creates a new page backed by the swap file. But since the file is kept open, no-one else can open the EXE file and write to it either.
Other than hacking the page protection to turn off COPY_ON_WRITE - Which I'm not sure is even possible. The only way I can think to do this would be to write a little program that runs after your exe finishes and opens the .exe file and writes to it.
I've gotta believe that whatever you are trying to do, there is a better way to go about it.
--- Later ----
Ok, I get it now. you are looking to watermark your exe. Here's the thing, this is pretty easy to do in your installer before the exe starts. But once the .exe is running it's MUCH harder to do.
Here's what I would do.
declare a global string variable of the necessary size, say const char g_szWatermark[100] = "";
Build my exe, then look in the map file to find the address of the variable within its segment (remember about C++ name decoration)
parse the EXE header to find the where the segment begins in the exe.
add these two numbers to get the location of the string within the exe file, give this number to my installer
have the installer run a little program that asks the user for information and then writes it into the .exe. Note: you have do do this before the exe runs or it won't work!
A licensing scheme based on some open, established cryptographic mechanism is going to be your most robust solution. Something using standard PKI should be much simpler and more secure than attempting to implement self-modifying code.
To be honest though, there are a lot of companies that spend a lot of money on R&D creating copy protection and those systems are cracked within days of release. So if you're trying to thwart crackers then you have a long, hard road ahead.
If you just want to keep the honest people honest, a simple online activation using a GUID as the "license key" would be quite effective.
How about this:
#include <string>
#include <iostream>
int main()
{
std::string strTest = "";
std::getline(std::cin,strTest);
if (strTest != "")
{
std::cout << "Modified String: " << strTest << "\n";
}
else
{
std::cout << "Not modified\n";
}
}