Poco failing to send mail - c++

I have installed the Poco C++ library (Release 1.12.4) with vcpkg on my computer and I'm trying to send a simple Mail by using the sample delivered on the Github Page.`The script is compile with Visual Studio 17.
The full code:
#include "Poco/Net/MailMessage.h"
#include "Poco/Net/MailRecipient.h"
#include "Poco/Net/SecureSMTPClientSession.h"
#include "Poco/Net/StringPartSource.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/ConsoleCertificateHandler.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.h"
#include "Poco/SharedPtr.h"
#include "Poco/Path.h"
#include "Poco/Exception.h"
#include <iostream>
using Poco::Net::MailMessage;
using Poco::Net::MailRecipient;
using Poco::Net::SMTPClientSession;
using Poco::Net::SecureSMTPClientSession;
using Poco::Net::StringPartSource;
using Poco::Net::SSLManager;
using Poco::Net::Context;
using Poco::Net::InvalidCertificateHandler;
using Poco::Net::ConsoleCertificateHandler;
using Poco::SharedPtr;
using Poco::Path;
using Poco::Exception;
using Poco::UInt16;
using namespace std;
class SSLInitializer
{
public:
SSLInitializer()
{
Poco::Net::initializeSSL();
}
~SSLInitializer()
{
Poco::Net::uninitializeSSL();
}
};
int main()
{
SSLInitializer sslInitializer;
std::string mailhost("smtp.office365.com");
std::string recipient("recipient#gmail.com");
std::string username("MyMail#gmail.com");
std::string password("MyPassword");
Poco:UInt16 port = 587;
try
{
// Note: we must create the passphrase handler prior Context
SharedPtr<InvalidCertificateHandler> pCert = new ConsoleCertificateHandler(false); // ask the user via console
Context::Ptr pContext = new Context(Context::CLIENT_USE, "");
SSLManager::instance().initializeClient(0, pCert, pContext);
MailMessage message;
message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, recipient));
message.setSubject("Hello from the POCO C++ Libraries");
std::string content;
content += "Hello ";
content += recipient;
content += ",\r\n\r\n";
content += "This is a greeting from the POCO C++ Libraries.\r\n\r\n";
message.addContent(new StringPartSource(content));
SecureSMTPClientSession session(mailhost, port);
session.login();
session.startTLS(pContext);
if (!username.empty())
{
session.login(SMTPClientSession::AUTH_LOGIN, username, password);
}
session.sendMessage(message);
session.close();
}
catch (Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
}
I already tried the code on my first computer and it works. I wanted to try it on my laptop but it raises following error:
Poco::Net::NoCertificateException
and after a while:
SSL Exception: Error during handshake: failed to read data
I located the error and it comes from this line:
session.startTLS(pContext);
Thank you for helping me!
P.S: I don't use OpenSSL but NetSSL_Win, an implementation of the POCO NetSSL library based on Windows Schannel.

Related

Is this code correct to send logs to remote syslog server using log4cplus?

