示例#1
0
int main (int argc, char *argv[])
{
	char    psBuffer[BUFFER_SIZE];
	char    psGnuplotCommandLine[MAX_PATH] = PROGNAME;
	LPTSTR  psCmdLine;
	BOOL    bSuccess;
	
	/* HBB 19990325, to allow pgnuplot < script > output.gif */
	_setmode(fileno(stdout), _O_BINARY);

	/* CRS: create the new command line, passing all of the command
	 * line options to wgnuplot so that it can process them:
	 * first, get the command line,
	 * then move past the name of the program (e.g., 'pgnuplot'),
	 * finally, add what's left of the line onto the gnuplot command line. */
	psCmdLine = GetCommandLine();

#ifdef SHOWCMDLINE
	fprintf(stderr,"CmdLine: %s\n", psCmdLine);
	fprintf(stderr,"argv[0]: %s\n",argv[0]);
#endif

	/* CRS 30061999: Search for the first unquoted space. This should 
	   separate the program name from the arguments. */
	psCmdLine = FindUnquotedSpace( psCmdLine );

	strncat(psGnuplotCommandLine, psCmdLine, MAX_PATH - strlen(psGnuplotCommandLine));

#ifdef SHOWCMDLINE
	fprintf(stderr,"Arguments: %s\n", psCmdLine);
	fprintf(stderr,"GnuplotCommandLine: %s\n",psGnuplotCommandLine);
#endif

	/* CRS: if stdin isn't redirected then just launch wgnuplot normally
	 * and exit. */
	if ( isatty(fileno(stdin)) ) {
		if ( WinExec(psGnuplotCommandLine, SW_SHOWDEFAULT) > 31 ){
			exit(EXIT_SUCCESS);
		}
		fprintf(stderr,"ERROR %u: Couldn't execute: \"%s\"\n", 
			    GetLastError(), psGnuplotCommandLine);
		exit(EXIT_FAILURE);
	}

	/* CRS: initialize the STARTUPINFO and call CreateProcess(). */ 
	siStartInfo.cb = sizeof(STARTUPINFO); 
	siStartInfo.lpReserved = NULL; 
	siStartInfo.lpReserved2 = NULL; 
	siStartInfo.cbReserved2 = 0; 
	siStartInfo.lpDesktop = NULL; 
	siStartInfo.dwFlags = STARTF_USESHOWWINDOW;
	siStartInfo.wShowWindow = SW_SHOWMINIMIZED;

	bSuccess = CreateProcess( 
			NULL,                   /* pointer to name of executable module   */
			psGnuplotCommandLine,   /* pointer to command line string         */
			NULL,                   /* pointer to process security attributes */
			NULL,                   /* pointer to thread security attributes  */
			FALSE,                  /* handle inheritance flag                */
			0,                      /* creation flags                         */
			NULL,                   /* pointer to new environment block       */
			NULL,                   /* pointer to current directory name      */
			&siStartInfo,           /* pointer to STARTUPINFO                 */
			&piProcInfo             /* pointer to PROCESS_INFORMATION         */
			);

	/* if CreateProcess() failed, print a warning and exit. */
	if ( ! bSuccess ) {
		fprintf(stderr,"ERROR %u: Couldn't execute: \"%s\"\n", 
						GetLastError(), psGnuplotCommandLine);
		exit(EXIT_FAILURE);
	}

	/* CRS: give gnuplot enough time to start (1 sec.) */
	if ( WaitForInputIdle(piProcInfo.hProcess, 1000) ) {
		fprintf(stderr, "Timeout: gnuplot is not ready\n");
		exit(EXIT_FAILURE);
	}

	/* CRS: get the HWND of the parent window and text windows */
	EnumThreadWindows(piProcInfo.dwThreadId, cbGetTextWindow, 0);

	/* CRS: free the process and thread handles */
	CloseHandle(piProcInfo.hProcess);
	CloseHandle(piProcInfo.hThread);

	if ( ! hwndParent || ! hwndText ) {
	/* Still no gnuplot window? Problem! */
		fprintf(stderr, "Can't find the gnuplot window");
		exit(EXIT_FAILURE);
	}

	/* wait for commands on stdin, and pass them on to the wgnuplot text
	 * window */
	while ( fgets(psBuffer, BUFFER_SIZE, stdin) != NULL ) {
		PostString(hwndText, psBuffer);
	}
	
	/* exit gracefully */
	/* CRS: Add a test to see if gnuplot is still running? */
	PostString(hwndText, "\nexit\n");

	return EXIT_SUCCESS;
}
示例#2
0
/*
 * This routine looks for the file in the local index directory
 * ("/tmp/indsvr/<filename>") and sends back the host names to uphost.
 *
 * It sends one RPC call with MAXCOUNT hosts in each of them.
 */
int
send_local_cache(char *fname_req, msg_id id, char *uphost)
{
    b_hitquery_reply res;
    char fname[MAXPATHLEN];
    char *p;
    FILE *fh;
    int fd;
    CLIENT *clnt;
    enum clnt_stat ret;
    int tmp;

    if (!fname_req || !uphost) {
        return (SUCCESS);
    }

    sprintf(fname, "%s/%s", SERVER_DIR, fname_req);

    fh = fopen(fname, "r");
    if (fh == NULL) {
        printf("send_local_cache: Failed to open filename %s : errno = %d\n", fname, errno);
        return SUCCESS;
    }

    fd = fileno(fh);

    clnt = clnt_create(uphost, OBTAINPROG, OBTAINVER, "tcp");
    if (clnt == NULL) {
        clnt_pcreateerror(uphost);
        fclose(fh);
        close(fd);
        printf("send_local_cache(): Failed to contact hitquery to : %s\n", uphost);
        return FAILED;
    }

    if (clnt_control(clnt, CLSET_TIMEOUT, (char *)&zero_timeout) == FALSE) {
        printf("Failed to set the timeout value to zero\n");
        printf("Cannot make one-way RPC call :-(\n");
    }

    flock(fd, LOCK_SH);

    res.id = id;
    strcpy(res.fname, fname_req);
    res.cnt = 0;
    p = res.hosts; 
    
    while (fscanf(fh, "%s\n", p) != EOF) {
        res.cnt++;
        if (res.cnt == MAXCOUNT) {
            flock(fd, LOCK_UN);
            /*
             * Make one-way RPC call to send the response back.
             */
#ifdef DEBUG
            printf("send_local_cache: Sending response to %s for file %s\n", uphost, res.fname);
#endif
            ret = b_hitquery_1(&res, &tmp, clnt);
            if (ret != RPC_SUCCESS && ret != RPC_TIMEDOUT) {
                clnt_perror(clnt, "b_hitquery failed");
            }
            res.cnt = 0;
            flock(fd, LOCK_SH);
        }
        p += MAXHOSTNAME;
    }

    flock(fd, LOCK_UN);
    fclose(fh);
    close(fd);

    ret = b_hitquery_1(&res, &tmp, clnt);
    if (ret != RPC_SUCCESS && ret != RPC_TIMEDOUT) {
        clnt_perror(clnt, "b_hitquery failed");
    }

    clnt_destroy(clnt);
}
示例#3
0
文件: log.c 项目: Milstein/ovs
struct ovsdb_error *
ovsdb_log_write(struct ovsdb_log *file, struct json *json)
{
    uint8_t sha1[SHA1_DIGEST_SIZE];
    struct ovsdb_error *error;
    char *json_string;
    char header[128];
    size_t length;

    json_string = NULL;

    if (file->mode == OVSDB_LOG_READ || file->write_error) {
        file->mode = OVSDB_LOG_WRITE;
        file->write_error = false;
        if (fseeko(file->stream, file->offset, SEEK_SET)) {
            error = ovsdb_io_error(errno, "%s: cannot seek to offset %lld",
                                   file->name, (long long int) file->offset);
            goto error;
        }
        if (ftruncate(fileno(file->stream), file->offset)) {
            error = ovsdb_io_error(errno, "%s: cannot truncate to length %lld",
                                   file->name, (long long int) file->offset);
            goto error;
        }
    }

    if (json->type != JSON_OBJECT && json->type != JSON_ARRAY) {
        error = OVSDB_BUG("bad JSON type");
        goto error;
    }

    /* Compose content.  Add a new-line (replacing the null terminator) to make
     * the file easier to read, even though it has no semantic value.  */
    json_string = json_to_string(json, 0);
    length = strlen(json_string) + 1;
    json_string[length - 1] = '\n';

    /* Compose header. */
    sha1_bytes(json_string, length, sha1);
    snprintf(header, sizeof header, "%s%"PRIuSIZE" "SHA1_FMT"\n",
             magic, length, SHA1_ARGS(sha1));

    /* Write. */
    if (fwrite(header, strlen(header), 1, file->stream) != 1
        || fwrite(json_string, length, 1, file->stream) != 1
        || fflush(file->stream))
    {
        error = ovsdb_io_error(errno, "%s: write failed", file->name);

        /* Remove any partially written data, ignoring errors since there is
         * nothing further we can do. */
        ignore(ftruncate(fileno(file->stream), file->offset));

        goto error;
    }

    file->offset += strlen(header) + length;
    free(json_string);
    return NULL;

error:
    file->write_error = true;
    free(json_string);
    return error;
}
示例#4
0
static void
sl (void)
{
  FILE *f = fopen (pidfile, "w");
  if (f == NULL)
    exit (1);

  fprintf (f, "%lld\n", (long long) getpid ());
  fflush (f);

  struct flock fl =
    {
      .l_type = F_WRLCK,
      .l_start = 0,
      .l_whence = SEEK_SET,
      .l_len = 1
    };
  if (fcntl (fileno (f), F_SETLK, &fl) != 0)
    exit (1);

  sigset_t ss;
  sigfillset (&ss);
  sigsuspend (&ss);
  exit (0);
}


static void
do_prepare (int argc, char *argv[])
{
  if (command == NULL)
    command = argv[0];

  if (pidfile)
    sl ();

  int fd = mkstemp (pidfilename);
  if (fd == -1)
    {
      puts ("mkstemp failed");
      exit (1);
    }

  write (fd, " ", 1);
  close (fd);
}


static int
do_test (void)
{
  pthread_t th;
  if (pthread_create (&th, NULL, tf, NULL) != 0)
    {
      puts ("pthread_create failed");
      return 1;
    }

  do
    sleep (1);
  while (access (pidfilename, R_OK) != 0);

  if (pthread_cancel (th) != 0)
    {
      puts ("pthread_cancel failed");
      return 1;
    }

  void *r;
  if (pthread_join (th, &r) != 0)
    {
      puts ("pthread_join failed");
      return 1;
    }

  sleep (1);

  FILE *f = fopen (pidfilename, "r+");
  if (f == NULL)
    {
      puts ("no pidfile");
      return 1;
    }

  long long ll;
  if (fscanf (f, "%lld\n", &ll) != 1)
    {
      puts ("could not read pid");
      unlink (pidfilename);
      return 1;
    }

  struct flock fl =
    {
      .l_type = F_WRLCK,
      .l_start = 0,
      .l_whence = SEEK_SET,
      .l_len = 1
    };
  if (fcntl (fileno (f), F_GETLK, &fl) != 0)
    {
      puts ("F_GETLK failed");
      unlink (pidfilename);
      return 1;
    }

  if (fl.l_type != F_UNLCK)
    {
      printf ("child %lld still running\n", (long long) fl.l_pid);
      if (fl.l_pid == ll)
	kill (fl.l_pid, SIGKILL);

      unlink (pidfilename);
      return 1;
    }

  fclose (f);

  unlink (pidfilename);

  return r != PTHREAD_CANCELED;
}

static void
do_cleanup (void)
{
  FILE *f = fopen (pidfilename, "r+");
  long long ll;

  if (f != NULL && fscanf (f, "%lld\n", &ll) == 1)
    {
      struct flock fl =
	{
	  .l_type = F_WRLCK,
	  .l_start = 0,
	  .l_whence = SEEK_SET,
	  .l_len = 1
	};
      if (fcntl (fileno (f), F_GETLK, &fl) == 0 && fl.l_type != F_UNLCK
	  && fl.l_pid == ll)
	kill (fl.l_pid, SIGKILL);

      fclose (f);
    }

  unlink (pidfilename);
}
示例#5
0
void
__fex_mklog(ucontext_t *uap, char *addr, int f, enum fex_exception e,
    int m, void *p)
{
	struct	frame	*fp;
	char		*stk, *name, buf[30];
	int		fd;

	/* if logging is disabled, just return */
	mutex_lock(&log_lock);
	if (log_fp == NULL) {
		mutex_unlock(&log_lock);
		return;
	}

	/* get stack info */
#if defined(__sparc)
	stk = (char*)uap->uc_mcontext.gregs[REG_PC];
	fp = FRAMEP(uap->uc_mcontext.gregs[REG_SP]);
#elif defined(__amd64)
	stk = (char*)uap->uc_mcontext.gregs[REG_PC];
	fp = FRAMEP(uap->uc_mcontext.gregs[REG_RBP]);
#elif defined(__i386)	/* !defined(__amd64) */
	stk = (char*)uap->uc_mcontext.gregs[PC];
	fp = FRAMEP(uap->uc_mcontext.gregs[EBP]);
#else
#error Unknown architecture
#endif

	/* if the handling mode is the default and this exception's
	   flag is already raised, don't make an entry */
	if (m == FEX_NONSTOP) {
		switch (e) {
		case fex_inexact:
			if (f & FE_INEXACT) {
				mutex_unlock(&log_lock);
				return;
			}
			break;
		case fex_underflow:
			if (f & FE_UNDERFLOW) {
				mutex_unlock(&log_lock);
				return;
			}
			break;
		case fex_overflow:
			if (f & FE_OVERFLOW) {
				mutex_unlock(&log_lock);
				return;
			}
			break;
		case fex_division:
			if (f & FE_DIVBYZERO) {
				mutex_unlock(&log_lock);
				return;
			}
			break;
		default:
			if (f & FE_INVALID) {
				mutex_unlock(&log_lock);
				return;
			}
			break;
		}
	}

	/* if we've already logged this exception at this address,
	   don't make an entry */
	if (check_exc_list(addr, (unsigned long)e, stk, fp)) {
		mutex_unlock(&log_lock);
		return;
	}

	/* make an entry */
	fd = fileno(log_fp);
	write(fd, "Floating point ", 15);
	write(fd, exception[e], strlen(exception[e]));
	write(fd, buf, sprintf(buf, " at 0x%0" PDIG "lx", (long)addr));
	__fex_sym_init();
	if (__fex_sym(addr, &name) != NULL) {
		write(fd, " ", 1);
		write(fd, name, strlen(name));
	}
	switch (m) {
	case FEX_NONSTOP:
		write(fd, ", nonstop mode\n", 15);
		break;

	case FEX_ABORT:
		write(fd, ", abort\n", 8);
		break;

	case FEX_NOHANDLER:
		if (p == (void *)SIG_DFL) {
			write(fd, ", handler: SIG_DFL\n", 19);
			break;
		}
		else if (p == (void *)SIG_IGN) {
			write(fd, ", handler: SIG_IGN\n", 19);
			break;
		}
		/* fall through*/
	default:
		write(fd, ", handler: ", 11);
		if (__fex_sym((char *)p, &name) != NULL) {
			write(fd, name, strlen(name));
			write(fd, "\n", 1);
		} else {
			write(fd, buf, sprintf(buf, "0x%0" PDIG "lx\n",
			    (long)p));
		}
		break;
	}
	print_stack(fd, stk, fp);
	mutex_unlock(&log_lock);
}
示例#6
0
/*!
  @abstract Sort an unsorted BAM file based on the chromosome order
  and the leftmost position of an alignment

  @param  is_by_qname whether to sort by query name
  @param  fn       name of the file to be sorted
  @param  prefix   prefix of the output and the temporary files; upon
	                   sucessess, prefix.bam will be written.
  @param  max_mem  approxiate maximum memory (very inaccurate)

  @discussion It may create multiple temporary subalignment files
  and then merge them by calling bam_merge_core(). This function is
  NOT thread safe.
 */
