コード例 #1
0
ファイル: clnt_udp.c プロジェクト: Kampi/Zybo-Linux
static void
clntudp_destroy (CLIENT *cl)
{
  struct cu_data *cu = (struct cu_data *) cl->cl_private;

  if (cu->cu_closeit)
    {
      (void) __close (cu->cu_sock);
    }
  XDR_DESTROY (&(cu->cu_outxdrs));
  mem_free ((caddr_t) cu, (sizeof (*cu) + cu->cu_sendsz + cu->cu_recvsz));
  mem_free ((caddr_t) cl, sizeof (CLIENT));
}
コード例 #2
0
ファイル: fts.c プロジェクト: avokhmin/RPM5
int
Fts_close(FTS * sp)
{
	register FTSENT *freep, *p;
	int saved_errno;

if (_fts_debug)
fprintf(stderr, "--> Fts_close(%p)\n", sp);

	if (sp == NULL)
		return 0;

	/*
	 * This still works if we haven't read anything -- the dummy structure
	 * points to the root list, so we step through to the end of the root
	 * list which has a valid parent pointer.
	 */
	if (sp->fts_cur) {
		for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
			freep = p;
			p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
			free(freep);
		}
		free(p);
	}

	/* Free up child linked list, sort array, path buffer. */
	if (sp->fts_child)
		fts_lfree(sp->fts_child);
	if (sp->fts_array)
		free(sp->fts_array);
	free(sp->fts_path);

	/* Return to original directory, save errno if necessary. */
	if (!ISSET(FTS_NOCHDIR)) {
		saved_errno = __fchdir(sp->fts_rfd) ? errno : 0;
		(void)__close(sp->fts_rfd);

		/* Set errno and return. */
		if (saved_errno != 0) {
			/* Free up the stream pointer. */
			free(sp);
			__set_errno (saved_errno);
			return (-1);
		}
	}

	/* Free up the stream pointer. */
	free(sp);
	return (0);
}
コード例 #3
0
ファイル: get_clockfreq.c プロジェクト: gf-chen/glibc
static hp_timing_t
__get_clockfreq_via_cpuinfo (void)
{
  hp_timing_t result;
  int fd;

  result = 0;

  fd = __open ("/proc/cpuinfo", O_RDONLY);
  if (fd != -1)
    {
      char buf[8192];
      ssize_t n;

      n = __read (fd, buf, sizeof buf);
      if (n > 0)
	{
	  char *mhz = memmem (buf, n, "Cpu0ClkTck", 7);

	  if (mhz != NULL)
	    {
	      char *endp = buf + n;

	      /* Search for the beginning of the string.  */
	      while (mhz < endp
		     && (*mhz < '0' || *mhz > '9')
		     && (*mhz < 'a' || *mhz > 'f')
		     && *mhz != '\n')
		++mhz;

	      while (mhz < endp && *mhz != '\n')
		{
		  if ((*mhz >= '0' && *mhz <= '9') ||
		      (*mhz >= 'a' && *mhz <= 'f'))
		    {
		      result <<= 4;
		      if (*mhz >= '0' && *mhz <= '9')
			result += *mhz - '0';
		      else
			result += (*mhz - 'a') + 10;
		    }
		  ++mhz;
		}
	    }
	}

      __close (fd);
    }

  return result;
}
コード例 #4
0
ファイル: spawn.c プロジェクト: NanXiao/illumos-joyent
static int
perform_file_actions(file_attr_t *fap, void *dirbuf)
{
	file_attr_t *froot = fap;
	int fd;

	do {
		switch (fap->fa_type) {
		case FA_OPEN:
			fd = __open(fap->fa_path, fap->fa_oflag, fap->fa_mode);
			if (fd < 0)
				return (errno);
			if (fd != fap->fa_filedes) {
				if (__fcntl(fd, F_DUP2FD, fap->fa_filedes) < 0)
					return (errno);
				(void) __close(fd);
			}
			break;
		case FA_CLOSE:
			if (__close(fap->fa_filedes) == -1 &&
			    errno != EBADF)	/* already closed, no error */
				return (errno);
			break;
		case FA_DUP2:
			fd = __fcntl(fap->fa_filedes, F_DUP2FD,
			    fap->fa_newfiledes);
			if (fd < 0)
				return (errno);
			break;
		case FA_CLOSEFROM:
			if (spawn_closefrom(fap->fa_filedes, dirbuf))
				return (errno);
			break;
		}
	} while ((fap = fap->fa_next) != froot);

	return (0);
}
コード例 #5
0
ファイル: clnt_tcp.c プロジェクト: JamesLinus/glibc-mips
static void
clnttcp_destroy (CLIENT *h)
{
  struct ct_data *ct =
  (struct ct_data *) h->cl_private;

  if (ct->ct_closeit)
    {
      (void) __close (ct->ct_sock);
    }
  XDR_DESTROY (&(ct->ct_xdrs));
  mem_free ((caddr_t) ct, sizeof (struct ct_data));
  mem_free ((caddr_t) h, sizeof (CLIENT));
}
コード例 #6
0
/* Store the name of the interface corresponding to index IFINDEX in
   IFNAME (which has space for at least IFNAMSIZ characters).  Return
   IFNAME, or NULL on error.  */
