/* socket.c -- socket handling for ttywatch
 *
 * Copyright © 2001 Michael K. Johnson <a1237+ttywatch@danlj.org>
 *
 * 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 <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "ttywatch.h"
#include "telnet.h"
#include "errors.h"

int
socket_listen(char *port, char *localaddr) {
    int sock;
    struct sockaddr_in addr;
    int i;

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

    i=1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    if (localaddr) {
	if (!inet_aton(localaddr, &addr.sin_addr)) {
	    warn(NULL, "could not parse local address %s for port %s",
	         localaddr, port);
	    return 0;
	}
    } else {
	memset(&addr.sin_addr, '\0', sizeof(addr.sin_addr));
    }

    if (bind(sock, (struct sockaddr *)&addr, sizeof(addr))) {
	warn(NULL, "bind failed for port %s, addr %s", port,
	     localaddr ? localaddr : "unbound");
	return 0;
    }

    if (listen(sock, 5)) die ("listen failed\n");

    return (sock);
}

int
socket_accept(int sock) {
    struct sockaddr_in addr;
    socklen_t addrlen = sizeof(addr);
    int conn;

    conn = accept(sock, (struct sockaddr *)&addr, &addrlen);
    if (conn == -1) {
	warn(NULL, "accept failed on socket %d", sock);
	return 0;
    }

    /* don't let, say, a suspended telnet session create a DOS */
    if (fcntl(conn, F_SETFL, O_NONBLOCK)) {
	warn(NULL, "unable to set nonblock for %d: %s", conn, strerror(errno));
    }

    /* This is where we would initiate authentication if we cared.
     * Feel free to add PAM authentication if you care.
     * However, if you do, you will have to move telnet
     * protocol setup here as well, and add authentication to the
     * m->ts state machine or to yet another state machine (m->auth?).
     * Actually, because PAM can block arbitrarily long, it should
     * probably be done in a fork().
     */

    return conn;
}


/* Start a non-blocking connection to the remote machine.
 * Returns the socket fd on success, -1 on error.
 * Sets m->dev_nc.fd, m->ss
 */
int
socket_connect(machine *m) {
    struct sockaddr_in addr;
    struct in_addr inaddr;
    struct hostent *host;
    char *ipaddr, *ipport;
    unsigned short ipportno;

    if (m->dev_nc.fd != -1)
	close(m->dev_nc.fd);

    m->dev_nc.fd = -1;

    ipaddr = strdup(m->devpath);
    if (!ipaddr) {
	warn (m, "out of memory allocating ipaddr");
	return m->dev_nc.fd;
    }

    ipport = strchr(ipaddr, ':');
    if (!ipport) {
	warn (m, "host:port %s illegal", ipaddr);
	goto out;
    }
    *ipport++ = '\0'; /* separate address from port */
    ipportno = atoi(ipport);

    /* If the argument can be converted to an IP, do so. If not, try
     * to look it up in DNS. */
    if (inet_aton(ipaddr, &inaddr)) {
	host = gethostbyaddr((char *) &inaddr, sizeof(inaddr), AF_INET);
    } else {
	host = gethostbyname(ipaddr);
    }

    if (!host) {
	warn(m, "could not look up host %s", ipaddr);
	goto out;
    }

    m->dev_nc.fd = socket(PF_INET, SOCK_STREAM, 0);
    if (m->dev_nc.fd < 0) {
	warn(m, "could not create socket for %s: %s", m->devpath, strerror(errno));
	goto out;
    }

    if (fcntl(m->dev_nc.fd, F_SETFL, O_NONBLOCK)) {
	warn(m, "unable to set nonblocking for %s: %s", m->devpath, strerror(errno));
	close(m->dev_nc.fd);
	m->dev_nc.fd = -1;
	goto out;
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(ipportno);

    memcpy(&addr.sin_addr, host->h_addr_list[0], sizeof(addr.sin_addr));

    if (connect(m->dev_nc.fd, (struct sockaddr *) &addr, sizeof(addr))) {
        if (errno == EINPROGRESS) {
	    m->ss = SS_INPROGRESS;
	} else {
	    warn(m, "could not connect to %s: %s", m->devpath, strerror(errno));
	    close(m->dev_nc.fd);
	    m->dev_nc.fd = -1;
	    goto out;
	}
    } else {
	m->ss = SS_CONNECTED;
	telnet_negotiate_client(m->dev_nc.fd);
    }

out:
    free (ipaddr);
    return m->dev_nc.fd;
}

/* Tests a non-blocking connection to the remote machine to see
 * whether the connection succeeded or failed.
 * Sets m->dev_nc.fd, m->ss
 */
void
socket_continue_connect(machine *m) {
    int i;
    socklen_t i_len = sizeof(i);

    getsockopt(m->dev_nc.fd, SOL_SOCKET, SO_ERROR, &i, &i_len);
    if (i == SO_ERROR) {
	m->ss = SS_TIMEOUT;
	close(m->dev_nc.fd);
	m->dev_nc.fd = -1;
    } else {
	m->ss = SS_CONNECTED;
	telnet_negotiate_client(m->dev_nc.fd);
    }
}