void bam_sort_core_ext(int is_by_qname, const char *fn, const char *prefix, size_t _max_mem, int is_stdout, int n_threads, int level)
{
	int ret, i, n_files = 0;
	size_t mem, max_k, k, max_mem;
	bam_header_t *header;
	bamFile fp;
	bam1_t *b, **buf;
	char *fnout = 0;

	if (n_threads < 2) n_threads = 1;
	g_is_by_qname = is_by_qname;
	max_k = k = 0; mem = 0;
	max_mem = _max_mem * n_threads;
	buf = 0;
	fp = strcmp(fn, "-")? bam_open(fn, "r") : bam_dopen(fileno(stdin), "r");
	if (fp == 0) {
		fprintf(stderr, "[bam_sort_core] fail to open file %s\n", fn);
		return;
	}
	header = bam_header_read(fp);
	if (is_by_qname) change_SO(header, "queryname");
	else change_SO(header, "coordinate");
	// write sub files
	for (;;) {
		if (k == max_k) {
			size_t old_max = max_k;
			max_k = max_k? max_k<<1 : 0x10000;
			buf = realloc(buf, max_k * sizeof(void*));
			memset(buf + old_max, 0, sizeof(void*) * (max_k - old_max));
		}
		if (buf[k] == 0) buf[k] = (bam1_t*)calloc(1, sizeof(bam1_t));
		b = buf[k];
		if ((ret = bam_read1(fp, b)) < 0) break;
		if (b->data_len < b->m_data>>2) { // shrink
			b->m_data = b->data_len;
			kroundup32(b->m_data);
			b->data = realloc(b->data, b->m_data);
		}
		mem += sizeof(bam1_t) + b->m_data + sizeof(void*) + sizeof(void*); // two sizeof(void*) for the data allocated to pointer arrays
		++k;
		if (mem >= max_mem) {
			n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads);
			mem = k = 0;
		}
	}
	if (ret != -1)
		fprintf(stderr, "[bam_sort_core] truncated file. Continue anyway.\n");
	// output file name
	fnout = calloc(strlen(prefix) + 20, 1);
	if (is_stdout) sprintf(fnout, "-");
	else sprintf(fnout, "%s.bam", prefix);
	// write the final output
	if (n_files == 0) { // a single block
		char mode[8];
		strcpy(mode, "w");
		if (level >= 0) sprintf(mode + 1, "%d", level < 9? level : 9);
		ks_mergesort(sort, k, buf, 0);
		write_buffer(fnout, mode, k, buf, header, n_threads);
	} else { // then merge
		char **fns;
		n_files = sort_blocks(n_files, k, buf, prefix, header, n_threads);
		fprintf(stderr, "[bam_sort_core] merging from %d files...\n", n_files);
		fns = (char**)calloc(n_files, sizeof(char*));
		for (i = 0; i < n_files; ++i) {
			fns[i] = (char*)calloc(strlen(prefix) + 20, 1);
			sprintf(fns[i], "%s.%.4d.bam", prefix, i);
		}
		bam_merge_core2(is_by_qname, fnout, 0, n_files, fns, 0, 0, n_threads, level);
		for (i = 0; i < n_files; ++i) {
			unlink(fns[i]);
			free(fns[i]);
		}
		free(fns);
	}
	free(fnout);
	// free
	for (k = 0; k < max_k; ++k) {
		if (!buf[k]) continue;
		free(buf[k]->data);
		free(buf[k]);
	}
	free(buf);
	bam_header_destroy(header);
	bam_close(fp);
}
示例#7
0
static int
update_usersfile (const char *usersfile,
		  const char *username,
		  const char *otp,
		  FILE * infh,
		  char **lineptr,
		  size_t * n, char *timestamp, uint64_t new_moving_factor)
{
  FILE *outfh, *lockfh;
  int rc;
  char *newfilename, *lockfile;

  /* Rewind input file. */
  {
    int pos;

    pos = fseeko (infh, 0L, SEEK_SET);
    if (pos == -1)
      return OATH_FILE_SEEK_ERROR;
    clearerr (infh);
  }

  /* Open lockfile. */
  {
    int l;

    l = asprintf (&lockfile, "%s.lock", usersfile);
    if (lockfile == NULL || ((size_t) l) != strlen (usersfile) + 5)
      return OATH_PRINTF_ERROR;

    lockfh = fopen (lockfile, "w");
    if (!lockfh)
      {
	free (lockfile);
	return OATH_FILE_CREATE_ERROR;
      }
  }

  /* Lock the lockfile. */
  {
    struct flock l;

    memset (&l, 0, sizeof (l));
    l.l_whence = SEEK_SET;
    l.l_start = 0;
    l.l_len = 0;
    l.l_type = F_WRLCK;

    while ((rc = fcntl (fileno (lockfh), F_SETLKW, &l)) < 0 && errno == EINTR)
      continue;
    if (rc == -1)
      {
	fclose (lockfh);
	free (lockfile);
	return OATH_FILE_LOCK_ERROR;
      }
  }

  /* Open the "new" file. */
  {
    int l;

    l = asprintf (&newfilename, "%s.new", usersfile);
    if (newfilename == NULL || ((size_t) l) != strlen (usersfile) + 4)
      {
	fclose (lockfh);
	free (lockfile);
	return OATH_PRINTF_ERROR;
      }

    outfh = fopen (newfilename, "w");
    if (!outfh)
      {
	free (newfilename);
	fclose (lockfh);
	free (lockfile);
	return OATH_FILE_CREATE_ERROR;
      }
  }

  rc = update_usersfile2 (username, otp, infh, outfh, lineptr, n,
			  timestamp, new_moving_factor);

  fclose (lockfh);
  fclose (outfh);

  {
    int tmprc1, tmprc2;

    tmprc1 = rename (newfilename, usersfile);
    free (newfilename);

    tmprc2 = unlink (lockfile);
    free (lockfile);

    if (tmprc1 == -1)
      return OATH_FILE_RENAME_ERROR;
    if (tmprc2 == -1)
      return OATH_FILE_UNLINK_ERROR;
  }

  return rc;
}
示例#8
0
int main(int argc, char **argv)
{
    int c, compress, pstdout, is_forced, index = 0, reindex = 0;
    BGZF *fp;
    void *buffer;
    long start, end, size;
    char *index_fname = NULL;

    static struct option loptions[] =
    {
        {"help",0,0,'h'},
        {"offset",1,0,'b'},
        {"stdout",0,0,'c'},
        {"decompress",0,0,'d'},
        {"force",0,0,'f'},
        {"index",0,0,'i'},
        {"index-name",1,0,'I'},
        {"reindex",0,0,'r'},
        {"size",1,0,'s'},
        {0,0,0,0}
    };

    compress = 1; pstdout = 0; start = 0; size = -1; end = -1; is_forced = 0;
    while((c  = getopt_long(argc, argv, "cdh?fb:s:iI:r",loptions,NULL)) >= 0){
        switch(c){
        case 'd': compress = 0; break;
        case 'c': pstdout = 1; break;
        case 'b': start = atol(optarg); compress = 0; pstdout = 1; break;
        case 's': size = atol(optarg); pstdout = 1; break;
        case 'f': is_forced = 1; break;
        case 'i': index = 1; break;
        case 'I': index_fname = optarg; break;
        case 'r': reindex = 1; compress = 0; break;
        case 'h':
        case '?': return bgzip_main_usage();
        }
    }
    if (size >= 0) end = start + size;
    if (end >= 0 && end < start) {
        fprintf(stderr, "[bgzip] Illegal region: [%ld, %ld]\n", start, end);
        return 1;
    }
    if (compress == 1) {
        struct stat sbuf;
        int f_src = fileno(stdin);
        int f_dst = fileno(stdout);

        if ( argc>optind )
        {
            if ( stat(argv[optind],&sbuf)<0 )
            {
                fprintf(stderr, "[bgzip] %s: %s\n", strerror(errno), argv[optind]);
                return 1;
            }

            if ((f_src = open(argv[optind], O_RDONLY)) < 0) {
                fprintf(stderr, "[bgzip] %s: %s\n", strerror(errno), argv[optind]);
                return 1;
            }

            if (pstdout)
                f_dst = fileno(stdout);
            else
            {
                char *name = malloc(strlen(argv[optind]) + 5);
                strcpy(name, argv[optind]);
                strcat(name, ".gz");
                f_dst = write_open(name, is_forced);
                free(name);
                if (f_dst < 0) return 1;
            }
        }
        else if (!pstdout && isatty(fileno((FILE *)stdout)) )
            return bgzip_main_usage();
        else if ( index && !index_fname )
        {
            fprintf(stderr, "[bgzip] Index file name expected when writing to stdout\n");
            return 1;
        }

        fp = bgzf_fdopen(f_dst, "w");
        if ( index ) bgzf_index_build_init(fp);
        buffer = malloc(WINDOW_SIZE);
        while ((c = read(f_src, buffer, WINDOW_SIZE)) > 0)
            if (bgzf_write(fp, buffer, c) < 0) error("Could not write %d bytes: Error %d\n", c, fp->errcode);
        // f_dst will be closed here
        if ( index )
        {
            if ( index_fname ) bgzf_index_dump(fp, index_fname, NULL);
            else bgzf_index_dump(fp, argv[optind], ".gz.gzi");
        }
        if (bgzf_close(fp) < 0) error("Close failed: Error %d", fp->errcode);
        if (argc > optind && !pstdout) unlink(argv[optind]);
        free(buffer);
        close(f_src);
        return 0;
    }
    else if ( reindex )
    {
        if ( argc>optind )
        {
            fp = bgzf_open(argv[optind], "r");
            if ( !fp ) error("[bgzip] Could not open file: %s\n", argv[optind]);
        }
        else
        {
            if ( !index_fname ) error("[bgzip] Index file name expected when reading from stdin\n");
            fp = bgzf_fdopen(fileno(stdin), "r");
            if ( !fp ) error("[bgzip] Could not read from stdin: %s\n", strerror(errno));
        }

        buffer = malloc(BGZF_BLOCK_SIZE);
        bgzf_index_build_init(fp);
        int ret;
        while ( (ret=bgzf_read(fp, buffer, BGZF_BLOCK_SIZE))>0 ) ;
        free(buffer);
        if ( ret<0 ) error("Is the file gzipped or bgzipped? The latter is required for indexing.\n");

        if ( index_fname )
            bgzf_index_dump(fp, index_fname, NULL);
        else
            bgzf_index_dump(fp, argv[optind], ".gzi");

        if ( bgzf_close(fp)<0 ) error("Close failed: Error %d\n",fp->errcode);
        return 0;
    }
    else
    {
        struct stat sbuf;
        int f_dst;

        if ( argc>optind )
        {
            if ( stat(argv[optind],&sbuf)<0 )
            {
                fprintf(stderr, "[bgzip] %s: %s\n", strerror(errno), argv[optind]);
                return 1;
            }
            char *name;
            int len = strlen(argv[optind]);
            if ( strcmp(argv[optind]+len-3,".gz") )
            {
                fprintf(stderr, "[bgzip] %s: unknown suffix -- ignored\n", argv[optind]);
                return 1;
            }
            fp = bgzf_open(argv[optind], "r");
            if (fp == NULL) {
                fprintf(stderr, "[bgzip] Could not open file: %s\n", argv[optind]);
                return 1;
            }

            if (pstdout) {
                f_dst = fileno(stdout);
            }
            else {
                name = strdup(argv[optind]);
                name[strlen(name) - 3] = '\0';
                f_dst = write_open(name, is_forced);
                free(name);
            }
        }
        else if (!pstdout && isatty(fileno((FILE *)stdin)) )
            return bgzip_main_usage();
        else
        {
            f_dst = fileno(stdout);
            fp = bgzf_fdopen(fileno(stdin), "r");
            if (fp == NULL) {
                fprintf(stderr, "[bgzip] Could not read from stdin: %s\n", strerror(errno));
                return 1;
            }
        }
        buffer = malloc(WINDOW_SIZE);
        if ( start>0 )
        {
            if ( bgzf_index_load(fp, argv[optind], ".gzi") < 0 ) error("Could not load index: %s.gzi\n", argv[optind]);
            if ( bgzf_useek(fp, start, SEEK_SET) < 0 ) error("Could not seek to %d-th (uncompressd) byte\n", start);
        }
        while (1) {
            if (end < 0) c = bgzf_read(fp, buffer, WINDOW_SIZE);
            else c = bgzf_read(fp, buffer, (end - start > WINDOW_SIZE)? WINDOW_SIZE:(end - start));
            if (c == 0) break;
            if (c < 0) error("Could not read %d bytes: Error %d\n", (end - start > WINDOW_SIZE)? WINDOW_SIZE:(end - start), fp->errcode);
            start += c;
            if ( write(f_dst, buffer, c) != c ) error("Could not write %d bytes\n", c);
            if (end >= 0 && start >= end) break;
        }
        free(buffer);
        if (bgzf_close(fp) < 0) error("Close failed: Error %d\n",fp->errcode);
        if (!pstdout) unlink(argv[optind]);
        return 0;
    }
    return 0;
}
示例#9
0
/* Read a sets of private DSA keys from a FILE* into the given
 * OtrlUserState.  The FILE* must be open for reading. */