char *
if_indextoname (unsigned int ifindex, char *ifname)
{
  struct ifreq ifr;
  int fd = __opensock ();

  if (fd < 0)
    return NULL;

  ifr.ifr_ifindex = ifindex;
  if (__ioctl (fd, SIOCGIFNAME, &ifr) < 0)
    {
      int saved_errno = errno;
      __close (fd);
      if (saved_errno == EINVAL || saved_errno == ENOTTY)
        __set_errno (ENOSYS);
      else if (saved_errno == ENODEV)
	__set_errno (ENXIO);
      return NULL;
    }
  __close (fd);
  return strncpy (ifname, ifr.ifr_name, IFNAMSIZ);
}
コード例 #7
0
ファイル: libpcanbasic.cpp プロジェクト: elitechrome/auv_ros
TPCANStatus CAN_Uninitialize(TPCANHandle Channel) {

	PCAN_DESCRIPTOR *desc = NULL;
	TPCANStatus Result = PCAN_ERROR_OK;
	int index = 0;

	try {

		// logging
		char szLog[MAX_LOG];
		LOG_EnteringTo("CAN_Uninitialize");
		sprintf(szLog, "Channel: 0x%02X", Channel);
		LOG_Parameters("CAN_Uninitialize", szLog);

		// descriptor
		if (ppDescriptors == NULL) {
			Result = PCAN_ERROR_INITIALIZE;
			goto leave;
		}
		if (ppDescriptors[Channel] == NULL && Channel != PCAN_NONEBUS) {
			Result = PCAN_ERROR_INITIALIZE;
			goto leave;
		}
		desc = ppDescriptors[Channel];


		if (Channel == PCAN_NONEBUS) {
			// uninit all
			for (index = 1; index < 0x100; index++)
				CAN_Uninitialize((TPCANHandle) index);
		} else {
			// close file
			if (desc->nFileNo > -1) {
				__close(desc->nFileNo);
				desc->nFileNo = -1;
			}
			// remove descriptor
			free(desc);
			ppDescriptors[Channel] = NULL;
		}

		leave: LOG_LeavingFrom("CAN_Uninitialize", Result);
		return Result;
	} catch (...) {
		Result = PCAN_ERROR_UNKNOWN;
		LOG_Exception("CAN_Uninitialize");
	}
	return Result;
}
コード例 #8
0
ファイル: syslog.c プロジェクト: jameshilliard/20-4-4
static void
internal_function
openlog_internal(const char *ident, int logstat, int logfac)
{
	if (ident != NULL)
		LogTag = ident;
	LogStat = logstat;
	if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
		LogFacility = logfac;

	int retry = 0;
	while (retry < 2) {
		if (LogFile == -1) {
			SyslogAddr.sun_family = AF_UNIX;
			(void)strncpy(SyslogAddr.sun_path, _PATH_LOG,
				      sizeof(SyslogAddr.sun_path));
			if (LogStat & LOG_NDELAY) {
				if ((LogFile = __socket(AF_UNIX, LogType, 0))
				    == -1)
					return;
				(void)__fcntl(LogFile, F_SETFD, 1);
			}
		}
		if (LogFile != -1 && !connected)
		{
			int old_errno = errno;
			if (__connect(LogFile, &SyslogAddr, sizeof(SyslogAddr))
			    == -1)
			{
				int saved_errno = errno;
				int fd = LogFile;
				LogFile = -1;
				(void)__close(fd);
				__set_errno (old_errno);
				if (saved_errno == EPROTOTYPE)
				{
					/* retry with the other type: */
					LogType = (LogType == SOCK_DGRAM
						   ? SOCK_STREAM : SOCK_DGRAM);
					++retry;
					continue;
				}
			} else
				connected = 1;
		}
		break;
	}
}
コード例 #9
0
ファイル: fclose.c プロジェクト: ArmstrongJ/open-watcom-v2
int __doclose( FILE *fp, int close_handle )
{
    int         ret;

    if( (fp->_flag & (_READ | _WRITE)) == 0 ) {
        return( -1 );                       /* file already closed */
    }
    ret = 0;
    if( fp->_flag & _DIRTY ) {
        if( __flush( fp ) ) {
            ret = -1;
        }
    }
    _AccessFile( fp );
/*
 *      02-nov-92 G.Turcotte  Syncronize buffer pointer with the file pointer
 *                        IEEE Std 1003.1-1988 B.8.2.3.2
 *      03-nov-03 B.Oldeman Inlined ftell; we already know the buffer isn't
 *                dirty (because of the flush), so only a "get" applies
 */
    if( fp->_cnt != 0 ) {                   /* if something in buffer */
        __lseek( fileno( fp ), -fp->_cnt, SEEK_CUR );
    }

    if( close_handle ) {
#if defined( __UNIX__ ) || defined( __NETWARE__ ) || defined( __RDOS__ ) || defined( __RDOSDEV__ )
        // we don't get to implement the close function on these systems
        ret |= close( fileno( fp ) );
#else
        ret |= __close( fileno( fp ) );
#endif
    }
    if( fp->_flag & _BIGBUF ) {     /* if we allocated the buffer */
        lib_free( _FP_BASE( fp ) );
        _FP_BASE( fp ) = NULL;
    }
#ifndef __UNIX__
    /* this never happens under UNIX */
    if( fp->_flag & _TMPFIL ) {     /* if this is a temporary file */
        __RmTmpFileFn( fp );
    }
#endif
    fp->_flag &= _DYNAMIC;
    _ReleaseFile( fp );
    return( ret );
}
コード例 #10
0
ファイル: opendir.c プロジェクト: BackupTheBerlios/wl530g-svn
static void
tryopen_o_directory (void)
{
  int serrno = errno;
  int x = __open ("/dev/null", O_RDONLY|O_NDELAY|O_DIRECTORY);

  if (x >= 0)
    {
      __close (x);
      o_directory_works = -1;
    }
  else if (errno != ENOTDIR)
    o_directory_works = -1;
  else
    o_directory_works = 1;

  __set_errno (serrno);
}
コード例 #11
0
ファイル: truncate.c プロジェクト: Drakey83/steamlink-sdk
/* Truncate PATH to LENGTH bytes.  */
int
__truncate (const char *path, off_t length)
{
  int fd, ret, save;

  fd = __open (path, O_WRONLY | (length == 0 ? O_TRUNC : 0));
  if (fd < 0)
    return -1;

  if (length == 0)
    ret = 0;
  else
    ret = __ftruncate (fd, length);
  save = errno;
  (void) __close (fd);
  if (ret < 0)
    __set_errno (save);
  return ret;
}
コード例 #12
0
static void
svctcp_destroy (SVCXPRT *xprt)
{
  struct tcp_conn *cd = (struct tcp_conn *) xprt->xp_p1;

  xprt_unregister (xprt);
  (void) __close (xprt->xp_sock);
  if (xprt->xp_port != 0)
    {
      /* a rendezvouser socket */
      xprt->xp_port = 0;
    }
  else
    {
      /* an actual connection socket */
      XDR_DESTROY (&(cd->xdrs));
    }
  mem_free ((caddr_t) cd, sizeof (struct tcp_conn));
  mem_free ((caddr_t) xprt, sizeof (SVCXPRT));
}
コード例 #13
0
ファイル: oldtmpfile.c プロジェクト: Drakey83/steamlink-sdk
attribute_compat_text_section
__old_tmpfile (void)
{
  char buf[FILENAME_MAX];
  int fd;
  FILE *f;

  if (__path_search (buf, FILENAME_MAX, NULL, "tmpf", 0))
    return NULL;
  fd = __gen_tempname (buf, 0, 0, __GT_FILE);
  if (fd < 0)
    return NULL;

  /* Note that this relies on the Unix semantics that
     a file is not really removed until it is closed.  */
  (void) __unlink (buf);

  if ((f = _IO_old_fdopen (fd, "w+b")) == NULL)
    __close (fd);

  return f;
}
コード例 #14
0
ファイル: svc_socket.c プロジェクト: crossbuild/nfs-utils
static int
svc_socket (u_long number, int type, int protocol, int reuse)
{
  struct sockaddr_in addr;
  socklen_t len = sizeof (struct sockaddr_in);
  int sock, ret;
  const char *proto = protocol == IPPROTO_TCP ? "tcp" : "udp";

  if ((sock = __socket (AF_INET, type, protocol)) < 0)
    {
      perror (_("svc_socket: socket creation problem"));
      return sock;
    }

  if (reuse)
    {
      ret = 1;
      ret = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &ret,
			sizeof (ret));
      if (ret < 0)
	{
	  perror (_("svc_socket: socket reuse problem"));
	  return ret;
	}
    }

  memset (&addr, 0, sizeof (addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(getservport(number, proto));

  if (bind(sock, (struct sockaddr *) &addr, len) < 0)
    {
      perror (_("svc_socket: bind problem"));
      (void) __close(sock);
      sock = -1;
    }

  return svcsock_nonblock(sock);
}
コード例 #15
0
ファイル: fts.c プロジェクト: avokhmin/RPM5
/*
 * Change to dir specified by fd or p->fts_accpath without getting
 * tricked by someone changing the world out from underneath us.
 * Assumes p->fts_dev and p->fts_ino are filled in.
 */
static int
fts_safe_changedir(FTS * sp, FTSENT * p, int fd, const char * path)
{
	int ret, oerrno, newfd;
	struct stat64 sb;

	newfd = fd;
	if (ISSET(FTS_NOCHDIR))
		return (0);

	/* Permit open(2) on file:// prefixed URI paths. */
	/* XXX todo: use Open(2), which is Chroot(2) path invariant. */
	/* XXX todo: add Fts(3) options to disable the hackery? */
	{	const char * lpath = NULL;
		int ut = urlPath(path, &lpath);
		if (ut == URL_IS_PATH) path = lpath;
	}

	if (fd < 0 && (newfd = __open(path, O_RDONLY, 0)) < 0)
		return (-1);
/*@-sysunrecog -unrecog @*/
	if (__fxstat64(_STAT_VER, newfd, &sb)) {
		ret = -1;
		goto bail;
	}
/*@=sysunrecog =unrecog @*/
	if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
		__set_errno (ENOENT);		/* disinformation */
		ret = -1;
		goto bail;
	}
	ret = __fchdir(newfd);
bail:
	oerrno = errno;
	if (fd < 0)
		(void)__close(newfd);
	__set_errno (oerrno);
	return (ret);
}
コード例 #16
0
/* Open a directory stream on NAME.  */
DIR *
__opendir (const char *name)
{
  if (name[0] == '\0')
    {
      /* POSIX.1-1990 says an empty name gets ENOENT;
	 but `open' might like it fine.  */
      __set_errno (ENOENT);
      return NULL;
    }

  int fd = __open (name, O_RDONLY | O_NONBLOCK | O_DIRECTORY);
  if (fd < 0)
    return NULL;

  /* Extract the pointer to the descriptor structure.  */
  DIR *dirp = _hurd_fd_opendir (_hurd_fd_get (fd));
  if (dirp == NULL)
    __close (fd);

  return dirp;
}
コード例 #17
0
/* This returns a new stream opened on a temporary file (generated
   by tmpnam).  The file is opened with mode "w+b" (binary read/write).
   If we couldn't generate a unique filename or the file couldn't
   be opened, NULL is returned.  */
