# include <kernel/kernel.h>
# include <kernel/user.h>
# include <trace.h>
# include <type.h>

private object driver;		/* driver object */
private object userd;		/* user manager object */
private string protocol;        /* telnet, tcp or udp */
private int myport;

/*
 * NAME:	create()
 * DESCRIPTION:	initialize port object
 */
static void create()
{
    driver = find_object(DRIVER);
    userd = find_object(USERD);
}

/*
 * NAME:	open_port()
 * DESCRIPTION:	start listening on a port
 */
static 
void open_port(string prot, varargs int port)
{
    DRIVER->message("opening "+prot+" port "+ (port ? port:0)+"\n");
    rlimits (-1; -1) {
/*	catch {*/
	if (typeof(port)==T_INT && port !=0) {
		::open_port(prot, port);
	    } else {
		::open_port(prot, port);
	    }
	    protocol = prot;
            myport = port;
            DRIVER->message("myport: "+myport+"\n");
	    return;
/*	} : {
	    error(::call_trace()[1][TRACE_FIRSTARG][1]);
	    return;
	    }*/
    }
}

object
connection(mixed *tls, string ip, int port)
{
    DRIVER->message("libcon: "+protocol + " connection from "+ip+":"+port+"\n");
    if(protocol == "telnet") {
        return userd->telnet_connection(tls,myport);
    } else {
        return userd->binary_connection(tls,myport);
    }
}

int 
open(mixed *tls,int port)
{
    return FALSE;
}

void
close(mixed *tls, int force)
{
}

string query_protocol() { return protocol; }
int query_port() { 
  if(!myport) error("Huh?");
  return myport; }
object query_userd() { return userd; }