gcry_error_t otrl_privkey_read_FILEp(OtrlUserState us, FILE *privf)
{
    int privfd;
    struct stat st;
    char *buf;
    const char *token;
    size_t tokenlen;
    gcry_error_t err;
    gcry_sexp_t allkeys;
    size_t i;

    if (!privf) return gcry_error(GPG_ERR_NO_ERROR);

    /* Release any old ideas we had about our keys */
    otrl_privkey_forget_all(us);

    /* Load the data into a buffer */
    privfd = fileno(privf);
    if (fstat(privfd, &st)) {
	err = gcry_error_from_errno(errno);
	return err;
    }
    buf = malloc(st.st_size);
    if (!buf && st.st_size > 0) {
	return gcry_error(GPG_ERR_ENOMEM);
    }
    if (fread(buf, st.st_size, 1, privf) != 1) {
	err = gcry_error_from_errno(errno);
	free(buf);
	return err;
    }

    err = gcry_sexp_new(&allkeys, buf, st.st_size, 0);
    free(buf);
    if (err) {
	return err;
    }

    token = gcry_sexp_nth_data(allkeys, 0, &tokenlen);
    if (tokenlen != 8 || strncmp(token, "privkeys", 8)) {
	gcry_sexp_release(allkeys);
	return gcry_error(GPG_ERR_UNUSABLE_SECKEY);
    }

    /* Get each account */
    for(i=1; i<gcry_sexp_length(allkeys); ++i) {
	gcry_sexp_t names, protos, privs;
	char *name, *proto;
	gcry_sexp_t accounts;
	OtrlPrivKey *p;
	
	/* Get the ith "account" S-exp */
	accounts = gcry_sexp_nth(allkeys, i);
	
	/* It's really an "account" S-exp? */
	token = gcry_sexp_nth_data(accounts, 0, &tokenlen);
	if (tokenlen != 7 || strncmp(token, "account", 7)) {
	    gcry_sexp_release(accounts);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_UNUSABLE_SECKEY);
	}
	/* Extract the name, protocol, and privkey S-exps */
	names = gcry_sexp_find_token(accounts, "name", 0);
	protos = gcry_sexp_find_token(accounts, "protocol", 0);
	privs = gcry_sexp_find_token(accounts, "private-key", 0);
	gcry_sexp_release(accounts);
	if (!names || !protos || !privs) {
	    gcry_sexp_release(names);
	    gcry_sexp_release(protos);
	    gcry_sexp_release(privs);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_UNUSABLE_SECKEY);
	}
	/* Extract the actual name and protocol */
	token = gcry_sexp_nth_data(names, 1, &tokenlen);
	if (!token) {
	    gcry_sexp_release(names);
	    gcry_sexp_release(protos);
	    gcry_sexp_release(privs);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_UNUSABLE_SECKEY);
	}
	name = malloc(tokenlen + 1);
	if (!name) {
	    gcry_sexp_release(names);
	    gcry_sexp_release(protos);
	    gcry_sexp_release(privs);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_ENOMEM);
	}
	memmove(name, token, tokenlen);
	name[tokenlen] = '\0';
	gcry_sexp_release(names);

	token = gcry_sexp_nth_data(protos, 1, &tokenlen);
	if (!token) {
	    free(name);
	    gcry_sexp_release(protos);
	    gcry_sexp_release(privs);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_UNUSABLE_SECKEY);
	}
	proto = malloc(tokenlen + 1);
	if (!proto) {
	    free(name);
	    gcry_sexp_release(protos);
	    gcry_sexp_release(privs);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_ENOMEM);
	}
	memmove(proto, token, tokenlen);
	proto[tokenlen] = '\0';
	gcry_sexp_release(protos);

	/* Make a new OtrlPrivKey entry */
	p = malloc(sizeof(*p));
	if (!p) {
	    free(name);
	    free(proto);
	    gcry_sexp_release(privs);
	    gcry_sexp_release(allkeys);
	    return gcry_error(GPG_ERR_ENOMEM);
	}

	/* Fill it in and link it up */
	p->accountname = name;
	p->protocol = proto;
	p->pubkey_type = OTRL_PUBKEY_TYPE_DSA;
	p->privkey = privs;
	p->next = us->privkey_root;
	if (p->next) {
	    p->next->tous = &(p->next);
	}
	p->tous = &(us->privkey_root);
	us->privkey_root = p;
	err = make_pubkey(&(p->pubkey_data), &(p->pubkey_datalen), p->privkey);
	if (err) {
	    gcry_sexp_release(allkeys);
	    otrl_privkey_forget(p);
	    return gcry_error(GPG_ERR_UNUSABLE_SECKEY);
	}
    }
    gcry_sexp_release(allkeys);

    return gcry_error(GPG_ERR_NO_ERROR);
}
示例#10
0
int main(int argc, char **argv) {
    int i, n;
    char **origenv;
    char **newenv;
    char *cwd;
    FILE *log = fopen(abs_builddir "/commandhelper.log", "w");

    if (!log)
        goto error;

    for (i = 1 ; i < argc ; i++) {
        fprintf(log, "ARG:%s\n", argv[i]);
    }

    origenv = environ;
    n = 0;
    while (*origenv != NULL) {
        n++;
        origenv++;
    }

    if (VIR_ALLOC_N(newenv, n) < 0) {
        exit(EXIT_FAILURE);
    }

    origenv = environ;
    n = i = 0;
    while (*origenv != NULL) {
        newenv[i++] = *origenv;
        n++;
        origenv++;
    }
    qsort(newenv, n, sizeof(newenv[0]), envsort);

    for (i = 0 ; i < n ; i++) {
        /* Ignore the variables used to instruct the loader into
         * behaving differently, as they could throw the tests off. */
        if (!STRPREFIX(newenv[i], "LD_"))
            fprintf(log, "ENV:%s\n", newenv[i]);
    }

    for (i = 0 ; i < sysconf(_SC_OPEN_MAX) ; i++) {
        int f;
        int closed;
        if (i == fileno(log))
            continue;
        closed = fcntl(i, F_GETFD, &f) == -1 &&
            errno == EBADF;
        if (!closed)
            fprintf(log, "FD:%d\n", i);
    }

    fprintf(log, "DAEMON:%s\n", getpgrp() == getsid(0) ? "yes" : "no");
    if (!(cwd = getcwd(NULL, 0)))
        return EXIT_FAILURE;
    if (strlen(cwd) > strlen(".../commanddata") &&
        STREQ(cwd + strlen(cwd) - strlen("/commanddata"), "/commanddata"))
        strcpy(cwd, ".../commanddata");
    fprintf(log, "CWD:%s\n", cwd);
    VIR_FREE(cwd);

    VIR_FORCE_FCLOSE(log);

    char buf[1024];
    ssize_t got;

    fprintf(stdout, "BEGIN STDOUT\n");
    fflush(stdout);
    fprintf(stderr, "BEGIN STDERR\n");
    fflush(stderr);

    for (;;) {
        got = read(STDIN_FILENO, buf, sizeof(buf));
        if (got < 0)
            goto error;
        if (got == 0)
            break;
        if (safewrite(STDOUT_FILENO, buf, got) != got)
            goto error;
        if (safewrite(STDERR_FILENO, buf, got) != got)
            goto error;
    }

    fprintf(stdout, "END STDOUT\n");
    fflush(stdout);
    fprintf(stderr, "END STDERR\n");
    fflush(stderr);

    return EXIT_SUCCESS;

error:
    return EXIT_FAILURE;
}
int main(int argc, char **argv) {
	
	char buffer[TAM_BUFFER];

	if (argc != 2) {
		strcpy (buffer, "Canal Memoria Compartida: Error - Cantidad de parametros invalida\n");
		write (fileno(stderr),buffer, strlen(buffer));
		exit(1);
	}
	
	int socketComunicacion = 0;
	sscanf(argv[1] , "%d", &socketComunicacion);
	
	sprintf (buffer,"Canal Memoria Compartida: Iniciando\n");
	write(fileno(stdout), buffer, strlen(buffer));
	
	// Obteniendo semaforo de control de acceso a la memoria compartida
	semControl = Semaphore();	
	semControl.getSemaphore((char *)DIRECTORY, ID_SEMCONTROL, 1);

	// Obteniendo memoria compartida
	shMem = TicketsInfoSharedMemory();
	shMem.getSharedMemory((char *)DIRECTORY, ID_SHMEM);
	
	char buffer[TAM_BUFFER];
	PaqueteTicketsInfo paqueteIntercambio;
	bool deboSeguir;

	do {
		
		if (recibir(socketComunicacion, buffer, TAM_BUFFER) != TAM_BUFFER) {
			sprintf(buffer, "Canal Memoria Compartida - Error al recibir un pedido de memoria. ERROR: %d.\n", errno);
			write (fileno(stderr),buffer, strlen(buffer));
			close(socketComunicacion);
			exit(-1);
		}
		memcpy(&paqueteIntercambio, buffer, sizeof(PaqueteTicketsInfo));
		
		deboSeguir = paqueteIntercambio.deboSeguir;
		
		if (deboSeguir) {
			// Lllego un pedido de memoria compartida
			senControl.wait();
				TicketsInfo *info =  shMem.readInfo();
				/* Envio la memoria compartida */
				memcpy(&paqueteIntercambio.ticketsInfo, info, sizeof(TicketsInfo));
				memcpy(buffer, &paqueteIntercambio, sizeof(PaqueteTicketsInfo));
				if (enviar(socketComunicacion, buffer, TAM_BUFFER) != TAM_BUFFER) {
					sprintf(buffer, "Canal Memoria Compartida - Error al enviar la memoria\n");
					write (fileno(stderr),buffer, strlen(buffer));
					senControl.signal();
					close(socketComunicacion);
					exit(-1);
				}
			
				/* Recibo la memoria compartida actualizada */
				if (recibir(socketComunicacion, buffer, TAM_BUFFER) != TAM_BUFFER) {
					sprintf(buffer, "Canal Memoria Compartida - Error al recibir una actualización de memoria. ERROR: %d.\n", errno);
					write (fileno(stderr),buffer, strlen(buffer));
					senControl.signal();
					close(socketComunicacion);
					exit(-1);
				}
				memcpy(&paqueteIntercambio, buffer, sizeof(PaqueteTicketsInfo));
				shMem.writeInfo(paqueteIntercambio.ticketsInfo);
				deboSeguir = paqueteIntercambio.deboSeguir;
			
			senControl.signal();
		}
	} while (deboSeguir);
				
	close(socketEntrada);
	
}
示例#12
0
文件: sdt.c 项目: srclib/sods
int
main(int argc, char *argv[])
{
    SDT_STATE *ss = NULL;
    pid_t pid = 0;
    int nd = 0;
    int ch = 0;
    int di = 0;

    IS_NULL(ss = calloc(1, sizeof(SDT_STATE)));

    ss->rand = sdt_rand_init();
    (void)sdt_dns_init();

    ss->sess.o.id = (u_int16_t)sdt_arc4random(ss->rand);
    ss->backoff = 1;
    ss->maxbackoff = MAXBACKOFF;
    ss->sleep = SLEEP_TXT;
    ss->bufsz = 110;
    ss->delay = 1000000/2; /* 2/second */
    ss->faststart = 3;
    ss->maxpollfail = MAXPOLLFAIL;
    ss->type = ns_t_txt;
    ss->verbose_lines = 100;
    ss->protocol = PROTO_STATIC_FWD;
    ss->target_port = 22;

    ss->dname_next = &sdt_dns_dn_roundrobin;

    ss->fd_in = fileno(stdin);
    ss->fd_out = fileno(stdout);

    while ( (ch = getopt(argc, argv, "A:B:b:D:dF:hM:m:n:p:R:r:S:s:T:t:V:vx:")) != -1) {
        switch (ch) {
        case 'A':	/* alarm, delay buf */
            ss->delay = (u_int32_t)atoi(optarg);
            break;
        case 'B':   /* send buf size */
            ss->bufsz = (size_t)atoi(optarg);
            break;
        case 'b':   /* max backoff */
            ss->maxbackoff = (u_int16_t)atoi(optarg);
            break;
        case 'D': { /* Dynamic forward */
            char *hostname = NULL;

            IS_NULL(hostname = strdup(optarg));
            sdt_parse_forward(ss, hostname);
            free(hostname);
        }
        break;
        case 'd':   /* Debug DNS */
            sdt_dns_setopt(SDT_RES_DEBUG, 1);
            break;
        case 'F':   /* fast start */
            ss->faststart = (int32_t)atoi(optarg);
            break;
        case 'M':
            ss->maxpollfail = (int32_t)atoi(optarg);
            break;
        case 'm':
            ss->sleep = (u_int32_t)atoi(optarg);
            break;
        case 'n':   /* strategy for shuffling domain name list */
            if (strcasecmp(optarg, "roundrobin") == 0)
                ss->dname_next = &sdt_dns_dn_roundrobin;
            else if (strcasecmp(optarg, "random") == 0)
                ss->dname_next = &sdt_dns_dn_random;
            else
                usage(ss);
            break;
        case 'p':   /* Proxy mode */
            ss->proxy_port = (in_port_t)atoi(optarg);
            break;
        case 'R':   /* Retry lookup */
            sdt_dns_setopt(SDT_RES_RETRY, (u_int32_t)atoi(optarg));
            break;
        case 'r':
            if (sdt_dns_parsens(ss, optarg) < 0)
                errx(EXIT_FAILURE, "Invalid NS address");

            nsauto = 1;
            break;
        case 'S':   /* Resolver strategies */
            if (strcasecmp(optarg, "blast") == 0)
                sdt_dns_setopt(SDT_RES_BLAST, 0);
            else if (strcasecmp(optarg, "rotate") == 0)
                sdt_dns_setopt(SDT_RES_ROTATE, 0);
            else
                usage(ss);
            break;
        case 's':   /* forwarded session */
            ss->sess.o.fwd = (u_int8_t)atoi(optarg);
            break;
        case 'T':
            sdt_dns_setopt(SDT_RES_USEVC, (int32_t)atoi(optarg));
            break;
        case 't':   /* DNS message type */
            if (strcasecmp(optarg, "TXT") == 0)
                ss->type = ns_t_txt;
            else if (strcasecmp(optarg, "CNAME") == 0)
                ss->type = ns_t_cname;
            else if (strcasecmp(optarg, "NULL") == 0)
                ss->type = ns_t_null;
            else
                usage(ss);
            break;
        case 'V':
            ss->verbose_lines = atoi(optarg);
            break;
        case 'v':
            ss->verbose++;
            break;
        case 'x':   /* Transmit lookup timeout */
            sdt_dns_setopt(SDT_RES_RETRANS, (int32_t)atoi(optarg));
            break;

        case 'h':
        default:
            usage(ss);
        }
    }

    argc -= optind;
    argv += optind;

    if ( (argc == 0) || (argc >= MAXDNAMELIST))
        usage(ss);

    ss->dname_max = argc;
    IS_NULL(ss->dname = calloc(argc, sizeof(char *)));
    for ( di = 0; di < argc; di++) {
        if (strlen(argv[di]) > NS_MAXCDNAME - 1)
            usage(ss);
        IS_NULL(ss->dname[di] = strdup(argv[di]));
    }

    if (ss->proxy_port > 0)
        IS_ERR(ss->fd_out = ss->fd_in = sdt_proxy_open(ss));

    IS_ERR(nd = open("/dev/null", O_RDWR, 0));

    VERBOSE(1, "session id = %u, opt = %u, session = %d\n", ss->sess.o.id,
            ss->sess.o.opt, ss->sess.o.fwd);

    (void)signal(SIGPIPE, SIG_IGN);

    switch (pid = fork()) {
    case -1:
        err(EXIT_FAILURE, "fork");
    case 0:
        if (ss->proxy_port > 0)
            IS_ERR(dup2(fileno(stdout), nd));
        IS_ERR(dup2(fileno(stdin), nd));
        (void)signal(SIGUSR1,wakeup);
        sdt_loop_poll(ss);
        break;
    default:
        if (ss->proxy_port > 0)
            IS_ERR(dup2(fileno(stdin), nd));
        IS_ERR(dup2(fileno(stdout), nd));
        (void)signal(SIGHUP,wakeup);
        (void)signal(SIGTERM,wakeup);
        (void)signal(SIGALRM,wakeup);
        (void)signal(SIGCHLD,wakeup);
        ss->child = pid;
        sdt_loop_A(ss);

        if (woken == 1) {
            (void)kill(pid, SIGHUP);
            (void)wait(NULL);
        }

        break;
    }

    free(ss->dname);
    free(ss);
    IS_ERR(close(nd));

    exit(EXIT_SUCCESS);
}
示例#13
0
int write_chunk(regionfile* region, int32_t cx, int32_t cz, chunk* chunk) {
    if (region == NULL)
        return -1;
    if (chunk == NULL)
        return -1;
    cx &= 0x1f;
    cz &= 0x1f;
    uint32_t offset = region->offsets[cx + cz * 32];
    if (offset == 0)
        return -2;
    uint32_t numSectors = offset & 0xff;
    if (numSectors == 0)
        return -3;
    nbt_node* raw = new_chunk_data_to_nbt(chunk);
    if (raw == NULL)
        return -1;
    uint32_t sectorStart = offset >> 8;
    FILE* f;
    if (region->keepopen == 1) {
        if (region->file)
            f = region->file;
        else {
            f = fopen(region->filename, "rb+");
            region->file = f;
        }
    } else
        f = fopen(region->filename, "rb+");
    struct buffer buf = nbt_dump_compressed(raw, STRAT_INFLATE);
    uint16_t sectorsNeeded = (buf.len + 5) / SECTOR_BYTES + 1;
    if (sectorsNeeded >= 256)
        goto error;
    if (sectorStart != 0 && numSectors >= sectorsNeeded) {
        if (fseek(f, sectorStart*SECTOR_BYTES, SEEK_SET) != 0)
            goto error;
        uint32_t size = htobe32(buf.len);
        if (fwrite(&size, 1, sizeof(uint32_t), f) != sizeof(uint32_t))
            goto error;
        static const char COMPRESSION = 2;
        if (fwrite(&COMPRESSION, 1, sizeof(COMPRESSION), f) != sizeof(COMPRESSION))
            goto error;
        if (fwrite(buf.data, 1, buf.len, f) != buf.len)
            goto error;
        goto success;
    } else {
        size_t i;
        size_t runLength = 0;
        uint32_t runStart = 0;
        unsigned char* curSector = region->freeSectors;
        for (i = 0; curSector[i] != 0x00; i++) {
            if (runLength > 0) {
                if (curSector[i] == 0x01)
                    runLength++;
                else
                    runLength = 0;
            } else if (curSector[i] == 0x01) {
                runStart = i;
                runLength = 1;
            }
            if (runLength >= sectorsNeeded)
                break;
        }
        if (runLength >= sectorsNeeded) {
            region->offsets[cx + cz * 32] = runStart << 8 | sectorsNeeded;
            if (__region_write_offsets(region) != 0)
                goto error;
            if (fseek(f, runStart*SECTOR_BYTES, SEEK_SET) != 0)
                goto error;
            uint32_t size = htobe32(buf.len);
            if (fwrite(&size, 1, sizeof(uint32_t), f) != sizeof(uint32_t))
                goto error;
            static const char COMPRESSION = 2;
            if (fwrite(&COMPRESSION, 1, sizeof(COMPRESSION), f) != sizeof(COMPRESSION))
                goto error;
            if (fwrite(buf.data, 1, buf.len, f) != buf.len)
                goto error;
            goto success;
        } else {
            if (fseek(f, 0L, SEEK_END) != 0)
                goto error;
            long filesize = ftell(f);
            uint32_t sectorNumber = filesize/SECTOR_BYTES;
            filesize += sectorsNeeded * SECTOR_BYTES;
            if (ftruncate(fileno(f), filesize) != 0)
                goto error;
            region->offsets[cx + cz * 32] = sectorNumber << 8 | sectorsNeeded;
            if (__region_write_offsets(region) != 0)
                goto error;
            if (fseek(f, sectorNumber*SECTOR_BYTES, SEEK_SET) != 0)
                goto error;
            uint32_t size = htobe32(buf.len);
            if (fwrite(&size, 1, sizeof(uint32_t), f) != sizeof(uint32_t))
                goto error;
            static const char COMPRESSION = 2;
            if (fwrite(&COMPRESSION, 1, sizeof(COMPRESSION), f) != sizeof(COMPRESSION))
                goto error;
            if (fwrite(buf.data, 1, buf.len, f) != buf.len)
                goto error;

            uint32_t freeSectorsLength = filesize/SECTOR_BYTES;
            region->freeSectors = realloc(region->freeSectors, sizeof(unsigned char) * (freeSectorsLength+1));
            region->freeSectors[freeSectorsLength] = 0x00;
            for (; sectorNumber < freeSectorsLength; sectorNumber++)
                region->freeSectors[sectorNumber] = 0x02;
            goto success;
        }
    }
error:
    nbt_free(raw);
    if (f && region->file != f)
        fclose(f);
    buffer_free(&buf);
    return 1;
success:
    nbt_free(raw);
    buffer_free(&buf);
    if (region->file != f)
        fclose(f);
    region->timestamps[cx + cz * 32] = time(NULL);
    __region_write_timestamps(region);
    return 0;
};
示例#14
0
/*
 * popen_with_stderr
 *
 * standard popen doesn't redirect stderr from the child process.
 * we need stderr in order to display the error that child process
 * encountered and show it to the user. This is, therefore, a wrapper
 * around a set of file descriptor redirections and a fork.
 *
 * if 'forwrite' is set then we set the data pipe write side on the
 * parent. otherwise, we set the read side on the parent.
 */