FILE *
tmpfile (void)
{
  char buf[FILENAME_MAX];
  int fd;
  FILE *f;

  if (__path_search (buf, FILENAME_MAX, NULL, "tmpf", 0))
    return NULL;
  fd = __gen_tempname (buf, GEN_THIS);
  if (fd < 0)
    return NULL;

#ifndef __WIN32__
	/* Note that this relies on the Unix semantics that
     a file is not really removed until it is closed.  */
  (void) remove (buf);
#endif
  if ((f = __fdopen (fd, "w+b")) == NULL)
    __close (fd);

  return f;
}
コード例 #18
0
ファイル: fclose.c プロジェクト: kendallb/scitech-mgl
int __doclose( FILE *fp, int close_handle )
{
    int                 ret;

    if( fp->_flag == 0 ) {
        return( -1 );                       /* file already closed */
    }
    ret = 0;
    if( fp->_flag & _DIRTY ) {
        ret = __flush( fp );
    }
    _AccessFile( fp );
    if( fp->_cnt != 0 ) {                   /* if something in buffer */
        __lseek( fileno( fp ), -fp->_cnt, SEEK_CUR );
    }

    if( close_handle ) {
        #if defined(__UNIX__) || defined(__NETWARE__)
            // we don't get to implement the close function on these systems
            ret |= close( fileno( fp ) );
        #else
            ret |= __close( fileno( fp ) );
        #endif
    }
    if( fp->_flag & _BIGBUF ) {     /* if we allocated the buffer */
        lib_free( _FP_BASE(fp) );
        _FP_BASE(fp) = NULL;
    }
#ifndef __UNIX__
    /* this never happens under UNIX */
    if( fp->_flag & _TMPFIL ) {     /* if this is a temporary file */
        __RmTmpFileFn( fp );
    }
#endif
    _ReleaseFile( fp );
    return( ret );
}
コード例 #19
0
/* Open a directory stream on NAME.  */
DIR *
__opendir (const char *name)
{
  DIR *dirp;
  int fd;
  struct hurd_fd *d;

  fd = __open (name, O_RDONLY);
  if (fd < 0)
    return NULL;

  dirp = (DIR *) malloc (sizeof (DIR));
  if (dirp == NULL)
    {
      __close (fd);
      return NULL;
    }

  /* Extract the pointer to the descriptor structure.  */
  __mutex_lock (&_hurd_dtable_lock);
  d = dirp->__fd = _hurd_dtable[fd];
  __mutex_unlock (&_hurd_dtable_lock);

  /* Set the descriptor to close on exec. */
  __spin_lock (&d->port.lock);
  d->flags |= FD_CLOEXEC;
  __spin_unlock (&d->port.lock);

  dirp->__data = dirp->__ptr = NULL;
  dirp->__entry_data = dirp->__entry_ptr = 0;
  dirp->__allocation = 0;
  dirp->__size = 0;

  __libc_lock_init (dirp->__lock);

  return dirp;
}
コード例 #20
0
ファイル: perror.c プロジェクト: alucas/glibc
/* Print a line on stderr consisting of the text in S, a colon, a space,
   a message describing the meaning of the contents of `errno' and a newline.
   If S is NULL or "", the colon and space are omitted.  */