Can someone please tell me if this is correct way of using SysLogAppender of log4cplus ? I did not find a proper example for log4cplus. I need to send numerous logs to remote syslog server.
main.cpp
int main()
{
SysLogHelper syslogHelper;
int errCode = syslogHelper.initialize("172.16.72.239");
errCode = syslogHelper.sendLogstoSyslog("send testing log");
// I need to send numerous logs to syslog
}
syslog.cpp
#include <log4cplus/syslogappender.h>
#include <log4cplus/spi/loggingevent.h>
#include <log4cplus/logger.h>
class SysLogHelper
{
string hostname;
log4cplus::SysLogAppender *syslogAppender;
// is it necessary to create a pointer? I am not able to use log4cplus in a class without creating a pointer? Is there any other way?
log4cplus::spi::InternalLoggingEvent syslogLoggingEvent;
public:
SysLogHelper();
int initialize(string hostname);
int sendLogstoSyslog(string message);
};
SysLogHelper::SysLogHelper()
{
hostname = "";
syslogAppender = NULL;
}
int SysLogHelper::initialize(string hostname)
{
syslogAppender = new log4cplus::SysLogAppender("ident", hostname);
//I am not getting what is "ident" here? what input is expected?
return 0;
}
int SysLogHelper::sendLogstoSyslog(string message)
{
syslogLoggingEvent.setLoggingEvent(
log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("test")).getName(),
log4cplus::FATAL_LOG_LEVEL, LOG4CPLUS_TEXT(message),__FILE__,
__LINE__, "main");
syslogAppender->doAppend(syslogLoggingEvent);
//Is this correct method of sending logs to syslog?
return 0;
}
questions:
I am able to send logs to remote syslog using above code. But is this correct way to use log4cplus APIs? Questions are given in the form of comments in above code example.
Why do we need to use log4cplus::initializer? I am not able to import log4cplus/initializer.h in my code.
In my opinion the phylosophy at the base of Log4cplus library is that you can have in your application one or more logger and for each logger you can have one or more output, called "appender". Inside your application you have to manage with logger and you don't have care which appender are linked to the logger. This is clear, for example, if you use a property file to config and to tune your logger.
By the way here in the following I show what I have done to configure syslog inside my application in both cases:
configuring syslog appender inside the code:
#include <log4cplus/logger.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/syslogappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/property.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/fileinfo.h>
#include <TCHAR.h>
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus;
int main()
{
log4cplus::initialize ();
Logger root = Logger::getRoot();
// log level INFO: you don't see TRACE and DEBUG on your syslogserver
root.setLogLevel(log4cplus::INFO_LOG_LEVEL);
SharedObjectPtr<Appender> ptrSys(
new SysLogAppender(
_T("mysyslog"),
_T("localhost"),
514,
_T("user"))) ;
root.addAppender(ptrSys);
for(int i=0; i<100; ++i)
{
LOG4CPLUS_TRACE(root, LOG4CPLUS_TEXT("Error log test")); //not visible
LOG4CPLUS_DEBUG(root, LOG4CPLUS_TEXT("Debug log test")); //not visible
LOG4CPLUS_INFO(root, LOG4CPLUS_TEXT("Info log test"));
LOG4CPLUS_WARN(root, LOG4CPLUS_TEXT("Warning log test"));
LOG4CPLUS_ERROR(root, LOG4CPLUS_TEXT("Error log test"));
}
log4cplus::Logger::shutdown();
return 0;
}
As I said the way, that I prefer, is by configuration file, called here configlog.properties
#include <log4cplus/logger.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/syslogappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/property.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/fileinfo.h>
#include <TCHAR.h>
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus;
log4cplus::tstring getPropertiesFileArgument (std::wstring argv)
{
log4cplus::tstring file = LOG4CPLUS_C_STR_TO_TSTRING (argv);
log4cplus::helpers::FileInfo fi;
if (getFileInfo (&fi, file) == 0)
return file;
return LOG4CPLUS_TEXT ("log4cplus.properties");
}
int main()
{
log4cplus::initialize ();
PropertyConfigurator::doConfigure( getPropertiesFileArgument(_T("c:\\ConfigLog.properties")));
Logger root = Logger::getRoot();
for(int i=0; i<100; ++i) {
LOG4CPLUS_TRACE(root, LOG4CPLUS_TEXT("Error log test"));
LOG4CPLUS_DEBUG(root, LOG4CPLUS_TEXT("Debug log test"));
LOG4CPLUS_INFO(root, LOG4CPLUS_TEXT("Info log test"));
LOG4CPLUS_WARN(root, LOG4CPLUS_TEXT("Warning log test"));
LOG4CPLUS_ERROR(root, LOG4CPLUS_TEXT("Error log test"));
}
log4cplus::Logger::shutdown();
return 0;
}
the configlog.properties file is something like this
log4cplus.rootLogger=INFO, syslog
log4cplus.appender.syslog=log4cplus::SysLogAppender
log4cplus.appender.syslog.ident=syslog
log4cplus.appender.syslog.layout=log4cplus::PatternLayout
log4cplus.appender.syslog.layout.ConversionPattern=[%T] %-5p %b %x - %m%n
log4cplus.appender.syslog.host=localhost
log4cplus.appender.syslog.udp=true
log4cplus.appender.syslog.port=514
log4cplus.appender.syslog.facility=user
I hope to be not too in late and I hope this can be helpful for you