int
popen_with_stderr(int *pipes, const char *exe, bool forwrite)
{
	int data[2];	/* pipe to send data child <--> parent */
	int err[2];		/* pipe to send errors child --> parent */
	int pid = -1;

	const int READ = 0;
	const int WRITE = 1;

	if (pgpipe(data) < 0)
		return -1;

	if (pgpipe(err) < 0)
	{
		close(data[READ]);
		close(data[WRITE]);
		return -1;
	}
#ifndef WIN32

	pid = fork();

	if (pid > 0) /* parent */
	{

		if (forwrite)
		{
			/* parent writes to child */
			close(data[READ]);
			pipes[EXEC_DATA_P] = data[WRITE];
		}
		else
		{
			/* parent reads from child */
			close(data[WRITE]);
			pipes[EXEC_DATA_P] = data[READ];
		}

		close(err[WRITE]);
		pipes[EXEC_ERR_P] = err[READ];

		return pid;
	}
	else if (pid == 0) /* child */
	{

		/*
		 * set up the data pipe
		 */
		if (forwrite)
		{
			close(data[WRITE]);
			close(fileno(stdin));

			/* assign pipes to parent to stdin */
			if (dup2(data[READ], fileno(stdin)) < 0)
			{
				perror("dup2 error");
				exit(EXIT_FAILURE);
			}

			/* no longer needed after the duplication */
			close(data[READ]);
		}
		else
		{
			close(data[READ]);
			close(fileno(stdout));

			/* assign pipes to parent to stdout */
			if (dup2(data[WRITE], fileno(stdout)) < 0)
			{
				perror("dup2 error");
				exit(EXIT_FAILURE);
			}

			/* no longer needed after the duplication */
			close(data[WRITE]);
		}

		/*
		 * now set up the error pipe
		 */
		close(err[READ]);
		close(fileno(stderr));

		if (dup2(err[WRITE], fileno(stderr)) < 0)
		{
			if(forwrite)
				close(data[WRITE]);
			else
				close(data[READ]);

			perror("dup2 error");
			exit(EXIT_FAILURE);
		}

		close(err[WRITE]);

		/* go ahead and execute the user command */
		execl("/bin/sh", "sh", "-c", exe, NULL);

		/* if we're here an error occurred */
		exit(EXIT_FAILURE);
	}
	else
	{
		if(forwrite)
		{
			close(data[WRITE]);
			close(data[READ]);
		}
		else
		{
			close(data[READ]);
			close(data[WRITE]);
		}
		close(err[READ]);
		close(err[WRITE]);

		return -1;
	}
#endif

	return pid;
}
示例#15
0
文件: oss.c 项目: Amalerd/SoxPlayer
/* common r/w initialization code */
static int ossinit(sox_format_t * ft)
{
    int sampletype, samplesize, dsp_stereo;
    int tmp, rc;
    priv_t *file = (priv_t *)ft->priv;

    if (ft->encoding.bits_per_sample == 8) {
        sampletype = AFMT_U8;
        samplesize = 8;
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
            ft->encoding.encoding = SOX_ENCODING_UNSIGNED;
        if (ft->encoding.encoding != SOX_ENCODING_UNSIGNED) {
            lsx_report("OSS driver only supports unsigned with bytes");
            lsx_report("Forcing to unsigned");
            ft->encoding.encoding = SOX_ENCODING_UNSIGNED;
        }
    }
    else if (ft->encoding.bits_per_sample == 16) {
        /* Attempt to use endian that user specified */
        if (ft->encoding.reverse_bytes)
            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_LE : AFMT_S16_BE;
        else
            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
        samplesize = 16;
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
            ft->encoding.encoding = SOX_ENCODING_SIGN2;
        if (ft->encoding.encoding != SOX_ENCODING_SIGN2) {
            lsx_report("OSS driver only supports signed with words");
            lsx_report("Forcing to signed linear");
            ft->encoding.encoding = SOX_ENCODING_SIGN2;
        }
    }
    else if (ft->encoding.bits_per_sample == 32) {
	/* Attempt to use endian that user specified */
	if (ft->encoding.reverse_bytes)
	    sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S32_LE : AFMT_S32_BE;
	else
	    sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S32_BE : AFMT_S32_LE;
	samplesize = 32;
	if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
	    ft->encoding.encoding = SOX_ENCODING_SIGN2;
	if (ft->encoding.encoding != SOX_ENCODING_SIGN2) {
	    lsx_report("OSS driver only supports signed with words");
	    lsx_report("Forcing to signed linear");
	    ft->encoding.encoding = SOX_ENCODING_SIGN2;
	}
    }
    else {
        /* Attempt to use endian that user specified */
        if (ft->encoding.reverse_bytes)
            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_LE : AFMT_S16_BE;
        else
            sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
        samplesize = 16;
        ft->encoding.bits_per_sample = 16;
        ft->encoding.encoding = SOX_ENCODING_SIGN2;
        lsx_report("OSS driver only supports bytes and words");
        lsx_report("Forcing to signed linear word");
    }

    if (ft->signal.channels > 2) ft->signal.channels = 2;

    if (ioctl(fileno(ft->fp), (size_t) SNDCTL_DSP_RESET, 0) < 0)
    {
        lsx_fail_errno(ft,SOX_EOF,"Unable to reset OSS driver.  Possibly accessing an invalid file/device");
        return(SOX_EOF);
    }

    /* Query the supported formats and find the best match
     */
    rc = ioctl(fileno(ft->fp), SNDCTL_DSP_GETFMTS, &tmp);
    if (rc == 0) {
        if ((tmp & sampletype) == 0)
        {
            /* is 16-bit supported? */
            if (samplesize == 16 && (tmp & (AFMT_S16_LE|AFMT_S16_BE)) == 0)
            {
                /* Must not like 16-bits, try 8-bits */
                ft->encoding.bits_per_sample = 8;
                ft->encoding.encoding = SOX_ENCODING_UNSIGNED;
                lsx_report("OSS driver doesn't like signed words");
                lsx_report("Forcing to unsigned bytes");
                tmp = sampletype = AFMT_U8;
                samplesize = 8;
            }
            /* is 8-bit supported */
            else if (samplesize == 8 && (tmp & AFMT_U8) == 0)
            {
                ft->encoding.bits_per_sample = 16;
                ft->encoding.encoding = SOX_ENCODING_SIGN2;
                lsx_report("OSS driver doesn't like unsigned bytes");
                lsx_report("Forcing to signed words");
                sampletype = (MACHINE_IS_BIGENDIAN) ? AFMT_S16_BE : AFMT_S16_LE;
                samplesize = 16;
            }
            /* determine which 16-bit format to use */
            if (samplesize == 16 && (tmp & sampletype) == 0)
            {
                /* Either user requested something not supported
                 * or hardware doesn't support machine endian.
                 * Force to opposite as the above test showed
                 * it supports at least one of the two endians.
                 */
                sampletype = (sampletype == AFMT_S16_BE) ? AFMT_S16_LE : AFMT_S16_BE;
                ft->encoding.reverse_bytes = !ft->encoding.reverse_bytes;
            }

        }
        tmp = sampletype;
        rc = ioctl(fileno(ft->fp), SNDCTL_DSP_SETFMT, &tmp);
    }
    /* Give up and exit */
    if (rc < 0 || tmp != sampletype)
    {
        lsx_fail_errno(ft,SOX_EOF,"Unable to set the sample size to %d", samplesize);
        return (SOX_EOF);
    }

    if (ft->signal.channels == 2) dsp_stereo = 1;
    else dsp_stereo = 0;

    tmp = dsp_stereo;
    if (ioctl(fileno(ft->fp), SNDCTL_DSP_STEREO, &tmp) < 0)
    {
        lsx_warn("Couldn't set to %s", dsp_stereo?  "stereo":"mono");
        dsp_stereo = 0;
    }

    if (tmp != dsp_stereo)
        ft->signal.channels = tmp + 1;

    tmp = ft->signal.rate;
    if (ioctl (fileno(ft->fp), SNDCTL_DSP_SPEED, &tmp) < 0 ||
        (int)ft->signal.rate != tmp) {
        /* If the rate the sound card is using is not within 1% of what
         * the user specified then override the user setting.
         * The only reason not to always override this is because of
         * clock-rounding problems. Sound cards will sometimes use
         * things like 44101 when you ask for 44100.  No need overriding
         * this and having strange output file rates for something that
         * we can't hear anyways.
         */
        if ((int)ft->signal.rate - tmp > (tmp * .01) ||
            tmp - (int)ft->signal.rate > (tmp * .01))
            ft->signal.rate = tmp;
    }

    /* Find out block size to use last because the driver could compute
     * its size based on specific rates/formats.
     */
    file->size = 0;
    ioctl (fileno(ft->fp), SNDCTL_DSP_GETBLKSIZE, &file->size);
    if (file->size < 4 || file->size > 65536) {
            lsx_fail_errno(ft,SOX_EOF,"Invalid audio buffer size %lu", (unsigned long)file->size);
            return (SOX_EOF);
    }
    file->count = 0;
    file->pos = 0;
    file->buf = lsx_malloc(file->size);

    if (ioctl(fileno(ft->fp), (size_t) SNDCTL_DSP_SYNC, NULL) < 0) {
        lsx_fail_errno(ft,SOX_EOF,"Unable to sync dsp");
        return (SOX_EOF);
    }

    /* Change to non-buffered I/O */
    setvbuf(ft->fp, NULL, _IONBF, sizeof(char) * file->size);
    return(SOX_SUCCESS);
}
示例#16
0
int main(

  int   argc,
  char *argv[])

  {
  char  *id = "main";

  struct hostent *hp;
  int  go, c, errflg = 0;
  int  lockfds;
  int  t = 1;
  pid_t  pid;
  char  host[100];
  char  *homedir = PBS_SERVER_HOME;
  unsigned int port;
  char  *dbfile = "sched_out";

  struct sigaction act;
  sigset_t oldsigs;
  caddr_t curr_brk = 0;
  caddr_t next_brk;
  extern char *optarg;
  extern int optind, opterr;
  extern int rpp_fd;
  fd_set fdset;

  int  schedinit(int argc, char **argv);
  int  schedule(int com, int connector);

  glob_argv = argv;
  alarm_time = 180;

  /* The following is code to reduce security risks                */
  /* move this to a place where nss_ldap doesn't hold a socket yet */

  c = sysconf(_SC_OPEN_MAX);

  while (--c > 2)
    (void)close(c); /* close any file desc left open by parent */

  port = get_svrport(PBS_SCHEDULER_SERVICE_NAME, "tcp",
                     PBS_SCHEDULER_SERVICE_PORT);

  pbs_rm_port = get_svrport(PBS_MANAGER_SERVICE_NAME, "tcp",
                            PBS_MANAGER_SERVICE_PORT);

  strcpy(pbs_current_user, "Scheduler");

  msg_daemonname = strdup("pbs_sched");

  opterr = 0;

  while ((c = getopt(argc, argv, "L:S:R:d:p:c:a:-:")) != EOF)
    {
    switch (c)
      {

      case '-':

        if ((optarg == NULL) || (optarg[0] == '\0'))
          {
          errflg = 1;
          }

        if (!strcmp(optarg, "version"))
          {
          fprintf(stderr, "version: %s\n", PACKAGE_VERSION);
          exit(0);
          }
        else
          {
          errflg = 1;
          }

        break;

      case 'L':
        logfile = optarg;
        break;

      case 'S':
        port = atoi(optarg);

        if (port == 0)
          {
          fprintf(stderr,
                  "%s: illegal port\n", optarg);
          errflg = 1;
          }

        break;

      case 'R':

        if ((pbs_rm_port = atoi(optarg)) == 0)
          {
          (void)fprintf(stderr, "%s: bad -R %s\n",
                        argv[0], optarg);
          return 1;
          }

        break;

      case 'd':
        homedir = optarg;
        break;

      case 'p':
        dbfile = optarg;
        break;

      case 'c':
        configfile = optarg;
        break;

      case 'a':
        alarm_time = atoi(optarg);

        if (alarm_time == 0)
          {
          fprintf(stderr,
                  "%s: bad alarm time\n", optarg);
          errflg = 1;
          }

        break;

      case '?':
        errflg = 1;
        break;
      }
    }

  if (errflg)
    {
    fprintf(stderr, "usage: %s %s\n", argv[0], usage);
    exit(1);
    }

#ifndef DEBUG
  if (IamRoot() == 0)
    {
        return (1);
    }
#endif        /* DEBUG */

  /* Save the original working directory for "restart" */
  if ((oldpath = getcwd((char *)NULL, MAXPATHLEN)) == NULL)
    {
    fprintf(stderr, "cannot get current working directory\n");
    exit(1);
    }

  (void)sprintf(log_buffer, "%s/sched_priv", homedir);
#if !defined(DEBUG) && !defined(NO_SECURITY_CHECK)
  c  = chk_file_sec(log_buffer, 1, 0, S_IWGRP | S_IWOTH, 1, NULL);
  c |= chk_file_sec(PBS_ENVIRON, 0, 0, S_IWGRP | S_IWOTH, 0, NULL);

  if (c != 0) exit(1);

#endif  /* not DEBUG and not NO_SECURITY_CHECK */
  if (chdir(log_buffer) == -1)
    {
    perror("chdir");
    exit(1);
    }

  (void)sprintf(path_log,   "%s/sched_logs", homedir);
  (void)sprintf(path_acct,   "%s/%s", log_buffer, PBS_ACCT);


  /* The following is code to reduce security risks                */
  /* start out with standard umask, system resource limit infinite */

  umask(022);

  if (setup_env(PBS_ENVIRON) == -1)
    exit(1);

  c = getgid();

  (void)setgroups(1, (gid_t *)&c); /* secure suppl. groups */

#ifndef DEBUG
#ifdef _CRAY
  (void)limit(C_JOB,      0, L_CPROC, 0);

  (void)limit(C_JOB,      0, L_CPU,   0);

  (void)limit(C_JOBPROCS, 0, L_CPU,   0);

  (void)limit(C_PROC,     0, L_FD,  255);

  (void)limit(C_JOB,      0, L_FSBLK, 0);

  (void)limit(C_JOBPROCS, 0, L_FSBLK, 0);

  (void)limit(C_JOB,      0, L_MEM  , 0);

  (void)limit(C_JOBPROCS, 0, L_MEM  , 0);

#else /* not  _CRAY */
    {

    struct rlimit rlimit;

    rlimit.rlim_cur = RLIM_INFINITY;
    rlimit.rlim_max = RLIM_INFINITY;
    (void)setrlimit(RLIMIT_CPU,   &rlimit);
    (void)setrlimit(RLIMIT_FSIZE, &rlimit);
    (void)setrlimit(RLIMIT_DATA,  &rlimit);
    (void)setrlimit(RLIMIT_STACK, &rlimit);
#ifdef  RLIMIT_RSS
    (void)setrlimit(RLIMIT_RSS  , &rlimit);
#endif  /* RLIMIT_RSS */
#ifdef  RLIMIT_VMEM
    (void)setrlimit(RLIMIT_VMEM  , &rlimit);
#endif  /* RLIMIT_VMEM */
    }
#endif /* not _CRAY */
#endif /* DEBUG */

  if (log_open(logfile, path_log) == -1)
    {
    fprintf(stderr, "%s: logfile could not be opened\n", argv[0]);
    exit(1);
    }

  if (gethostname(host, sizeof(host)) == -1)
    {
    log_err(errno, id, "gethostname");
    die(0);
    }

  if ((hp = gethostbyname(host)) == NULL)
    {
    log_err(errno, id, "gethostbyname");
    die(0);
    }

  if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
    log_err(errno, id, "socket");
    die(0);
    }

  if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR,
                 (char *)&t, sizeof(t)) == -1)
    {
    log_err(errno, id, "setsockopt");
    die(0);
    }

  saddr.sin_family = AF_INET;

  saddr.sin_port = htons(port);
  memcpy(&saddr.sin_addr, hp->h_addr, hp->h_length);

  if (bind(server_sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
    {
    log_err(errno, id, "bind");
    die(0);
    }

  if (listen(server_sock, 5) < 0)
    {
    log_err(errno, id, "listen");
    die(0);
    }

  okclients = (pbs_net_t *)calloc(START_CLIENTS, sizeof(pbs_net_t));

  addclient("localhost");   /* who has permission to call MOM */
  addclient(host);

  if (configfile)
    {
    if (read_config(configfile) != 0)
      die(0);
    }

  lockfds = open("sched.lock", O_CREAT | O_TRUNC | O_WRONLY, 0644);

  if (lockfds < 0)
    {
    log_err(errno, id, "open lock file");
    exit(1);
    }

  lock_out(lockfds, F_WRLCK);

  fullresp(0);

  if (sigemptyset(&allsigs) == -1)
    {
    perror("sigemptyset");
    exit(1);
    }

  if (sigprocmask(SIG_SETMASK, &allsigs, NULL) == -1)   /* unblock */
    {
    perror("sigprocmask");
    exit(1);
    }

  act.sa_flags = 0;

  sigaddset(&allsigs, SIGHUP);    /* remember to block these */
  sigaddset(&allsigs, SIGINT);    /* during critical sections */
  sigaddset(&allsigs, SIGTERM);   /* so we don't get confused */
  act.sa_mask = allsigs;

  act.sa_handler = restart;       /* do a restart on SIGHUP */
  sigaction(SIGHUP, &act, NULL);

  act.sa_handler = toolong; /* handle an alarm call */
  sigaction(SIGALRM, &act, NULL);

  act.sa_handler = die;           /* bite the biscuit for all following */
  sigaction(SIGINT, &act, NULL);
  sigaction(SIGTERM, &act, NULL);

  /*
   * Catch these signals to ensure we core dump even if
   * our rlimit for core dumps is set to 0 initially.
   *
   * Chris Samuel - VPAC
   * [email protected] - 29th July 2003
   *
   * Now conditional on the PBSCOREDUMP environment variable
   */

  if (getenv("PBSCOREDUMP"))
    {
    act.sa_handler = catch_abort;   /* make sure we core dump */

    sigaction(SIGSEGV, &act, NULL);
    sigaction(SIGBUS, &act, NULL);
    sigaction(SIGFPE, &act, NULL);
    sigaction(SIGILL, &act, NULL);
    sigaction(SIGTRAP, &act, NULL);
    sigaction(SIGSYS, &act, NULL);
    }

  /*
   *  Local initialization stuff
   */

  if (schedinit(argc, argv))
    {
    (void) sprintf(log_buffer,
                   "local initialization failed, terminating");
    log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);
    exit(1);
    }

  if (getenv("PBSDEBUG") == NULL)
    {
    lock_out(lockfds, F_UNLCK);

#ifdef DISABLE_DAEMONS
    pid = getpid();
#else
    if ((pid = fork()) == -1)
      {
      /* error on fork */
      perror("fork");

      exit(1);
      }
    else
    if (pid > 0)               /* parent exits */
      {
      exit(0);
      }

    if ((pid = setsid()) == -1)
      {
      perror("setsid");

      exit(1);
      }
#endif  /*  DISABLE_DAEMONS  */

    lock_out(lockfds, F_WRLCK);

    if (freopen(dbfile, "a", stdout) == NULL)
      {
      perror("opening lockfile");

      exit(1);
      }


    setvbuf(stdout, NULL, _IOLBF, 0);

    dup2(fileno(stdout), fileno(stderr));
    }
  else
    {
    setvbuf(stdout, NULL, _IOLBF, 0);
    setvbuf(stderr, NULL, _IOLBF, 0);

    pid = getpid();
    }

  if (freopen("/dev/null", "r", stdin) == NULL)
    {
    perror("opening /dev/null");

    exit(1);
    }

  /* write scheduler's pid into lockfile */

  (void)sprintf(log_buffer, "%ld\n", (long)pid);

  if (write(lockfds, log_buffer, strlen(log_buffer) + 1) != (ssize_t)(strlen(log_buffer) + 1))
    {
    perror("writing to lockfile");

    exit(1);
    }

#if (PLOCK_DAEMONS & 2)
  (void)plock(PROCLOCK); /* lock daemon into memory */

#endif

  sprintf(log_buffer, "%s startup pid %ld", argv[0], (long)pid);

  log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

  FD_ZERO(&fdset);

  for (go = 1;go;)
    {
    int cmd;

    if (rpp_fd != -1)
      FD_SET(rpp_fd, &fdset);

    FD_SET(server_sock, &fdset);

    if (select(FD_SETSIZE, &fdset, NULL, NULL, NULL) == -1)
      {
      if (errno != EINTR)
        {
        log_err(errno, id, "select");
        die(0);
        }

      continue;
      }

    if (rpp_fd != -1 && FD_ISSET(rpp_fd, &fdset))
      {
      if (rpp_io() == -1)
        log_err(errno, id, "rpp_io");
      }

    if (!FD_ISSET(server_sock, &fdset))
      continue;

    cmd = server_command();

    if (sigprocmask(SIG_BLOCK, &allsigs, &oldsigs) == -1)
      log_err(errno, id, "sigprocmaskSIG_BLOCK)");

    alarm(alarm_time);

    if (schedule(cmd, connector)) /* magic happens here */
      go = 0;

    alarm(0);

    if (connector >= 0 && server_disconnect(connector))
      {
      log_err(errno, id, "server_disconnect");
      die(0);
      }

    next_brk = (caddr_t)sbrk(0);

    if (next_brk > curr_brk)
      {
      sprintf(log_buffer, "brk point %ld", (long)next_brk);
      log_record(PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
                 id, log_buffer);
      curr_brk = next_brk;
      }

    if (sigprocmask(SIG_SETMASK, &oldsigs, NULL) == -1)
      log_err(errno, id, "sigprocmask(SIG_SETMASK)");
    }

  sprintf(log_buffer, "%s normal finish pid %ld",

          argv[0],
          (long)pid);

  log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer);

  close(server_sock);

  exit(0);
  }  /* END main() */
