/* Serial interface for raw TCP connections on Un*x like systems
   Copyright 1992, 1993 Free Software Foundation, Inc.

This file was lifted from GDB,
Modified for use with xcopilot by D. Jeff Dionne, July 7, 1997

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 <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/tcp.h>

#define min(X,Y) ((X) > (Y) ? (Y) : (X))

/* Open up a raw tcp socket */

int
tcp_open(name)
     const char *name;
{
  int fd, nfd;
  char *port_str;
  int port;
  struct sockaddr_in sockaddr;
  int tmp;
  char hostname[100];
  struct protoent *protoent;

  /* We know name contains a ':' */
  port_str = strchr (name, ':');

  tmp = min (port_str - name, (int) sizeof hostname - 1);
  strncpy (hostname, name, tmp); /* Don't want colon */
  hostname[tmp] = '\000';	/* Tie off host name */
  port = atoi (port_str + 1);

  /* Ignore the hostname... */

  fd = socket (PF_INET, SOCK_STREAM, 0);
  if (fd < 0)
    return -1;

  /* Allow rapid reuse of this port. */
  tmp = 1;
  setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (char *)&tmp, sizeof(tmp));

  /* Enable TCP keep alive process. */
  tmp = 1;
  setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE, (char *)&tmp, sizeof(tmp));

  sockaddr.sin_family = PF_INET;
  sockaddr.sin_port = htons(port);
  sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

  if (bind (fd, (struct sockaddr *) &sockaddr, sizeof(sockaddr))) {
    perror("bind");
    close (fd);
    return -1;
  }

  if (listen(fd, 1)) {
    close (fd);
    return -1;
  }

  fprintf(stderr,"Waiting for connection on %s\n",name);

  if ((nfd=accept(fd, (struct sockaddr *) &sockaddr, &tmp)) < 0) {
    close (fd);
    return -1;
  }

  close (fd);
  protoent = getprotobyname ("tcp");
  if (!protoent)
    return -1;

  tmp = 1;
  if (setsockopt (nfd, protoent->p_proto, TCP_NODELAY,
		  (char *)&tmp, sizeof(tmp)))
    return -1;

  signal(SIGPIPE, SIG_IGN);	/* If we don't do this, then GDB simply exits
				   when the remote side dies.  */

  return nfd;
}
