/*
 *  Copyright (C) 1999 AT&T Laboratories Cambridge.  All Rights Reserved.
 *
 *  This 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 software 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 software; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 *  USA.
 */

/*
 * sockets.c - functions to deal with sockets.
 */


#include <time.h>

#include "oslib/socket.h"

#include "vncviewer.h"
#include "ip.h"


Bool errorMessageOnReadFailure = True;

#define BUF_SIZE 8192
static char buf[BUF_SIZE];
static char *bufoutptr = buf;
int buffered = 0;

static int totalread = 0;
/*
 * ReadFromRFBServer is called whenever we want to read some data from the RFB
 * server.  It is non-trivial for two reasons:
 *
 * 1. For efficiency it performs some intelligent buffering, avoiding invoking
 *    the read() system call too often.  For small chunks of data, it simply
 *    copies the data out of an internal buffer.  For large amounts of data it
 *    reads directly into the buffer provided by the caller.
 *
 * 2. Whenever read() would block, it invokes the Xt event dispatching
 *    mechanism to process X events.  In fact, this is the only place these
 *    events are processed, as there is no XtAppMainLoop in the program.
 */


Bool ReadFromRFBServer(char *out, unsigned int n) {

  if (n <= buffered) {
    memcpy(out, bufoutptr, n);
    bufoutptr += n;
    buffered -= n;
    return True;
  }

  if (buffered > 0)    memcpy(out, bufoutptr, buffered);

  out += buffered;
  n -= buffered;

  bufoutptr = buf;
  buffered = 0;

  if (n <= BUF_SIZE) {

    while (buffered < n) {
      int i, ready, to_read;

      ready = ip_ready(rfbsock);
      if (ready > BUF_SIZE - buffered)
        to_read = BUF_SIZE - buffered;
      else
        to_read = ready;
      i = ip_read(rfbsock, buf + buffered, to_read);
      if (i < 0)
        return False;
      totalread += i;
      buffered += i;
      poll();
    }

    memcpy(out, bufoutptr, n);
    bufoutptr += n;
    buffered -= n;

  } else {

    while (n > 0) {
      int i, ready, to_read;

      ready = ip_ready(rfbsock);
      if (ready > BUF_SIZE - buffered)
        to_read = BUF_SIZE - buffered;
      else
        to_read = ready;
      i = ip_read(rfbsock, out, to_read);
      if (i < 0)    return False;
      totalread += i;
      out += i;
      n -= i;
      poll();
    }

  }
  return True;
}


/*
 * Write an exact number of bytes, and don't return until you've sent them.
 */

Bool WriteExact(int sock, void *buf, int n) {

  int i = 0;

  for(;;) {
    int j;

    j = ip_write(sock, (char *)buf + i, (n - i));
    if (j <= 0)
      return False;
    i += j;
    if (i == n)
      return True;
    poll();
  }
}


/*
 * ConnectToTcpAddr connects to the given TCP port.
 */

int
ConnectToTcpAddr(unsigned int host, int port)
{
  int sock;

  sock = ip_create(0);
  if (sock < 0) {
    fprintf(stderr, "Failed to create socket\n");
    return -1;
  }

  if (ip_connect(sock, host, port) <= 0) {
    fprintf(stderr, "Failed to connect on port %d\n", port);
    ip_close(sock);
    return -1;
  }

  ip_nonblocking(sock);

  return sock;
}



/*
 * SetNonBlocking sets a socket into non-blocking mode.
 */

Bool SetNonBlocking(int sock) {
  ip_nonblocking(sock);
  return True;
}

/*
 * CloseSocket
 */
void CloseSocket(int sock) {
  fprintf(stderr, "BYTES READ %d  (%d)\n", totalread, clock());
  ip_close(sock);
}
