Sunday, August 12, 2012

Hanoi tower in C++

Here I'm sending a recursive solution for solving Hanoi tower problem with 3 columns and n disks.
Columns are in following order :

    ||                ||             ||
    ||                ||             ||
    ||                ||             ||
    ||                ||             ||
====         ====      ====
 c_from         c_other         c_to

The problem is moving n disks from column c_from to column c_to ( we can't put bigger disks over smaller disks in a column )
Solution is :
1- moving n-1 disks from c_from to c_other
2- moving last disk from c_from to c_to
3- moving n-1 disks from c_other to c_to
.
here is simple code in C++ to solve the problem:

class HanoiTower
{
 
private :
 int N;
 stack<int> towers[3];
public:
 enum TOWERS
 {
  A=0,
  B=1,
  C=2
 };
 HanoiTower(int pN)
 {
  N=pN;
  for(int i=N-1;i>=0;i--)
   towers[A].Push(i);
 }
 void MoveRec(int pN,TOWERS tFrom,TOWERS tTo)
 { 
  if(pN==0)
  {
   int disk=towers[tFrom].Top();
   towers[tFrom].Pop();
   towers[tTo].Push(disk);
   cout <<" move "<<disk<<" from "<<tFrom<< " to "<< tTo<<endl;
   //cout <<disk+1<<tFrom+1<<tTo+1<<endl;
   return;
  }
  TOWERS other=(TOWERS)(3-tFrom-tTo);
  MoveRec(pN-1,tFrom,other);
  MoveRec(0,tFrom,tTo);
  MoveRec(pN-1,other,tTo);
 }
};

// usage :
HanoiTower hn(15);
hn.MoveRec(14,HanoiTower::TOWERS::A,HanoiTower::TOWERS::C);

Saturday, August 11, 2012

Send Email in C++ ( SMTP Client in C++ )

Boost! Yes! It's a good library for you to help you develop cross-platform C++ applications; headache free. among all libraries in boost, boost::asio is for implementing asynchronous input output operations and working with network. After having a look at boost asio samples and SMTP RFC : http://www.ietf.org/rfc/rfc2821.txt I implemented this simple class to be used in your C++ programs.
the only tricky part is base64 encoding which is required for sending user/password to SMTP Server.
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
using boost::asio::ip::tcp;
using namespace boost::archive::iterators;
typedef base64_from_binary<transform_width<const char *,6,8> > base64_text;
class SMTPClient
{
public:
 SMTPClient(std::string pServer,unsigned int pPort,std::string pUser,std::string pPassword):
   mServer(pServer),mPort(pPort),mUserName(pUser),mPassword(pPassword),mSocket(mIOService),mResolver(mIOService)
   {
    tcp::resolver::query qry(mServer,boost::lexical_cast<std::string>( mPort ));
    mResolver.async_resolve(qry,boost::bind(&SMTPClient::handleResolve,this,boost::asio::placeholders::error,
     boost::asio::placeholders::iterator));
   }
   bool Send(std::string pFrom,std::string pTo,std::string pSubject,std::string pMessage)
   {
    mFrom=pFrom;
    mTo=pTo;
    mSubject=pSubject;
    mMessage=pMessage;
    mIOService.run();
    return mHasError;
   }
private:
 std::string encodeBase64(std::string pData)
 {
  std::stringstream os;
  size_t sz=pData.size();
  std::copy(base64_text(pData.c_str()),base64_text(pData.c_str()+sz),ostream_iterator<char>(os));
  return os.str();
 }
 void handleResolve(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator)
 {
  if(!err)
  {
   tcp::endpoint endpoint=*endpoint_iterator;
   mSocket.async_connect(endpoint,
    boost::bind(&SMTPClient::handleConnect,this,boost::asio::placeholders::error,++endpoint_iterator));
  }
  else
  {
   mHasError=true;
   mErrorMsg= err.message();
  }
 }
 void writeLine(std::string pData)
 {
  std::ostream req_strm(&mRequest);
  req_strm << pData << "\r\n";
  boost::asio::write(mSocket,mRequest);
  req_strm.clear();
 }
 void handleConnect(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator)
 {
  if (!err)
  {
   // The connection was successful. Send the request.
   std::ostream req_strm(&mRequest);
   writeLine("EHLO "+mServer);
   writeLine("AUTH LOGIN");
   writeLine(encodeBase64(mUserName));
   writeLine(encodeBase64(mPassword));
   writeLine( "MAIL FROM:<"+mFrom+">");
   writeLine( "RCPT TO:<"+mTo+">");
   writeLine( "DATA");
   writeLine( "SUBJECT:"+mSubject);
   writeLine( "From:"+mFrom);
   writeLine( "To:"+mTo);
   writeLine( "");
   writeLine( mMessage );
   writeLine( ".\r\n");
  }
  else
  {
   mHasError=true;
   mErrorMsg= err.message();
  }
 }
 std::string mServer;
 std::string mUserName;
 std::string mPassword;
 std::string mFrom;
 std::string mTo;
 std::string mSubject;
 std::string mMessage;
 unsigned int mPort;
 boost::asio::io_service mIOService;
 tcp::resolver mResolver;
 tcp::socket mSocket;
 boost::asio::streambuf mRequest;
 boost::asio::streambuf mResponse;
 bool mHasError;
 std::string mErrorMsg;

};
Yest ! that's it. you are free to copy and paste this code into your application:
SMTPClient mailc("yoursmtpserver.com",25,"user@yourdomain.com","password");
mailc.Send("from@yourdomain.com","to@somewhere.com","subject","Hello from C++ SMTP Client!");





Saturday, August 4, 2012

How to find DOS attackers in Linux

#netstat -anp | grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | grep -v "^$" | uniq -c | sort -nr


output will be ;


Number_of_connections          Client_IP
-------------------------------------       ------------------

Thursday, August 2, 2012

Implementing thread safe queue in C++11

Concurrency again!
I'm going to show you how to implement thread safe queue using lock/mutex and condition variable based synchronization in C++11.
As you know protecting shared data in multi-threaded  environment is very important.
at this following sample I demonstrated how to use mutexes and condition variables to write a thread-safe queue.
I put all description as comments to help you understand better.

#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>

template <class T>
class tsqueue
{
private :
	std::queue<T> mData;
	// check empty() method for description of "mutable"
	mutable std::mutex mMut; 
	std::condition_variable mEmptyCondition;
	void wait_for_debugging()
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(200+rand()%200));
	}