void
perror (const char *s)
{
  int errnum = errno;
  FILE *fp;
  int fd = -1;


  /* The standard says that 'perror' must not change the orientation
     of the stream.  What is supposed to happen when the stream isn't
     oriented yet?  In this case we'll create a new stream which is
     using the same underlying file descriptor.  */
  if (__builtin_expect (_IO_fwide (stderr, 0) != 0, 1)
      || (fd = fileno (stderr)) == -1
      || (fd = __dup (fd)) == -1
      || (fp = fdopen (fd, "w+")) == NULL)
    {
      if (__glibc_unlikely (fd != -1))
	__close (fd);

      /* Use standard error as is.  */
      perror_internal (stderr, s, errnum);
    }
  else
    {
      /* We don't have to do any special hacks regarding the file
	 position.  Since the stderr stream wasn't used so far we just
	 write to the descriptor.  */
      perror_internal (fp, s, errnum);

      if (_IO_ferror_unlocked (fp))
	stderr->_flags |= _IO_ERR_SEEN;

      /* Close the stream.  */
      fclose (fp);
    }
}
コード例 #21
0
ファイル: lckpwdf.c プロジェクト: Lind-Project/Lind-GlibC
int
__ulckpwdf (void)
{
  int result;

  if (lock_fd == -1)
    /* There is no lock set.  */
    result = -1;
  else
    {
      /* Prevent problems caused by multiple threads.  */
      __libc_lock_lock (lock);

      result = __close (lock_fd);

      /* Mark descriptor as unused.  */
      lock_fd = -1;

      /* Clear mutex.  */
      __libc_lock_unlock (lock);
    }

  return result;
}
コード例 #22
0
ファイル: pthread.c プロジェクト: 32bitmicro/newlib-nano-1.0
/* Test whether the machine has more than one processor.  This is not the
   best test but good enough.  More complicated tests would require `malloc'
   which is not available at that time.  */