示例#17
0
int
main(int argc, char **argv)
{
	int c, i;
	int tflag = 0, hflag = 0, cflag = 0, wflag = 0, nflag = 0;
	int count = 0, waittime = 0;
	char *memf = NULL, *nlistf = NULL;
	struct devstat_match *matches;
	struct itimerval alarmspec;
	int num_matches = 0;
	char errbuf[_POSIX2_LINE_MAX];
	kvm_t *kd = NULL;
	long generation;
	int num_devices_specified;
	int num_selected, num_selections;
	long select_generation;
	char **specified_devices;
	devstat_select_mode select_mode;
	float f;
	int havelast = 0;

	matches = NULL;
	maxshowdevs = 3;

	while ((c = getopt(argc, argv, "c:CdhIKM:n:N:ot:Tw:xz?")) != -1) {
		switch(c) {
			case 'c':
				cflag++;
				count = atoi(optarg);
				if (count < 1)
					errx(1, "count %d is < 1", count);
				break;
			case 'C':
				Cflag++;
				break;
			case 'd':
				dflag++;
				break;
			case 'h':
				hflag++;
				break;
			case 'I':
				Iflag++;
				break;
			case 'K':
				Kflag++;
				break;
			case 'M':
				memf = optarg;
				break;
			case 'n':
				nflag++;
				maxshowdevs = atoi(optarg);
				if (maxshowdevs < 0)
					errx(1, "number of devices %d is < 0",
					     maxshowdevs);
				break;
			case 'N':
				nlistf = optarg;
				break;
			case 'o':
				oflag++;
				break;
			case 't':
				tflag++;
				if (devstat_buildmatch(optarg, &matches,
						       &num_matches) != 0)
					errx(1, "%s", devstat_errbuf);
				break;
			case 'T':
				Tflag++;
				break;
			case 'w':
				wflag++;
				f = atof(optarg);
				waittime = f * 1000;
				if (waittime < 1)
					errx(1, "wait time is < 1ms");
				break;
			case 'x':
				xflag++;
				break;
			case 'z':
				zflag++;
				break;
			default:
				usage();
				exit(1);
				break;
		}
	}

	argc -= optind;
	argv += optind;

	if (nlistf != NULL || memf != NULL) {
		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);

		if (kd == NULL)
			errx(1, "kvm_openfiles: %s", errbuf);

		if (kvm_nlist(kd, namelist) == -1)
			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
	}

	/*
	 * Make sure that the userland devstat version matches the kernel
	 * devstat version.  If not, exit and print a message informing
	 * the user of his mistake.
	 */
	if (devstat_checkversion(kd) < 0)
		errx(1, "%s", devstat_errbuf);

	/*
	 * Make sure Tflag and/or Cflag are set if dflag == 0.  If dflag is
	 * greater than 0, they may be 0 or non-zero.
	 */
	if (dflag == 0 && xflag == 0) {
		Cflag = 1;
		Tflag = 1;
	}

	/* find out how many devices we have */
	if ((num_devices = devstat_getnumdevs(kd)) < 0)
		err(1, "can't get number of devices");

	/*
	 * Figure out how many devices we should display.
	 */
	if (nflag == 0) {
		if (xflag > 0)
			maxshowdevs = num_devices;
		else if (oflag > 0) {
			if ((dflag > 0) && (Cflag == 0) && (Tflag == 0))
				maxshowdevs = 5;
			else if ((dflag > 0) && (Tflag > 0) && (Cflag == 0))
				maxshowdevs = 5;
			else
				maxshowdevs = 4;
		} else {
			if ((dflag > 0) && (Cflag == 0))
				maxshowdevs = 4;
			else
				maxshowdevs = 3;
		}
	}

	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
	if (cur.dinfo == NULL)
		err(1, "calloc failed");

	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
	if (last.dinfo == NULL)
		err(1, "calloc failed");

	/*
	 * Grab all the devices.  We don't look to see if the list has
	 * changed here, since it almost certainly has.  We only look for
	 * errors.
	 */
	if (devstat_getdevs(kd, &cur) == -1)
		errx(1, "%s", devstat_errbuf);

	num_devices = cur.dinfo->numdevs;
	generation = cur.dinfo->generation;

	/*
	 * If the user specified any devices on the command line, see if
	 * they are in the list of devices we have now.
	 */
	specified_devices = (char **)malloc(sizeof(char *));
	if (specified_devices == NULL)
		err(1, "malloc failed");

	for (num_devices_specified = 0; *argv; ++argv) {
		if (isdigit(**argv))
			break;
		num_devices_specified++;
		specified_devices = (char **)realloc(specified_devices,
						     sizeof(char *) *
						     num_devices_specified);
		if (specified_devices == NULL)
			err(1, "realloc failed");

		specified_devices[num_devices_specified - 1] = *argv;

	}
	if (nflag == 0 && maxshowdevs < num_devices_specified)
		maxshowdevs = num_devices_specified;

	dev_select = NULL;

	if ((num_devices_specified == 0) && (num_matches == 0))
		select_mode = DS_SELECT_ADD;
	else
		select_mode = DS_SELECT_ONLY;

	/*
	 * At this point, selectdevs will almost surely indicate that the
	 * device list has changed, so we don't look for return values of 0
	 * or 1.  If we get back -1, though, there is an error.
	 */
	if (devstat_selectdevs(&dev_select, &num_selected,
			       &num_selections, &select_generation, generation,
			       cur.dinfo->devices, num_devices, matches,
			       num_matches, specified_devices,
			       num_devices_specified, select_mode, maxshowdevs,
			       hflag) == -1)
		errx(1, "%s", devstat_errbuf);

	/*
	 * Look for the traditional wait time and count arguments.
	 */
	if (*argv) {
		f = atof(*argv);
		waittime = f * 1000;

		/* Let the user know he goofed, but keep going anyway */
		if (wflag != 0)
			warnx("discarding previous wait interval, using"
			      " %g instead", waittime / 1000.0);
		wflag++;

		if (*++argv) {
			count = atoi(*argv);
			if (cflag != 0)
				warnx("discarding previous count, using %d"
				      " instead", count);
			cflag++;
		} else
			count = -1;
	}

	/*
	 * If the user specified a count, but not an interval, we default
	 * to an interval of 1 second.
	 */
	if ((wflag == 0) && (cflag > 0))
		waittime = 1 * 1000;

	/*
	 * If the user specified a wait time, but not a count, we want to
	 * go on ad infinitum.  This can be redundant if the user uses the
	 * traditional method of specifying the wait, since in that case we
	 * already set count = -1 above.  Oh well.
	 */
	if ((wflag > 0) && (cflag == 0))
		count = -1;

	bzero(cur.cp_time, sizeof(cur.cp_time));
	cur.tk_nout = 0;
	cur.tk_nin = 0;

	/*
	 * Set the snap time to the system boot time (ie: zero), so the
	 * stats are calculated since system boot.
	 */
	cur.snap_time = 0;

	/*
	 * If the user stops the program (control-Z) and then resumes it,
	 * print out the header again.
	 */
	(void)signal(SIGCONT, needhdr);

	/*
	 * If our standard output is a tty, then install a SIGWINCH handler
	 * and set wresized so that our first iteration through the main
	 * iostat loop will peek at the terminal's current rows to find out
	 * how many lines can fit in a screenful of output.
	 */
	if (isatty(fileno(stdout)) != 0) {
		wresized = 1;
		(void)signal(SIGWINCH, needresize);
	} else {
		wresized = 0;
		wrows = IOSTAT_DEFAULT_ROWS;
	}

	/*
	 * Register a SIGINT handler so that we can print out final statistics
	 * when we get that signal
	 */
	(void)signal(SIGINT, needreturn);

	/*
	 * Register a SIGALRM handler to implement sleeps if the user uses the
	 * -c or -w options
	 */
	(void)signal(SIGALRM, alarm_clock);
	alarmspec.it_interval.tv_sec = waittime / 1000;
	alarmspec.it_interval.tv_usec = 1000 * (waittime % 1000);
	alarmspec.it_value.tv_sec = waittime / 1000;
	alarmspec.it_value.tv_usec = 1000 * (waittime % 1000);
	setitimer(ITIMER_REAL, &alarmspec, NULL);

	for (headercount = 1;;) {
		struct devinfo *tmp_dinfo;
		long tmp;
		long double etime;
		sigset_t sigmask, oldsigmask;

		if (Tflag > 0) {
			if ((readvar(kd, "kern.tty_nin", X_TTY_NIN, &cur.tk_nin,
			     sizeof(cur.tk_nin)) != 0)
			 || (readvar(kd, "kern.tty_nout", X_TTY_NOUT,
			     &cur.tk_nout, sizeof(cur.tk_nout))!= 0)) {
				Tflag = 0;
				warnx("disabling TTY statistics");
			}
		 }

		if (Cflag > 0) {
			if (kd == NULL) {
				if (readvar(kd, "kern.cp_time", 0,
				    &cur.cp_time, sizeof(cur.cp_time)) != 0)
					Cflag = 0;
			} else {
				if (kvm_getcptime(kd, cur.cp_time) < 0) {
					warnx("kvm_getcptime: %s",
					    kvm_geterr(kd));
					Cflag = 0;
				}
			}
			if (Cflag == 0)
				warnx("disabling CPU time statistics");
		}

		if (!--headercount) {
			phdr();
			if (wresized != 0)
				doresize();
			headercount = wrows;
		}

		tmp_dinfo = last.dinfo;
		last.dinfo = cur.dinfo;
		cur.dinfo = tmp_dinfo;

		last.snap_time = cur.snap_time;

		/*
		 * Here what we want to do is refresh our device stats.
		 * devstat_getdevs() returns 1 when the device list has changed.
		 * If the device list has changed, we want to go through
		 * the selection process again, in case a device that we
		 * were previously displaying has gone away.
		 */
		switch (devstat_getdevs(kd, &cur)) {
		case -1:
			errx(1, "%s", devstat_errbuf);
			break;
		case 1: {
			int retval;

			num_devices = cur.dinfo->numdevs;
			generation = cur.dinfo->generation;
			retval = devstat_selectdevs(&dev_select, &num_selected,
						    &num_selections,
						    &select_generation,
						    generation,
						    cur.dinfo->devices,
						    num_devices, matches,
						    num_matches,
						    specified_devices,
						    num_devices_specified,
						    select_mode, maxshowdevs,
						    hflag);
			switch(retval) {
			case -1:
				errx(1, "%s", devstat_errbuf);
				break;
			case 1:
				phdr();
				if (wresized != 0)
					doresize();
				headercount = wrows;
				break;
			default:
				break;
			}
			break;
		}
		default:
			break;
		}

		/*
		 * We only want to re-select devices if we're in 'top'
		 * mode.  This is the only mode where the devices selected
		 * could actually change.
		 */
		if (hflag > 0) {
			int retval;
			retval = devstat_selectdevs(&dev_select, &num_selected,
						    &num_selections,
						    &select_generation,
						    generation,
						    cur.dinfo->devices,
						    num_devices, matches,
						    num_matches,
						    specified_devices,
						    num_devices_specified,
						    select_mode, maxshowdevs,
						    hflag);
			switch(retval) {
			case -1:
				errx(1,"%s", devstat_errbuf);
				break;
			case 1:
				phdr();
				if (wresized != 0)
					doresize();
				headercount = wrows;
				break;
			default:
				break;
			}
		}

		if (Tflag > 0) {
			tmp = cur.tk_nin;
			cur.tk_nin -= last.tk_nin;
			last.tk_nin = tmp;
			tmp = cur.tk_nout;
			cur.tk_nout -= last.tk_nout;
			last.tk_nout = tmp;
		}

		etime = cur.snap_time - last.snap_time;

		if (etime == 0.0)
			etime = 1.0;

		for (i = 0; i < CPUSTATES; i++) {
			tmp = cur.cp_time[i];
			cur.cp_time[i] -= last.cp_time[i];
			last.cp_time[i] = tmp;
		}

		if (xflag == 0 && Tflag > 0)
			printf("%4.0Lf %5.0Lf", cur.tk_nin / etime,
			    cur.tk_nout / etime);

		devstats(hflag, etime, havelast);

		if (xflag == 0) {
			if (Cflag > 0)
				cpustats();

			printf("\n");
		}
		fflush(stdout);

		if ((count >= 0 && --count <= 0) || return_requested)
			break;

		/*
		 * Use sigsuspend to safely sleep until either signal is
		 * received
		 */
		alarm_rang = 0;
		sigemptyset(&sigmask);
		sigaddset(&sigmask, SIGINT);
		sigaddset(&sigmask, SIGALRM);
		sigprocmask(SIG_BLOCK, &sigmask, &oldsigmask);
		while (! (alarm_rang || return_requested) ) {
			sigsuspend(&oldsigmask);
		}
		sigprocmask(SIG_UNBLOCK, &sigmask, NULL);

		havelast = 1;
	}

	exit(0);
}
示例#18
0
int getnewutmpent( struct user_info *up)
{
    int utmpfd;
    struct user_info *uentp;
    time_t  now;
    int     i, n, num[2];
    FILE * fp;

    fp=fopen(ULIST, "rw+");
    utmpfd = fileno(fp);
    if (utmpfd < 0)
        return -1;

    flock(utmpfd, LOCK_EX);

    resolve_utmp();
    flock(utmpfd, LOCK_EX);
    if (utmpshm->max_login_num < count_users)
        utmpshm->max_login_num = count_users;
    for (i = 0; i < USHM_SIZE; i++)
    {
        uentp = &(utmpshm->uinfo[i]);
        if (!uentp->active || !uentp->pid)
            break;
    }
    if (i >= USHM_SIZE)
    {
        flock(utmpfd, LOCK_UN);
        close(utmpfd);/* add by yiyo */
        return -2;
    }
    utmpshm->uinfo[i] = *up;

    now = time(0);
    if (now > utmpshm->uptime + 60)
    {
        num[0] = num[1] = 0;
        utmpshm->uptime = now;
        for (n = 0; n < USHM_SIZE; n++)
        {
            uentp = &(utmpshm->uinfo[n]);
            if (uentp->active && uentp->pid)
            {
                //web登陆没有守护进程,pid没有意义,所以,不检测web的pid
                if (uentp->mode < 20000 && kill(uentp->pid, 0) == -1)
                {
                    //huangxu@071220:貌似不能这样
                    //kill(uentp->pid, 9);
                    //memset(uentp, 0, sizeof(struct user_info));
                    continue;
                }
                else
                {
                    num[(uentp->invisible == YEA) ? 1 : 0]++;
                    //huangxu@071203:这个数组有嘛用?还是尝试清0吧。
                    //memset(uentp, 0, sizeof(struct user_info));
                    //todo:需要一个专门的函数处理时间计算。
                }
            }
        }
        utmpshm->usersum = allusers();
        n = USHM_SIZE - 1;
        while (n > 0 && utmpshm->uinfo[n].active == 0)
            n--;
        ftruncate(utmpfd, 0);
        write(utmpfd, utmpshm->uinfo, (n + 1) * sizeof(struct user_info));
    }
    flock(utmpfd, LOCK_UN);
    close(utmpfd);
    return i + 1;
}
示例#19
0
/*!
  @abstract    Merge multiple sorted BAM.
  @param  is_by_qname whether to sort by query name
  @param  out  output BAM file name
  @param  headers  name of SAM file from which to copy '@' header lines,
                   or NULL to copy them from the first file to be merged
  @param  n    number of files to be merged
  @param  fn   names of files to be merged

  @discussion Padding information may NOT correctly maintained. This
  function is NOT thread safe.
 */