public:
	void Push(T pValue)
	{
		// block execution here, if other thread already locked mMute!
		std::lock_guard<std::mutex> lock(mMut); 
		// if weare here no other thread is owned/locked mMute. so we can modify the internal data
		mData.push(pValue); 
		// OK! notify one of threads which was blocked because , queue empty and make them happy!
		mEmptyCondition.notify_one(); 
		wait_for_debugging();
	} // //lock.unlock(); !!!! does not have such method!
	// now mMute is unlocked in destcutor of lock_guard!

	std::shared_ptr<T> Pop()
	{
		// own the mMute like in Push method excep that lock can be unlocked manually without need to destructor of lock!
		std::unique_lock<std::mutex> lock(mMut); 
		// if we are here. mMute is locked and no other thread can access/modify the data!
		// wait() method first checks if mData is not empty, allowes execution to go on. else :
		// unlocks the mMut and waits for signla.
		// because mMute is released other threads have a chance to Push new data into queue 
		// ... in notify this condition variable!
		mEmptyCondition.wait(lock,[this]{ return !mData.empty();});
		// if we are are here, mData is not empty and mMut is locked !
		// be careful ! std::shared_ptr<T> ret(new T(mData.front()) performs 2 memory allocation!
		std::shared_ptr<T> ret=std::shared_ptr<T>(std::make_shared<T>(mData.front()));
		mData.pop();
		wait_for_debugging();
		return ret;
	}
	std::shared_ptr<T> TryPop()
	{
		std::lock_guard<std::mutex> lock(mMut); 
		if(mData.empty())
			return std::shared_ptr<T>(); // null
		std::shared_ptr<T> ret=std::shared_ptr<T>(std::make_shared<T>(mData.front()));
		mData.pop();
		wait_for_debugging();
		return ret;
	}
	bool Empty() const
	{
		//  this function is "const", so why are we allowed to modify a member vaiable "mMute"?....
		//we can, because we marked it "mutable"! see definition of mMute.
		std::lock_guard<std::mutex> lock(mMut); 
		return mData.empty();
	}
};

