/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <windows.h>
#include <winsock.h>

#include "IMTrans.hh"

static int initialized = 0;



IMTransListen::IMTransListen(CompoundString im_address, CompoundString protocol_name) {
  struct sockaddr_in sin; // get a listening socket
  struct servent *sp;

  if (!initialized) {
	  WSADATA Data;
	  WSAStartup(MAKEWORD(1,1), &Data);
	  initialized = 1;
  }
  listen_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (listen_socket == -1) {
    fprintf(stderr, "cannot open socket for %s\n", (char*)protocol_name);
    return;
  }

  char *p;
  char *port_number;

  if (im_address && (p = (char *)strstr(im_address, ":"))) {
    port_number = ++p;
    sin.sin_port = htons((short)atoi(port_number));
  } else if ((sp = getservbyname("IIIMP", "tcp")) != 0) {
    sin.sin_port = sp->s_port;
  } else {
    sin.sin_port = htons((short)9010);	// default
  }

  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = htonl(INADDR_ANY);

  const char reuse = 1;
  setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int));

  if (bind(listen_socket, (struct sockaddr*) &sin, sizeof(sin)) != 0) {
    shutdown(listen_socket, 2);
    fprintf(stderr, "Another IIIMP Server might be running.\n");
    return;
  }

  int len = sizeof sin;
  if (getsockname(listen_socket, (struct sockaddr*) &sin, &len) == -1) {
    fprintf(stderr, "Can't get socket name\n");
    return;
  }

  if (listen(listen_socket, 5) < 0) {
    shutdown(listen_socket, 2);
    fprintf(stderr, "Can't listen to the socket\n");
    return;
  }
}

IMTransListen::~IMTransListen() {
  closesocket(listen_socket);
  WSACleanup();
}

IMTransAccept*
IMTransListen::accept() {
  int ss;
  struct sockaddr_in addr_in;
  int addrlen = sizeof(addr_in);

LOOP:
  if ((ss = ::accept(listen_socket,
		     (struct sockaddr*)&addr_in, &addrlen)) != -1) {
    IMTransAccept *client = new IMTransAccept(ss);
    return client;
  } else {
    if (WSAGetLastError() != WSAEINTR)
       throw "Can't accept requests";
    else
	goto LOOP;		// has been interrupted. accept again	
  }
  return (IMTransAccept *)0;
}

IMTransAccept::~IMTransAccept() {
  if (accept_fd) {
      FD_CLR(accept_fd, &rmask_fd);
      closesocket(accept_fd);
      shutdown(accept_fd, 2);
      accept_fd = 0;
  }	
}

int
IMTransAccept::read(char *buf, int len) {
	int numrecv = recv(accept_fd, buf, len, 0);
	if ((numrecv == 0) || (numrecv == SOCKET_ERROR)) {
		fprintf(stderr, "Error in reading\n");
	}
  return numrecv;
}

int
IMTransAccept::select_fd(struct timeval timeout) {
  fd_set select_mask;
  select_mask = rmask_fd;
  int nfds = accept_fd + 1;

  while(1) {
    if (select(nfds, &select_mask, NULL, NULL, &timeout) == SOCKET_ERROR) {
      if (WSAGetLastError() == WSAEINTR)
        continue;
      else
        return Trans_ERROR;
    }
    if (FD_ISSET(accept_fd, &select_mask)) {
      return Trans_ACCEPT;
    }
    // timeout
    return Trans_TIMEOUT;
  }
}

int
IMTransAccept::write(char *buf, int len) {
	int numsend = send(accept_fd, buf, len, 0);
	if (numsend != len)
		fprintf(stderr, "Error in sending\n");
  return numsend;
}

int
IMTransAccept::connection_id() {return accept_fd;}
