/* 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 "opt.h"
#include "utils.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>

void
string_dequote (const char *escaped,
                char **result, unsigned *result_size,
                const char *where)
{
  unsigned len = strlen (escaped);
  char temp[len];
  const char *source;
  char *target;
  unsigned j;

  source = escaped;
  target = temp;
  for (;;) {
    switch (*source) {
    case '\0':
      goto out;

    case '\\':
      source++;
      switch (*source) {
      case 't':
        source++;
        *(target++) = '\t';
        break;

      case 'r':
        source++;
        *(target++) = '\r';
        break;

      case 'n':
        source++;
        *(target++) = '\n';
        break;

      case '\\':
        source++;
        *(target++) = '\\';
        break;

      case '\0':
        fprintf (stderr, "%s: trailing backslash in %s\n",
                 opt_program, where);
        exit (EXIT_FAILURE);
        break;

      case '0':
      case '1':
      case '2':
      case '3':
        j = *(source++) - '0';

        if ((source[0] == '\0') || (source[1] == '\0')) {
          fprintf (stderr, "%s: incomplete octet escape in %s\n",
                   opt_program, where);
          exit (EXIT_FAILURE);
          break;
        }
        if ((source[0] < '0') || (source[0] > '7') || (source[1] < '0') || (source[1] > '7')) {
          fprintf (stderr, "%s: invalid octet escape in %s\n",
                   opt_program, where);
          exit (EXIT_FAILURE);
          break;
        }

        j *= 8;
        j += *(source++) - '0';
        j *= 8;
        j += *(source++) - '0';
        *(target++) = j;
        break;

      default:
        fprintf (stderr, "%s: invalid escape sequence '\\%c' in %s\n",
                 opt_program, *source, where);
        exit (EXIT_FAILURE);
        break;
      }
      break;

    default:
      *(target++) = *(source++);
    }
  }

 out:
  *result_size = target - temp;
  target = new char[*result_size];
  memcpy (target, temp, *result_size);
  *result = target;
}
