/*
 *  ident.c - TCP/IP ident protocol query
 *
 *  Copyright (C) 1999 Etienne Bernard
 *
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <setjmp.h>

#include "defines.h"
#include "ident.h"

static jmp_buf ident_alarm;

void timeout_alarm(int sig) {
  siglongjmp(ident_alarm, 1);
}

char * get_ident_info(unsigned short int local_port, unsigned short int remote_port, __u32 local_addr, __u32 remote_addr) {
  unsigned int remote, local;
  int s, i, j;
  char *c;
  struct sockaddr_in sin;
  char buffer[LINE], user[IDENT_LENGTH];

  signal(SIGALRM, timeout_alarm);

  s = socket(AF_INET, SOCK_STREAM, 0);
  if (s < 0)
    goto unknown;
  
  if (sigsetjmp(ident_alarm, 1) != 0)
    goto unknown;

  alarm(IDENT_TIMEOUT);

  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = local_addr;
  sin.sin_port = INADDR_ANY;
  if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    goto unknown;

  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = remote_addr;
  sin.sin_port = IDENT_PORT;
  
  if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
    goto unknown;

  sprintf(buffer, "%u,%u\r\n", ntohs(remote_port), ntohs(local_port));
  /* send query */
  i = 0;
  while (i < strlen(buffer)) {
    j = write(s, buffer + i, strlen(buffer+i));
    if (j < 0 && errno != EINTR)
      goto unknown;
    else if (j > 0)
      i+=j;
  }

  /* read response */
  i = 0;
  *buffer = '\0';
  while ((c=strchr(buffer, '\n')) == NULL && i < sizeof(buffer) - 1) {
    j = read(s, buffer + i, sizeof(buffer) - 1 - i);
    if (j==0 || (j < 0 && errno != EINTR))
      goto unknown;
    else if (j > 0)
      i+=j; 
  }

  if (sscanf(buffer, "%u , %u : USERID :%*[^:]:%64s", &remote, &local, user) != 3 ||
      ntohs(remote_port) != remote ||
      ntohs(local_port) != local)
    goto unknown;
  
  if ((c = strchr(user, '\r')))
    *c = '\0';

  alarm(0);
  close(s);
  return strdup(user);

 unknown:
  if (s > 0)
    close(s);
  alarm(0);
  return strdup(IDENT_UNKNOWN);
}