int bam_merge_core2(int by_qname, const char *out, const char *headers, int n, char * const *fn, int flag, const char *reg, int n_threads, int level)
{
	bamFile fpout, *fp;
	heap1_t *heap;
	bam_header_t *hout = 0;
	bam_header_t *hheaders = NULL;
	int i, j, *RG_len = 0;
	uint64_t idx = 0;
	char **RG = 0, mode[8];
	bam_iter_t *iter = 0;

	if (headers) {
		tamFile fpheaders = sam_open(headers);
		if (fpheaders == 0) {
			const char *message = strerror(errno);
			fprintf(stderr, "[bam_merge_core] cannot open '%s': %s\n", headers, message);
			return -1;
		}
		hheaders = sam_header_read(fpheaders);
		sam_close(fpheaders);
	}

	g_is_by_qname = by_qname;
	fp = (bamFile*)calloc(n, sizeof(bamFile));
	heap = (heap1_t*)calloc(n, sizeof(heap1_t));
	iter = (bam_iter_t*)calloc(n, sizeof(bam_iter_t));
	// prepare RG tag
	if (flag & MERGE_RG) {
		RG = (char**)calloc(n, sizeof(void*));
		RG_len = (int*)calloc(n, sizeof(int));
		for (i = 0; i != n; ++i) {
			int l = strlen(fn[i]);
			const char *s = fn[i];
			if (l > 4 && strcmp(s + l - 4, ".bam") == 0) l -= 4;
			for (j = l - 1; j >= 0; --j) if (s[j] == '/') break;
			++j; l -= j;
			RG[i] = calloc(l + 1, 1);
			RG_len[i] = l;
			strncpy(RG[i], s + j, l);
		}
	}
	// read the first
	for (i = 0; i != n; ++i) {
		bam_header_t *hin;
		fp[i] = bam_open(fn[i], "r");
		if (fp[i] == 0) {
			int j;
			fprintf(stderr, "[bam_merge_core] fail to open file %s\n", fn[i]);
			for (j = 0; j < i; ++j) bam_close(fp[j]);
			free(fp); free(heap);
			// FIXME: possible memory leak
			return -1;
		}
		hin = bam_header_read(fp[i]);
		if (i == 0) { // the first BAM
			hout = hin;
		} else { // validate multiple baf
			int min_n_targets = hout->n_targets;
			if (hin->n_targets < min_n_targets) min_n_targets = hin->n_targets;

			for (j = 0; j < min_n_targets; ++j)
				if (strcmp(hout->target_name[j], hin->target_name[j]) != 0) {
					fprintf(stderr, "[bam_merge_core] different target sequence name: '%s' != '%s' in file '%s'\n",
							hout->target_name[j], hin->target_name[j], fn[i]);
					return -1;
				}

			// If this input file has additional target reference sequences,
			// add them to the headers to be output
			if (hin->n_targets > hout->n_targets) {
				swap_header_targets(hout, hin);
				// FIXME Possibly we should also create @SQ text headers
				// for the newly added reference sequences
			}

			bam_header_destroy(hin);
		}
	}

	if (hheaders) {
		// If the text headers to be swapped in include any @SQ headers,
		// check that they are consistent with the existing binary list
		// of reference information.
		if (hheaders->n_targets > 0) {
			if (hout->n_targets != hheaders->n_targets) {
				fprintf(stderr, "[bam_merge_core] number of @SQ headers in '%s' differs from number of target sequences\n", headers);
				if (!reg) return -1;
			}
			for (j = 0; j < hout->n_targets; ++j)
				if (strcmp(hout->target_name[j], hheaders->target_name[j]) != 0) {
					fprintf(stderr, "[bam_merge_core] @SQ header '%s' in '%s' differs from target sequence\n", hheaders->target_name[j], headers);
					if (!reg) return -1;
				}
		}

		swap_header_text(hout, hheaders);
		bam_header_destroy(hheaders);
	}

	if (reg) {
		int tid, beg, end;
		if (bam_parse_region(hout, reg, &tid, &beg, &end) < 0) {
			fprintf(stderr, "[%s] Malformated region string or undefined reference name\n", __func__);
			return -1;
		}
		for (i = 0; i < n; ++i) {
			bam_index_t *idx;
			idx = bam_index_load(fn[i]);
			iter[i] = bam_iter_query(idx, tid, beg, end);
			bam_index_destroy(idx);
		}
	}

	for (i = 0; i < n; ++i) {
		heap1_t *h = heap + i;
		h->i = i;
		h->b = (bam1_t*)calloc(1, sizeof(bam1_t));
		if (bam_iter_read(fp[i], iter[i], h->b) >= 0) {
			h->pos = ((uint64_t)h->b->core.tid<<32) | (uint32_t)((int32_t)h->b->core.pos+1)<<1 | bam1_strand(h->b);
			h->idx = idx++;
		}
		else h->pos = HEAP_EMPTY;
	}
	if (flag & MERGE_UNCOMP) level = 0;
	else if (flag & MERGE_LEVEL1) level = 1;
	strcpy(mode, "w");
	if (level >= 0) sprintf(mode + 1, "%d", level < 9? level : 9);
	if ((fpout = strcmp(out, "-")? bam_open(out, "w") : bam_dopen(fileno(stdout), "w")) == 0) {
		fprintf(stderr, "[%s] fail to create the output file.\n", __func__);
		return -1;
	}
	bam_header_write(fpout, hout);
	bam_header_destroy(hout);
	if (!(flag & MERGE_UNCOMP)) bgzf_mt(fpout, n_threads, 256);

	ks_heapmake(heap, n, heap);
	while (heap->pos != HEAP_EMPTY) {
		bam1_t *b = heap->b;
		if (flag & MERGE_RG) {
			uint8_t *rg = bam_aux_get(b, "RG");
			if (rg) bam_aux_del(b, rg);
			bam_aux_append(b, "RG", 'Z', RG_len[heap->i] + 1, (uint8_t*)RG[heap->i]);
		}
		bam_write1_core(fpout, &b->core, b->data_len, b->data);
		if ((j = bam_iter_read(fp[heap->i], iter[heap->i], b)) >= 0) {
			heap->pos = ((uint64_t)b->core.tid<<32) | (uint32_t)((int)b->core.pos+1)<<1 | bam1_strand(b);
			heap->idx = idx++;
		} else if (j == -1) {
			heap->pos = HEAP_EMPTY;
			free(heap->b->data); free(heap->b);
			heap->b = 0;
		} else fprintf(stderr, "[bam_merge_core] '%s' is truncated. Continue anyway.\n", fn[heap->i]);
		ks_heapadjust(heap, 0, n, heap);
	}

	if (flag & MERGE_RG) {
		for (i = 0; i != n; ++i) free(RG[i]);
		free(RG); free(RG_len);
	}
	for (i = 0; i != n; ++i) {
		bam_iter_destroy(iter[i]);
		bam_close(fp[i]);
	}
	bam_close(fpout);
	free(fp); free(heap); free(iter);
	return 0;
}
示例#20
0
static int dict_read_header( const char *filename,
			     dictData *header, int computeCRC )
{
   FILE          *str;
   int           id1, id2, si1, si2;
   char          buffer[BUFFERSIZE];
   int           extraLength, subLength;
   int           i;
   char          *pt;
   int           c;
   struct stat   sb;
   unsigned long crc   = crc32( 0L, Z_NULL, 0 );
   int           count;
   unsigned long offset;

   if (!(str = gd_fopen( filename, "rb" )))
   {
      err_fatal_errno( __func__,
		       "Cannot open data file \"%s\" for read\n", filename );
      return 1;
   }

   header->filename     = NULL;//str_find( filename );
   header->headerLength = GZ_XLEN - 1;
   header->type         = DICT_UNKNOWN;
   
   id1                  = getc( str );
   id2                  = getc( str );

   if (id1 != GZ_MAGIC1 || id2 != GZ_MAGIC2) {
      header->type = DICT_TEXT;
      fstat( fileno( str ), &sb );
      header->compressedLength = header->length = sb.st_size;
      header->origFilename     = NULL;//str_find( filename );
      header->mtime            = sb.st_mtime;
      if (computeCRC) {
	 rewind( str );
	 while (!feof( str )) {
	    if ((count = fread( buffer, 1, BUFFERSIZE, str ))) {
	       crc = crc32( crc, (Bytef *)buffer, count );
	    }
	 }
      }
      header->crc = crc;
      fclose( str );
      return 0;
   }
   header->type = DICT_GZIP;
   
   header->method       = getc( str );
   header->flags        = getc( str );
   header->mtime        = getc( str ) <<  0;
   header->mtime       |= getc( str ) <<  8;
   header->mtime       |= getc( str ) << 16;
   header->mtime       |= getc( str ) << 24;
   header->extraFlags   = getc( str );
   header->os           = getc( str );
   
   if (header->flags & GZ_FEXTRA) {
      extraLength          = getc( str ) << 0;
      extraLength         |= getc( str ) << 8;
      header->headerLength += extraLength + 2;
      si1                  = getc( str );
      si2                  = getc( str );
      
      if (si1 == GZ_RND_S1 && si2 == GZ_RND_S2) {
	 subLength            = getc( str ) << 0;
	 subLength           |= getc( str ) << 8;
	 header->version      = getc( str ) << 0;
	 header->version     |= getc( str ) << 8;
	 
	 if (header->version != 1)
	 {
	    err_internal( __func__,
			  "dzip header version %d not supported\n",
			  header->version );
	    fclose( str );
	    return 1;
	 }
   
	 header->chunkLength  = getc( str ) << 0;
	 header->chunkLength |= getc( str ) << 8;
	 header->chunkCount   = getc( str ) << 0;
	 header->chunkCount  |= getc( str ) << 8;
	 
	 if (header->chunkCount <= 0) {
	    fclose( str );
	    return 5;
	 }
	 header->chunks = xmalloc( sizeof( header->chunks[0] )
				   * header->chunkCount );
	 for (i = 0; i < header->chunkCount; i++) {
	    header->chunks[i]  = getc( str ) << 0;
	    header->chunks[i] |= getc( str ) << 8;
	 }
	 header->type = DICT_DZIP;
      } else {
	 fseek( str, header->headerLength, SEEK_SET );
      }
   }
   
   if (header->flags & GZ_FNAME) { /* FIXME! Add checking against header len */
      pt = buffer;
      while ((c = getc( str )) && c != EOF){
	 *pt++ = c;

	 if (pt == buffer + sizeof (buffer)){
	    err_fatal (
	       __func__,
	       "too long FNAME field in dzip file \"%s\"\n", filename);
	    fclose( str );
	    return 1;
	 }
      }

      *pt = '\0';
      header->origFilename = NULL;//str_find( buffer );
      header->headerLength += strlen( buffer ) + 1;
   } else {
      header->origFilename = NULL;
   }
   
   if (header->flags & GZ_COMMENT) { /* FIXME! Add checking for header len */
      pt = buffer;
      while ((c = getc( str )) && c != EOF){
	 *pt++ = c;

	 if (pt == buffer + sizeof (buffer)){
	    err_fatal (
	       __func__,
	       "too long COMMENT field in dzip file \"%s\"\n", filename);
	    fclose( str );
	    return 1;
	 }
      }

      *pt = '\0';
      header->comment = NULL;//str_find( buffer );
      header->headerLength += strlen( header->comment ) + 1;
   } else {
      header->comment = NULL;
   }

   if (header->flags & GZ_FHCRC) {
      getc( str );
      getc( str );
      header->headerLength += 2;
   }

   if (ftell( str ) != header->headerLength + 1)
   {
      err_internal( __func__,
		    "File position (%lu) != header length + 1 (%d)\n",
		    ftell( str ), header->headerLength + 1 );
      fclose( str );
      return 1;
   }

   fseek( str, -8, SEEK_END );
   header->crc     = getc( str ) <<  0;
   header->crc    |= getc( str ) <<  8;
   header->crc    |= getc( str ) << 16;
   header->crc    |= getc( str ) << 24;
   header->length  = getc( str ) <<  0;
   header->length |= getc( str ) <<  8;
   header->length |= getc( str ) << 16;
   header->length |= getc( str ) << 24;
   header->compressedLength = ftell( str );

				/* Compute offsets */
   header->offsets = xmalloc( sizeof( header->offsets[0] )
			      * header->chunkCount );
   for (offset = header->headerLength + 1, i = 0;
	i < header->chunkCount;
	i++)
   {
      header->offsets[i] = offset;
      offset += header->chunks[i];
   }

   fclose( str );
   return 0;
}
示例#21
0
void
output_listing(char *ifilename)
{
	char buf[1024];
	FILE *ifile;
	struct instruction *cur_instr;
	patch_t *cur_patch;
	symbol_node_t *cur_func;
	int *func_values;
	int instrcount;
	int instrptr;
	int line;
	int func_count;
	int skip_addr;

	instrcount = 0;
	instrptr = 0;
	line = 1;
	skip_addr = 0;
	if ((ifile = fopen(ifilename, "r")) == NULL) {
		perror(ifilename);
		stop(NULL, EX_DATAERR);
	}

	/*
	 * Determine which options to apply to this listing.
	 */
	for (func_count = 0, cur_func = SLIST_FIRST(&patch_functions);
	    cur_func != NULL;
	    cur_func = SLIST_NEXT(cur_func, links))
		func_count++;

	func_values = NULL;
	if (func_count != 0) {
		func_values = (int *)malloc(func_count * sizeof(int));

		if (func_values == NULL)
			stop("Could not malloc", EX_OSERR);
		
		func_values[0] = 0; /* FALSE func */
		func_count--;

		/*
		 * Ask the user to fill in the return values for
		 * the rest of the functions.
		 */
		
		
		for (cur_func = SLIST_FIRST(&patch_functions);
		     cur_func != NULL && SLIST_NEXT(cur_func, links) != NULL;
		     cur_func = SLIST_NEXT(cur_func, links), func_count--) {
			int input;
			
			fprintf(stdout, "\n(%s)\n", cur_func->symbol->name);
			fprintf(stdout,
				"Enter the return value for "
				"this expression[T/F]:");

			while (1) {

				input = getchar();
				input = toupper(input);

				if (input == 'T') {
					func_values[func_count] = 1;
					break;
				} else if (input == 'F') {
					func_values[func_count] = 0;
					break;
				}
			}
			if (isatty(fileno(stdin)) == 0)
				putchar(input);
		}
		fprintf(stdout, "\nThanks!\n");
	}

	/* Now output the listing */
	cur_patch = STAILQ_FIRST(&patches);
	for (cur_instr = STAILQ_FIRST(&seq_program);
	     cur_instr != NULL;
	     cur_instr = STAILQ_NEXT(cur_instr, links), instrcount++) {

		if (check_patch(&cur_patch, instrcount,
				&skip_addr, func_values) == 0) {
			/* Don't count this instruction as it is in a patch
			 * that was removed.
			 */
                        continue;
		}

		while (line < cur_instr->srcline) {
			fgets(buf, sizeof(buf), ifile);
				fprintf(listfile, "\t\t%s", buf);
				line++;
		}
		fprintf(listfile, "%03x %02x%02x%02x%02x", instrptr,
#if BYTE_ORDER == LITTLE_ENDIAN
			cur_instr->format.bytes[0],
			cur_instr->format.bytes[1],
			cur_instr->format.bytes[2],
			cur_instr->format.bytes[3]);
#else
			cur_instr->format.bytes[3],
			cur_instr->format.bytes[2],
			cur_instr->format.bytes[1],
			cur_instr->format.bytes[0]);
#endif
		fgets(buf, sizeof(buf), ifile);
		fprintf(listfile, "\t%s", buf);
		line++;
		instrptr++;
	}
	/* Dump the remainder of the file */
	while(fgets(buf, sizeof(buf), ifile) != NULL)
		fprintf(listfile, "\t\t%s", buf);

	fclose(ifile);
}
示例#22
0
int GWEN_Gui_CProgress_Advance(GWEN_GUI_CPROGRESS *cp, uint64_t progress) {
#ifndef OS_WIN32
  int fl;
#endif

  assert(cp);
  if (!cp->shown) {
    time_t t1;

    t1=time(0);
    if (difftime(t1, cp->startTime)>GWEN_GUI_DELAY_SECS) {
      if (!(GWEN_Gui_GetFlags(cp->gui) & GWEN_GUI_FLAGS_NONINTERACTIVE))
        GWEN_Gui_StdPrintf(cp->gui, stderr, "%s: Started.\n", cp->title);
      cp->shown=1;
    }
  }

  if (progress==GWEN_GUI_PROGRESS_ONE)
    progress=cp->current+1;
  if (progress!=GWEN_GUI_PROGRESS_NONE) {
    if (progress!=cp->current) {
      if (cp->shown) {
        if (!(GWEN_Gui_GetFlags(cp->gui) & GWEN_GUI_FLAGS_NONINTERACTIVE)) {
          if (cp->total==GWEN_GUI_PROGRESS_NONE)
            GWEN_Gui_StdPrintf(cp->gui, stderr, "%s: %llu\n", cp->title,
                               (long long unsigned)progress);
          else
            GWEN_Gui_StdPrintf(cp->gui, stderr, "%s: %llu of %llu\n",
                               cp->title,
                               (long long unsigned)progress,
                               (long long unsigned)cp->total);
        }
      }
      cp->current=progress;
    }
  }
  if (cp->aborted)
    return GWEN_ERROR_USER_ABORTED;

#ifndef OS_WIN32
  if (!(GWEN_Gui_GetFlags(cp->gui) & GWEN_GUI_FLAGS_NONINTERACTIVE)) {
    /* check for abort */
    fl=fcntl(fileno(stdin), F_GETFL);
    if (fl!=-1) {
      int chr;

      /* set stdin to nonblocking */
      if (fcntl(fileno(stdin), F_SETFL, fl | O_NONBLOCK)) {
        DBG_INFO(GWEN_LOGDOMAIN, "fcntl(stdin): %s", strerror(errno));
        return 0;
      }
      /* check whether there is a character */
      chr=getchar();
      /* set blocking mode to what we found before modification */
      fcntl(fileno(stdin), F_SETFL, fl);
      if (chr==GWEN_GUI_CPROGRESS_CHAR_ABORT) {
        GWEN_Gui_StdPrintf(cp->gui, stderr, "------> ABORTED BY USER\n");
        cp->aborted=1;
        return GWEN_ERROR_USER_ABORTED;
      }
    }
  }
#endif

  return 0;
}
示例#23
0
文件: poll.c 项目: shoshan/workspace
  int
  main(int argc,char **argv) {
      int z;              /* General status code */
      int f1;             /* Open fifo 1 */
      int f2;             /* Open fifo 2 */
      struct pollfd fds[2]; /* Poll events */
      int nfds;           /* Number of file descriptors */
      char buf[200+1];    /* I/O Buffer */
      FILE *p1, *p2;      /* Pipes from popen(3) */
 
      /*
       * Pipes :
        */
       if ( !(p1 = popen("ls -l|tr '[a-z]''[A-Z]'","r")) )
           quit(1,"popen(3) failed for p1");
 
       if ( !(p2 = popen("ls -l|tr '[A-Z]''[a-z]'&& sleep 8","r")) )
           quit(1,"popen(3) failed for p2");
 
       /*
        * Obtain the underlying file descriptors :
        */
       f1 = fileno(p1);
       fds[0].fd = f1;             /* File descriptor to poll.. */
       fds[0].events = POLLIN;     /* for input events */
 
       f2 = fileno(p2);
       fds[1].fd = f2;             /* File descriptor to poll.. */
       fds[1].events = POLLIN;     /* for input events */
 
       nfds = 2;                   /* nfds is fds[2] array size */
 
       printf("BEGUN: f1=%d, f2=%d\n",f1,f2);
 
       /*
        * Enter a poll loop :
        */
       do {
           do {
               z = poll(fds,nfds,3500); /* Timeout is 3.5 seconds
*/
           } while ( z == -1 && errno == EINTR );
 
           if ( z == -1 )          /* Error? */
               quit(13,"poll(2)");
           if ( z == 0 ) {
               printf("TIMEOUT: f1=%d, f2=%d\n",f1,f2);
               continue;
           }
 
           /*
            * Control is here if f1 or f2 has data
            * available to be read.
            */
           if ( fds[0].revents & POLLIN ) {
               z = read(f1,buf,sizeof buf-1);
               if ( z == -1 )
                   quit(6,"read(2) of f1.");
               if ( z > 0 ) {
                   buf[z] = 0;
                   printf("*** read %d bytes <<<%s>>> from f1;\n",z,buf);
               } else {
                   puts("read EOF from f1;");
                   pclose(p1);
                   fds[0].fd = f1 = -1;
               }
           }
 
           if ( fds[1].revents & POLLIN ) {
               z = read(f2,buf,sizeof buf-1);
              if ( z == -1 )
                       quit(6,"read(2) of f2.");
                   if ( z > 0 ) {
                        buf[z] = 0;
                        printf("*** read %d bytes <<<%s>>> from f2;\n",z,buf);
                   } else {
                        puts("read EOF from f2;");
                        pclose(p2);
                        fds[1].fd = f2 = -1;
                   }
             }
 
         } while ( f1 >= 0 || f2 >= 0 );
 
         puts("End poll.");
 
         return 0;
  }
