int mserv_get_command_interleave(
              int client_fd,
              char *cmd, 
              uint64_t num_pages_allocated, 
              int  servno,
              char *checkpoint_name){
    int ret = -1; 

    if((ret = write_full(client_fd, cmd, CHKPT_CMD_LEN)) < 0){
        printf(" mserv_get: Error: Unsuccessful cmd write: %s\n", cmd);
    	return ret;
    }

    if((ret = write_full(client_fd, &num_pages_allocated, sizeof(uint64_t))) < 0){
        printf(" mserv_get: Error: Unsuccessful numpagealloc write %" PRIx64 "\n", num_pages_allocated);
    	return ret;
    }

    if((ret = write_full(client_fd, &servno, sizeof(int))) < 0){
        printf(" mserv_get: Error: Unsuccessful numpagealloc write %" PRIx64 "\n", num_pages_allocated);
    	return ret;
    }
    //if((ret = write_full(client_fd, checkpoint_name, CHKPT_NAME_LEN)) < 0){
    //    printf(" mserv_get: Error: Unsuccessful chkptname write: %s\n", checkpoint_name);
    // 	return ret;
    //}

    return ret;
}
int mserv_init_command_block(
              int client_fd,
              char *cmd, 
              uint64_t num_pages_allocated, 
              uint64_t base_page_id, 
              char *checkpoint_name){
    int ret = -1; 

    if((ret = write_full(client_fd, cmd, CHKPT_CMD_LEN)) < 0){
        printf(" mserv_init_set: Error: Unsuccessful cmd write: %s\n", cmd);
    	return ret;
    }

    if((ret = write_full(client_fd, &base_page_id, sizeof(uint64_t))) < 0){
        printf(" mserv_init_set: Error: Unsuccessful basepageid write %" PRIx64 "\n", base_page_id);
     	return ret;
    }

    if((ret = write_full(client_fd, &num_pages_allocated, sizeof(uint64_t))) < 0){
        printf(" mserv_init_set: Error: Unsuccessful numpagealloc write %" PRIx64 "\n", num_pages_allocated);
    	return ret;
    }

    //if((ret = write_full(client_fd, checkpoint_name, CHKPT_NAME_LEN)) < 0){
    //    printf(" mserv_init_set: Error: Unsuccessful chkptname write: %s\n", checkpoint_name);
    // 	return ret;
    //}

    return ret;
}
Exemple #3
0
static int save_file(const char *path)
{
	struct line *line, *tmp;
	int fd;
	int ret = 0;

	fd = open(path, O_WRONLY | O_TRUNC | O_CREAT);
	if (fd < 0) {
		printf("could not open file for writing: %s\n", errno_str());
		return fd;
	}

	line = buffer;

	while(line) {
		tmp = line->next;
		ret = write_full(fd, line->data, strlen(line->data));
		if (ret < 0)
			goto out;
		ret = write_full(fd, "\n", 1);
		if (ret < 0)
			goto out;
		line = tmp;
	}

	ret = 0;

out:
	close(fd);
	return ret;
}
int mserv_base_set(const void *mkey, size_t mkey_size, const void *buf, size_t buf_size){
    int ret = -1;
    
    uint64_t addr = *((uint64_t *)mkey);
    uint64_t page_id;
    // determine which server to send to based on block distribution
    uint64_t mserv_id; 
    int fd = -1;

    // assertion
    if(!((tlc_chkpt_status == TLC_CHKPT_READY)&&(mserv_target_page_bits > 0))){ 
        printf("mserv_set: assertion! error mserv_target_page_bits = % " PRId64 "\n",
          mserv_target_page_bits);
        exit(1);
    }

    // choose a memory server
    page_id = addr >> mserv_target_page_bits;
    
    if(
       (tlc_chkpt_type_flag == TLC_MEM_ADDR_BLOCK) ||
       (tlc_chkpt_type_flag == TLC_MEM_ADDR_BLOCK_DOUBLE_CHANNELS)
      ){
        mserv_id = page_id/per_mserv_allocate_pages; // for block distribution 
    }
    else if(
       (tlc_chkpt_type_flag == TLC_MEM_ADDR_CYCLIC) ||
       (tlc_chkpt_type_flag == TLC_MEM_ADDR_CYCLIC_DOUBLE_CHANNELS)
    ){
        mserv_id = page_id % chkpt_mserv_cnt;  // for cyclic distribution
    }

    if (mserv_id < chkpt_mserv_cnt){ 
        fd = base_chkpt_mserv_client_fd[mserv_id];
    }
    else{
        printf(" mserv_set: Abort! fatal error sending ptr = %" PRIx64 " key (addr) = %" PRId64 " page id = %" PRId64 "\n", (uint64_t)mkey, *((uint64_t *)mkey), page_id);
        printf(" mserv_set: mserv_id = %" PRId64 " chkpt_cnt = %d per_mserv = %" PRId64 " sent_item %" PRId64  "\n", mserv_id, chkpt_mserv_cnt, per_mserv_allocate_pages, base_mserv_set_item_cnt);
        fflush(stdout);
        exit(1);
    }
 
    // sending addr and page's contents
    base_mserv_set_item_cnt++;

    if((ret = write_full(fd, mkey, mkey_size)) < 0){
        printf(" mserv_set: Error: Unsuccessful key write %" PRIx64 "\n", (uint64_t) mkey);
    	return ret;
    }
    if((ret = write_full(fd, buf, buf_size)) < 0){
        printf(" mserv_set: Error: Unsuccessful value write (key = %" PRIx64 ") \n", (uint64_t) mkey);
        return ret;
    }
    return ret;   
}
Exemple #5
0
static void tcpwrap_client_handle(struct tcpwrap_client *client, int check_fd,
				  const char *daemon_name)
{
	struct request_info request;

	request_init(&request, RQ_DAEMON, daemon_name,
		     RQ_FILE, check_fd, 0);
	fromhost(&request);

	if (!hosts_access(&request))
		(void)write_full(client->fd, "0\n", 2);
	else
		(void)write_full(client->fd, "1\n", 2);
	exit(0);
}
int mc_set2(const void *mkey, size_t mkey_size, const void *buf, size_t buf_size){
    int ret = -1;
    
    if((ret = write_full(mclient_fd2, mkey, mkey_size)) < 0){
        printf(" mc_set2: Error: Unsuccessful key write %" PRIx64 "\n", (uint64_t) mkey);
    	return ret;
    }
    //printf(" mc_set2: first write %d ret = %d\n", mclient_fd, ret);
    if((ret = write_full(mclient_fd2, buf, buf_size)) < 0){
        printf(" mc_set2: Error: Unsuccessful page write (key = %" PRIx64 ") \n", (uint64_t) mkey);
        return ret;
    }
    //printf(" mc_set2: second write ret = %d\n", ret);
    return ret;   
}
int mc_set(const void *mkey, size_t mkey_size, const void *buf, size_t buf_size){
    int ret = -1;
    
    if((ret = write_full(mclient_fd, mkey, mkey_size)) < 0){
        printf(" mc_set: Error: Unsuccessful key write %" PRIx64 "\n", (uint64_t) mkey);
    	return ret;
    }

    if((ret = write_full(mclient_fd, buf, buf_size)) < 0){
        printf(" mc_set: Error: Unsuccessful page write (key = %" PRIx64 ") \n", (uint64_t) mkey);
        return ret;
    }

    return ret;   
}
int vic_report(char *message){
    int ret; 
    if((ret = write_full(vic_fd, message, strlen(message))) < 0){
        printf(" vic_report: Error: fail sending a message %s\n", message);
    }
    return ret;
}
Exemple #9
0
static ssize_t
o_stream_temp_fd_sendv(struct temp_ostream *tstream,
		       const struct const_iovec *iov, unsigned int iov_count)
{
	size_t bytes = 0;
	unsigned int i;

	for (i = 0; i < iov_count; i++) {
		if (write_full(tstream->fd, iov[i].iov_base, iov[i].iov_len) < 0) {
			i_error("iostream-temp %s: write(%s*) failed: %m - moving to memory",
				o_stream_get_name(&tstream->ostream.ostream),
				tstream->temp_path_prefix);
			if (o_stream_temp_move_to_memory(&tstream->ostream.ostream) < 0)
				return -1;
			for (; i < iov_count; i++) {
				buffer_append(tstream->buf, iov[i].iov_base, iov[i].iov_len);
				bytes += iov[i].iov_len;
				tstream->ostream.ostream.offset += iov[i].iov_len;
			}
			i_assert(tstream->fd_tried);
			return bytes;
		}
		bytes += iov[i].iov_len;
		tstream->ostream.ostream.offset += iov[i].iov_len;
	}
	tstream->fd_size += bytes;
	return bytes;
}
Exemple #10
0
static void fts_queue_index(struct mailbox *box)
{
	struct mail_user *user = box->storage->user;
	string_t *str = t_str_new(256);
	const char *path, *value;
	unsigned int max_recent_msgs;
	int fd;

	path = t_strconcat(user->set->base_dir, "/"INDEXER_SOCKET_NAME, NULL);
	fd = net_connect_unix(path);
	if (fd == -1) {
		i_error("net_connect_unix(%s) failed: %m", path);
		return;
	}

	value = mail_user_plugin_getenv(user, "fts_autoindex_max_recent_msgs");
	if (value == NULL || str_to_uint(value, &max_recent_msgs) < 0)
		max_recent_msgs = 0;

	str_append(str, INDEXER_HANDSHAKE);
	str_append(str, "APPEND\t0\t");
	str_append_tabescaped(str, user->username);
	str_append_c(str, '\t');
	str_append_tabescaped(str, box->vname);
	str_printfa(str, "\t%u", max_recent_msgs);
	str_append_c(str, '\t');
	str_append_tabescaped(str, box->storage->user->session_id);
	str_append_c(str, '\n');
	if (write_full(fd, str_data(str), str_len(str)) < 0)
		i_error("write(%s) failed: %m", path);
	i_close_fd(&fd);
}
Exemple #11
0
static void log_error_core(int logfile,const char *file, int line,
	const char *fmt, va_list args)
{
    char errstr[MAX_LOG_LEN];
    memset(errstr,0,sizeof(errstr));
    size_t len=0;

    const char *p;
    /* On Unix, __FILE__ may be an absolute path in a
     * VPATH build. */
    if (file[0] == '/' && (p = strrchr(file, '/')) != NULL) {
	file = p + 1;
    }
    char time_str[CTIME_LEN];
    log_ctime(time_str,time_now());
    len += snprintf(errstr + len, MAX_LOG_LEN - len,
	    "[%s]%s(%d): ",time_str,file, line);

    len += vsnprintf(errstr+len, MAX_LOG_LEN-len, fmt, args);

    if (logfile) {
	/* Truncate for the terminator (as apr_snprintf does) */
	if (len > MAX_LOG_LEN - sizeof(EOL_STR)) {
	    len = MAX_LOG_LEN - sizeof(EOL_STR);
	}
	strcpy(errstr + len, EOL_STR);
	size_t len;
	len = strlen(errstr);
	write_full(logfile, errstr, len); 
    }
}
Exemple #12
0
static int mbox_seek_to_end(struct mbox_save_context *ctx, uoff_t *offset)
{
	struct stat st;
	char ch;
	int fd;

	if (ctx->mbox->mbox_writeonly) {
		*offset = 0;
		return 0;
	}

	fd = ctx->mbox->mbox_fd;
	if (fstat(fd, &st) < 0)
                return mbox_set_syscall_error(ctx->mbox, "fstat()");

	ctx->orig_atime = st.st_atime;

	*offset = (uoff_t)st.st_size;
	if (st.st_size == 0)
		return 0;

	if (lseek(fd, st.st_size-1, SEEK_SET) < 0)
                return mbox_set_syscall_error(ctx->mbox, "lseek()");

	if (read(fd, &ch, 1) != 1)
		return mbox_set_syscall_error(ctx->mbox, "read()");

	if (ch != '\n') {
		if (write_full(fd, "\n", 1) < 0)
			return write_error(ctx);
		*offset += 1;
	}

	return 0;
}
Exemple #13
0
int sio_write(int level, const char * format, ...) {
  char bf[1024];

  int ilevel = level & 0xFFF;
  if (ilevel==0) ilevel = 50;  

  switch (level & 0xF000) {
  case SIO_DATA:    ilevel = sio_dbglevel+1; bf[0] = 0; break;
  case SIO_DEBUG:   sprintf(bf, "SYS-DEBUG\t%s\t%d\t", appname, ilevel); break;
  case SIO_LOG:     ilevel += 100; sprintf(bf, "SYS-LOG\t%s\t", appname); break;
  case SIO_ERROR:   ilevel += 500; sprintf(bf, "SYS-LOG\t%s\tERR: ", appname); break;
  case SIO_WARN:    ilevel += 400; sprintf(bf, "SYS-LOG\t%s\tWARN: ", appname); break;
  default:
	sprintf(bf, "SYS-LOG\tag%X: ", level);
  };

  if (ilevel < sio_dbglevel) return 0;


  va_list args;
  va_start(args, format);
  vsnprintf(strchr(bf,0), sizeof(bf)-strlen(bf)-4, format, args);
  va_end(args);
  strcat(bf, "\n");

  if (sio_commdump & 1) {
	printf("WRITE\t%s", bf);
  };

  GLOB_LOCK();
  write_full(ser_fd_write, bf, strlen(bf));
  GLOB_UNLOCK();
  return 0;
};
Exemple #14
0
static int o_stream_temp_move_to_fd(struct temp_ostream *tstream)
{
	string_t *path;

	if (tstream->fd_tried)
		return -1;
	tstream->fd_tried = TRUE;

	path = t_str_new(128);
	str_append(path, tstream->temp_path_prefix);
	tstream->fd = safe_mkstemp_hostpid(path, 0600, (uid_t)-1, (gid_t)-1);
	if (tstream->fd == -1) {
		i_error("safe_mkstemp(%s) failed: %m", str_c(path));
		return -1;
	}
	if (i_unlink(str_c(path)) < 0) {
		i_close_fd(&tstream->fd);
		return -1;
	}
	if (write_full(tstream->fd, tstream->buf->data, tstream->buf->used) < 0) {
		i_error("write(%s) failed: %m", str_c(path));
		i_close_fd(&tstream->fd);
		return -1;
	}
	/* make the fd available also to o_stream_get_fd(),
	   e.g. for unit tests */
	tstream->ostream.fd = tstream->fd;
	tstream->fd_size = tstream->buf->used;
	buffer_free(&tstream->buf);
	return 0;
}
Exemple #15
0
int get(const char *hashfile, const char *logfile, const char *key) {
  sparkey_hashreader *reader;
  sparkey_logreader *logreader;
  sparkey_logiter *iter;
  assert(sparkey_hash_open(&reader, hashfile, logfile));
  logreader = sparkey_hash_getreader(reader);
  assert(sparkey_logiter_create(&iter, logreader));

  uint64_t keylen = strlen(key);
  assert(sparkey_hash_get(reader, (uint8_t*) key, keylen, iter));

  int exitcode = 2;
  if (sparkey_logiter_state(iter) == SPARKEY_ITER_ACTIVE) {
    exitcode = 0;
    uint8_t * res;
    uint64_t len;
    do {
      assert(sparkey_logiter_valuechunk(iter, logreader, 1 << 31, &res, &len));
      assert(write_full(STDOUT_FILENO, res, len));
    } while (len > 0);
  }
  sparkey_logiter_close(&iter);
  sparkey_hash_close(&reader);
  return exitcode;
}
Exemple #16
0
static int
index_mailbox_precache(struct master_connection *conn, struct mailbox *box)
{
    struct mail_storage *storage = mailbox_get_storage(box);
    const char *username = mail_storage_get_user(storage)->username;
    const char *box_vname = mailbox_get_vname(box);
    struct mailbox_status status;
    struct mailbox_transaction_context *trans;
    struct mail_search_args *search_args;
    struct mail_search_context *ctx;
    struct mail *mail;
    struct mailbox_metadata metadata;
    uint32_t seq;
    char percentage_str[2+1+1];
    unsigned int counter = 0, max, percentage, percentage_sent = 0;
    int ret = 0;

    if (mailbox_get_metadata(box, MAILBOX_METADATA_PRECACHE_FIELDS,
                             &metadata) < 0 ||
            mailbox_get_status(box, STATUS_MESSAGES | STATUS_LAST_CACHED_SEQ,
                               &status) < 0)
        return -1;
    seq = status.last_cached_seq + 1;

    trans = mailbox_transaction_begin(box, MAILBOX_TRANSACTION_FLAG_NO_CACHE_DEC);
    search_args = mail_search_build_init();
    mail_search_build_add_seqset(search_args, seq, status.messages);
    ctx = mailbox_search_init(trans, search_args, NULL,
                              metadata.precache_fields, NULL);
    mail_search_args_unref(&search_args);

    max = status.messages - seq + 1;
    while (mailbox_search_next(ctx, &mail)) {
        mail_precache(mail);
        if (++counter % 100 == 0) {
            percentage = counter*100 / max;
            if (percentage != percentage_sent && percentage < 100) {
                percentage_sent = percentage;
                if (i_snprintf(percentage_str,
                               sizeof(percentage_str), "%u\n",
                               percentage) < 0)
                    i_unreached();
                (void)write_full(conn->fd, percentage_str,
                                 strlen(percentage_str));
            }
            indexer_worker_refresh_proctitle(username, box_vname,
                                             counter, max);
        }
    }
    if (mailbox_search_deinit(&ctx) < 0)
        ret = -1;
    if (mailbox_transaction_commit(&trans) < 0)
        ret = -1;
    if (ret == 0) {
        i_info("Indexed %u messages in %s",
               counter, mailbox_get_vname(box));
    }
    return ret;
}
Exemple #17
0
static int uimage_flush(void *buf, unsigned int len)
{
	int ret;

	ret = write_full(uimage_fd, buf, len);

	return ret;
}
void mc_close2(void){
    uint64_t eof_flag = TLC_EOF_MARKER;
    
    if(write_full(mclient_fd2, &eof_flag, sizeof(uint64_t)) < 0){
        printf(" mc_close2: Error: Unsuccessful EOF key write %" PRIx64 "\n", (uint64_t) eof_flag);
    }
    close(mclient_fd2);
}
static int replication_notify_sync(struct mail_user *user)
{
	struct replication_user *ruser = REPLICATION_USER_CONTEXT(user);
	string_t *str;
	char buf[1024];
	int fd;
	ssize_t ret;

	fd = net_connect_unix(ruser->socket_path);
	if (fd == -1) {
		i_error("net_connect_unix(%s) failed: %m", ruser->socket_path);
		return -1;
	}
	net_set_nonblock(fd, FALSE);

	/* <username> \t "sync" */
	str = t_str_new(256);
	str_append_tabescaped(str, user->username);
	str_append(str, "\tsync\n");
	alarm(ruser->sync_secs);
	if (write_full(fd, str_data(str), str_len(str)) < 0) {
		i_error("write(%s) failed: %m", ruser->socket_path);
		ret = -1;
	} else {
		/* + | - */
		ret = read(fd, buf, sizeof(buf));
		if (ret < 0) {
			if (errno != EINTR) {
				i_error("read(%s) failed: %m",
					ruser->socket_path);
			} else {
				i_warning("replication(%s): Sync failure: "
					  "Timeout in %u secs",
					  user->username, ruser->sync_secs);
			}
		} else if (ret == 0) {
			i_error("read(%s) failed: EOF", ruser->socket_path);
			ret = -1;
		} else if (buf[0] == '+') {
			/* success */
			ret = 0;
		} else if (buf[0] == '-') {
			/* failure */
			if (buf[ret-1] == '\n') ret--;
			i_warning("replication(%s): Sync failure: %s",
				  user->username, t_strndup(buf+1, ret-1));
			ret = -1;
		} else {
			i_warning("replication(%s): "
				  "Remote sent invalid input: %s",
				  user->username, t_strndup(buf, ret));
		}
	}
	alarm(0);
	if (close(fd) < 0)
		i_error("close(%s) failed: %m", ruser->socket_path);
	return ret;
}
Exemple #20
0
static void client_connected(struct master_service_connection *conn)
{
	char response[2];

	response[0] = client_exec_script(conn) ? '+' : '-';
	response[1] = '\n';
	if (write_full(conn->fd, &response, 2) < 0)
		i_error("write(response) failed: %m");
}
Exemple #21
0
static int copy_to_temp_file(struct seekable_istream *sstream)
{
	struct istream_private *stream = &sstream->istream;
	const char *path;
	const unsigned char *buffer;
	size_t size;
	int fd;

	fd = sstream->fd_callback(&path, sstream->context);
	if (fd == -1)
		return -1;

	/* copy our currently read buffer to it */
	i_assert(stream->pos <= sstream->buffer_peak);
	if (write_full(fd, stream->buffer, sstream->buffer_peak) < 0) {
		if (!ENOSPACE(errno))
			i_error("istream-seekable: write_full(%s) failed: %m", path);
		i_close_fd(&fd);
		return -1;
	}
	sstream->temp_path = i_strdup(path);
	sstream->write_peak = sstream->buffer_peak;

	sstream->fd = fd;
	sstream->fd_input = i_stream_create_fd_autoclose(&fd,
		I_MAX(stream->pos, sstream->istream.max_buffer_size));
	i_stream_set_name(sstream->fd_input, t_strdup_printf(
		"(seekable temp-istream for: %s)", i_stream_get_name(&stream->istream)));

	/* read back the data we just had in our buffer */
	for (;;) {
		buffer = i_stream_get_data(sstream->fd_input, &size);
		if (size >= stream->pos)
			break;

		ssize_t ret;
		if ((ret = i_stream_read_memarea(sstream->fd_input)) <= 0) {
			i_assert(ret != 0);
			i_assert(ret != -2);
			i_error("istream-seekable: Couldn't read back "
				"in-memory input %s: %s",
				i_stream_get_name(&stream->istream),
				i_stream_get_error(sstream->fd_input));
			i_stream_destroy(&sstream->fd_input);
			i_close_fd(&sstream->fd);
			return -1;
		}
	}
	/* Set the max buffer size only after we've already read everything
	   into memory. For example with istream-data it's possible that
	   more data exists in buffer than max_buffer_size. */
	i_stream_set_max_buffer_size(sstream->fd_input,
				     sstream->istream.max_buffer_size);
	stream->buffer = buffer;
	i_stream_free_buffer(&sstream->istream);
	return 0;
}
void mc_close2(void){
    uint64_t eof_flag = TLC_EOF_MARKER;
    
    if(write_full(mclient_fd2, &eof_flag, sizeof(uint64_t)) < 0){
        printf(" mc_close2: Error: Unsuccessful EOF key write %" PRIx64 "\n", (uint64_t) eof_flag);
    }
    //printf(" mc_close: write eof\n");
    close(mclient_fd2);
    //shutdown(mclient_fd, SHUT_WR);
}
int memserver_send_eof(void){
  // Sending addr+flag and *ptr
  int ret;
  uint8_t *pp;
  ram_addr_t          addr = 0;

  addr= (addr|MY_EOF);
  ret = write_full(connected,&addr,sizeof(addr));
  return ret;
}
Exemple #24
0
/*
 * Hexadecimal dump in the canonical hex + ascii display
 * See -C option in man hexdump
 */