using boost asio to write to carbon gives broken pipe

I have Grafana and Graphite running on localhost. Everything is setup as default, so the plaintext protocol is configured for port 2003, as described here
The following works as desired:
export SERVER=localhost
export PORT=2003
echo "no_cluster.fake_xen.sample 25 1488542618" | nc ${SERVER} ${PORT}
Gives me the datapoint I expect (adjust timestamp as needed).
The following minimal compileable example:
#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/asio.hpp>
namespace basio = boost::asio;
void post_to_carbon (std::string message)
{
using btcp = boost::asio::ip::tcp;
constexpr const char* carbon_port="2003";
basio::io_service ios;
btcp::resolver resolver(ios);
btcp::resolver::query query("localhost", carbon_port);
btcp::endpoint carbon_endpoint = *resolver.resolve(query);
btcp::socket sock(ios,carbon_endpoint);
boost::system::error_code ignored_error;
basio::write(sock, basio::buffer(message), ignored_error);
std::cout << "posting: " << message << " gave: " << ignored_error.message() << "\n";
}
int main() {
post_to_carbon("no_cluster.fake_xen.sample 25 1488542800");
}
Fails with the error message:
posting: no_cluster.fake_xen.sample 25 1488542800 gave: Broken pipe
Can someone tell me what I'm doing wrong?
The constructor form socket(io_service, endpoint) binds the local endpoint of the socket to the given endpoint.
I think what you want to do is:
btcp::socket sock(ios);
sock.connect(carbon_endpoint /* , error_code */);

c++ Debug Assertion Failed on HTTP Request