static void test_mmap_wrong_format_version (const char * tmpFile)
{
	// first write a mmap file
	{
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = simpleTestKeySet ();
		succeed_if (plugin->kdbSet (plugin, ks, parentKey) == 1, "kdbSet was not successful");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}

	// set wrong version number in mmap header
	FILE * fp;
	if ((fp = fopen (tmpFile, "r+")) == 0)
	{
		yield_error ("fopen() error");
	}
	struct stat sbuf;
	if (stat (tmpFile, &sbuf) == -1)
	{
		yield_error ("stat() error");
	}

	int fd = fileno (fp);
	char * mappedRegion = mmap (0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (mappedRegion == MAP_FAILED)
	{
		ELEKTRA_LOG_WARNING ("error mapping file %s\nmmapSize: " ELEKTRA_STAT_ST_SIZE_F, tmpFile, sbuf.st_size);
		yield_error ("mmap() error");
		return;
	}
	if (fp)
	{
		fclose (fp);
	}

	MmapHeader * mmapHeader = (MmapHeader *) mappedRegion;
	mmapHeader->formatVersion = ELEKTRA_MMAP_FORMAT_VERSION + 1;

	if (msync ((void *) mappedRegion, sbuf.st_size, MS_SYNC) != 0)
	{
		yield_error ("msync() error");
		return;
	}

	if (munmap (mappedRegion, sbuf.st_size) != 0)
	{
		yield_error ("munmap() error");
		return;
	}

	// wrong format version should be detected now
	{
		// we expect an error here
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = ksNew (0, KS_END);
		succeed_if (plugin->kdbGet (plugin, ks, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR,
			    "kdbGet did not detect wrong format version");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}
}
示例#25
0
int
build_peers_from_cache(char *fname, peers_t *resp)
{
    FILE *fh;
    int cnt = 0;
    char filepath[MAXPATHLEN];
    char *p;
    int fd;
    char host[MAXHOSTNAME+2];

#ifdef DEBUG
    printf("build_peers_from_cache %s : Processing query for file : %s\n", localhostname, fname);
#endif

    resp->count = 0;
    sprintf(filepath, "%s/%s", SERVER_DIR, fname);
    fh = fopen(filepath, "r");
    if (fh == NULL) {
        return (cnt);
    }

    /*
     * If we have reached here there is possibly a peer which is serving this
     * file.
     */
    fd = fileno(fh);

    /*
     * Obtain a shared lock on the file while we are reading the contents.
     * This would block any modifications to the file while we are searching.
     * However, other searches can continue to access it.
     */
    flock(fd, LOCK_SH);

    while (cnt < MAXCOUNT && fscanf(fh, "%s\n", host) != EOF) {
        resp->peer[cnt] = malloc((MAXHOSTNAME + 2) * sizeof(char));
        if (resp->peer[cnt] == NULL) {
            printf("search_cache: Out of memory !! Quitting !\n");
            exit (1);	
        }
        strcpy(resp->peer[cnt], host);
        cnt++;
    }

    /*
     * Pass back the count of peers that are serving this file.
     */
	resp->count = cnt;

    flock(fd, LOCK_UN);
    fclose(fh);
    close(fd);

#ifdef DEBUG
    {
        int i;
        printf("Peers serving %s = %d \n", fname, resp->count);
        for (i = 0; i < resp->count; i++) {
            printf("hostname : %s\n", resp->peer[i]);
        }
    }
#endif /* DEBUG */

	return (cnt);
}
static void test_mmap_wrong_magic_keyset (const char * tmpFile)
{
	// first write a mmap file
	{
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = simpleTestKeySet ();
		succeed_if (plugin->kdbSet (plugin, ks, parentKey) == 1, "kdbSet was not successful");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}

	// now manipulate magic keyset inside the mapped region
	FILE * fp;
	if ((fp = fopen (tmpFile, "r+")) == 0)
	{
		yield_error ("fopen() error");
	}
	struct stat sbuf;
	if (stat (tmpFile, &sbuf) == -1)
	{
		yield_error ("stat() error");
	}

	int fd = fileno (fp);
	char * mappedRegion = mmap (0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (mappedRegion == MAP_FAILED)
	{
		ELEKTRA_LOG_WARNING ("error mapping file %s\nmmapSize: " ELEKTRA_STAT_ST_SIZE_F, tmpFile, sbuf.st_size);
		yield_error ("mmap() error");
		return;
	}
	if (fp)
	{
		fclose (fp);
	}

	KeySet * magicKs = (KeySet *) (mappedRegion + sizeof (MmapHeader));
	magicKs->size = 1234; // magic keyset contains SIZE_MAX here

	if (msync ((void *) mappedRegion, sbuf.st_size, MS_SYNC) != 0)
	{
		yield_error ("msync() error");
		return;
	}

	if (munmap (mappedRegion, sbuf.st_size) != 0)
	{
		yield_error ("munmap() error");
		return;
	}

	// manipulated magic keyset should be detected now
	{
		// we expect an error here
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = ksNew (0, KS_END);
		succeed_if (plugin->kdbGet (plugin, ks, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR,
			    "kdbGet did not detect wrong magic keyset");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}
}
示例#27
0
bool_t
search_1_svc(query_req *argp, query_rec *result, struct svc_req *rqstp)
{
	bool_t retval = TRUE;
	b_query_req *query;
    query_node_t *node;
    char *p;
	char fname[MAXPATHLEN];
    char peer[MAXHOSTNAME+2];
	int i, fd;
    FILE *fh;
	peers_t resp;
    int ret;
    struct timeval now;
    struct timespec timeout;

#ifdef DEBUG
    printf("search_1_svc() %s  : Received request for file : %s\n", localhostname, argp->fname);
#endif

    /*
     * Build the b_query_req for this request.
     */
    if ((query = (b_query_req *) malloc(sizeof(b_query_req))) == NULL) {
        printf("Failed to allocate memory !\n");
        printf("Hoping the reaper thread will free some memory !\n");
        goto send_result;
    }

	query->id.hostid = gethostid();
	query->id.seqno = getseqno(); 
    query->ttl = MAXTTL;
    strcpy(query->uphost, localhostname);
    strcpy(query->fname, argp->fname);

    /*
     * Now propagate the query to the peers.
     */
    node = b_query_propagate(query, LOCKED);

    /*
     * If we propagated to some peers then we should wait for some time for the
     * results to arrive and send the results.
     */
    if (node) { 
        if (node->sent) {
            /*
             * We now wait for a max of WAITTIME (1 second) on the CV (allhome_cv).
             * And the b_hitquery_reply() signals the CV when all the
             * peers that we had queried have reponded back. However, if no one
             * responds back we bail out in 1 secs.
             *
             * NOTE : This timeout may be short for large number of nodes.
             * However, for the current set up of upto to 12 nodes this is
             * reasonable.
             */
            gettimeofday(&now, NULL);
            timeout.tv_sec = now.tv_sec + WAITTIME;
            timeout.tv_nsec = now.tv_usec *1000;

            pthread_cond_timedwait(&node->allhome_cv, &node->node_lock, &timeout);
        }
        pthread_mutex_unlock(&node->node_lock);
    }

send_result:
    /*
     * At this point we should have received results from our peers and their
     * peers and the local cache should have been updated. So we now send our
     * hits from the local cache.
     */
    sprintf(fname, "%s/%s", SERVER_DIR, argp->fname);

    fh = fopen(fname, "r");
    if (fh == NULL) {
        printf("search_1_svc:Failed to open filename %s : errno = %d\n", fname, errno);
        result->count = 0;
        return retval;
    }

    fd = fileno(fh);
    flock(fd, LOCK_SH);

    strcpy(result->fname, argp->fname);
    result->count = 0;
    p = result->peers; 
    
    while (fgets(p, MAXHOSTNAME, fh) != NULL) {
        p[strlen(p) - 1] = '\0';
        result->count++;
        /* 
         * We have filled up the response with MAXCOUNT results.
         * Send it back.
         */
        if (result->count == MAXCOUNT) {
            flock(fd, LOCK_UN);
            fclose(fh);
            close(fd);
            result->eof = 0;
            return retval;
        }
        p += MAXHOSTNAME;
    }

    printf("p = %s\n", p);
    /*
    if (*p) {
        result->count++;
    }
    */

    flock(fd, LOCK_UN);
    fclose(fh);
    close(fd);
    result->eof = 1;
#ifdef DEBUG
    printf("search_1_svc: Done. count = %d\n", result->count);
#endif
	return retval;
}
示例#28
0
static void  Usage( void )
/************************/
{
    char const  **list;
    char const  *p;
    int         lines_printed;
    unsigned int i, n;
    auto        char buf[82];
#ifndef __UNIX__
    int const   paging = isatty( fileno( stdout ) );
    int const   height = 24; /* Number of lines assumed on screen */
#endif

    print_banner();
    lines_printed = 4;
    list = EnglishHelp;
    while( *list ) {
        memset( buf, ' ', 80 );
        if( **list == '[' ) {                   /* title to be centered */
            i = strlen( *list );
            strcpy( &buf[38 - i / 2], *list );
            ++list;
            for( n = 0; list[n]; ++n ) {        /* count number in list */
                if( *list[n] == '[' ) {
                    break;
                }
            }
            n = (n + 1) / 2;                    /* half way through list */
#ifndef __UNIX__
            if( paging && lines_printed != 0 && lines_printed >= height ) {
                fputs( WclMsgs[PRESS_ANY_KEY_TO_CONTINUE], stdout );
                fflush( stdout );
                getch();
                puts( "" );
                lines_printed = 0;
            }
#endif
            puts( buf );
            lines_printed++;
            for( ;; ) {
                memset( buf, ' ', 80 );
                p = *list;
                if( p == NULL )
                    break;
                for( i = 0; *p; )
                    buf[i++] = *p++;
                p = list[n];
                if( p != NULL  &&  *p != '[' ) {
                    for( i = 38; *p; ) {
                        buf[i++] = *p++;
                    }
                }
                buf[i] = '\0';
                puts( buf );
                lines_printed++;
#ifndef __UNIX__
                if( paging && lines_printed != 0 && lines_printed >= height ) {
                    fputs( WclMsgs[PRESS_ANY_KEY_TO_CONTINUE], stdout );
                    fflush( stdout );
                    getch();
                    puts( "" );
                    lines_printed = 0;
                }
#endif
                p = list[n];
                if( p == NULL )
                    break;
                if( *p == '[' )
                    break;
                list[n] = NULL; /* indicate already printed */
                ++list;
            }
            list = &list[n];
        } else {
            puts( *list );
            lines_printed++;
            ++list;
        }
    }
}
示例#29
0
文件: RNAup.c 项目: jrgreen7/SMIRP
/*--------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
  char *string1=NULL, *string2=NULL, *temp, *line;
  char *structure=NULL, *cstruc=NULL;
  char  fname[53], my_contrib[10], *up_out;
  char  *ParamFile=NULL;
  char  *ns_bases=NULL, *c;
  int   i, length1,length2,length, l, sym, r;
  double energy, min_en;
  double kT, sfact=1.07;
  int   pf, istty;
  int noconv=0;
  double Zu, Zup;
  /* variables for output */
  pu_contrib *unstr_out, *unstr_short;
  FLT_OR_DBL **inter_out;
  char *title;
  /* commandline parameters */
  int w;       /* length of region of interaction */
  int incr3;   /* add x unpaired bases after 3'end of short RNA*/
  int incr5;   /* add x unpaired bases after 5'end of short RNA*/
  int  unstr;  /* length of unpaired region for output*/
  int  upmode; /* output mode for pf_unpaired and pf_up()*/
  upmode = 0;
  unstr = 4; 
  incr3=0;
  incr5=0;
  w=25;
  do_backtrack = 1;
  pf=1; /* partition function has to be calculated */
  length1=length2=0;
  up_out=NULL;
  title=NULL;
  unstr_out=NULL;
  inter_out=NULL;
  my_contrib[0] = 'S';
  my_contrib[1] = '\0';
  
  for (i=1; i<argc; i++) {
    if (argv[i][0]=='-') 
      switch ( argv[i][1] )
	{
	case 'T':  if (argv[i][2]!='\0') usage();
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i], "%lf", &temperature);
	  if (!r) usage();
	  break;
	case 'w':
	  /* -w maximal length of unstructured region */  
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i],"%d", &w);
	  if (!r) usage();
	  break;
	case 'n':
	  if ( strcmp(argv[i], "-noGU")==0) noGU=1;
	  if ( strcmp(argv[i], "-noCloseGU")==0) no_closingGU=1;
	  if ( strcmp(argv[i], "-noLP")==0) noLonelyPairs=1;
	  if ( strcmp(argv[i], "-nsp") ==0) {
	    if (i==argc-1) usage();
	    ns_bases = argv[++i];
	  }
	  if ( strcmp(argv[i], "-noconv")==0) noconv=1;
	  break;
	case '4':
	  tetra_loop=0;
	  break;
	case 'e':
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i],"%d", &energy_set);
	  if (!r) usage();
	  break;
	case 'C':
	  fold_constrained=1;
	  break;
	case 'S':
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i],"%lf", &sfact);
	  if (!r) usage();
	  break;
	case 'd': dangles=0;
	  if (argv[i][2]!='\0') {
	    r=sscanf(argv[i]+2, "%d", &dangles);
	    if (r!=1) usage();
	  }
	  break;
	case 'o': upmode=1;
	  /* output mode 0: non, 1:only pr_unpaired, 2: pr_unpaired + pr_up */
	  if (argv[i][2]!='\0') {
	    r=sscanf(argv[i]+2, "%d", &upmode);
	    if (r!=1) usage();
	  }
	  break;
	case 'u':
	  /* -u length of unstructured region in pr_unpaired output
	     makes only sense in combination with -o1 or -o2 */  
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i],"%d", &unstr);
	  if (!r) usage();
	  break;
	  /* incr5 and incr3 are only for the longer (target) sequence */
	  /* increments w (length of the unpaired region) to incr5+w+incr3*/
	  /* the longer sequence is given in 5'(= position 1) to */
	  /* 3' (=position n) direction */
	  /* incr5 adds incr5 residues to the 5' end of w */
	case '5':
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i],"%d", &incr5);
	  if (!r) usage();
	  break; 
	  /* incr3 adds incr3 residues to the 3' end of w */
	case '3':
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i],"%d", &incr3);
	  if (!r) usage();
	  break;
	case 'P':
	  if (i==argc-1) usage();
	  ParamFile = argv[++i];
	  break;
	case 'x':  
	  if(i==argc-1) usage();
	  r=sscanf(argv[++i], "%s", my_contrib);
	  if (!r) usage();
	  break;  
	default: usage();
	} 
  }
  
  if (ParamFile != NULL)
    read_parameter_file(ParamFile);
   
  if (ns_bases != NULL) {
    nonstandards = space(33);
    c=ns_bases;
    i=sym=0;
    if (*c=='-') {
      sym=1; c++;
    }
    while (*c!='\0') {
      if (*c!=',') {
	nonstandards[i++]=*c++;
	nonstandards[i++]=*c;
	if ((sym)&&(*c!=*(c-1))) {
	  nonstandards[i++]=*c;
	  nonstandards[i++]=*(c-1);
	}
      }
      c++;
    }
  }
  istty = isatty(fileno(stdout))&&isatty(fileno(stdin));
  if ((fold_constrained)&&(istty)) {
    printf("Input constraints using the following notation:\n");
    printf("| : paired with another base\n");
    printf(". : no constraint at all\n");
    printf("x : base must not pair\n");
    printf("< : base i is paired with a base j<i\n");
    printf("> : base i is paired with a base j>i\n");
    printf("matching brackets ( ): base i pairs base j\n");
  } 
	
  do {				/* main loop: continue until end of file */
    cut_point=-1;
    if (istty) {
      printf("\nInput string (upper or lower case); @ to quit\n");
      printf("Use '&' to connect 2 sequences that shall form a complex.\n");
      printf("%s%s\n", scale1, scale2);
    }
    fname[0]='\0';
   
    if ((line = get_line(stdin))==NULL) break;

    /* skip comment lines and get filenames */
    while ((*line=='*')||(*line=='\0')||(*line=='>')) {
      if (*line=='>')
	
	(void) sscanf(line, ">%51s", fname);
      free(line);
      if ((line = get_line(stdin))==NULL) break;
    } 
    if ((line == NULL) || (strcmp(line, "@") == 0)) break;

    tokenize(line,&string1,&string2);
    
    if(upmode != 0){
      if(cut_point == -1 && upmode == 2) {
	  nrerror("only one sequence - can not cofold one sequence!");
      }
    } else {
      if(cut_point == -1){
	upmode=1;
      } else {
	upmode=2;
      }
    }
    
    if(string1 != NULL)
      length1 = (int) strlen(string1);
    if(string2 != NULL) 
      length2 = (int) strlen(string2);
    else
      length2=0;    

    /* write longer seq in string1 and and shorter one in string2 */ 
    if(length1 < length2)
      {
	length=length1; length1=length2; length2=length;
	
	temp=(char *) space(strlen(string1)+1);
	(void) sscanf(string1,"%s",temp);
	string1 = (char *) xrealloc (string1,sizeof(char)*length1+1);
	(void) sscanf(string2,"%s",string1);
	string2 = (char *) xrealloc(string2,sizeof(char)*length2+1);
	(void) sscanf(temp,"%s",string2);
	free(temp);
      }
   
    structure = (char *) space((unsigned) length1+1);
    if (fold_constrained) {
      cstruc = get_line(stdin);
      if (cstruc!=NULL) 
	strncpy(structure, cstruc, length1);
      else
	fprintf(stderr, "constraints missing\n");
    }
    for (l = 0; l < length1; l++) {
      string1[l] = toupper(string1[l]);
      if (!noconv && string1[l] == 'T') string1[l] = 'U';
    }
    for (l = 0; l < length2; l++) {
      string2[l] = toupper(string2[l]);
      if (!noconv && string2[l] == 'T') string2[l] = 'U';
    }

    if (istty)
      printf("length1 = %d\n", length1);
    
    /* initialize_fold(length); */
    update_fold_params();
    printf("\n%s", string1);
    min_en = fold(string1, structure);
    
    if (istty)
      {
	printf("\n minimum free energy = %6.2f kcal/mol\n", min_en);
      }
    else
      printf(" (%6.2f)\n", min_en);
    
    (void) fflush(stdout);
    
    /* parse cml parameters for the filename*/
    if(upmode > 0) {
      char wuadd[10];
      up_out = (char*) space(sizeof(char)*53);
      /* create the name of the output file */
      if(fname[0]!='\0' && up_out[0] =='\0' ){
	if(strlen(fname)< 30){
	  strcpy(up_out, fname);
	} else {  
	  strncpy(up_out, fname,30);
	}
      }
      else if(fname[0]=='\0' && up_out[0] == '\0'){
	char defaultn[10] = "RNA";
	sprintf(up_out,"%s",defaultn);
      }
	
      sprintf(wuadd,"%d",w);
      strcat(up_out, "_w");
      strcat(up_out, wuadd);
      strcat(up_out, "u");
      sprintf(wuadd,"%d",unstr);
      strcat(up_out, wuadd);
      strcat(up_out, "_up.out");
      printf("RNAup output in file: %s\n",up_out);
	    
      /* create the title for the output file */      
      if (title == NULL) {
	char wuadd[10];
	title = (char*) space(sizeof(char)*60);
	if(fname[0]!='\0'){
	  if(strlen(fname)< 30){
	    strcpy(title, fname);
	  } else {  
	    strncpy(title, fname,30);
	  }
	}
	else if (fname[0]=='\0'){
	  char defaultn[10]= "RNAup";
	  sprintf(title,"%s",defaultn);
	}
	sprintf(wuadd,"%d",unstr);
	strcat(title," u=");
	strcat(title, wuadd);
	sprintf(wuadd,"%d",w);
	strcat(title," w=");
	strcat(title, wuadd);
	sprintf(wuadd,"%d",length1);
	strcat(title," n=");
	strcat(title, wuadd);
      }
    } else {
      nrerror("no output format given: use [-o[1|2]] to select output format");
    }
    
    
    if (pf) {
      
      if (dangles==1) {
	dangles=2;   /* recompute with dangles as in pf_fold() */
	min_en = energy_of_struct(string1, structure);
	dangles=1;
      }
	 
      kT = (temperature+273.15)*1.98717/1000.; /* in Kcal */
      
      if(upmode != 0){
	int wplus;
	wplus=w+incr3+incr5;
	/* calculate prob. unstructured for the shorter seq */
	if(upmode == 3) {
	  min_en = fold(string2, structure);
	  pf_scale = exp(-(sfact*min_en)/kT/length2);
	  if (length2>2000) fprintf(stderr, "scaling factor %f\n", pf_scale);
	  init_pf_fold(length2);
	  if (cstruc!=NULL)
	    strncpy(structure, cstruc, length2+1);
	  energy = pf_fold(string2, structure);
	  if(wplus > length2){ wplus = length2;} /* for the shorter seq */
	  unstr_short = pf_unstru(string2, structure, wplus);
	  free_pf_unstru();
	  free_pf_arrays(); /* for arrays for pf_fold(...) */
	}

	/* calculate prob. unstructured for the longer seq */
	wplus=w+incr3+incr5; 
	min_en = fold(string1, structure);
	pf_scale = exp(-(sfact*min_en)/kT/length1);
	if (length1>2000) fprintf(stderr, "scaling factor %f\n", pf_scale);
	init_pf_fold(length1);
	if (cstruc!=NULL)
	  strncpy(structure, cstruc, length1+1);
	energy = pf_fold(string1, structure);
	unstr_out = pf_unstru(string1, structure, wplus);
	free_pf_unstru();
	free_pf_arrays(); /* for arrays for pf_fold(...) */
	/* calculate the interaction between the two sequences */
	if(upmode > 1 && cut_point > -1){
	  inter_out = pf_interact(string1,string2,unstr_out,w, incr3, incr5);
	  if(Up_plot(unstr_out,inter_out,length1,up_out,unstr,my_contrib)==0){
	    nrerror("Up_plot: no output values assigned");
	  }
	} else if(cut_point == -1 && upmode > 1) { /* no second seq given */
	  nrerror("only one sequence given - cannot cofold one sequence!");
	} else { /* plot only the results for prob unstructured */
	  if(Up_plot(unstr_out,NULL,length1,up_out,unstr,my_contrib)==0){
	    nrerror("Up_plot: no output values assigned");
	  }
	}	
      } else {
	nrerror("no output format given: use [-o[1|2]] to select output format");
      }
       
      if (do_backtrack) {
	printf("%s", structure);
	if (!istty) printf(" [%6.2f]\n", energy);
	else printf("\n");
      }
      if ((istty)||(!do_backtrack)) 
	printf(" free energy of ensemble = %6.2f kcal/mol\n", energy);
      energy = pf_fold(string1, structure);
      printf(" frequency of mfe structure in ensemble %g; "
	     "ensemble diversity %-6.2f\n", exp((energy-min_en)/kT),
	     mean_bp_dist(length1));
      free_pf_arrays();
    }
    if (cstruc!=NULL) free(cstruc);
    (void) fflush(stdout);
    if (string1!=NULL) free(string1);
    if (string2!=NULL) free(string2);
    free(structure);
    if(up_out != NULL) free(up_out);
    up_out=NULL;
    if(title != NULL) free(title);
    title=NULL;
    if(upmode == 1) free_pf_two(unstr_out,NULL);
    if(upmode > 1) free_pf_two(unstr_out,inter_out);
    if(upmode == 3)free_pf_two(unstr_short,NULL);
    free_arrays(); /* for arrays for fold(...) */
    
  } while (1);
  return 0;
}
示例#30
0
文件: ftp.c 项目: galexcode/w3m
static int
ftp_pasv(FTP ftp)
{
    int status;
    int n1, n2, n3, n4, p1, p2;
    int data;
    char *p;
    Str tmp;
    int family;
#ifdef INET6
    struct sockaddr_storage sockaddr;
    int sockaddrlen, port;
    unsigned char d1, d2, d3, d4;
    char abuf[INET6_ADDRSTRLEN];
#endif

#ifdef INET6
    sockaddrlen = sizeof(sockaddr);
    if (getpeername(fileno(ftp->wf),
		    (struct sockaddr *)&sockaddr, &sockaddrlen) < 0)
	return -1;
#ifdef HAVE_OLD_SS_FAMILY
    family = sockaddr.__ss_family;
#else
    family = sockaddr.ss_family;
#endif
#else
    family = AF_INET;
#endif
    switch (family) {
#ifdef INET6
    case AF_INET6:
	tmp = ftp_command(ftp, "EPSV", NULL, &status);
	if (status != 229)
	    return -1;
	for (p = tmp->ptr + 4; *p && *p != '('; p++) ;
	if (*p == '\0')
	    return -1;
	if (sscanf(++p, "%c%c%c%d%c", &d1, &d2, &d3, &port, &d4) != 5
	    || d1 != d2 || d1 != d3 || d1 != d4)
	    return -1;
	if (getnameinfo((struct sockaddr *)&sockaddr, sockaddrlen,
			abuf, sizeof(abuf), NULL, 0, NI_NUMERICHOST) != 0)
	    return -1;
	data = openSocket(abuf, "", port);
	break;
#endif
    case AF_INET:
	tmp = ftp_command(ftp, "PASV", NULL, &status);
	if (status != 227)
	    return -1;
	for (p = tmp->ptr + 4; *p && !IS_DIGIT(*p); p++) ;
	if (*p == '\0')
	    return -1;
	sscanf(p, "%d,%d,%d,%d,%d,%d", &n1, &n2, &n3, &n4, &p1, &p2);
	tmp = Sprintf("%d.%d.%d.%d", n1, n2, n3, n4);
	data = openSocket(tmp->ptr, "", p1 * 256 + p2);
	break;
    default:
	return -1;
    }
    if (data < 0)
	return -1;
    ftp->data = fdopen(data, "rb");
    return 0;
}