/*
 *   Pure Data Packet header file. Stream stuff (parsing & printing)
 *   Copyright (c) by Tom Schouten <tom@zwizwa.be>
 *
 *   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.
 *
 */

/* contents:

   1. PACKET INTERFACE
   2. STREAM SUBLCLASS C METHODS (file, string, ...)
   3. STREAM C METHODS
   4. INPUT (READ)
   5. OUTPUT (WRITE)
   6. FORTH INTERFACE (OPEN/READ/WRITE)

*/


/* streams are sort of independent objects used all over the place, 
   but in forth they are wrapped in a packet. 

   this is really way to complex: due to a bootstrapping problem:
   more things can be written in forth, but I/O needs to be functional
   BEFORE any forth code can be read, so we need a complex C interface
   to the forth kernel..

   so we have 2 interfaces:
   lowlevel:  pf_stream_t
   highlevel: stream packet

   to top that off, there's 2 kinds of streams: strings and files.

 */

/* BUFFERED WRITES

   i chose not to use threads to perform buffered output. instead, at
   each blocking point (input), all the pending buffered output is
   checked.
*/



// we need long file support on 32bit systems
// this makes sure off_t is a 64 bit entity
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <errno.h>

#include <fcntl.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>

#include <pf/typedefs.h>
#include <pf/packet.h>
#include <pf/forth.h>
#include <pf/symbol.h>
#include <pf/packet.h>
#include <pf/type.h>
#include <pf/mem.h>
#include <pf/stream.h>
#include <pf/debug.h>
#include <pf/string.h>
#include <pf/macros.h>

#include <pf/plugin.h> // this is simpler than core api.

#define BLOCKSIZE 512   
// this is the size to which indexable files (block files) are aligned
// this could be used for raw partition access

#define D if (0)
#define SAFE(x) if (x) x


union addr {
    struct sockaddr_un un;
    struct sockaddr_in in;
};



/*** 1. PACKET INTERFACE ***/

/*
  stream packet = wrapper around stream struct to interface to forth.

  packet constraints: 
  this packet cannot cause circular refs.
  the only place that can contain a ref to a packet is the name of the stream.
  this is always a string, so the constraint is not violated.

  reuse constraints: dead packet contains an empty struct that can be used
  for any stream.

 */

static pf_class_t *stream_class = 0;


typedef void (*kill_t)(void *);
static void stream_sleep(pf_stream_t *s){
    SAFE(s->m->m_close)(s);                    // this should free (and zero) all state
    pf_packet_unregister((pf_packet_t)s->base.name);  // in case child doesn't
    s->base.name = 0;
}


static pf_packet_t stream_factory(pf_list_t *type){
    pf_stream_t *s = (pf_stream_t *)pf_packet_create(PF_STREAM, sizeof(pf_stream_t), 0);
    if (!s) return 0;
    s->super.desc = pf_symbol("stream");
    s->super.theclass = stream_class;
    return (pf_packet_t)s;
}

// FIXME: vm_print
static pf_error_t stream_printinfo(pf_stream_t *s,
				   pf_string_t *string){
    return pf_string_printf(string, "#<stream:%s>", DATA(s->base.name));
}


static void setup_packet(void){
    stream_class = pf_class_new(pf_symbol("stream"), stream_factory);
    stream_class->report   = (pf_method_pheader_string_t)stream_printinfo;
    stream_class->sleep    = (pf_method_pheader_t)stream_sleep;
}

static int string_fd(pf_stream_t *stream){
    // pf_post("FIXME: string stream lacks fd.");
    return 0;
}



/*
  s->line point to the coordinates in the stream:
  the line that will be read next time
 */




/*** 2. STREAM SUBCLASS MEMBERS (METHODS) ***/

/* BASE */

static void base_update_line_count(pf_stream_t *s, int c){
    if (c == '\n') s->base.line++;
}

static void base_downdate_line_count(pf_stream_t *s, int c){
    if (c == '\n') s->base.line--;
}

/* STRING */
static int string_read(pf_stream_t *stream, void *buf, int bytes){
    int read_bytes = bytes;
    pf_string_t *x = stream->string.buffer;
    if (bytes + stream->base.index > pf_string_size(x)){
	read_bytes = pf_string_size(x) - stream->base.index;
    }
    memcpy(buf, pf_string_data(x) + stream->base.index, bytes);

    return bytes;
}