void test_tsq()
{
	tsqueue<int> tsq;
	int N=100;
	std::thread thrpush([&]{
		for(int i=0;i<N;i++)
		{
			tsq.Push(i);
			std::cout <<i<<" pushed \n";
		}
	});
	std::thread thrpop([&]{
		for(int i=0;i<N/2;i++)
		{
			std::cout <<"popping\n";
			std::shared_ptr<int> data=tsq.Pop();
			std::cout <<i<<": poped "<<*data<<"\n";
		}
	});
	std::thread thrtrypop([&]{
		int i=0;
		for(;i<N/2;)
		{
			std::cout <<"trying for pop\n";
			std::shared_ptr<int> data=tsq.TryPop();
			if(data.get()!=NULL)
			{
			std::cout <<i++<<": try poped "<<*data<<"\n";
			}
			else
				std::cout <<"failed trying pop \n";

		}
	});
	thrpush.join();
	thrpop.join();
	thrtrypop.join();
}


The only reminded point to be notices about mEmptyCondition.wait(...) method is that if this condition variable was notified after any push() method from other thread, It checks the mData.empty() condition for avoiding race condition. because there is a chance for "pop"ing last inserted item by other thread. So even being notified is not enough reason to continuing execution and modifying data. ( in this case because of notifyone(). only one condition variable is notified among all waiting condition variables)

Saturday, July 28, 2012

My experience on C++ Serialization Solutions

Recently I tried 3 solutions for serializing request data in my Apache filter module in C++:
1- Google Protocol Buffer
2- boost serialization
3- msgpack
I was disappointed of using solutions 1 and 2 because of errors I faced. I submitted errors in many forums and related mailing lists, but I couldn't get any answer.
Google protocol buffer seems professional but It needs classes to be defined in specific way which that protocol forces.
BTW I started with this solution and designed *.protoc files and generated my model files.
the solutions worked fine in a console application but I've got segmentation fault in Apache module without any specific error. ( I tried debugging with gdb, ddd,.... but no chance to resolve the error).
So I switched to boost serialization. It was much simpler than Google solution but It didn't work completely.
It worked fine in console application and Apache filter too.
but I've segfault when I tried to serialize nested classes.
I returned to my mind, searching a solution recommended by one of my friends( Kamyar, which has been used that solution in .NET).
It was msgpack, the 3rd solution.
It's much simple than Google solution and even simpler than boost serialization.
It worked fine without any headache. As msgpack website says, It's much fast from Google and boost solution :
http://www.msgpack.org

Friday, July 27, 2012

How to run class member function in C++11 thread


class X
{
private:
 int mX;
public:
 F()
 {
   // some work
 }
};

void thread_sample()
{
  X x;
  std::thread th(&X::F,&x);
  th.join(); // call detach() if you want this method not to wait for F() to finish
 }

Tuesday, July 17, 2012

Simplest threading sample in C++11

If you were looking for multitasking and threading library in C++.
C++11 standard brought multitasking for you in the best way.
Here is the simplest threading sample in C++11. I'll post more advanced samples progressively.
I've tested this code sample in VS2012 RC(It's free for download).
#include <thread>
#include <iostream>
void hello()
{
 std::cout << "hello multitasking world!";
}
int main(int argc, char* argv[])
{
 std::thread tr(hello);
 tr.join();
 getchar();
 return 0;
}




