//
// 
//	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
// 
//	This program is free software; you can redistribute it 
//	and/or modify it under the terms of the GLOBALBASE 
//	Library General Public License (G-LGPL) as published by 
//
//	http://www.globalbase.org/
// 
//	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.
//
//

extern "C" {

#define STREAM_LIB

#include	<stdio.h>
#include	<fcntl.h>
#include	"machine/err.h"
#include	<stdlib.h>
#include	"memory_debug.h"
#include	"server.h"
#include	"task.h"
#include	"net_msg.h"

#include	"CServerMaster.h"

int accept_test;
int accept_tid;

extern SEM stream_lock;
//void _s_open(STREAM * s,int mode);

ACCESS_KEY *
accept_connection(STREAM * s)
{
ACCESS_KEY * key;
extern S_TABLE s_accept_table;

	lock_task(stream_lock);
	if ( ! s ) {
		unlock_task(stream_lock, "accept_connection");
		return 0;
	}
	if ( ! s->h.tbl ) {
		unlock_task(stream_lock, "accept_connection");
		return 0;
	}
	if ( s->h.tbl != &s_accept_table ) {
		unlock_task(stream_lock, "accept_connection");
		return 0;
	}
	unlock_task(stream_lock, "accept_connection");

	key = (ACCESS_KEY *)d_alloc(sizeof(*key));
	key->s = (STREAM *)d_alloc(sizeof(STREAM));
	try {
		key->s->socket.ep = s->accept.sm->AcceptConnection();
	} catch(...) {
		sleep_sec(3);
		void er_panic(char*);
		er_panic("accept_connection");
	}
	key->s->socket.state = S_STATE_OK;

	key->s->h.tbl = &s_socket_table;
	key->s->h.thread = 0;
	lock_task(stream_lock);
	_s_open(key->s,0);
	unlock_task(stream_lock,"accept_connection");
	try {
		key->ip = key->s->socket.ep->GetRemoteHostAddress()->GetIPAddress();
	}
	catch(...) {
		key->ip = 0;
	}
	key->work = 0;

	return key;
}

} // extern "C"