// -*- c++ -*-
//------------------------------------------------------------------------------
//                            Connector.h
//------------------------------------------------------------------------------
//  Copyright (C) 1999  Vladislav Grinchenko <vladg@erols.com>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//------------------------------------------------------------------------------
#ifndef CONNECTOR_H
#define CONNECTOR_H

#include <unistd.h>		// fcntl(2)
#include <fcntl.h>		// fcntl(2)
#include <sys/types.h>		// getsockopt(3)
#include <sys/socket.h>		// getsockopt(3)
#include <string.h>		// strerror(3)
#include <errno.h>		// errno(3)

#include "assa/Logger.h"
#include "assa/EventHandler.h"
#include "assa/Reactor.h"
#include "assa/TimeVal.h"
#include "assa/Address.h"

namespace ASSA {

/** @file Connector.h

	A generic pattern for establishing connection with TCP/IP servers.
*/

/** @enum ConnectMode.
	Connection mode.
*/
enum ConnectMode { 
	sync,					/**< Synchronous connection mode. */
	async					/**< Asynchronous connection mode. */
};

/**
	Connector is a  template class for initialization of communication services.

	This template class implements the generic strategy for actively<br>
	initializing communication services.

	SERVICE_HANDLER is the type of service. It shall be a type derived
	from ServiceHandler interface class.

	PEER_CONNECTOR is the type of concrete Socket class - particular
	transport mechanism used by the Connector to actively establish 
	the connection. It should be derived from Socket interface class.
*/

template<class SERVICE_HANDLER, class PEER_CONNECTOR>
class Connector : public virtual EventHandler
{
public:
	/// Constructor. Do-nothing.
	Connector ();

	/// Destructor. Do-nothing.
	virtual ~Connector ();
	
	/** Configure Connector. Timeout will be used to timeout 
	    connection operation. If mode_ is async, then Reactor r_
	    ought to be specified for handling asynchronous event
	    processing.
	    Derive classes can change this strategy by overloading this method.

	    @param tv_ Time for connection timeout (Default = 5.0 secs.)
	    @param mode_ Synchronous or Asynchronous mode.
	    @param r_ Reactor to work with (for async mode).
	    @return 0 on success, -1 on error.
	*/
	virtual int open (const TimeVal& tv_ = TimeVal (5.0), 
					  ConnectMode mode_ = sync,
					  Reactor* r_ = (Reactor*)NULL);

	/** Do-nothing close. Derive classes can change this 
	    strategy by overloading this method.
	    @return 0 on success, -1 on error.
	 */
	virtual int close (void);

	/** Define strategy for establishing connection. Default is
	    to connect synchronously to the remote peer.
	    In sync mode connection either will be established or 
	    failed when returned from Connector::connect() call. 

	    In  async mode, call to  Connector::connect()
	    returns immediately reporting only immediate error. Later on
	    connection is completed asynchronously.

	    Default timeout on connection waiting is 10 seconds. Timeout can 
	    be configured by passing TimeVal parameter to the 
	    Connector::open() member function.

	    If connetion failed, caller should definitely close 
	    PEER_CONNECTOR communication point.

	    @param sh_ Pointer to class object derived from ServiceHandler.
	    @param addr_ Reference to the address to connect to.

	    @param protocol_ AF_INET for internet socket, AF_UNIX for the
	    UNIX Domain socket (defaults to AF_INET).
	    
	    @return 0 on success, -1 on error.
	*/
	virtual int connect (SERVICE_HANDLER* sh_, 
						 Address& addr_, 
						 int protocol_ = AF_INET);

	/// Handle connection completion
	virtual int handle_write (int fd);

	/// Handler connection timeout
	virtual int handle_timeout (TimerId tid);

protected:
	/** @enum ProgressState state.
		Connection state.
	*/
	enum ProgressState { 
		idle,		/**< Initialized.  */
		waiting,    /**< Asynchronously waiting on connection completion.  */
		conned,		/**< Connected.  */
		failed		/**< Failed to connect.  */
	};

	/** Defines creation strategy for ServiceHandler. Default is
	    to dynamically allocate new SERVICE_HANDLER, if one is not
	    given as an argument.
	    @param  sh_ pointer to SERVICE_HANDLER, or NULL, if it is
	    expected to be created here
	    @return pointer to SERVICE_HANDLER
	*/
	virtual SERVICE_HANDLER* makeServiceHandler (SERVICE_HANDLER* sh_);

	/** Default strategy is to make synchronous connection with no
	    timeouts. Derived  class can change this  strategy by 
	    overloading this method.
	    @return 0 on success, -1 on error.
	 */
	virtual int connectServiceHandler (Address& addr, int protocol);

