/*
 * Micro-X -- an X server for DOS
 * Copyright (C) 1994 StarNet Communications Corp.
 *
 * 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.
 * 
 * StarNet Communications Corp.
 * 550 Lakeside Dr. #3
 * Sunnyvale CA 94086 US
 * http://www.starnet.com
 * x-dos@starnet.com
 */

#include <pctcp/types.h>
#include <pctcp/pctcp.h>
#include <pctcp/options.h>
#define MSW3
#include <pctcp/error.h>
#include "funcdef.h"
#include "../defs.h"

extern int _near neterrno;
extern int _near netsuberrno;

int _fastcall
tcp_socket(arg, len, buf)
int arg, *len;
void _far *buf;
{
    int fd, type;
    struct addr tcp_addr;
    struct net_addr _far *addr = (struct net_addr _far *)buf;

    fd = net_getdesc();
    if (fd < 0) {
	net_perror("net_getdesc");
	return fd;
    }

    if (set_option(fd, 0, NET_OPT_NONBLOCKING, (char _far *)1, 0)) {
	net_perror("set_option");
	net_release(fd);
	return -1;
    }
    switch (arg) {
	case NET_TYPE_TCP:
	    tcp_addr.protocol = 0;
	    type = STREAM;
	    break;
	case NET_TYPE_UDP:
	    tcp_addr.protocol = 0;
	    type = DGRAM;
	    break;
	default:
	    printd(arg);
	    dfputs(": unknown socket type\r\n");
	    return fd;
    }
    tcp_addr.lsocket = addr->socket;
    tcp_addr.fhost = addr->host;
    tcp_addr.fsocket = 0;

    if (net_listen(fd, type, &tcp_addr) < 0) {
	net_perror("net_listen");
	net_release(fd);
	return -1;
    }
    addr->socket = tcp_addr.lsocket;
    addr->host = tcp_addr.fhost;
    *len = sizeof (struct net_addr);
    return fd;
}

void
net_perror(str)
char _near *str;
{
    dfputs(str);
    if (neterrno == NET_DOS_ERR) {
	dfputs(": System Error");
    } else {
	dfputs(": Error ");
	printd(neterrno);
    }
    dfputs("\r\n");
}
