i installed openssl#3 using brew and it is installed in classpath:/opt/homebrew/etc/openssl#3
but during installing poco libraries i am keeping the key directory for openssl by using the command-->
cmake .. -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl
what is the use of this command and how to put it correctly.
but the headers of openssl are not showing inside the /usr/local/include/Poco/Net
because of this, whenever i am compiling the https connection or wss code it is showing HTTPSClientSession.h is not found (fatal error: 'Poco/Net/HTTPSClientSession.h' file not found)
i have done the installation of using this link- https://github.com/pocoproject/poco/tree/3fc3e5f5b8462f7666952b43381383a79b8b5d92
here is the code and please help me with the compiling command and error
fatal error: 'Poco/Net/HTTPSClientSession.h' file not found
#include "Poco/Net/HTTPSClientSession.h"
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
hari-14146:src hari-14146$ vi httpget.cpp
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPCredentials.h"
#include "Poco/StreamCopier.h"
#include "Poco/NullStream.h"
#include "Poco/Path.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include <iostream>
using Poco::Net::HTTPSClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::StreamCopier;
using Poco::Path;
using Poco::URI;
using Poco::Exception;
using Poco::Net:Context;
bool doRequest(Poco::Net::HTTPSClientSession& session, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response)
{
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
StreamCopier::copyStream(rs, std::cout);
return true;
}
else
{
Poco::NullOutputStream null;
StreamCopier::copyStream(rs, null);
return false;
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
Path p(argv[0]);
std::cout << "usage: " << p.getBaseName() << " <uri>" << std::endl;
std::cout << " fetches the resource identified by <uri> and print it to the standard output" << std::endl;
return 1;
}
try
{
URI uri(argv[1]);
std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
std::string username;
std::string password;
Poco::Net::HTTPCredentials::extractCredentials(uri, username, password);
Poco::Net::HTTPCredentials credentials(username, password);
//HTTPClientSession session(uri.getHost(), uri.getPort());
const Context::Ptr context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
HTTPSClientSession Client(uri.getHost(), uri.getPort(), &context);
HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
HTTPResponse response;
if (!doRequest(session, request, response))
{
credentials.authenticate(request, response);
if (!doRequest(session, request, response))
{
std::cerr << "Invalid username or password" << std::endl;
return 1;
}
}
}
catch (Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
how to compile this code and how to give arguments in execution also
how to setup openssl headers in the path /usr/local/include/Poco/Net.
any simple ways to do it and the compiler has to read the header files from above path(/usr/local/include/Poco/Net)
please anyone help me what to do here I am new to c++
Related
I am new to c++ and tring to send a mail using gmail smtp. I have done this in python but I am unable to do it in c++. I think I need to add startTLS() but it seems to be not defined. Please help me, I have tried my best. Searched the internet also could not find any thing.
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
#include <string>
using namespace Poco::Net;
using namespace std;
int main(int argc, char** argv)
{
std::string Username = "farhantestingsmtp#gmail.com";
std::string Password = "cpguxktxoyibiybd";
std::string Receiver = "jattfarhan10#gmail.com";
std::string Name = "Jatt Farhan";
std::string Subject = "Hello!";
std::string Content = "TEXT OF THE EMAIL";
try
{
MailMessage msg;
msg.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, Receiver, Name));
msg.setSender(Username);
msg.setSubject(Subject);
msg.setContent(Content);
SMTPClientSession smtp("smtp.gmail.com", 487);
smtp.open();
cout << "Before Login";
smtp.login(SMTPClientSession::AUTH_LOGIN, Username, Password);
cout << "After Login";
smtp.sendMessage(msg);
smtp.close();
std::cerr << "Sent mail successfully!" << std::endl;
}
catch (std::exception& e)
{
std::cerr << "Failed to send mail: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
I have added my mail username and password, as it for testing. Thanks in advance.
I tried to add startTLS and could not do it as The SecureSMTPClientSession was not defined in my VS environment. I also searched the internet, but could not fix it.
I tried this code but I get SMTP Exception, What could I do?
I tried changing the login id and password making sure they are the correct so.
If anyone knows what I can try to make it work I would be very grateful.
// compile with: g++ -Wall -O3 Email.cc -lPocoNet -lPocoFoundation -o Email && ./Email
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
#include <string>
using namespace Poco::Net;
int main(int argc, char **argv)
{
std::string Username = "email_id";
std::string Password = "password";
std::string Receiver = "receiver#gmail.com";
std::string Name = "Charles";
std::string Subject = "Hello!";
std::string Content = "TEXT OF THE EMAIL";
try
{
MailMessage msg;
msg.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, Receiver, Name));
msg.setSender(Username);
msg.setSubject(Subject);
msg.setContent(Content);
SMTPClientSession smtp("smtp.gmail.com");
smtp.login(SMTPClientSession::AUTH_LOGIN, Username, Password);
smtp.sendMessage(msg);
smtp.close();
std::cerr << "Sent mail successfully!" << std::endl;
}
catch (std::exception &e)
{
std::cerr << "Failed to send mail: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
I am having problems with Windows file path separators using the libssh c++ wrapper libsshpp.
Suppose I have following code:
#define SSH_NO_CPP_EXCEPTIONS
#include "libssh/libsshpp.hpp"
#include <iostream>
#pragma comment(lib, "ssh")
int main()
{
ssh::Session session;
int sessionMsg = -1;
std::string host = "myhost.com";
std::string user = "username";
std::string idfile = "%s\\.ssh\\id_ed25519";
std::string hostkeys = "ssh-ed25519";
std::string keyExchange = "curve25519-sha256";
session.setOption(SSH_OPTIONS_HOST, host.c_str());
session.setOption(SSH_OPTIONS_USER, user.c_str());
session.setOption(SSH_OPTIONS_STRICTHOSTKEYCHECK, (long)0);
session.setOption(SSH_OPTIONS_HOSTKEYS, hostkeys.c_str());
session.setOption(SSH_OPTIONS_KEY_EXCHANGE, keyExchange.c_str());
session.setOption(SSH_OPTIONS_ADD_IDENTITY, idfile.c_str());
std::cout << "Trying to connect to " << host << " with user " << user << "...\n";
session.connect();
if (session.isServerKnown() != SSH_SERVER_KNOWN_OK) {
std::cout << "Server unknown.\n";
if (session.writeKnownhost() != SSH_OK) {
std::cout << "Unable to write to known_hosts file.\n";
}
else {
session.connect();
}
}
sessionMsg = session.userauthPublickeyAuto();
std::string err = session.getError();
if (sessionMsg != SSH_AUTH_SUCCESS) {
if (!err.empty()) {
std::cout << err;
}
std::cout << "Auth failed.";
}
else {
std::cout << err.empty() ? session.getIssueBanner() : err;
}
}
In the beginning I had set the idfile value to just id_ed25519 but then libssh complained: Failed to read private key: C:\Users\MyUser/.ssh/id_ed25519 (notice the switching slashes). After changing it to %s\\.ssh\\id_ed25519 it seemed to have had a positive impact on the connection routine, however now I keep falling into the (session.writeKnownhost() != SSH_OK) code part.
Now, I am wondering if this might be due to the same "switching slashes" problem which came up for the private key file path because apparently libssh wants to access C:\Users\MyUser\.ssh\known_hosts but quite possibly the path is set as something like C:\Users\MyUser/.ssh/known_hosts.
My question is: is there a possibility to change the path seperators to windows-style somehow in the session or is there something else I am overseeing or doing wrong here?
I was able to solve the problem adding the SSH_OPTIONS_SSH_DIR option and changing the private key and known_hosts paths (now relative to the ssh directory path):
// note here: %s will be replaced by libssh with the home directory path
std::string sshDir = "%s//.ssh";
std::string idFile = "id_ed25519";
std::string knownHosts = "known_hosts";
// ...
session.setOption(SSH_OPTIONS_USER, user.c_str());
session.setOption(SSH_OPTIONS_SSH_DIR, sshDir.c_str()); // <-- added
// ...
when i build my own cpprestsdk server and client,i found that when my server receive a request and reply to it, my client have no reaction to it,and it never goes into the breakpoint where i handle the http_response,here is my code;
i was stuck for so many days,will someone help me fix this,thanks a lot
(client send request,server receives it and reply, client fail to receive http_response)
Server(i just got it from somewhere on internet):
#include "cpprest/json.h"
#include "cpprest/http_listener.h"
#include "cpprest/uri.h"
#include "cpprest/asyncrt_utils.h"
#include "cpprest/http_client.h"
using namespace web::http::experimental::listener;
using namespace web::http;
using namespace web;
void handle_get(http_request message)
{
message.reply(status_codes::OK, U("Hello, World!"));
};
void handle_post(http_request message)
{
message.reply(status_codes::NotFound);
};
void handle_put(http_request message)
{
message.reply(status_codes::NotFound);
};
void handle_delete(http_request message)
{
message.reply(status_codes::NotFound);
};
#define TRACE(msg) std::wcout << msg
#define TRACE_ACTION(a, k, v) std::wcout << a << L" (" << k << L", " << v << L")\n"
int main(int argc, char ** argv)
{
uri_builder uri(U("http://localhost:8888"));
http_listener listener(uri.to_uri());
listener.support(methods::GET, handle_get);
listener.support(methods::POST, handle_post);
listener.support(methods::PUT, handle_put);
listener.support(methods::DEL, handle_delete);
try
{
listener
.open()
.then([&listener](){TRACE(L"\nstarting to listen\n"); })
.wait();
while (true);
}
catch (std::exception const & e)
{
std::wcout << e.what() << std::endl;
}
catch (...)
{
std::wcout << "Unknown exception" << std::endl;
}
return 0;
}
and here is my Client
#include "cpprest/http_client.h"
#include "cpprest/filestream.h"
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://www.bing.com/"));
http_client localclient(U("http://localhost:8888"));
return localclient.request(methods::GET);
})
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
system("pause");
return response.body().read_to_end(fileStream->streambuf());
})
.then([=](size_t)
{
return fileStream->close();
});
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
system("pause");
}
return 0;
}
Another question on a Mysql connection failing:
I'm using the Poco library (1.5.2) and I would like to know why, when I try to open a MySQL connection, I got this message:
Connection attempt failed
Whereas, when I try a connection via console (mysql -u root -p ...), it works.
Maybe I forget an important step in the MySQL configuration ?
Here is my code :
#include <iostream>
#include <string>
#include <Poco/Data/MySQL/MySQLException.h>
#include <Poco/Data/MySQL/Connector.h>
#include <Poco/Data/SessionFactory.h>
using namespace std;
int main()
{
Poco::Data::MySQL::Connector::registerConnector();
try
{
string str = "host=localhost;user=root;password=mypassword;compress=true;auto-reconnect=true";
Poco::Data::Session test(Poco::Data::SessionFactory::instance().create(Poco::Data::MySQL::Connector::KEY, str ));
}
catch (Poco::Data::MySQL::ConnectionException& e)
{
cout << e.what() << endl;
return -1;
}
catch(Poco::Data::MySQL::StatementException& e)
{
cout << e.what() << endl;
return -1;
}
return 0;
}
Thank you !!
ok the problem was the "localhost" value for "host" doesn't work on my linux (I don't know why). For fixing the bug, I had to change my string to:
string str = "host=127.0.0.1;user=root;password=mypassword;compress=true;auto-reconnect=true";