static int
is_smp_system (void)
{
  static const int sysctl_args[] = { CTL_KERN, KERN_VERSION };
  char buf[512];
  size_t reslen = sizeof (buf);

  /* Try reading the number using `sysctl' first.  */
  if (__sysctl ((int *) sysctl_args,
		sizeof (sysctl_args) / sizeof (sysctl_args[0]),
		buf, &reslen, NULL, 0) < 0)
    {
      /* This was not successful.  Now try reading the /proc filesystem.  */
      int fd = __open ("/proc/sys/kernel/version", O_RDONLY);
      if (__builtin_expect (fd, 0) == -1
	  || (reslen = __read (fd, buf, sizeof (buf))) <= 0)
	/* This also didn't work.  We give up and say it's a UP machine.  */
	buf[0] = '\0';

      __close (fd);
    }

  return strstr (buf, "SMP") != NULL;
}
コード例 #23
0
ファイル: fts.c プロジェクト: eva-oss/glibc-linaro
FTSENTRY *
FTS_CHILDREN(FTSOBJ *sp, int instr)
{
	FTSENTRY *p;
	int fd;

	if (instr != 0 && instr != FTS_NAMEONLY) {
		__set_errno (EINVAL);
		return (NULL);
	}

	/* Set current node pointer. */
	p = sp->fts_cur;

	/*
	 * Errno set to 0 so user can distinguish empty directory from
	 * an error.
	 */
	__set_errno (0);

	/* Fatal errors stop here. */
	if (ISSET(FTS_STOP))
		return (NULL);

	/* Return logical hierarchy of user's arguments. */
	if (p->fts_info == FTS_INIT)
		return (p->fts_link);

	/*
	 * If not a directory being visited in pre-order, stop here.  Could
	 * allow FTS_DNR, assuming the user has fixed the problem, but the
	 * same effect is available with FTS_AGAIN.
	 */
	if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
		return (NULL);

	/* Free up any previous child list. */
	if (sp->fts_child != NULL)
		fts_lfree(sp->fts_child);

	if (instr == FTS_NAMEONLY) {
		SET(FTS_NAMEONLY);
		instr = BNAMES;
	} else
		instr = BCHILD;

	/*
	 * If using chdir on a relative path and called BEFORE fts_read does
	 * its chdir to the root of a traversal, we can lose -- we need to
	 * chdir into the subdirectory, and we don't know where the current
	 * directory is, so we can't get back so that the upcoming chdir by
	 * fts_read will work.
	 */
	if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
	    ISSET(FTS_NOCHDIR))
		return (sp->fts_child = fts_build(sp, instr));

	if ((fd = __open(".", O_RDONLY, 0)) < 0)
		return (NULL);
	sp->fts_child = fts_build(sp, instr);
	if (__fchdir(fd))
		return (NULL);
	(void)__close(fd);
	return (sp->fts_child);
}
コード例 #24
0
ファイル: fts.c プロジェクト: eva-oss/glibc-linaro
FTSENTRY *
FTS_READ (FTSOBJ *sp)
{
	FTSENTRY *p, *tmp;
	int instr;
	char *t;
	int saved_errno;

	/* If finished or unrecoverable error, return NULL. */
	if (sp->fts_cur == NULL || ISSET(FTS_STOP))
		return (NULL);

	/* Set current node pointer. */
	p = sp->fts_cur;

	/* Save and zero out user instructions. */
	instr = p->fts_instr;
	p->fts_instr = FTS_NOINSTR;

	/* Any type of file may be re-visited; re-stat and re-turn. */
	if (instr == FTS_AGAIN) {
		p->fts_info = fts_stat(sp, p, 0);
		return (p);
	}

	/*
	 * Following a symlink -- SLNONE test allows application to see
	 * SLNONE and recover.  If indirecting through a symlink, have
	 * keep a pointer to current location.  If unable to get that
	 * pointer, follow fails.
	 */
	if (instr == FTS_FOLLOW &&
	    (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
		p->fts_info = fts_stat(sp, p, 1);
		if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
			if ((p->fts_symfd = __open(".", O_RDONLY, 0)) < 0) {
				p->fts_errno = errno;
				p->fts_info = FTS_ERR;
			} else
				p->fts_flags |= FTS_SYMFOLLOW;
		}
		return (p);
	}

	/* Directory in pre-order. */
	if (p->fts_info == FTS_D) {
		/* If skipped or crossed mount point, do post-order visit. */
		if (instr == FTS_SKIP ||
		    (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
			if (p->fts_flags & FTS_SYMFOLLOW)
				(void)__close(p->fts_symfd);
			if (sp->fts_child) {
				fts_lfree(sp->fts_child);
				sp->fts_child = NULL;
			}
			p->fts_info = FTS_DP;
			return (p);
		}

		/* Rebuild if only read the names and now traversing. */
		if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
			CLR(FTS_NAMEONLY);
			fts_lfree(sp->fts_child);
			sp->fts_child = NULL;
		}

		/*
		 * Cd to the subdirectory.
		 *
		 * If have already read and now fail to chdir, whack the list
		 * to make the names come out right, and set the parent errno
		 * so the application will eventually get an error condition.
		 * Set the FTS_DONTCHDIR flag so that when we logically change
		 * directories back to the parent we don't do a chdir.
		 *
		 * If haven't read do so.  If the read fails, fts_build sets
		 * FTS_STOP or the fts_info field of the node.
		 */
		if (sp->fts_child != NULL) {
			if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
				p->fts_errno = errno;
				p->fts_flags |= FTS_DONTCHDIR;
				for (p = sp->fts_child; p != NULL;
				     p = p->fts_link)
					p->fts_accpath =
					    p->fts_parent->fts_accpath;
			}
		} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
			if (ISSET(FTS_STOP))
				return (NULL);
			return (p);
		}
		p = sp->fts_child;
		sp->fts_child = NULL;
		sp->fts_cur = p;
		goto name;
	}

	/* Move to the next node on this level. */
next:	tmp = p;
	if ((p = p->fts_link) != NULL) {
		sp->fts_cur = p;
		free(tmp);

		/*
		 * If reached the top, return to the original directory (or
		 * the root of the tree), and load the paths for the next root.
		 */
		if (p->fts_level == FTS_ROOTLEVEL) {
			if (FCHDIR(sp, sp->fts_rfd)) {
				SET(FTS_STOP);
				return (NULL);
			}
			fts_load(sp, p);
			return p;
		}

		/*
		 * User may have called fts_set on the node.  If skipped,
		 * ignore.  If followed, get a file descriptor so we can
		 * get back if necessary.
		 */
		if (p->fts_instr == FTS_SKIP)
			goto next;
		if (p->fts_instr == FTS_FOLLOW) {
			p->fts_info = fts_stat(sp, p, 1);
			if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
				if ((p->fts_symfd =
				    __open(".", O_RDONLY, 0)) < 0) {
					p->fts_errno = errno;
					p->fts_info = FTS_ERR;
				} else
					p->fts_flags |= FTS_SYMFOLLOW;
			}
			p->fts_instr = FTS_NOINSTR;
		}