// always succeeds. zero errno before calling, to emulate '2 write'
static int string_write(pf_stream_t *stream, void *buf, int bytes){
    char *point = pf_string_allot(stream->string.buffer, bytes);
    memcpy(point, buf, bytes);
    errno = 0;
    return bytes;
}

static int string_remaining(pf_stream_t *s){
    pf_string_t *x = s->string.buffer; PF_ASSERT(x);
    return (pf_string_size(x) - s->base.index);
}

static int string_transfer(pf_stream_t *buf, pf_stream_t *out){
    pf_string_t *x = buf->string.buffer; PF_ASSERT(x);
    int remaining =  pf_string_size(x) - buf->base.index;
    char *data = pf_string_data(x) + buf->base.index;
    int written = out->m->m_write(out, data, remaining);
    if (written >= 0){
	buf->base.index += written;
    }
    return written;
}


static int string_get_char(pf_stream_t *s, int *c){
    pf_string_t *x = s->string.buffer;
    if (s->base.index == pf_string_size(x)) return 0; // like '2 read' : 0 = EOF


    *c = pf_string_data(x)[s->base.index];
    // if (!c) {s->base.index = x->size; return EOF;}
    s->base.index++;
    base_update_line_count(s, *c);
    return 1;
} 

static int string_unget_char(pf_stream_t *s, int c){
    PF_ASSERT(s->string.buffer);
    pf_string_t *x = s->string.buffer;
    PF_ASSERT(s->base.index > 0); // can't happen, means not preceeded by get_char
    pf_string_data(x)[s->base.index - 1] = c;
    s->base.index--;
    base_downdate_line_count(s,c);
    return 1;
} 

static void string_close(pf_stream_t *s){
    pf_packet_unregister((pf_packet_t)s->string.buffer);
}


/* FILE */
static void file_close(pf_stream_t *s){ 
    pf_dealloc(s->file.buffer);
    close(s->file.fd);
}

static void unix_server_socket_close(pf_stream_t *s){
    file_close(s);
    char *node;
    if (node = DATA(s->base.name)){
	// fprintf(stderr, "removing %s\n", node);
	remove(node); // delete node in filesystem
    }
}

static int file_fd(pf_stream_t *stream){
    return stream->file.fd;
}

static int max(int a, int b) { return (a > b) ? a : b; }
static int min(int a, int b) { return (a < b) ? a : b; }

// read directly from file, update base struct, and return total
// number of bytes read.

static int file_read_direct(pf_stream_t *stream, void *buf, int bytes){
    int readbytes = read(pf_stream_fd(stream), buf, bytes);

    // only update counters when there's no error
    if (readbytes >= 0){
	stream->base.index += readbytes;
    }

    return readbytes;
}

static int file_read_buffered(pf_stream_t *stream, void *buf, int bytes){

    int total_bufbytes = stream->file.write - stream->file.read;
    PF_ASSERT(total_bufbytes >= 0);

    int bufbytes = min(bytes, total_bufbytes);
    memcpy(buf, stream->file.buffer + stream->file.read, bufbytes);

    // update pointers and counts
    stream->base.index += bufbytes;
    stream->file.read  += bufbytes;

    // reset buffer if empty
    if (stream->file.read == stream->file.write){
	stream->file.read = stream->file.write = 0;
    }

    return bufbytes;
}

static int file_rebuffer(pf_stream_t *stream){
    PF_ASSERT(stream->file.read == 0);
    PF_ASSERT(stream->file.write == 0);
    int rebuffered = read(pf_stream_fd(stream), 
			  stream->file.buffer, PF_STREAM_BUFSIZE);
    if (rebuffered >= 0){
	stream->file.write += rebuffered;
    }
    return rebuffered;
}

// read is buffered: necessary for parser since it needs to look ahead
// one character, and put it back. in addition, it makes reading a bit
// faster.