I'm doing some code where i need to do a GET request and manipulate the info received. For this i'm using C++ REST SDK (codename "Casablanca") for the request
This is my code
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
//This method i saw on the Microsoft documentation
pplx::task<void> HTTPStreamingAsync()
{
http_client client(L"http://localhost:10000/Something"); //The api is running at the moment
// Make the request and asynchronously process the response.
return client.request(methods::GET).then([](http_response response)
{
// Print the status code.
std::wostringstream ss;
ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
std::wcout << ss.str();
// TODO: Perform actions here reading from the response stream.
auto bodyStream = response.body();
// In this example, we print the length of the response to the console.
ss.str(std::wstring());
ss << L"Content length is " << response.headers().content_length() << L" bytes." << std::endl;
std::wcout << ss.str();
});
}
void main(int argc, char **argv)
{
HTTPStreamingAsync().wait();
//...
}
And when i use debug i get error on the following line:
return client.request(methods::GET).then([](http_response response)
With debug i see that variable "client" has content, but i still receive this error:
Image with the Error Message
I google it the error, and most of the people say that it is error on the code (trying to access some parts of the memory)...
Any ideas?
This issue can happen when the cpprestsdk DLL is build with Multi-Threaded DLL /MD and the calling library is build with Multi-Threaded /MT. Since the cpprestsdk does not offer a configuration for a .lib file, you are forced to use /MD. At least that is best to my knowledge, as I haven't been able to compile cpprestsdk.lib out of the box without a bunch of linker errors.

POCO C++ Library, HTTPResponse bad status

I am trying to unzip a file from a network stream using POCO C++ library on Ubuntu Linux, but decompressing fails with "Illegal state" exception. HTTPResponse status and reason are 302 Moved Temporarily. At the same time i can download and unzip the link with a browser. What should i do with HTTPClientSession when HTTPResponse is in such state?
...
HTTPResponse res;
std::istream& rs = h_ses.receiveResponse (res);
if (res.getStatus () != HTTPResponse::HTTP_OK) {
poco_error (logger, "http response status: " + std::to_string (res.getStatus ()) + " " + res.getReason ());
}
if (!rs) {
poco_error (logger, "responese stream is in bad state: " + std::to_string (rs.rdstate()));
}
Decompress dec (rs, target_dir_.native ());
poco_debug (logger, "Unzipping: " + dl + " ...");
dec.EError += Poco::Delegate<Addon_Loader, std::pair<const Poco::Zip::ZipLocalFileHeader, const std::string> >(this, &Addon_Loader::on_decompress_error);
dec.decompressAllFiles ();
...
You can do it with HTTPStreamFactory; here's a full example:
#include "Poco/URI.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/StreamCopier.h"
#include <iostream>
#include <memory>
using namespace Poco;
using namespace Poco::Net;
int main()
{
URIStreamOpener opener;
opener.registerStreamFactory("http", new HTTPStreamFactory);
URI uri("http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F");
std::auto_ptr<std::istream> pStr(opener.open(uri));
StreamCopier::copyStream(*pStr.get(), std::cout);
return 0;
}
If you have to use HTTPClientSession, look at how HTTPStreamFactory does it.
In the 302 response, there should be a header field which points out the new location. You simply have to follow that link instead.
See e.g. this link, or this Wikipedia page, and of course the actual HTTP 1.1 RFC.

How to use OpenSSL in POCO C++ library correctly

According to the Specification in POCO assistant:
Initialize the NetSSL library, as well as the underlying OpenSSL
libraries, by calling Poco::Crypto::OpenSSLInitializer::initialize().
Should be called before using any class from the NetSSL library.
The NetSSL will be initialized automatically, through
Poco::Crypto::OpenSSLInitializer instances or similar mechanisms
when creating Context or SSLManager instances.
However, it is recommended to call initializeSSL()
in any case at application startup.
When I want to use HTTPSClientSession,do I have to construct an Application object first?
How can I use it in Client? Any guy can tell me ?Thank you very much!
Let's take Net/samples/httpget as an example, let's copy httpget/ as a new httpsget directory:
open Makefile, add "PocoNetSSL" to target_libs
replace 'HTTPClientSession' with 'HTTPSClientSession'
you need to create Poco::Net::Context for SSL use
replace 'HTTPClientSession session(uri.getHost(), uri.getPort());' with following two lines:
const Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
Summary:
add PocoNetSSL as a lib_depends
use Poco::Net::Context with HTTPSClientSession
No, you do not need the Application object. Here's a fully functional example:
$ httpsget https://httpbin.org/user-agent
{
"user-agent": "Poco HTTPSClientSession"
}
Code:
#include "Poco/StreamCopier.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include "Poco/SharedPtr.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/KeyConsoleHandler.h"
#include "Poco/Net/ConsoleCertificateHandler.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include <memory>
#include <iostream>
using namespace Poco;
using namespace Poco::Net;
class SSLInitializer {
public:
SSLInitializer() { Poco::Net::initializeSSL(); }
~SSLInitializer() { Poco::Net::uninitializeSSL(); }
};
int main(int argc, char** argv)
{
SSLInitializer sslInitializer;
SharedPtr<InvalidCertificateHandler> ptrCert = new ConsoleCertificateHandler(false);
Context::Ptr ptrContext = new Context(Context::CLIENT_USE, "", "", "rootcert.pem", Context::VERIFY_STRICT, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
SSLManager::instance().initializeClient(0, ptrCert, ptrContext);
try
{
if (argc > 1)
{
URI uri(argv[1]);
HTTPSClientSession s(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_GET, uri.getPath());
request.set("user-agent", "Poco HTTPSClientSession");
s.sendRequest(request);
HTTPResponse response;
std::istream& rs = s.receiveResponse(response);
StreamCopier::copyStream(rs, std::cout);
}
}
catch (Exception& ex)
{
std::cout << ex.displayText() << std::endl;
return 1;
}
return 0;
}