name:		t = sp->fts_path + NAPPEND(p->fts_parent);
		*t++ = '/';
		memmove(t, p->fts_name, p->fts_namelen + 1);
		return p;
	}

	/* Move up to the parent node. */
	p = tmp->fts_parent;
	sp->fts_cur = p;
	free(tmp);

	if (p->fts_level == FTS_ROOTPARENTLEVEL) {
		/*
		 * Done; free everything up and set errno to 0 so the user
		 * can distinguish between error and EOF.
		 */
		free(p);
		__set_errno (0);
		return (sp->fts_cur = NULL);
	}

	/* NUL terminate the pathname. */
	sp->fts_path[p->fts_pathlen] = '\0';

	/*
	 * Return to the parent directory.  If at a root node or came through
	 * a symlink, go back through the file descriptor.  Otherwise, cd up
	 * one directory.
	 */
	if (p->fts_level == FTS_ROOTLEVEL) {
		if (FCHDIR(sp, sp->fts_rfd)) {
			SET(FTS_STOP);
			return (NULL);
		}
	} else if (p->fts_flags & FTS_SYMFOLLOW) {
		if (FCHDIR(sp, p->fts_symfd)) {
			saved_errno = errno;
			(void)__close(p->fts_symfd);
			__set_errno (saved_errno);
			SET(FTS_STOP);
			return (NULL);
		}
		(void)__close(p->fts_symfd);
	} else if (!(p->fts_flags & FTS_DONTCHDIR) &&
		   fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
		SET(FTS_STOP);
		return (NULL);
	}
	p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
	return p;
}
コード例 #25
0
ファイル: syslog.c プロジェクト: KubaKaszycki/kklibc
void
__vsyslog_chk(int pri, int flag, const char *fmt, va_list ap)
{
    struct tm now_tm;
    time_t now;
    int fd;
    FILE *f;
    char *buf = 0;
    size_t bufsize = 0;
    size_t msgoff;
#ifndef NO_SIGPIPE
    struct sigaction action, oldaction;
    int sigpipe;
#endif
    int saved_errno = errno;
    char failbuf[3 * sizeof (pid_t) + sizeof "out of memory []"];

#define	INTERNALLOG	LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
    /* Check for invalid bits. */
    if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
        syslog(INTERNALLOG,
               "syslog: unknown facility/priority: %x", pri);
        pri &= LOG_PRIMASK|LOG_FACMASK;
    }

    /* Check priority against setlogmask values. */
    if ((LOG_MASK (LOG_PRI (pri)) & LogMask) == 0)
        return;

    /* Set default facility if none specified. */
    if ((pri & LOG_FACMASK) == 0)
        pri |= LogFacility;

    /* Build the message in a memory-buffer stream.  */
    f = __open_memstream (&buf, &bufsize);
    if (f == NULL)
    {
        /* We cannot get a stream.  There is not much we can do but
           emitting an error messages.  */
        char numbuf[3 * sizeof (pid_t)];
        char *nump;
        char *endp = __stpcpy (failbuf, "out of memory [");
        pid_t pid = __getpid ();

        nump = numbuf + sizeof (numbuf);
        /* The PID can never be zero.  */
        do
            *--nump = '0' + pid % 10;
        while ((pid /= 10) != 0);

        endp = __mempcpy (endp, nump, (numbuf + sizeof (numbuf)) - nump);
        *endp++ = ']';
        *endp = '\0';
        buf = failbuf;
        bufsize = endp - failbuf;
        msgoff = 0;
    }
    else
    {
        __fsetlocking (f, FSETLOCKING_BYCALLER);
        fprintf (f, "<%d>", pri);
        (void) time (&now);
        f->_IO_write_ptr += __strftime_l (f->_IO_write_ptr,
                                          f->_IO_write_end
                                          - f->_IO_write_ptr,
                                          "%h %e %T ",
                                          __localtime_r (&now, &now_tm),
                                          _nl_C_locobj_ptr);
        msgoff = ftell (f);
        if (LogTag == NULL)
            LogTag = __progname;
        if (LogTag != NULL)
            __fputs_unlocked (LogTag, f);
        if (LogStat & LOG_PID)
            fprintf (f, "[%d]", (int) __getpid ());
        if (LogTag != NULL)
        {
            putc_unlocked (':', f);
            putc_unlocked (' ', f);
        }

        /* Restore errno for %m format.  */
        __set_errno (saved_errno);

        /* We have the header.  Print the user's format into the
               buffer.  */
        if (flag == -1)
            vfprintf (f, fmt, ap);
        else
            __vfprintf_chk (f, flag, fmt, ap);

        /* Close the memory stream; this will finalize the data
           into a malloc'd buffer in BUF.  */
        fclose (f);
    }

    /* Output to stderr if requested. */
    if (LogStat & LOG_PERROR) {
        struct iovec iov[2];
        struct iovec *v = iov;

        v->iov_base = buf + msgoff;
        v->iov_len = bufsize - msgoff;
        /* Append a newline if necessary.  */
        if (buf[bufsize - 1] != '\n')
        {
            ++v;
            v->iov_base = (char *) "\n";
            v->iov_len = 1;
        }

        __libc_cleanup_push (free, buf == failbuf ? NULL : buf);

        /* writev is a cancellation point.  */
        (void)__writev(STDERR_FILENO, iov, v - iov + 1);

        __libc_cleanup_pop (0);
    }

    /* Prepare for multiple users.  We have to take care: open and
       write are cancellation points.  */
    struct cleanup_arg clarg;
    clarg.buf = buf;
    clarg.oldaction = NULL;
    __libc_cleanup_push (cancel_handler, &clarg);
    __libc_lock_lock (syslog_lock);

#ifndef NO_SIGPIPE
    /* Prepare for a broken connection.  */
    memset (&action, 0, sizeof (action));
    action.sa_handler = sigpipe_handler;
    sigemptyset (&action.sa_mask);
    sigpipe = __sigaction (SIGPIPE, &action, &oldaction);
    if (sigpipe == 0)
        clarg.oldaction = &oldaction;
#endif

    /* Get connected, output the message to the local logger. */
    if (!connected)
        openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);

    /* If we have a SOCK_STREAM connection, also send ASCII NUL as
       a record terminator.  */
    if (LogType == SOCK_STREAM)
        ++bufsize;

    if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
    {
        if (connected)
        {
            /* Try to reopen the syslog connection.  Maybe it went
               down.  */
            closelog_internal ();
            openlog_internal(LogTag, LogStat | LOG_NDELAY, 0);
        }

        if (!connected || __send(LogFile, buf, bufsize, send_flags) < 0)
        {
            closelog_internal ();	/* attempt re-open next time */
            /*
             * Output the message to the console; don't worry
             * about blocking, if console blocks everything will.
             * Make sure the error reported is the one from the
             * syslogd failure.
             */
            if (LogStat & LOG_CONS &&
                    (fd = __open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY, 0)) >= 0)
            {
                __dprintf (fd, "%s\r\n", buf + msgoff);
                (void)__close(fd);
            }
        }
    }

#ifndef NO_SIGPIPE
    if (sigpipe == 0)
        __sigaction (SIGPIPE, &oldaction, (struct sigaction *) NULL);