static int file_read(pf_stream_t *stream, void *buf, int bytes){

    int error, bufbytes, directbytes;

    // get em from buffer first
    bufbytes = file_read_buffered(stream, buf, bytes);

    // done?
    if (bytes == bufbytes) return bufbytes;

    // advance pointers
    buf   += bufbytes;
    bytes -= bufbytes;

    // rebuffer?
    if (bytes < PF_STREAM_BUFSIZE){
	if ((error = file_rebuffer(stream)) < 0) goto readerror;
	return bufbytes + file_read_buffered(stream, buf, bytes);
    }
    else {
	if ((error = directbytes = file_read_direct(stream, buf, bytes)) < 0)
	    goto readerror;
	return bufbytes + directbytes;
    }
    // handle read error
  readerror:
    if (bufbytes) return bufbytes; // ignore error if there's buffered bytes
    return error;                  // else return error

}

static int file_get_char(pf_stream_t *s, int *c){
    PF_ASSERT(s);
    char buf[1];
    int error = file_read(s, buf, 1);

    if (error <= 0) return error;
    PF_ASSERT(error == 1);
    *c = buf[0];
    base_update_line_count(s, buf[0]);
    return 1;
} 

static int file_unget_char(pf_stream_t *s, int c){
    PF_ASSERT(s);
    if (s->file.read > 0){
	s->file.buffer[--s->file.read] = c;
    }
    else if (s->file.write == 0){
	s->file.write = 1;
	s->file.buffer[0] = c;
    }
    else {
	// this can't happen. means ungetc is not preceeded by getc.
	PF_ASSERT(0);
    }
    base_downdate_line_count(s, c);
    return 1;
} 


// writing is non-buffered.. there's a separate buffering mechanism,
// which can be used if non-blocking output is necessary. not it is
// possible that this won't write out everyting.

static int file_write(pf_stream_t *stream, void *buf, int bytes){
    int rv, fd;
    fd = file_fd(stream);
    rv = write(fd, buf, bytes);
    return rv;
}



/* PROCESS */

static void process_close(pf_stream_t *stream){
    int pid;
    file_close(stream);
    if ((pid = stream->process.pid) != -1) {
	// pf_post("reaping process %d", pid);
	kill(stream->process.pid, 9); //HUP
	//kill(s->pid, 15); //TERM
	waitpid(stream->process.pid, 0, 0); // wait for inferior to terminate
    }
}



static pf_stream_interface_t *string_interface = 0;
static pf_stream_interface_t *file_interface = 0;
static pf_stream_interface_t *process_interface = 0;
static pf_stream_interface_t *unix_server_socket_interface = 0;

static pf_stream_interface_t *
clone_interface(pf_stream_interface_t *from){
    pf_stream_interface_t *to = pf_alloc(sizeof(*to));
    memset(to, 0, sizeof(*to));
    if (from) memcpy(to, from, sizeof(*to));
    return to;
}

static void setup_interfaces(void){
    string_interface = clone_interface(0);

    string_interface->m_get_char    = string_get_char;
    string_interface->m_unget_char  = string_unget_char;
    string_interface->m_read    = string_read;
    string_interface->m_write   = string_write;
    string_interface->m_close   = string_close;
    string_interface->m_fd      = string_fd;

    string_interface->m_transfer  = string_transfer;
    string_interface->m_remaining = string_remaining;

    file_interface = clone_interface(0);

    file_interface->m_get_char    = file_get_char;
    file_interface->m_unget_char  = file_unget_char;
    file_interface->m_read    = file_read;
    file_interface->m_write   = file_write;
    file_interface->m_close   = file_close;
    file_interface->m_fd      = file_fd;

    process_interface = clone_interface(file_interface);
    process_interface->m_close   = process_close;

    unix_server_socket_interface = clone_interface(file_interface);
    unix_server_socket_interface->m_close = unix_server_socket_close;

}



/* STRUCT INIT
   these initialize pf_stream_t form several possible sources  */

static void init_base(pf_stream_t *stream, pf_packet_t name){
    PF_ASSERT(pf_packet_string_data(name));
    stream->base.name = (pf_string_t *)pf_packet_register(name);    
    stream->base.index = 0; 
    stream->base.line = 0;
}

static void init_string(pf_stream_t *stream, pf_packet_t name){
    init_base(stream, name);
    stream->m = string_interface;
    stream->string.buffer = 0;
}


