/* Nessus
 * Copyright (C) 1998 - 2001 Renaud Deraison
 * Copyright (C) 2004 Intevation GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation
 *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * In addition, as a special exception, Renaud Deraison
 * gives permission to link the code of this program with any
 * version of the OpenSSL library which is distributed under a
 * license identical to that listed in the included COPYING.OpenSSL
 * file, and distribute linked combinations including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * this file, you may extend this exception to your version of the
 * file, but you are not obligated to do so.  If you do not wish to
 * do so, delete this exception statement from your version.
 */

/**
 * @file
 * Signal handler and code for closing connections to the server.
 */

#include <includes.h>
#include "nessus_i18n.h"
#include "error_dlg.h"
#include "context.h"
#include "backend.h"
#include "auth.h"

/**
 * @brief Closes all connections to the server(s) that are within or under a
 *        certain context.
 * 
 * @param ctx Contexts into which to descend (next and children) and close the
 *            connection(s) to the server.
 */
static void
close_all_context_cnx (struct context * ctx)
{
  if ( ctx == NULL )
    return;

  while ( ctx != NULL )
    {
      if ( ctx->socket > 0 )
        {
          network_printf (ctx->socket, "CLIENT <|> STOP_WHOLE_TEST <|> CLIENT\n");
          close_stream_connection (ctx->socket);
          ctx->socket = -1;
        }
      close_all_context_cnx (ctx->children);
      ctx = ctx->next;
    }
}

/**
 * @brief Closes all connections to server, clears the backends and exits with
 * @brief given code.
 * 
 * @param code The exit code.
 */
void
nessus_exit (int code)
{
  close_all_context_cnx (Global);
  backend_clear_all ();
  exit (code);
}

void
sighand_pipe ()
{
  Context->socket = -1;
  show_error(_("Connection closed by the server (SIGPIPE caught)"));
}

void sighand_exit ()
{
  close_all_context_cnx (Global);
  nessus_exit (1);
}