#endif

    /* End of critical section.  */
    __libc_cleanup_pop (0);
    __libc_lock_unlock (syslog_lock);

    if (buf != failbuf)
        free (buf);
}
コード例 #26
0
ファイル: freopen64.c プロジェクト: JamesLinus/glibc-mips
FILE *
freopen64 (const char *filename, const char *mode, FILE *fp)
{
  FILE *result;
  CHECK_FILE (fp, NULL);
  if (!(fp->_flags & _IO_IS_FILEBUF))
    return NULL;
  _IO_acquire_lock (fp);
  int fd = _IO_fileno (fp);
  const char *gfilename = (filename == NULL && fd >= 0
			   ? fd_to_filename (fd) : filename);
  fp->_flags2 |= _IO_FLAGS2_NOCLOSE;
  _IO_file_close_it (fp);
  _IO_JUMPS_FILE_plus (fp) = &_IO_file_jumps;
  if (_IO_vtable_offset (fp) == 0 && fp->_wide_data != NULL)
    fp->_wide_data->_wide_vtable = &_IO_wfile_jumps;
  result = _IO_file_fopen (fp, gfilename, mode, 0);
  fp->_flags2 &= ~_IO_FLAGS2_NOCLOSE;
  if (result != NULL)
    result = __fopen_maybe_mmap (result);
  if (result != NULL)
    {
      /* unbound stream orientation */
      result->_mode = 0;

      if (fd != -1)
	{
#ifdef O_CLOEXEC
# ifndef __ASSUME_DUP3
	  int newfd;
	  if (__have_dup3 < 0)
	    newfd = -1;
	  else
	    newfd =
# endif
	      __dup3 (_IO_fileno (result), fd,
                      (result->_flags2 & _IO_FLAGS2_CLOEXEC) != 0
                      ? O_CLOEXEC : 0);
#else
# define newfd 1
#endif

#ifndef __ASSUME_DUP3
	  if (newfd < 0)
	    {
	      if (errno == ENOSYS)
		__have_dup3 = -1;

	      __dup2 (_IO_fileno (result), fd);
	      if ((result->_flags2 & _IO_FLAGS2_CLOEXEC) != 0)
		__fcntl (fd, F_SETFD, FD_CLOEXEC);
	    }
#endif
	  __close (_IO_fileno (result));
	  _IO_fileno (result) = fd;
	}
    }
  else if (fd != -1)
    __close (fd);
  if (filename == NULL)
    free ((char *) gfilename);
  _IO_release_lock (fp);
  return result;
}
コード例 #27
0
ファイル: shmget.c プロジェクト: OSLL/elfperf
/* Open the shared memory segment KEY (creating it if it doesn't yet
   exist) and return a file descriptor to it in R_FD.  */
static error_t
get_shared (int shmflags, size_t size, key_t key, int *r_fd)
{
  error_t err = 0;
  char filename[sizeof (SHM_DIR) - 1 + SHM_NAMEMAX];
  int fd = -1;
  int create_flag;

  create_flag = (shmflags & IPC_CREAT) ? O_CREAT : 0;
  sprintf (filename, SHM_DIR SHM_NAMEPRI, key);

  do
    {
      fd = __open (filename, O_NORW | create_flag, shmflags & 0777);

      if (fd < 0 && errno != ENOENT)
	/* We give up.  */
	return errno;
      else if (fd >= 0)
	{
	  int res;
	  struct stat statbuf;

	  /* Check the size (we only need to do this if we did not
	     create the shared memory segment file ourselves).  */
	  res = __fstat (fd, &statbuf);
	  if (res < 0)
	    {
	      err = errno;
	      __close (fd);
	      return err;
	    }

	  if (statbuf.st_size < size)
	    {
	      __close (fd);
	      return EINVAL;
	    }
	}	  
      else
	{
	  /* The memory segment doesn't exist.  */
	  if (create_flag)
	    {
	      /* Try to create it exclusively.  */
	      err = get_exclusive (shmflags, size, &key, &fd);
	      if (err == EEXIST)
		/* If somebody created it in the meanwhile, just try again.  */
		err = 0;
	    }
	  else
	    err = ENOENT;
	}
    }
  while (fd < 0 && !err);

  if (!err)
    *r_fd = fd;
  else
    *r_fd = -1;

  return err;
}
コード例 #28
0
ファイル: freopen.c プロジェクト: siddhesh/glibc
FILE *
freopen (const char *filename, const char *mode, FILE *fp)
{
  FILE *result;
  CHECK_FILE (fp, NULL);
  if (!(fp->_flags & _IO_IS_FILEBUF))
    return NULL;
  _IO_acquire_lock (fp);
  int fd = _IO_fileno (fp);
  const char *gfilename = (filename == NULL && fd >= 0
			   ? fd_to_filename (fd) : filename);
  fp->_flags2 |= _IO_FLAGS2_NOCLOSE;
#if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_1)
  if (&_IO_stdin_used == NULL)
    {
      /* If the shared C library is used by the application binary which
	 was linked against the older version of libio, we just use the
	 older one even for internal use to avoid trouble since a pointer
	 to the old libio may be passed into shared C library and wind
	 up here. */
      _IO_old_file_close_it (fp);
      _IO_JUMPS_FILE_plus (fp) = &_IO_old_file_jumps;
      result = _IO_old_file_fopen (fp, gfilename, mode);
    }
  else
#endif
    {
      _IO_file_close_it (fp);
      _IO_JUMPS_FILE_plus (fp) = &_IO_file_jumps;
      if (_IO_vtable_offset (fp) == 0 && fp->_wide_data != NULL)
	fp->_wide_data->_wide_vtable = &_IO_wfile_jumps;
      result = _IO_file_fopen (fp, gfilename, mode, 1);
      if (result != NULL)
	result = __fopen_maybe_mmap (result);
    }
  fp->_flags2 &= ~_IO_FLAGS2_NOCLOSE;
  if (result != NULL)
    {
      /* unbound stream orientation */
      result->_mode = 0;

      if (fd != -1)
	{
#ifdef O_CLOEXEC
# ifndef __ASSUME_DUP3
	  int newfd;
	  if (__have_dup3 < 0)
	    newfd = -1;
	  else
	    newfd =
# endif
	      __dup3 (_IO_fileno (result), fd,
                      (result->_flags2 & _IO_FLAGS2_CLOEXEC) != 0
                      ? O_CLOEXEC : 0);
#else
# define newfd 1
#endif

#ifndef __ASSUME_DUP3
	  if (newfd < 0)
	    {
	      if (errno == ENOSYS)
		__have_dup3 = -1;

	      __dup2 (_IO_fileno (result), fd);
	      if ((result->_flags2 & _IO_FLAGS2_CLOEXEC) != 0)
		__fcntl (fd, F_SETFD, FD_CLOEXEC);
	    }
#endif
	  __close (_IO_fileno (result));
	  _IO_fileno (result) = fd;
	}
    }
  else if (fd != -1)
    __close (fd);
  if (filename == NULL)
    free ((char *) gfilename);

  _IO_release_lock (fp);
  return result;
}
コード例 #29
0
/* Return an array of if_nameindex structures, one for each network
   interface present, plus one indicating the end of the array.  On
   error, return NULL.  */
