/*

  Copyright (c) 2003,2004 uim Project http://uim.freedesktop.org/

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
  3. Neither the name of authors nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGE.

*/

#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

/* This function is come from the GNU C Library manual */
int
set_cloexec(int fd)
{
  int oldflags = fcntl (fd, F_GETFD, 0);
  /* If reading the flags failed, return error indication now.
  if (oldflags < 0)
  return oldflags;*/

  oldflags |= FD_CLOEXEC;
  /* Store modified flag word in the fdriptor. */
  return fcntl (fd, F_SETFD, oldflags);
}


static pid_t
open_pipe_rw(FILE **fr, FILE **fw)
{
  int fdr[2];
  int fdw[2];
  int pipe_fd[2];
  pid_t pid;
  int res;

  if (pipe(pipe_fd) < 0)
    return (pid_t)-1;

  if (fr && pipe(fdr) < 0)
    goto err0;
  if (fw && pipe(fdw) < 0)
    goto err1;

  pid = fork();
  if (pid < 0)
    goto err2;
  if (pid == 0) {
    /* child */
    pid = fork();
    if (pid) {
      /* child. report status of grand child for father anyway and _exit() */
      write(pipe_fd[1], &pid, sizeof(pid_t));
      _exit(0);
    } else {
      /* grand child */
      if (fr) {
	close(fdr[0]);
	dup2(fdr[1], 1);
      }
      if (fw) {
	close(fdw[1]);
	dup2(fdw[0], 0);
      }
      close(pipe_fd[0]);
      close(pipe_fd[1]);
    }
    return 0;
  }
  /* parent */
  waitpid(pid, &res, 0);
  if (fr) {
    close(fdr[1]);
    if (*fr == stdin)
      dup2(fdr[0], 0);
    else
      *fr = fdopen(fdr[0], "r");
  }
  if (fw) {
    close(fdw[0]);
    if (*fw == stdout)
      dup2(fdw[1], 1);
    else
      *fw = fdopen(fdw[1], "w");
  }

  read(pipe_fd[0], &pid, sizeof(pid_t));
  close(pipe_fd[0]);
  close(pipe_fd[1]);

  if (pid != -1) {
    return pid;
  }
 err2:
  if (fw) {
    close(fdw[0]);
    close(fdw[1]);
  }
 err1:
  if (fr) {
    close(fdr[0]);
    close(fdr[1]);
  }
 err0:
  return (pid_t) -1;
}

int
uim_ipc_open_command(int old_pid, FILE **read_handler,
		     FILE **write_handler, char *command)
{
  int new_pid, result;

  if (*read_handler  != NULL)
    fclose(*read_handler);
  if (*write_handler != NULL)
    fclose(*write_handler);
  
  *read_handler = *write_handler = NULL;
  
  /* kill child process if exists */
  if (old_pid)
    kill(old_pid, SIGKILL);

  new_pid = open_pipe_rw(read_handler, write_handler);

  if (new_pid < 0)
    return 0;

  if (new_pid == 0) {
    /* child */

    int open_max;
    int i;
    
    open_max = sysconf (_SC_OPEN_MAX);
    for (i = 3; i < open_max; i++) {
      set_cloexec(i);      
    }

    result = execlp(command, command, NULL);
    
    if(result == -1) {
      write(1,"err",strlen("err"));
    }
    _exit(127);
  }

  return new_pid;

}



char *
uim_ipc_send_command(int *pid, FILE **read_handler,
		     FILE **write_handler, char* command, char *str)
{
  char *tmp = strdup("");
  char buf[8192];

  if (*read_handler == NULL || *write_handler == NULL) {
    *pid = uim_ipc_open_command(*pid, read_handler, write_handler, command);
  }
  if(*pid == 0) {
    free(tmp);
    return NULL;
  }

  fputs(str, *write_handler);

 again:
  if (fflush(*write_handler) != 0) {
    switch (errno) {
    case EINTR:
      goto again;
    default:
      goto err;
    }
  }

  while (fgets (buf, sizeof(buf), *read_handler ) != NULL ) {
    if(strcmp( buf, "\n" ) == 0)
      break;

    tmp = realloc(tmp, strlen(tmp) + strlen(buf) + 1);
    strcat(tmp, buf);
  }
 
  return tmp;

 err:
  free(tmp);
  *pid = uim_ipc_open_command(*pid, read_handler, write_handler, command );
  return NULL;
}