static void init_file(pf_stream_t *stream, pf_packet_t name){
    init_base(stream, name);
    stream->m = file_interface;
    stream->file.fd = 0;
    stream->file.read = 0;
    stream->file.write = 0;
    stream->file.buffer = pf_alloc(PF_STREAM_BUFSIZE);
}

static void init_process(pf_stream_t *stream, pf_packet_t name){
    init_file(stream, name);
    stream->m = process_interface;
    stream->process.pid = -1;
}


/*** 3. STREAM C METHODS ***/

int pf_stream_remaining(pf_stream_t *buf){
    if (buf->m->m_remaining) return buf->m->m_remaining(buf);
    else return -1;
}

int pf_stream_transfer(pf_stream_t *buf, pf_stream_t *out){
    if (buf->m->m_transfer) return buf->m->m_transfer(buf, out);
    else return -1;
}


// return a pf string describing current point in stream
pf_packet_t pf_stream_point(pf_stream_t *s){
    if (!s) return pf_packet_stringf("<runtime>"); // no stream : it's a runtime error
    char *c = DATA(s->base.name);
    if (!c) c = "???";
    return pf_packet_stringf("%s:%d", c, s->base.line+1);
}

void pf_stream_post_error(pf_stream_t *s){
    pf_packet_t p = pf_stream_point(s);
    char *c = pf_packet_string_data(p);
    PF_ASSERT(c);
    pf_post_n(c);
    pf_packet_unregister(p);
}


pf_stream_t *pf_packet_stream(pf_header_t *h){
    if (!h) return 0;
    if (h->type != PF_STREAM) return 0;
    return (pf_stream_t*)h;
}




int pf_stream_fd(pf_stream_t *s){
    return s->m->m_fd(s);
}





/*** 4. READ -> read.c ***/
/*** 5. WRITE -> write.c ***/


/*** 6. FORTH INTERFACE ***/

/* OPEN */

#define PUSH_NEW_STREAM \
pf_stream_t *stream = PUSH_NEW("stream"); \
pf_error_t e

#define PUSH_STREAM PUSH_PACKET(streamp)

static PF_PRIMITIVE(open_string){ // ( buffer.string -- stream )
    CHECKN(1);
    STRING(ARG0); // check args
    pf_packet_t buffer = ARG0->w.w_packet;
    pf_packet_t name = pf_packet_stringf("<string>"); 
    PUSH_PACKET(name);
    PUSH_NEW_STREAM;
    init_string(stream, name);
    stream->string.buffer = (pf_string_t *)pf_packet_register(buffer);
    NIP2; EXIT;
}

//FIXME: better get rid of "r" and "w" in the forth interface too
static int str2flags(char *cmode){
    if (!strcmp(cmode, "r")) return O_RDONLY;
    if (!strcmp(cmode, "w")) return O_WRONLY|O_CREAT|O_TRUNC; 
    if (!strcmp(cmode, "a")) return O_WRONLY|O_CREAT|O_APPEND;
    if (!strcmp(cmode, "c")) return O_CREAT;
    if (!strcmp(cmode, "rw")) return O_RDWR;
    return -1;
}

#define R_MODE S_IRUSR | S_IRGRP | S_IROTH
#define W_MODE S_IWUSR | S_IWGRP | S_IWOTH

#define MODE R_MODE | W_MODE



static PF_PRIMITIVE(open_file){ // ( filename mode -- stream )
    CHECKN(2);
    char *cmode = STRING(ARG0);
    char *cname = STRING(ARG1);
    pf_packet_t name = ARG1->w.w_packet;
    PUSH_NEW_STREAM;
    init_file(stream, name);
    int flags = str2flags(cmode) | O_NONBLOCK;
    if (-1 == flags) {
	THROW(e_inval, "invalid mode \"%s\"", cmode);
    }
    if (-1 == (stream->file.fd = open(cname, flags, MODE))) {
	THROW(e_file, "can't open %s mode \"%s\": %s", 
	      cname, cmode, strerror(errno));
    }

    // need nonblocking IO
    // int fd = pf_stream_fd(stream);
    // if (-1 == fcntl(fd, F_SETFL, O_NONBLOCK | flags)){
    //	THROW(e_internal, "can't set nonblock mode on fd %d", fd);
    //}

    NIP2;
    EXIT;
}