struct if_nameindex *
if_nameindex (void)
{
  error_t err = 0;
  char data[2048];
  file_t server;
  int fd = __opensock ();
  struct ifconf ifc;
  unsigned int nifs, i;
  struct if_nameindex *idx = NULL;

  ifc.ifc_buf = data;

  if (fd < 0)
    return NULL;

  server = _hurd_socket_server (PF_INET, 0);
  if (server == MACH_PORT_NULL)
    nifs = 0;
  else
    {
      size_t len = sizeof data;
      err = __pfinet_siocgifconf (server, -1, &ifc.ifc_buf, &len);
      if (err == MACH_SEND_INVALID_DEST || err == MIG_SERVER_DIED)
	{
	  /* On the first use of the socket server during the operation,
	     allow for the old server port dying.  */
	  server = _hurd_socket_server (PF_INET, 1);
	  if (server == MACH_PORT_NULL)
	    goto out;
	  err = __pfinet_siocgifconf (server, -1, &ifc.ifc_buf, &len);
	}
      if (err)
	goto out;

      ifc.ifc_len = len;
      nifs = len / sizeof (struct ifreq);
    }

  idx = malloc ((nifs + 1) * sizeof (struct if_nameindex));
  if (idx == NULL)
    {
      err = ENOBUFS;
      goto out;
    }

  for (i = 0; i < nifs; ++i)
    {
      struct ifreq *ifr = &ifc.ifc_req[i];
      idx[i].if_name = __strdup (ifr->ifr_name);
      if (idx[i].if_name == NULL
          || __ioctl (fd, SIOCGIFINDEX, ifr) < 0)
        {
          unsigned int j;
          err = errno;

          for (j =  0; j < i; ++j)
            free (idx[j].if_name);
          free (idx);
	  idx = NULL;

          if (err == EINVAL)
            err = ENOSYS;
          else if (err == ENOMEM)
            err = ENOBUFS;
          goto out;
        }
      idx[i].if_index = ifr->ifr_ifindex;
    }

  idx[i].if_index = 0;
  idx[i].if_name = NULL;

 out:
  __close (fd);
  if (data != ifc.ifc_buf)
    __vm_deallocate (__mach_task_self (), (vm_address_t) ifc.ifc_buf,
		     ifc.ifc_len);
  __set_errno (err);
  return idx;
}
コード例 #30
0
ファイル: signer.cpp プロジェクト: dudochkin-victor/nodewm
int Signer::LoadKeys()
{
    bool bKeysReaded = false, bNotOldFmt = false;
    int nReaden;
    int errLoadKey;
    int fh = -1;
    int st_size = 0;
    const int nMaxBufLen = 164;
    char *pBufRead = new char[nMaxBufLen];   // Here Keys must be
    m_siErrorCode = 0;
    KeyFromCL = FALSE;

    if( (!isIgnoreKeyFile) && (Key64Flag == FALSE) ) {
#ifdef O_BINARY
        fh = __open( m_szKeyFileName, O_RDONLY | O_BINARY);
#else
        fh = __open( m_szKeyFileName, O_RDONLY);
#endif

        if( fh == -1 )
        {
            m_siErrorCode = 2;//errno;
            return false;
        }

        st_size = lseek(fh, 0, SEEK_END);
        lseek(fh, 0, SEEK_SET);
        if (st_size == lMinKeyFileSize)
        {
            // load 164 bytes from "small" keys file
            nReaden = __read( fh, pBufRead, nMaxBufLen );
            bKeysReaded = (nReaden == lMinKeyFileSize);
        }
        __close( fh );
    }
    else {
        bKeysReaded = true;
        nReaden = lMinKeyFileSize;
        memcpy( pBufRead, szKeyData, lMinKeyFileSize);
    }

    //*************************************************************************

    if(bKeysReaded)
    {
        SecureKeyByIDPWHalf(pBufRead, lMinKeyFileSize);
        WORD old_SignFlag;
        old_SignFlag = ((KeyFileFormat *)pBufRead)->wSignFlag;
        ((KeyFileFormat *)pBufRead)->wSignFlag = 0;
        errLoadKey = keys.LoadFromBuffer( pBufRead, lMinKeyFileSize );
        if(errLoadKey)
        {
            // Restore for correct Loading (CRC) !
            ((KeyFileFormat *)pBufRead)->wSignFlag = old_SignFlag;
            SecureKeyByIDPWHalf(pBufRead, lMinKeyFileSize); // restore buffer

            SecureKeyByIDPW(pBufRead, lMinKeyFileSize);

            ((KeyFileFormat *)pBufRead)->wSignFlag = 0;
            errLoadKey = keys.LoadFromBuffer( pBufRead, lMinKeyFileSize );
        }

        delete[] pBufRead;
        if( !errLoadKey )
            bKeysReaded = true;
        else
        {
            Keys flushKey;
            keys = flushKey;
            m_siErrorCode = -3;
        }
    }

    return bKeysReaded;
}