Sunday, August 12, 2012

Hanoi tower in C++

Here I'm sending a recursive solution for solving Hanoi tower problem with 3 columns and n disks.
Columns are in following order :

    ||                ||             ||
    ||                ||             ||
    ||                ||             ||
    ||                ||             ||
====         ====      ====
 c_from         c_other         c_to

The problem is moving n disks from column c_from to column c_to ( we can't put bigger disks over smaller disks in a column )
Solution is :
1- moving n-1 disks from c_from to c_other
2- moving last disk from c_from to c_to
3- moving n-1 disks from c_other to c_to
.
here is simple code in C++ to solve the problem:

class HanoiTower
{
 
private :
 int N;
 stack<int> towers[3];
public:
 enum TOWERS
 {
  A=0,
  B=1,
  C=2
 };
 HanoiTower(int pN)
 {
  N=pN;
  for(int i=N-1;i>=0;i--)
   towers[A].Push(i);
 }
 void MoveRec(int pN,TOWERS tFrom,TOWERS tTo)
 { 
  if(pN==0)
  {
   int disk=towers[tFrom].Top();
   towers[tFrom].Pop();
   towers[tTo].Push(disk);
   cout <<" move "<<disk<<" from "<<tFrom<< " to "<< tTo<<endl;
   //cout <<disk+1<<tFrom+1<<tTo+1<<endl;
   return;
  }
  TOWERS other=(TOWERS)(3-tFrom-tTo);
  MoveRec(pN-1,tFrom,other);
  MoveRec(0,tFrom,tTo);
  MoveRec(pN-1,other,tTo);
 }
};

// usage :
HanoiTower hn(15);
hn.MoveRec(14,HanoiTower::TOWERS::A,HanoiTower::TOWERS::C);

Saturday, August 11, 2012

Send Email in C++ ( SMTP Client in C++ )

Boost! Yes! It's a good library for you to help you develop cross-platform C++ applications; headache free. among all libraries in boost, boost::asio is for implementing asynchronous input output operations and working with network. After having a look at boost asio samples and SMTP RFC : http://www.ietf.org/rfc/rfc2821.txt I implemented this simple class to be used in your C++ programs.
the only tricky part is base64 encoding which is required for sending user/password to SMTP Server.
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
using boost::asio::ip::tcp;
using namespace boost::archive::iterators;
typedef base64_from_binary<transform_width<const char *,6,8> > base64_text;
class SMTPClient
{
public:
 SMTPClient(std::string pServer,unsigned int pPort,std::string pUser,std::string pPassword):
   mServer(pServer),mPort(pPort),mUserName(pUser),mPassword(pPassword),mSocket(mIOService),mResolver(mIOService)
   {
    tcp::resolver::query qry(mServer,boost::lexical_cast<std::string>( mPort ));
    mResolver.async_resolve(qry,boost::bind(&SMTPClient::handleResolve,this,boost::asio::placeholders::error,
     boost::asio::placeholders::iterator));
   }
   bool Send(std::string pFrom,std::string pTo,std::string pSubject,std::string pMessage)
   {
    mFrom=pFrom;
    mTo=pTo;
    mSubject=pSubject;
    mMessage=pMessage;
    mIOService.run();
    return mHasError;
   }
private:
 std::string encodeBase64(std::string pData)
 {
  std::stringstream os;
  size_t sz=pData.size();
  std::copy(base64_text(pData.c_str()),base64_text(pData.c_str()+sz),ostream_iterator<char>(os));
  return os.str();
 }
 void handleResolve(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator)
 {
  if(!err)
  {
   tcp::endpoint endpoint=*endpoint_iterator;
   mSocket.async_connect(endpoint,
    boost::bind(&SMTPClient::handleConnect,this,boost::asio::placeholders::error,++endpoint_iterator));
  }
  else
  {
   mHasError=true;
   mErrorMsg= err.message();
  }
 }
 void writeLine(std::string pData)
 {
  std::ostream req_strm(&mRequest);
  req_strm << pData << "\r\n";
  boost::asio::write(mSocket,mRequest);
  req_strm.clear();
 }
 void handleConnect(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator)
 {
  if (!err)
  {
   // The connection was successful. Send the request.
   std::ostream req_strm(&mRequest);
   writeLine("EHLO "+mServer);
   writeLine("AUTH LOGIN");
   writeLine(encodeBase64(mUserName));
   writeLine(encodeBase64(mPassword));
   writeLine( "MAIL FROM:<"+mFrom+">");
   writeLine( "RCPT TO:<"+mTo+">");
   writeLine( "DATA");
   writeLine( "SUBJECT:"+mSubject);
   writeLine( "From:"+mFrom);
   writeLine( "To:"+mTo);
   writeLine( "");
   writeLine( mMessage );
   writeLine( ".\r\n");
  }
  else
  {
   mHasError=true;
   mErrorMsg= err.message();
  }
 }
 std::string mServer;
 std::string mUserName;
 std::string mPassword;
 std::string mFrom;
 std::string mTo;
 std::string mSubject;
 std::string mMessage;
 unsigned int mPort;
 boost::asio::io_service mIOService;
 tcp::resolver mResolver;
 tcp::socket mSocket;
 boost::asio::streambuf mRequest;
 boost::asio::streambuf mResponse;
 bool mHasError;
 std::string mErrorMsg;

};
Yest ! that's it. you are free to copy and paste this code into your application:
SMTPClient mailc("yoursmtpserver.com",25,"user@yourdomain.com","password");
mailc.Send("from@yourdomain.com","to@somewhere.com","subject","Hello from C++ SMTP Client!");





Saturday, August 4, 2012

How to find DOS attackers in Linux

#netstat -anp | grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | grep -v "^$" | uniq -c | sort -nr


output will be ;


Number_of_connections          Client_IP
-------------------------------------       ------------------

Thursday, August 2, 2012

Implementing thread safe queue in C++11

Concurrency again!
I'm going to show you how to implement thread safe queue using lock/mutex and condition variable based synchronization in C++11.
As you know protecting shared data in multi-threaded  environment is very important.
at this following sample I demonstrated how to use mutexes and condition variables to write a thread-safe queue.
I put all description as comments to help you understand better.

#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>

template <class T>
class tsqueue
{
private :
	std::queue<T> mData;
	// check empty() method for description of "mutable"
	mutable std::mutex mMut; 
	std::condition_variable mEmptyCondition;
	void wait_for_debugging()
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(200+rand()%200));
	}