static int fd_nonblock(int fd){
    int flags;
    if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { return -1; }
    if (-1 == (fcntl(fd, F_SETFL, flags | O_NONBLOCK))) { return -1; }
    return 0;
}

static PF_PRIMITIVE(open_fd){ // ( fd name mode -- stream )
    CHECKN(3);
    char *cmode = STRING(ARG0);
    char *cname = STRING(ARG1);
    pf_packet_t name = ARG1->w.w_packet;
    int fd = INT(ARG2);

    PUSH_NEW_STREAM; 
    init_file(stream, name);
    stream->file.fd = fd;

    if (-1 == fd_nonblock(fd)) {
	THROW(e_internal, "can't set nonblock mode on fd %d", fd);
    }
    NIP3;
    EXIT;
}

static PF_PRIMITIVE(open_inferior){ // ( program+args mode -- stream )
    CHECKN(2);
    char *cmode    = STRING(ARG0);
    pf_list_t *arg = LIST(ARG1);

    int connect_fd; // child fd to connect
    if (cmode[1]) goto badmode;
    switch(cmode[0]){
    case 'w': connect_fd = 0; break;
    case 'r': connect_fd = 1; break;
    default:
      badmode:
	THROW(e_inval, "invalid mode string \"%s\"", cmode);
    }



    int argc = arg->elements;
    char *argv[argc+1];

    if (arg->elements < 1){ 
	THROW(e_inval, "argument list needs at least 1 element"); 
    }

    // check args
    {
	pf_list_t *s = arg;  // shadow s so we can use pf/macros.h
	pf_atom_t *a = ARG0;
	char **c = argv;
	while(a){
	    *c = STRING(a);   // this throws error if not a string
	    a = a->next;
	    c++;
	}
	*c = 0; // terminate arg list
    }

    // create pipe
    int fd[2];
    pipe(fd);
    int pid = fork();


    // process is sink(1) or source(0)

    
    /* CHILD */
    if (!pid){

	close(connect_fd);    // connect input (sink==1) or output (sink==0)
	dup(fd[connect_fd]);

	close(fd[0]);       // don't need these
	close(fd[1]); 

	// try to execute child
	if (-1 == execvp(argv[0], argv)){
	    perror ("can't execute inferior process");
	    exit(1);
	}
    }

    /* PARENT */
    int filedes = fd[connect_fd ^ 1];
    close(fd[connect_fd]);

    PUSH_NEW_STREAM;
    init_process(stream, arg->first->w.w_packet);
    stream->process.pid = pid;
    stream->file.fd = filedes;
    if (-1 == fd_nonblock(filedes)) {
	THROW(e_internal, "can't set nonblock mode on fd %d", filedes);
    }

    NIP2;
    EXIT;
}

static PF_PRIMITIVE(open_accept){ // (serverstream mode -- )
    CHECKN(2);
    union addr address;  // connection address
    socklen_t addrlen = sizeof(address);
    char *cmode = STRING(ARG0);
    pf_stream_t *server = STREAM(ARG1);
    int fd_server = pf_stream_fd(server);
    int fd_con;
    if (-1 == (fd_con = accept(fd_server, 
			       (struct sockaddr *)&address,
			       &addrlen))){
	THROW(e_inval, "can't accept connection: %s",
	      strerror(errno));
    }
    // create PF stream
    PUSH_NEW_STREAM;


    pf_packet_t name;
    if (address.un.sun_family == AF_UNIX){
	name = pf_packet_stringf("%s", "UNIX");
    }
    else if (address.in.sin_family == AF_INET){
	name = pf_packet_stringf("%s:%d", "TCP", ntohs(address.in.sin_port));
    }
    else {
	THROW(e_inval, "not a UNIX or TCP connection");
    }

    init_file(stream, name);
    pf_packet_unregister(name); name = 0;
    stream->file.fd = fd_con;

    if (-1 == fd_nonblock(fd_con)) {
	THROW(e_internal, "can't set nonblock mode on fd %d", fd_con);
    }

    NIP2;
    EXIT;
}

/*
  create TCP/UNIX server/client socket.
  result is a stream object.

 */

