/*
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 <errno.h>
#include "IMTrans.hh"
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef	linux
#include <sys/un.h>
#endif
#include <sys/resource.h>

IMTransListen::IMTransListen(CompoundString im_address, CompoundString protocol_name, 
      int network) {
  struct rlimit glp;
  char  *err_msg;

  if (getrlimit(RLIMIT_NOFILE, &glp) < 0) {
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "Error in getrlimit \n");
    throw err_msg;
  }

  cur_maxfd = glp.rlim_cur; /* initial value */
  incr_fd = glp.rlim_cur;   /* initial value */
  fd_resource_limit = glp.rlim_max; /* initial value */

  if(network) {
    IMTransListenINET(im_address, protocol_name);
  } else {
#ifdef	linux
    IMTransListenUNIX(im_address, protocol_name);
#endif /* linux */
  }
}

#ifdef	linux
#define UNIX_SOCKET_DIR         "/tmp/.iiim-unix"

void
IMTransListen::IMTransListenUNIX(CompoundString im_address, CompoundString protocol_name) {
  struct sockaddr_un sin; // get a listening socket
  struct servent *sp;
  struct hostent *hp;
  char  *err_msg;
  int oldUmask;

  listen_socket = socket(AF_UNIX, SOCK_STREAM, 0);
  if (listen_socket == -1) {
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "cannot open socket for %s", (char*)protocol_name); 
    throw err_msg;
  }

  char *p;
  char *port_number = "9010";	// default

  if (im_address && (p = (char *)index(im_address, ':'))) {
    port_number = ++p;
  }

  sin.sun_family = AF_UNIX;
  sprintf(sin.sun_path, "%s/%s", UNIX_SOCKET_DIR, port_number);

  oldUmask = umask (0);

  (void)mkdir(UNIX_SOCKET_DIR, 0777);
  (void)chmod(UNIX_SOCKET_DIR, 0777);

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

  (void)unlink(sin.sun_path);

  if (bind(listen_socket, (struct sockaddr*) &sin, sizeof(sin)) != 0) {
    shutdown(listen_socket, 2);
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1,"Another IIIMP Server might be running.");
    umask (oldUmask);
    throw err_msg;
  }

  socklen_t len = sizeof sin;
  if (getsockname(listen_socket, (struct sockaddr*) &sin, &len) == -1) {
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "Can't get socket name");
    umask (oldUmask);
    throw err_msg;
  }

  if (listen(listen_socket, 5) < 0) {
    shutdown(listen_socket, 2);
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "Can't listen to the socket");
    umask (oldUmask);
    throw err_msg;
  }
    umask (oldUmask);
    return;
}
#endif /* linux */

void
IMTransListen::IMTransListenINET(CompoundString im_address, CompoundString protocol_name) {
  struct sockaddr_in sin; // get a listening socket
  struct servent *sp;
  struct hostent *hp;
  char  *err_msg;
  listen_socket = socket(AF_INET, SOCK_STREAM, 0);
  if (listen_socket == -1) {
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "cannot open socket for %s", (char*)protocol_name); 
    throw err_msg;
  }

  char *p;
  char *port_number;

  if (im_address && (p = (char *)index(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,
	     (const char*)&reuse, sizeof(int));

  if (bind(listen_socket, (struct sockaddr*) &sin, sizeof(sin)) != 0) {
    shutdown(listen_socket, 2);
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "Another IIIMP Server might be running.");
    throw err_msg;
  }

  socklen_t len = sizeof sin;
  if (getsockname(listen_socket, (struct sockaddr*) &sin, &len) == -1) {
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "Can't get socket name");
    throw err_msg;
  }

  if (listen(listen_socket, 5) < 0) {
    shutdown(listen_socket, 2);
    err_msg = new char[BUFSIZ];
    snprintf(err_msg, BUFSIZ -1, "Can't listen to the socket");
    throw err_msg;
  }
    return;
}

IMTransListen::~IMTransListen() {
  close(listen_socket);
}

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

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

int
IMTransListen::check_fd_resource_limit(int fd) {
  char *err_msg;

  if (fd < (cur_maxfd - 1)) 
    return fd;

  if (fd >= (cur_maxfd - 1)) {
      struct rlimit slp;
      if (cur_maxfd == fd_resource_limit) 
        return -1;
      cur_maxfd += incr_fd;
      if (cur_maxfd > fd_resource_limit) 
        cur_maxfd = fd_resource_limit;
      slp.rlim_cur = cur_maxfd;
      slp.rlim_max = fd_resource_limit;
      if (setrlimit(RLIMIT_NOFILE, (const struct rlimit*)&slp) < 0) {
        err_msg = new char[BUFSIZ];
        snprintf(err_msg, BUFSIZ -1, "Error in setrlimit \n");
        throw err_msg;
      }
  }
  return fd;
}

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

int
IMTransAccept::read(char *buf, int len) {
  return ::read(accept_fd, buf, len);
}

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) == -1) {
      if (errno == EINTR)
	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) {
  return ::write(accept_fd, buf, len);
}

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