public:
	void Push(T pValue)
	{
		// block execution here, if other thread already locked mMute!
		std::lock_guard<std::mutex> lock(mMut); 
		// if weare here no other thread is owned/locked mMute. so we can modify the internal data
		mData.push(pValue); 
		// OK! notify one of threads which was blocked because , queue empty and make them happy!
		mEmptyCondition.notify_one(); 
		wait_for_debugging();
	} // //lock.unlock(); !!!! does not have such method!
	// now mMute is unlocked in destcutor of lock_guard!

	std::shared_ptr<T> Pop()
	{
		// own the mMute like in Push method excep that lock can be unlocked manually without need to destructor of lock!
		std::unique_lock<std::mutex> lock(mMut); 
		// if we are here. mMute is locked and no other thread can access/modify the data!
		// wait() method first checks if mData is not empty, allowes execution to go on. else :
		// unlocks the mMut and waits for signla.
		// because mMute is released other threads have a chance to Push new data into queue 
		// ... in notify this condition variable!
		mEmptyCondition.wait(lock,[this]{ return !mData.empty();});
		// if we are are here, mData is not empty and mMut is locked !
		// be careful ! std::shared_ptr<T> ret(new T(mData.front()) performs 2 memory allocation!
		std::shared_ptr<T> ret=std::shared_ptr<T>(std::make_shared<T>(mData.front()));
		mData.pop();
		wait_for_debugging();
		return ret;
	}
	std::shared_ptr<T> TryPop()
	{
		std::lock_guard<std::mutex> lock(mMut); 
		if(mData.empty())
			return std::shared_ptr<T>(); // null
		std::shared_ptr<T> ret=std::shared_ptr<T>(std::make_shared<T>(mData.front()));
		mData.pop();
		wait_for_debugging();
		return ret;
	}
	bool Empty() const
	{
		//  this function is "const", so why are we allowed to modify a member vaiable "mMute"?....
		//we can, because we marked it "mutable"! see definition of mMute.
		std::lock_guard<std::mutex> lock(mMut); 
		return mData.empty();
	}
};