#define PF_SOCKET_SERVER    (1<<0)  // 0 = CLIENT
#define PF_SOCKET_UDP       (1<<1)  // 0 = TCP
#define PF_SOCKET_UNIX      (1<<2)  // 0 = INET
#define PF_SOCKET_BROADCAST (1<<3)

static PF_PRIMITIVE(open_socket){ // ((host port) mode kind -- stream )
    CHECKN(2);
    char kind      = INT(ARG0);
    char *cmode    = STRING(ARG1);

    char *sockname, *action;
    int port = 0; // not used for UNIX sockets

    int sockfd = -1;
    int intarg = -1; // for setsockopt
    struct hostent *hp = 0; // name lookup
    union addr address;  // target/listen address
    socklen_t addrlen = 0;
    memset(&address, 0, sizeof(struct sockaddr_in));

    // UNIX socket
    if (kind & PF_SOCKET_UNIX) {
	// FIXME check arg
	sockname = SYMBOLORSTRING(ARG2);

	// create UNIX socket
 	sockfd = socket(PF_UNIX, SOCK_STREAM,0);
	if (sockfd < -1) THROW(e_internal, "can't create socket");
	address.un.sun_family = AF_UNIX;
 	strcpy(address.un.sun_path, sockname); // FIXME: buffer overrun UNIX_PATH_MAX
	addrlen = sizeof(address.un.sun_family) 
	    + strlen(address.un.sun_path) + 1;
    }


    // TCP/UDP socket
    else{
	pf_list_t *arg = LIST(ARG2);
	
	{
	    pf_list_t *s = arg;
	    CHECKN(2);
	    sockname = SYMBOLORSTRING(ARG0);
	    port  = INT(ARG1); // FIXME: i had a string->int implicit conv here
	    
	    if ((port < 0) || (port >= 0xFFFF)){
		THROW(e_inval, "invalid IP port number %d "
		      "(valid: 1->65534)", port);
	    }
	}

	// lookup DNS name
	if (sockname[0]){
	    hp = gethostbyname(sockname);
	    if (!hp){
		THROW(e_inval, "lookup failed for host %s", sockname);
	    }
	    memcpy((char *)&address.in.sin_addr, 
		   (char *)hp->h_addr, hp->h_length);	
	}
	else {
	    // only listening TCP socket can be anonymous.
	    sockname = "0.0.0.0";
	}

	// create socket
	address.in.sin_port = htons((u_short)port);
	address.in.sin_family = AF_INET;
	
	// UDP
	if (kind & PF_SOCKET_UDP){
	    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	    if (sockfd < -1) THROW(e_internal, "can't create socket");
	    if (kind & PF_SOCKET_BROADCAST){
		intarg =  1;
		if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST,
			       &intarg, sizeof(intarg)) < 0){
		    close(sockfd);
		    THROW(e_file, "can't set broadcast socket option");
		}
	    }
	}
	// TCP
	else {
	    sockfd = socket(AF_INET, SOCK_STREAM, 0);
	    if (sockfd < -1) THROW(e_internal, "can't create socket");
	    if (setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY,
			   &intarg, sizeof(intarg)) < 0){
		close(sockfd);
		THROW(e_internal, "setsockopt error");
	    }
	}
	addrlen = sizeof(address.in);
    }
    // server socket
    if (kind & PF_SOCKET_SERVER){
	if (-1 == bind(sockfd, (struct sockaddr *) &address, addrlen)){
	    action = "bind";
	    goto error;
	}
	if (!(kind & PF_SOCKET_UDP)){
	    if (-1 == listen(sockfd, 5)) { // FIXME: magic number
		close(sockfd);
		THROW(e_inval, "can't listen: %s", strerror(errno));
	    }
	}

	// need nonblocking IO
	if (-1 == fd_nonblock(sockfd)) {
	    THROW(e_internal, "can't set nonblock mode on sockfd %d", sockfd);
	}
    }

    // client socket
    else {
	if (-1 == connect(sockfd, (struct sockaddr *) &address, addrlen)){
	    action = "connect";
	    goto error;
	}
    }
    
    // create PF stream
    PUSH_NEW_STREAM;
    pf_packet_t name = port ? 
	pf_packet_stringf("%s:%d", sockname, port) :
	pf_packet_stringf("%s", sockname);
	
    init_file(stream, name);
    pf_packet_unregister(name); name = 0;
    stream->file.fd = sockfd;

    // for server sockets, we have a different interface
    if (kind == (PF_SOCKET_UNIX | PF_SOCKET_SERVER)){
	// pf_post("setting unix socket interface");
	stream->m = unix_server_socket_interface;
    }
   
    // ok, cleanup
    NIP3;
    EXIT;


    // connect / bind error handler
  error:
    close(sockfd);
    if (port) { 
	THROW(e_inval, "%s to host %s, TCP port %d failed: %s", 
	      action, sockname, port, strerror(errno)); 
    }
    else {
	THROW(e_inval, "%s to UNIX socket %s failed: %s", 
	      action, sockname, strerror(errno));
    }
}