	/** Activate handler by calling its open() method.
	    @return 0 on success, -1 on error.
	 */
	virtual int activateServiceHandler ();

protected:
	/// Timeout
	TimeVal m_timeout;

	/// Timer id
	TimerId m_tid;

	/// Reference to Reactor (for async)
	Reactor* m_reactor;
	
	/// Connection progress state
	ProgressState m_state;

	/// Socket options
	int m_flags;

	/// Reference to ServiceHandler
	SERVICE_HANDLER* m_sh;

	/// Socket file descriptor
	int m_fd;

	/// Mode (sync/async)
	ConnectMode m_mode;

private:
	/// Setup for asynchronous mode completion.
	void doAsync (void);

	/** Synchronous mode completion.
	    @return 0 on success; -1 if error.
	*/
	int doSync (void);
};

// Convenience definitions

#define SH SERVICE_HANDLER
#define PC PEER_CONNECTOR

//------------------------------------------------------------------------------
// Template member functions definitions
//------------------------------------------------------------------------------

template<class SH, class PC> 
Connector<SH, PC>::
Connector () 
	: m_tid (0), m_reactor (0), m_state (idle),
	  m_flags (0), m_sh ((SERVICE_HANDLER*)NULL), m_fd (-1), m_mode (sync)
{
	trace_with_mask("Connector::Connector",SOCKTRACE);
}

template<class SH, class PC> 
Connector<SH, PC>::
~Connector () 
{
	trace_with_mask("Connector::~Connector",SOCKTRACE);
	// If I created SERVICE_HANDLER, should I delete it too?
}

template<class SH, class PC> int
Connector<SH, PC>::
open (const TimeVal& tv_, ConnectMode mode_, Reactor* r_) 
{
	trace_with_mask("Connector::open", SOCKTRACE);

	m_timeout = tv_;
	if (async == mode_ && (Reactor*) NULL == r_) 
		return -1;
	m_mode = mode_;
	m_reactor = r_;
	return 0;
}

template<class SH, class PC> int
Connector<SH, PC>::
close () 
{
	trace_with_mask("Connector::close",SOCKTRACE);
	return 0;
}

template<class SH, class PC> int
Connector<SH, PC>::
connect (SH* sh_, Address& addr_, int protocol_family_)
{
	/*
	 * We restore socket to its original mode only on 
	 * successful connection. If error occured, client would have
	 * to close socket anyway.
	 *
	 * NOTE: If sh_==0, then result is dangling pointer
	 * new_sh produced ! Destructor should determine whether 
	 * SERVICE_HANDLER has been created dynamically and if so, delete
	 * it.
	 */
	trace_with_mask("Connector::connect",SOCKTRACE);
	errno = 0;

	m_sh = makeServiceHandler (sh_);
	PEER_CONNECTOR& s = *m_sh;

	if (addr_.bad ()) {
		errno = EFAULT;	// Bad address
		EL((ERROR,"Bad address (errno %d)\n", errno));
		return -1;
	}

	if (connectServiceHandler (addr_, protocol_family_) == -1) {

		if (errno == EINPROGRESS) {

			if (async == m_mode) { 
				doAsync (); 
				return 0; 
			}
			return doSync ();
		}
		return -1;
	}
	/* Switch to blocking mode */
	fcntl (s.getHandler (), F_SETFL, m_flags);

	return activateServiceHandler ();
}

template<class SH, class PC> SERVICE_HANDLER*
Connector<SH, PC>::
makeServiceHandler (SERVICE_HANDLER* sh_) 
{
	trace_with_mask("Connector::makeServiceHandler",SOCKTRACE);

	SERVICE_HANDLER* new_sh = sh_;

	if (sh_ == 0) {
		new_sh = new SERVICE_HANDLER;
	}
	return new_sh;
}

template<class SH, class PC> int
Connector<SH, PC>::
connectServiceHandler (Address& addr_, int protocol_family_)
{
	trace_with_mask("Connector::connectServiceHandler",SOCKTRACE);

	PEER_CONNECTOR& s = *m_sh;
	
	if ( !s.open (protocol_family_) ) {
		EL((ERROR,"Socket::open (protocol=%d) failed\n",
		    protocol_family_));
		return -1;
	}
	// Switch to non-blocking mode

	m_fd = s.getHandler ();
	m_flags = fcntl (m_fd, F_GETFL, 0);
	fcntl (m_fd, F_SETFL, m_flags | O_NONBLOCK);

	return s.connect (addr_) ? 0 : -1;
}

template<class SH, class PC> int
Connector<SH, PC>::
activateServiceHandler ()
{
	trace_with_mask("Connector::activateServiceHandler",SOCKTRACE);

	return m_sh->open ();
}

template<class SH, class PC> void
Connector<SH, PC>::
doAsync (void)
{
	trace_with_mask("Connector::doAsync",SOCKTRACE);

	/* We are doing async and 3-way handshake is in
	 * progress - hook up with Reactor and wait on timer.
	 * Write event will be our indicator whether connection
	 * was completed or not.
	 */
	m_reactor->registerIOHandler (this, m_fd, WRITE_EVENT);

	m_tid = m_reactor->registerTimerHandler (this, m_timeout);
	m_state = waiting;
}

template<class SH, class PC> int
Connector<SH, PC>::
doSync (void)
{
	trace_with_mask("Connector::doSync",SOCKTRACE);

	m_reactor = new Reactor;

	m_reactor->registerIOHandler (this, m_fd, WRITE_EVENT);
	m_reactor->registerTimerHandler (this, m_timeout);
	m_state = waiting;

	m_reactor->waitForEvents (&m_timeout); // Let the ball rolling ...

	m_reactor->removeHandler (this);	// Remove all handlers.
	delete m_reactor;
	m_reactor = 0;

	if (conned == m_state) {
		DL((SOCKTRACE,"Synchronous connect() completed\n"));
		fcntl (m_fd, F_SETFL, m_flags); // Switch to blocking mode
		return 0;
	}
	EL((ERROR,"Synchronous connect() timed out\n"));
	errno = ETIMEDOUT;	// Connection timed out
	return -1;
}

template<class SH, class PC> int
Connector<SH, PC>::
handle_write (int fd_)
{
	trace_with_mask("Connector::handle_write",SOCKTRACE);

	/* Precondition 
	 */
	if (fd_ != m_fd) {
		return -1;
	}

	/* This method serves both sync and async modes - thus the
	 * differences. For async we remove Timer here. sync runs
	 * its own private Reactor and handler termination is 
	 * handled in doSync().
	 */

	if (async == m_mode) { // Complete SH activation
		m_reactor->removeTimerHandler (m_tid);
		m_tid = 0;
	}

	/*
	 * Although SUN and Linux man pages on connect(3) claims that
	 * "upon asynchronous establishement of connection, select(3)
	 * will indicate that the file descriptor for the socket is ready
	 * for writing", as discussed in W.S.Stevens "UNIX network
	 * programming", Vol I, 2nd edition, BSD-derived systems also
	 * mark file descriptor both readable and writable when the
	 * connection establishment encouters an error.
	 *
	 * Therefore we need an extra step to find out what really happened.
	 * One way to do so is to look at socket pending errors...
	 */

	int error;
	int ret;
	error = ret = errno = 0;
	socklen_t n = sizeof (error);

	/* Always remove IO handler first. */
	m_reactor->removeHandler (this, WRITE_EVENT);	

#if defined(linux)
	ret = getsockopt (m_fd, SOL_SOCKET, SO_ERROR, (void*)&error, &n);
#else  // Solaris 2.6 
	ret = getsockopt (m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &n);
#endif

	if (ret == 0) {
		if (error == 0) {
			if (activateServiceHandler () == 0) {
				DL((SOCKTRACE,"Nonblocking connect() completed\n"));
				m_state = conned;
			}
			else {
				DL((SOCKTRACE,"Nonblocking connect() failed\n"));
				m_state = failed;
			}
			return (0);			// return value doesn't really matter
		}
		/* Socket pending error - propagate it via errno. */
		EL((ERROR,"Socket pending error: %d\n",error));
		errno = error;
	}
	else {
		/* Solaris pending error. */
		EL((ERROR,"getsockopt(3) = %d\n", ret));
		EL((ERROR,"Solaris pending error!\n"));
	}
	m_state = failed;

        EL((ERROR,"Nonblocking connect (2) failed\n"));

	if (errno == ECONNREFUSED) {
		EL((ERROR,"Try to compare port "
			 "numbers on client and service hosts.\n"));
	}
        /* This is the only way to tell SH that we failed to connect. 
	 */
	if (async == m_mode) {
		m_sh->close ();	
	}

	/* Don't alter fd mask - SERVICE_HANDLER::open() could have changed 
	 * it already for application processing needs.
	 */
	return 0;
}

template<class SH, class PC> int
Connector<SH, PC>::
handle_timeout (TimerId tid_)
{
	trace_with_mask("Connector::handle_timeout",SOCKTRACE);

	m_state = failed;
	errno = ETIMEDOUT;	// Connection timed out

	if (async == m_mode) {
		m_reactor->removeHandler (this, WRITE_EVENT);
	}
	return -1;		// Remove Timer Handler
}

} // end namespace ASSA

#endif /* CONNECTOR_H */  