void test_tsq()
{
	tsqueue<int> tsq;
	int N=100;
	std::thread thrpush([&]{
		for(int i=0;i<N;i++)
		{
			tsq.Push(i);
			std::cout <<i<<" pushed \n";
		}
	});
	std::thread thrpop([&]{
		for(int i=0;i<N/2;i++)
		{
			std::cout <<"popping\n";
			std::shared_ptr<int> data=tsq.Pop();
			std::cout <<i<<": poped "<<*data<<"\n";
		}
	});
	std::thread thrtrypop([&]{
		int i=0;
		for(;i<N/2;)
		{
			std::cout <<"trying for pop\n";
			std::shared_ptr<int> data=tsq.TryPop();
			if(data.get()!=NULL)
			{
			std::cout <<i++<<": try poped "<<*data<<"\n";
			}
			else
				std::cout <<"failed trying pop \n";

		}
	});
	thrpush.join();
	thrpop.join();
	thrtrypop.join();
}


The only reminded point to be notices about mEmptyCondition.wait(...) method is that if this condition variable was notified after any push() method from other thread, It checks the mData.empty() condition for avoiding race condition. because there is a chance for "pop"ing last inserted item by other thread. So even being notified is not enough reason to continuing execution and modifying data. ( in this case because of notifyone(). only one condition variable is notified among all waiting condition variables)

Saturday, July 28, 2012

My experience on C++ Serialization Solutions

Recently I tried 3 solutions for serializing request data in my Apache filter module in C++:
1- Google Protocol Buffer
2- boost serialization
3- msgpack
I was disappointed of using solutions 1 and 2 because of errors I faced. I submitted errors in many forums and related mailing lists, but I couldn't get any answer.
Google protocol buffer seems professional but It needs classes to be defined in specific way which that protocol forces.
BTW I started with this solution and designed *.protoc files and generated my model files.
the solutions worked fine in a console application but I've got segmentation fault in Apache module without any specific error. ( I tried debugging with gdb, ddd,.... but no chance to resolve the error).
So I switched to boost serialization. It was much simpler than Google solution but It didn't work completely.
It worked fine in console application and Apache filter too.
but I've segfault when I tried to serialize nested classes.
I returned to my mind, searching a solution recommended by one of my friends( Kamyar, which has been used that solution in .NET).
It was msgpack, the 3rd solution.
It's much simple than Google solution and even simpler than boost serialization.
It worked fine without any headache. As msgpack website says, It's much fast from Google and boost solution :
http://www.msgpack.org

Friday, July 27, 2012

How to run class member function in C++11 thread


class X
{
private:
 int mX;
public:
 F()
 {
   // some work
 }
};

void thread_sample()
{
  X x;
  std::thread th(&X::F,&x);
  th.join(); // call detach() if you want this method not to wait for F() to finish
 }

Tuesday, July 17, 2012

Simplest threading sample in C++11

If you were looking for multitasking and threading library in C++.
C++11 standard brought multitasking for you in the best way.
Here is the simplest threading sample in C++11. I'll post more advanced samples progressively.
I've tested this code sample in VS2012 RC(It's free for download).
#include <thread>
#include <iostream>
void hello()
{
 std::cout << "hello multitasking world!";
}
int main(int argc, char* argv[])
{
 std::thread tr(hello);
 tr.join();
 getchar();
 return 0;
}