/* FORTH STREAM OPERATIONS  */



static PF_PRIMITIVE(stream_info){
    pf_stream_t *stream = STREAM(ARG0); 
    int line = stream->base.line;
    PUSH_PACKET(pf_packet_register((pf_header_t*)stream->base.name));
    NIP1;
    PUSH_INT(line);
    EXIT;
}

static PF_PRIMITIVE(stream_set_name){
    CHECKN(2);
    pf_stream_t *stream = STREAM(ARG0); 
    STRING(ARG1);

    pf_packet_unregister((pf_header_t*)stream->base.name);
    stream->base.name = (pf_string_t *)pf_packet_register(ARG1->w.w_packet);
    DROP2;
    EXIT;
}

// HACK: return proper values even if it's not a stream.
// this routine is used to set error values, so can't produce any.
static PF_PRIMITIVE(_stream_info){
    TRY_THROW(_stream_info);
    DROP1;
    PUSH_PACKET(-1);
    PUSH_INT(0);
    EXIT;
}


/* READ: see read.c */
/* WRITE: see write.c */



/* DEBUG */

static pf_stream_t *stderr_stream = 0;
pf_stream_t *pf_stream_log() { return stderr_stream; }


// these post to stderr, they are for debug only!!
void pf_post_n(char *fmt, ...){
    va_list ap; va_start (ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
}
void pf_post(char *fmt, ...){
    va_list ap; va_start (ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fprintf(stderr, "\n");
}



/* SETUP */

PF_PRIMITIVE(pf_word_write_setup);
PF_PRIMITIVE(pf_word_read_setup);

PF_FUNCTION(pf_forth_stream_setup){
    setup_interfaces();
    setup_packet();
    
    PUSH_NEW_STREAM;
    init_file(stream, pf_packet_stringf("<stderr>"));
    stream->file.fd = 2; // already nonblocking
    stderr_stream = stream;
    pf_list_pop(s);
    
    TRY_THROW(pf_word_read_setup);
    TRY_THROW(pf_word_write_setup);

    
    PF_REGISTER_FUNCTION
	(open_fd, "open-fd", "( fd name mode -- stream )\t"
	 "Create a stream from a file descriptor.");

    PF_REGISTER_FUNCTION
	(open_file, "open-file", "( filename mode -- stream )\t"
	 "Create a stream from a filename.");

    PF_REGISTER_FUNCTION
	(open_string, "open-string",
	 "( string -- stream )\tCreate a strean from a string packet.");

    PF_REGISTER_FUNCTION
	(open_inferior, "open-inferior",
	 "( args mode -- stream )\t"
	 "Like open-program, but all args need to be strings.");

    PF_REGISTER_FUNCTION
	(open_socket, "open-socket",
	 "( host/port.list mode server? -- stream )\t"
	 "Open a socket's input or output as a stream.");

    PF_REGISTER_FUNCTION
	(open_accept, "open-accept-nb", 
	 "( serverstream mode -- stream )\t"
	 "Accept the next connection from a server socket (non-blocking).");

    PF_REGISTER_FUNCTION
	(stream_info, "stream-info",
	 "( stream -- name line.number )\t"
	 "Return the name and line number for stream.");

    PF_REGISTER_FUNCTION
	(stream_set_name, "stream-name!",
	 "( name stream -- )\t"
	 "Set the stream name.");

    EXIT;

}



