/* PIPClient - A client for finger protocol v2
 *
 * Copyright (C) 1999 Michael Baumer
 *
 * 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., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <unistd.h>
#include <stdio.h>

#include "log.h"
#include "parser.h"

extern int debug;

/* Send a request to a remote end
 *
 * parameters:
 *    fdin : fd to send data to
 *    fdout: fd read send data from
 *    cmd  : the command string to send. Must include "</pip>"
 *
 * return value:
 *    1: suceeded
 *    0: protocol error (most likely: remote end does not understand
 *       the pip protocol),
 *       but can also indicate an I/O error
 *
 * If a write fails we simply return, since this function we be called again
 * anyway. Perhaps we could at least check for EINTR.
 */
int send_request(int fdin, int fdout, char *cmd)
{
  char *pip = "<pip>\n";
  int nread;
  char inbuf[256];
  static Node pipnode = { PIP + 1 };
  int retval = 0;

  if (write(fdin, pip, strlen(pip)+1)<0)
    return 0;

  while ((nread = read(fdout, inbuf, sizeof(inbuf)))) {
    if (nread == -1) {
      log(LOG_ERR, "Reading from child: %m");
      break;
    }
    inbuf[nread] = '\0';
    
    if (debug)
      printf("inbuf:%s\n", inbuf);
     
    if (!strncmp(inbuf, "<pip>", 5)) {
      if (debug)
	printf("Sending command \n");

      if (write(fdin, cmd, strlen(cmd)+1) < 0)
	return 0;

      /* starting parsing */

      if (pipnode.type != PIP) {
	/* initialize the parse tree */
	
	pipnode.next = NULL;
	pipnode.child = NULL;
	pipnode.last = NULL;
	pipnode.parent = NULL;
	strcpy(pipnode.id, "pip");
	pipnode.type = PIP;
	pipnode.value = (char *)malloc(BUFSIZE);
	pipnode.val_len = BUFSIZE;
      }

      retval = ParseNode(fdout, &pipnode);

      /* free parse tree */
      FreeParseTree(pipnode.child);
      pipnode.next = NULL;
      pipnode.child = NULL;
      pipnode.last = NULL;
    }
  }
  return retval;
}


syntax highlighted by Code2HTML, v. 0.9.1