/* doscan - Denial Of Service Capable Auditing of Networks
 * 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
 */

#include "config.h"
#include "scan.h"
#include "opt.h"
#include "proto.h"
#include "scan_udp.h"
#include "utils.h"

#include <memory>
#include <cstdio>
#include <string>

static bool udp_start(subnets&);
static void udp_open(scan_host_t *);

void
proto_udp_register(void)
{
  proto_register ("udp", udp_start, udp_open);
}

static void udp_open(scan_host_t *)
{
}

static const char *send_buffer = 0;
static unsigned send_length = 0;

struct scan_udp : scan_udp_single::handler {
  scan_udp* clone() const
  {
    return new scan_udp();
  }

  void create_query(ipv4_t, std::string& data)
  {
    data.assign(send_buffer, send_length);
  }

  void reply_received(ipv4_t host, unsigned short remote_port,
                      const std::string& data)
  {
    results_add(ticks_get_cached(), host, 0, data.data(), data.size());
  }

  void timeout(ipv4_t host, ticks_t ticks)
  {
  }
};

static bool
udp_start(subnets& nets)
{
  if (opt_receive && opt_receive[0]) {
    fprintf (stderr, "%s: --receive is currently not supported\n",
             opt_program);
    exit (EXIT_FAILURE);
  }

  if (opt_banner_size) {
    fprintf (stderr, "%s: --banner is implicitly activated by this module.\n",
             opt_program);
    exit (EXIT_FAILURE);
  }

  if (opt_send && (opt_send[0] != 0)) {
    char *sb;
    string_dequote (opt_send, &sb, &send_length,
                    "--send option");
    send_buffer = sb;
  } else {
    fprintf (stderr, "%s: The --send option is required for this module.\n",
             opt_program);
    exit (EXIT_FAILURE);
  }

  std::auto_ptr<event_queue> q(event_queue::create(1));
  scan_udp su;
  scan_udp_single scanner(*q, nets, su, opt_fd_count,
                          opt_add_timeout, opt_add_burst,
                          5, opt_connect_timeout / 5);

  q->run();

  return false;
};
