/* doscan - Denial Of Service Capable Auditing of Networks       -*- C++ -*-
 * Copyright (C) 2003 Florian Weimer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef TCP_SERVER_H
#define TCP_SERVER_H

#include "event_queue.h"
#include "ipv4.h"

class tcp_accept_handler : public event_queue::fd_handler {
  virtual bool on_activity(activity);
  virtual bool on_timeout(ticks_t);

  static int make_server(ipv4_t host, unsigned short port);

protected:
  virtual void new_connection(int fd, ipv4_t host, unsigned port) = 0;

public:
  tcp_accept_handler(event_queue&, unsigned port);
  tcp_accept_handler(event_queue&, ipv4_t, unsigned port);

  virtual ~tcp_accept_handler();

  // Schedules termination of the server.

  void terminate();
};

template <class Handler>
class tcp_default_accept_handler : public tcp_accept_handler {
  virtual void new_connection(int fd, ipv4_t, unsigned);
public:
  tcp_default_accept_handler(event_queue&, unsigned port);
  tcp_default_accept_handler(event_queue&, ipv4_t, unsigned port);
};

// tcp_accept_handler

inline void
tcp_accept_handler::terminate()
{
  set_immediate_timeout();
}

// tcp_default_accept_handler

template <class Handler> inline
tcp_default_accept_handler<Handler>::tcp_default_accept_handler(event_queue& q,
                                                                unsigned port)
  : tcp_accept_handler(q, port)
{
}

template <class Handler> inline
tcp_default_accept_handler<Handler>::tcp_default_accept_handler(event_queue& q,
                                                                ipv4_t host,
                                                                unsigned port)
  : tcp_accept_handler(q, host, port)
{
}

template <class Handler> void
tcp_default_accept_handler<Handler>::new_connection(int fd, ipv4_t host,
                                                    unsigned port)
{
  new Handler(queue(), fd, host, port);
}

#endif // TCP_SERVER_H