void
_log_hexdump(log_t *log,char *data, int datalen)
{
    struct log_t *l = log;
    char buf[MAX_LOG_LEN];
    int i, off, len, size, errno_save;

    if (l->logfile < 0) {
        return;
    }

    /* log hexdump */
    errno_save = errno;
    off = 0;                  /* data offset */
    len = 0;                  /* length of output buffer */
    size = MAX_LOG_LEN;   /* size of output buffer */

    while (datalen != 0 && (len < size - 1)) {
        char *save, *str;
        unsigned char c;
        int savelen;

        len += snprintf(buf + len, size - len, "%08x  ", off);

        save = data;
        savelen = datalen;

        for (i = 0; datalen != 0 && i < 16; data++, datalen--, i++) {
            c = (unsigned char)(*data);
            str = (char *)((i == 7) ? "  " : " ");
            len += snprintf(buf + len, size - len, "%02x%s", c, str);
        }
        for ( ; i < 16; i++) {
            str = (char *)((i == 7) ? "  " : " ");
            len += snprintf(buf + len, size - len, "  %s", str);
        }

        data = save;
        datalen = savelen;

        len += snprintf(buf + len, size - len, "  |");

        for (i = 0; datalen != 0 && i < 16; data++, datalen--, i++) {
            c = (unsigned char)(isprint(*data) ? *data : '.');
            len += snprintf(buf + len, size - len, "%c", c);
        }
        len += snprintf(buf + len, size - len, "|\n");

        off += 16;
    }

	write_full(l->logfile, buf, len); 
    errno = errno_save;
}
Exemple #25
0
static void
run_cmd(struct dsync_cmd_context *ctx, const char *const *args)
{
	int fd_in[2], fd_out[2], fd_err[2];

	if (pipe(fd_in) < 0 || pipe(fd_out) < 0 || pipe(fd_err) < 0)
		i_fatal("pipe() failed: %m");

	ctx->remote_pid = fork();
	switch (ctx->remote_pid) {
	case -1:
		i_fatal("fork() failed: %m");
	case 0:
		/* child, which will execute the proxy server. stdin/stdout
		   goes to pipes which we'll pass to proxy client. */
		if (dup2(fd_in[0], STDIN_FILENO) < 0 ||
		    dup2(fd_out[1], STDOUT_FILENO) < 0 ||
		    dup2(fd_err[1], STDERR_FILENO) < 0)
			i_fatal("dup2() failed: %m");

		i_close_fd(&fd_in[0]);
		i_close_fd(&fd_in[1]);
		i_close_fd(&fd_out[0]);
		i_close_fd(&fd_out[1]);
		i_close_fd(&fd_err[0]);
		i_close_fd(&fd_err[1]);

		execvp_const(args[0], args);
	default:
		/* parent */
		break;
	}

	i_close_fd(&fd_in[0]);
	i_close_fd(&fd_out[1]);
	i_close_fd(&fd_err[1]);
	ctx->fd_in = fd_out[0];
	ctx->fd_out = fd_in[1];
	ctx->fd_err = fd_err[0];

	if (ctx->remote_user_prefix) {
		const char *prefix =
			t_strdup_printf("%s\n", ctx->ctx.cur_username);
		if (write_full(ctx->fd_out, prefix, strlen(prefix)) < 0)
			i_fatal("write(remote out) failed: %m");
	}

	fd_set_nonblock(ctx->fd_err, TRUE);
	ctx->err_stream = i_stream_create_fd(ctx->fd_err, IO_BLOCK_SIZE, FALSE);
	i_stream_set_return_partial_line(ctx->err_stream, TRUE);
}
void ssl_generate_parameters(int fd, unsigned int dh_length, const char *fname)
{
	int bits;

	/* this fails in FIPS mode */
	(void)generate_dh_parameters(512, fd, fname);
	if (!generate_dh_parameters(dh_length, fd, fname)) {
		i_fatal("DH_generate_parameters(bits=%d, gen=%d) failed: %s",
			dh_length, DH_GENERATOR, ssl_last_error());
	}
	bits = 0;
	if (write_full(fd, &bits, sizeof(bits)) < 0)
		i_fatal("write_full() failed for file %s: %m", fname);
}
void mserv_base_close(void){
    int i;
    uint64_t eof_flag = TLC_EOF_MARKER;
    
    for(i = 0; i < chkpt_mserv_cnt; i++){
        if(write_full(base_chkpt_mserv_client_fd[i], &eof_flag, sizeof(uint64_t)) < 0){
          printf(" mserv_base_close: Error: Unsuccessful EOF key write %" PRIx64 "\n", (uint64_t) eof_flag);
        }
        //if(read_full(chkpt_mserv_client_fd[i], &ret_eof_flag, sizeof(uint64_t)) < 0){
        //  printf(" mserv_close: Unsuccessful EOF key read back %" PRIx64 "\n", (uint64_t) ret_eof_flag);
        //}
        //close(chkpt_mserv_client_fd[i]);
    }
}
static bool generate_dh_parameters(int bitsize, int fd, const char *fname)
{
        DH *dh = DH_generate_parameters(bitsize, DH_GENERATOR, NULL, NULL);
	unsigned char *buf, *p;
	int len;

	if (dh == NULL)
		return FALSE;

	len = i2d_DHparams(dh, NULL);
	if (len < 0)
		i_fatal("i2d_DHparams() failed: %s", ssl_last_error());

	buf = p = i_malloc(len);
	len = i2d_DHparams(dh, &p);

	if (write_full(fd, &bitsize, sizeof(bitsize)) < 0 ||
	    write_full(fd, &len, sizeof(len)) < 0 ||
	    write_full(fd, buf, len) < 0)
		i_fatal("write_full() failed for file %s: %m", fname);
	i_free(buf);
	return TRUE;
}
static bool stats_top_round(struct top_context *ctx)
{
#define TOP_CMD "EXPORT\tsession\tconnected\n"
	const char *const *args;
	pool_t tmp_pool;

	if (write_full(ctx->fd, TOP_CMD, strlen(TOP_CMD)) < 0)
		i_fatal("write(%s) failed: %m", ctx->path);

	/* read header */
	if (ctx->headers != NULL) {
		args = read_next_line(ctx->input);
		if (args == NULL)
			i_fatal("read(%s) unexpectedly disconnected", ctx->path);
		if (*args == NULL)
			return TRUE;
		if (str_array_length(args) != ctx->headers_count)
			i_fatal("headers changed");
	} else {
		ctx->headers = p_read_next_line(default_pool, ctx->input);
		if (ctx->headers == NULL)
			i_fatal("read(%s) unexpectedly disconnected", ctx->path);
		if (*ctx->headers == NULL) {
			i_free_and_null(ctx->headers);
			return FALSE;
		}
		ctx->headers_count = str_array_length((void *)ctx->headers);
		if (!stats_header_find(ctx, "last_update", &ctx->last_update_idx))
			i_fatal("last_update header missing");
		if (!stats_header_find(ctx, "user", &ctx->user_idx))
			i_fatal("user header missing");
		stats_top_get_sorting(ctx);
	}

	array_clear(&ctx->lines);
	p_clear(ctx->prev_pool);
	tmp_pool = ctx->prev_pool;
	ctx->prev_pool = ctx->cur_pool;
	ctx->cur_pool = tmp_pool;

	ctx->flip = !ctx->flip;
	stats_read(ctx);
	stats_drop_stale(ctx);

	sort_ctx = ctx;
	array_sort(&ctx->lines, *ctx->lines_sort);
	sort_ctx = NULL;
	return TRUE;
}
int vic_create_connection(int num_conn){
        char vic_message[150];
	int ret;

        if(vic_fd > 0){
            printf(" vic fd already exist = %d\n", vic_fd); 
            fflush(stdout);
            return -1;
        }

	vic_fd = socket(AF_INET, SOCK_STREAM, 0); 

	vic_addr.sin_family = AF_INET;
	
	if(vic_port != 0){
//printf(" VIC conn vic port = %d\n", vic_port); 
		vic_addr.sin_port = htons(vic_port);
	}
	else{
		vic_addr.sin_port = htons(MC_VIC_PORT);
	}
	
	if(vic_ip != NULL){
//printf(" VIC conn vic ip = %s\n", vic_ip); 
		vic_addr.sin_addr.s_addr = inet_addr(vic_ip);
	}
	else{
		vic_addr.sin_addr.s_addr = inet_addr(MC_VIC_IP_ADDR);
	}

	if((ret = connect_w(vic_fd, (struct sockaddr *) &vic_addr, sizeof(vic_addr))) < 0){
		printf("VIC Connect error occured errno = %d\n", errno);
		//exit(1); 
		vic_flag = 0;
	}
        // register to vic server

        if(vic_flag == 1){
                strcpy(vic_message, "vmRegis vm001\0");

        	printf(" vic_connect: sending a message %s\n", vic_message);
        	if((ret = write_full(vic_fd, vic_message, strlen(vic_message))) < 0){
            		printf(" vic_connect: Error: fail sending a message %s\n", vic_message);
			vic_flag = 0;
        	}
	}

	return ret;
}