Ejemplo n.º 1
0
int
Mono_Posix_Syscall_rewinddir (void* dir)
{
	rewinddir (dir);
	return 0;
}
Ejemplo n.º 2
0
void	scandirect ( char *dirname )
{
	DIR *dir;
	char	**names;
	long	numfiles;
	int	longest;
	struct dirent *ent;
	int i;
	int	chrs;
	struct stat buf;
	char pathname[1024];

	if ( (dir=opendir(dirname)) == NULL )
		return;

	i = 0;
	chrs = 0;
	longest = 0;
	numfiles = 0;

	while ( (ent = readdir (dir)) != NULL )
	{
		numfiles++;
	}

	names = (char **) malloc ( numfiles * sizeof (char *) );

	rewinddir(dir);

	while ( (ent = readdir (dir)) != NULL )
	{
		names[i] = (char *) malloc ( strlen(ent->d_name) );

		strcpy( names[i], ent->d_name );

		printf("%s", names[i]);
		chrs += strlen (names[i]);

		if ( i%5 == 0 )
		{
			printf("\n");
			chrs = 0;
		}
		else
		{
			while ( chrs%14 != 0)
			{
				printf(" ");
				chrs++;
			}
		}

		i++;
	}
	printf ("\n");

	if (closedir(dir) != 0)
	{
		perror("mkern: Error closing directory.\n");
		exit (1);
	}
}
Ejemplo n.º 3
0
char *get_file_list(const char *dirname, int file_type, uint32_t *count)
{

    DIR           *pdir = NULL;
    struct dirent *pdirent = NULL;
    int           curr_offset = 0;
    int           byte_count = 0;
    int           file_count = 0;
    char          *ret_str = NULL;
    char          filename[MAX_PATH_SIZE];
    int           cond1, cond2;

    if ((dirname == NULL) || ((pdir = opendir(dirname)) == NULL )) {
        if (dirname == NULL) {
            report("%s %s:line %d %s", __FILE__, __FUNCTION__, __LINE__,
                   "NULL directory is passed as parameter to funtion");
        } else {
            report("%s %s:line %d Error in opening the dir %s", __FILE__,
                   __FUNCTION__, __LINE__, dirname);
        }
        if (count)
            *count = 0;
        return NULL;
    }

    while (1) {
        if ((pdirent = readdir(pdir)) == NULL)
            break;

        /* Skip over '.' and '..' directores */
        if ((pdirent->d_name[0] == '.') ||
            !strcmp(pdirent->d_name, FILENAME_NUM_REF))
            continue;
        
        sprintf(filename, "%s/%s", dirname, pdirent->d_name);
        cond1 = (file_type == FILE_TYPE) && is_directory(filename);
        cond2 = (file_type == DIR_TYPE) && (!is_directory(filename));

        if (cond1 || cond2)
            continue;

        /* Calculate the number of bytes for this new entry.*/                    
        byte_count += strlen(pdirent->d_name) + 1;
        file_count++;
    }
    if (count)
        *count = file_count;
    
    if (file_count != 0) {
        
        /* need one extra one for the finall NULL terminator*/
        if ((ret_str = (char *) malloc(byte_count + 1)) == NULL) {
            report("get_file_list() failed to malloc(%d)",byte_count+1);
            closedir(pdir);
            return NULL;
        }    
        
        rewinddir(pdir);
        
        while (file_count != 0) {
            if ((pdirent = readdir(pdir)) == NULL)
                break;

            if ((pdirent->d_name[0] == '.') ||
                !strcmp(pdirent->d_name, FILENAME_NUM_REF))
                continue;
            
            sprintf(filename, "%s/%s", dirname, pdirent->d_name);
            cond1 = (file_type == FILE_TYPE) && is_directory(filename);
            cond2 = (file_type == DIR_TYPE) && (!is_directory(filename));

            if (cond1 || cond2)
                continue;

            strcpy(ret_str + curr_offset, pdirent->d_name);
            curr_offset = curr_offset + strlen(pdirent->d_name) + 1;
            file_count--;
        }
        /* Put in the finall null terminator*/
        ret_str[byte_count] = '\0';
    }
    closedir(pdir);
    return ret_str;
}
Ejemplo n.º 4
0
/**
 * FSAL_readdir :
 *     Read the entries of an opened directory.
 *     
 * \param dir_descriptor (input):
 *        Pointer to the directory descriptor filled by FSAL_opendir.
 * \param start_position (input):
 *        Cookie that indicates the first object to be read during
 *        this readdir operation.
 *        This should be :
 *        - FSAL_READDIR_FROM_BEGINNING for reading the content
 *          of the directory from the beginning.
 *        - The end_position parameter returned by the previous
 *          call to FSAL_readdir.
 * \param get_attr_mask (input)
 *        Specify the set of attributes to be retrieved for directory entries.
 * \param buffersize (input)
 *        The size (in bytes) of the buffer where
 *        the direntries are to be stored.
 * \param pdirent (output)
 *        Adresse of the buffer where the direntries are to be stored.
 * \param end_position (output)
 *        Cookie that indicates the current position in the directory.
 * \param nb_entries (output)
 *        Pointer to the number of entries read during the call.
 * \param end_of_dir (output)
 *        Pointer to a boolean that indicates if the end of dir
 *        has been reached during the call.
 * 
 * \return Major error codes :
 *        - ERR_FSAL_NO_ERROR     (no error)
 *        - Another error code if an error occured.
 */
fsal_status_t POSIXFSAL_readdir(fsal_dir_t * dir_descriptor,     /* IN */
                                fsal_cookie_t start_pos,      /* IN */
                                fsal_attrib_mask_t get_attr_mask,       /* IN */
                                fsal_mdsize_t buffersize,       /* IN */
                                fsal_dirent_t * p_pdirent,      /* OUT */
                                fsal_cookie_t * end_position,    /* OUT */
                                fsal_count_t * p_nb_entries,    /* OUT */
                                fsal_boolean_t * p_end_of_dir   /* OUT */
    )
{
  posixfsal_dir_t * p_dir_descriptor = (posixfsal_dir_t *) dir_descriptor;
  posixfsal_cookie_t start_position, telldir_pos;
  posixfsal_cookie_t * p_end_position = (posixfsal_cookie_t *) end_position;
  fsal_status_t st;
  fsal_posixdb_status_t stdb;
  fsal_count_t max_dir_entries;
  struct dirent *dp;
  struct dirent dpe;
  struct stat buffstat;
  fsal_path_t fsalpath;
  fsal_posixdb_fileinfo_t infofs;
  int rc;

  /*****************/
  /* sanity checks */
  /*****************/

  if(!p_dir_descriptor || !p_pdirent || !p_end_position || !p_nb_entries || !p_end_of_dir)
    Return(ERR_FSAL_FAULT, 0, INDEX_FSAL_readdir);

  max_dir_entries = (buffersize / sizeof(fsal_dirent_t));

  /***************************/
  /* seek into the directory */
  /***************************/
  memcpy ( (char *)&start_position.data.cookie, (char *)&start_pos.data, sizeof( off_t ) ) ;

  errno = 0;
  if(start_position.data.cookie == 0)
    {
      rewinddir(p_dir_descriptor->p_dir);
      rc = errno;
    }
  else
    {
      seekdir(p_dir_descriptor->p_dir, start_position.data.cookie);
      rc = errno;
    }

  if(rc)
    {
      st.major = posix2fsal_error(rc);
      st.minor = rc;
      goto readdir_error;
    }

  /************************/
  /* browse the directory */
  /************************/

  *p_nb_entries = 0;
  while(*p_nb_entries < max_dir_entries)
    {
    /***********************/
      /* read the next entry */
    /***********************/
      TakeTokenFSCall();
      rc = readdir_r(p_dir_descriptor->p_dir, &dpe, &dp);
      ReleaseTokenFSCall();
      if(rc)
        {
          st.major = posix2fsal_error(errno);
          st.minor = errno;
          goto readdir_error;
        }                       /* End of directory */
      if(!dp)
        {
          *p_end_of_dir = 1;
          break;
        }

    /***********************************/
      /* Get information about the entry */
    /***********************************/

      /* build the full path of the file into "fsalpath */
      if(FSAL_IS_ERROR
         (st =
          FSAL_str2name(dp->d_name, FSAL_MAX_NAME_LEN, &(p_pdirent[*p_nb_entries].name))))
        goto readdir_error;
      memcpy(&fsalpath, &(p_dir_descriptor->path), sizeof(fsal_path_t));
      st = fsal_internal_appendFSALNameToFSALPath(&fsalpath,
                                                  &(p_pdirent[*p_nb_entries].name));
      if(FSAL_IS_ERROR(st))
        goto readdir_error;

      /* get object info */
      TakeTokenFSCall();
      rc = lstat(fsalpath.path, &buffstat);
      ReleaseTokenFSCall();
      if(rc)
        {
          st.major = posix2fsal_error(errno);
          st.minor = errno;
          goto readdir_error;
        }
      if(FSAL_IS_ERROR(st = fsal_internal_posix2posixdb_fileinfo(&buffstat, &infofs)))
        goto readdir_error;

    /********************/
      /* fills the handle */
    /********************/

      /* check for "." and ".." */
      if(!strcmp(dp->d_name, "."))
        {
          memcpy(&(p_pdirent[*p_nb_entries].handle), &(p_dir_descriptor->handle),
                 sizeof(posixfsal_handle_t));
        }
      else if(!strcmp(dp->d_name, ".."))
        {
          stdb = fsal_posixdb_getParentDirHandle(p_dir_descriptor->context.p_conn,
                                                 &(p_dir_descriptor->handle),
                                                 (posixfsal_handle_t *) &(p_pdirent[*p_nb_entries].handle));
          if(FSAL_POSIXDB_IS_ERROR(stdb) && FSAL_IS_ERROR(st = posixdb2fsal_error(stdb)))
            goto readdir_error;
        }
      else
        {
#ifdef _USE_POSIXDB_READDIR_BLOCK
          if(p_dir_descriptor->dbentries_count > -1)
            {                   /* look for the entry in dbentries */
              st = fsal_internal_getInfoFromChildrenList(&(p_dir_descriptor->context),
                                                         &(p_dir_descriptor->handle),
                                                         &(p_pdirent[*p_nb_entries].name),
                                                         &infofs,
                                                         p_dir_descriptor->p_dbentries,
                                                         p_dir_descriptor->
                                                         dbentries_count,
                                                         &(p_pdirent[*p_nb_entries].
                                                           handle));
            }
          else
#endif
            {                   /* get handle for the entry */
              st = fsal_internal_getInfoFromName(&(p_dir_descriptor->context),
                                                 &(p_dir_descriptor->handle),
                                                 &(p_pdirent[*p_nb_entries].name),
                                                 &infofs,
                                                 (posixfsal_handle_t *) &(p_pdirent[*p_nb_entries].handle));
            }
          if(FSAL_IS_ERROR(st))
            goto readdir_error;
        }                       /* end of name check for "." and ".." */

    /************************
     * Fills the attributes *
     ************************/
      p_pdirent[*p_nb_entries].attributes.asked_attributes = get_attr_mask;
      st = posix2fsal_attributes(&buffstat, &(p_pdirent[*p_nb_entries].attributes));
      if(FSAL_IS_ERROR(st))
        goto readdir_error;

      /*
       * 
       **/
      telldir_pos.data.cookie = telldir(p_dir_descriptor->p_dir);
      memcpy(&p_pdirent[*p_nb_entries].cookie, &telldir_pos, sizeof(fsal_cookie_t));
      p_pdirent[*p_nb_entries].nextentry = NULL;
      if(*p_nb_entries)
        p_pdirent[*p_nb_entries - 1].nextentry = &(p_pdirent[*p_nb_entries]);

      memcpy(p_end_position, &p_pdirent[*p_nb_entries].cookie, sizeof(fsal_cookie_t));
      (*p_nb_entries)++;
    };

  Return(ERR_FSAL_NO_ERROR, 0, INDEX_FSAL_readdir);

  /* return error, and free what must be freed */
 readdir_error:
  Return(st.major, st.minor, INDEX_FSAL_readdir);
}
Ejemplo n.º 5
0
/**
  * Meniul de navigare in fisiere
  */
void printdirs(struct DIR * dir){
	char namebuf [12];
	uint32_t size = 0;
	uint8_t bitmap = 0, selected = 0, cnt = 0, ret_code = 0, is=0;
	struct dirent * crt_dir;

	do{
		/* Afisam continutul directorului curent */
		rewinddir(dir);
		LCD_clear();
		cnt = 0;
		while(1){
			crt_dir = readdir( dir, buffer);
			ret_code = check (crt_dir);
			if(ret_code == DIR_INVALID)
				continue;
			if(ret_code == DIR_END)
				break;

			get_dirent_name(crt_dir, namebuf);
			if(cnt ++ == selected){
				LCD_str( namebuf,SELECTED );
			}else{
				LCD_str( namebuf, NOT_SELECTED);
			}
		}

		/* Asteptam sa selecteze un fisier sau director */
		bitmap = BTN_wait();

		switch(bitmap){
			case UP:
				selected = (selected +1)%cnt;
				continue;
			case DOWN:
				selected = (selected + cnt-1) % cnt;
				continue;
			case ENTER:
				rewinddir(dir);
				selected ++;
				while(1){
					crt_dir = readdir( dir, buffer);
					ret_code = check (crt_dir);
					if( ret_code == DIR_VALID) selected--;
					if( !selected ) break;
				}
				break;
			default:
				continue;

		}

		is_dir(crt_dir, &is);
		if( is){
			dir = opendir(crt_dir);
		}else{
			get_dirent_size(crt_dir, &size);
			open_f(crt_dir);

			/* Curatam ecranul si afisam poza */
			LCD_clear();
			draw_bmp();
			close_f();

			/* Asteptam sa apese butonul de exit */
			while( BTN_wait() != CLOSE);
		}
	}while(1);
	exit(EXIT_SUCCESS);
}
Ejemplo n.º 6
0
char *
__getcwd (char *buf, size_t size)
{
    /* Lengths of big file name components and entire file names, and a
       deep level of file name nesting.  These numbers are not upper
       bounds; they are merely large values suitable for initial
       allocations, designed to be large enough for most real-world
       uses.  */
    enum
    {
        BIG_FILE_NAME_COMPONENT_LENGTH = 255,
        BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),
        DEEP_NESTING = 100
    };

#if HAVE_OPENAT_SUPPORT
    int fd = AT_FDCWD;
    bool fd_needs_closing = false;
#else
    char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1];
    char *dotlist = dots;
    size_t dotsize = sizeof dots;
    size_t dotlen = 0;
#endif
    DIR *dirstream = NULL;
    dev_t rootdev, thisdev;
    ino_t rootino, thisino;
    char *dir;
    register char *dirp;
    struct stat st;
    size_t allocated = size;
    size_t used;

#if HAVE_PARTLY_WORKING_GETCWD
    /* The system getcwd works, except it sometimes fails when it
       shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT.  If
       AT_FDCWD is not defined, the algorithm below is O(N**2) and this
       is much slower than the system getcwd (at least on GNU/Linux).
       So trust the system getcwd's results unless they look
       suspicious.

       Use the system getcwd even if we have openat support, since the
       system getcwd works even when a parent is unreadable, while the
       openat-based approach does not.  */

# undef getcwd
    dir = getcwd (buf, size);
    if (dir || (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT))
        return dir;
#endif

    if (size == 0)
    {
        if (buf != NULL)
        {
            __set_errno (EINVAL);
            return NULL;
        }

        allocated = BIG_FILE_NAME_LENGTH + 1;
    }

    if (buf == NULL)
    {
        dir = malloc (allocated);
        if (dir == NULL)
            return NULL;
    }
    else
        dir = buf;

    dirp = dir + allocated;
    *--dirp = '\0';

    if (__lstat (".", &st) < 0)
        goto lose;
    thisdev = st.st_dev;
    thisino = st.st_ino;

    if (__lstat ("/", &st) < 0)
        goto lose;
    rootdev = st.st_dev;
    rootino = st.st_ino;

    while (!(thisdev == rootdev && thisino == rootino))
    {
        struct dirent *d;
        dev_t dotdev;
        ino_t dotino;
        bool mount_point;
        int parent_status;
        size_t dirroom;
        size_t namlen;
        bool use_d_ino = true;

        /* Look at the parent directory.  */
#if HAVE_OPENAT_SUPPORT
        fd = openat (fd, "..", O_RDONLY);
        if (fd < 0)
            goto lose;
        fd_needs_closing = true;
        parent_status = fstat (fd, &st);
#else
        dotlist[dotlen++] = '.';
        dotlist[dotlen++] = '.';
        dotlist[dotlen] = '\0';
        parent_status = __lstat (dotlist, &st);
#endif
        if (parent_status != 0)
            goto lose;

        if (dirstream && __closedir (dirstream) != 0)
        {
            dirstream = NULL;
            goto lose;
        }

        /* Figure out if this directory is a mount point.  */
        dotdev = st.st_dev;
        dotino = st.st_ino;
        mount_point = dotdev != thisdev;

        /* Search for the last directory.  */
#if HAVE_OPENAT_SUPPORT
        dirstream = fdopendir (fd);
        if (dirstream == NULL)
            goto lose;
        /* Reset fd.  It may have been closed by fdopendir.  */
        fd = dirfd (dirstream);
        fd_needs_closing = false;
#else
        dirstream = __opendir (dotlist);
        if (dirstream == NULL)
            goto lose;
        dotlist[dotlen++] = '/';
#endif
        for (;;)
        {
            /* Clear errno to distinguish EOF from error if readdir returns
               NULL.  */
            __set_errno (0);
            d = __readdir (dirstream);

            /* When we've iterated through all directory entries without finding
               one with a matching d_ino, rewind the stream and consider each
               name again, but this time, using lstat.  This is necessary in a
               chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
               .., ../.., ../../.., etc. all had the same device number, yet the
               d_ino values for entries in / did not match those obtained
               via lstat.  */
            if (d == NULL && errno == 0 && use_d_ino)
            {
                use_d_ino = false;
                rewinddir (dirstream);
                d = __readdir (dirstream);
            }

            if (d == NULL)
            {
                if (errno == 0)
                    /* EOF on dirstream, which can mean e.g., that the current
                       directory has been removed.  */
                    __set_errno (ENOENT);
                goto lose;
            }
            if (d->d_name[0] == '.' &&
                    (d->d_name[1] == '\0' ||
                     (d->d_name[1] == '.' && d->d_name[2] == '\0')))
                continue;

            if (use_d_ino)
            {
                bool match = (MATCHING_INO (d, thisino) || mount_point);
                if (! match)
                    continue;
            }

            {
                int entry_status;
#if HAVE_OPENAT_SUPPORT
                entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
#else
                /* Compute size needed for this file name, or for the file
                   name ".." in the same directory, whichever is larger.
                   Room for ".." might be needed the next time through
                   the outer loop.  */
                size_t name_alloc = _D_ALLOC_NAMLEN (d);
                size_t filesize = dotlen + MAX (sizeof "..", name_alloc);

                if (filesize < dotlen)
                    goto memory_exhausted;

                if (dotsize < filesize)
                {
                    /* My, what a deep directory tree you have, Grandma.  */
                    size_t newsize = MAX (filesize, dotsize * 2);
                    size_t i;
                    if (newsize < dotsize)
                        goto memory_exhausted;
                    if (dotlist != dots)
                        free (dotlist);
                    dotlist = malloc (newsize);
                    if (dotlist == NULL)
                        goto lose;
                    dotsize = newsize;

                    i = 0;
                    do
                    {
                        dotlist[i++] = '.';
                        dotlist[i++] = '.';
                        dotlist[i++] = '/';
                    }
                    while (i < dotlen);
                }

                memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
                entry_status = __lstat (dotlist, &st);
#endif
                /* We don't fail here if we cannot stat() a directory entry.
                   This can happen when (network) file systems fail.  If this
                   entry is in fact the one we are looking for we will find
                   out soon as we reach the end of the directory without
                   having found anything.  */
                if (entry_status == 0 && S_ISDIR (st.st_mode)
                        && st.st_dev == thisdev && st.st_ino == thisino)
                    break;
            }
        }

        dirroom = dirp - dir;
        namlen = _D_EXACT_NAMLEN (d);

        if (dirroom <= namlen)
        {
            if (size != 0)
            {
                __set_errno (ERANGE);
                goto lose;
            }
            else
            {
                char *tmp;
                size_t oldsize = allocated;

                allocated += MAX (allocated, namlen);
                if (allocated < oldsize
                        || ! (tmp = realloc (dir, allocated)))
                    goto memory_exhausted;

                /* Move current contents up to the end of the buffer.
                This is guaranteed to be non-overlapping.  */
                dirp = memcpy (tmp + allocated - (oldsize - dirroom),
                               tmp + dirroom,
                               oldsize - dirroom);
                dir = tmp;
            }
        }
        dirp -= namlen;
        memcpy (dirp, d->d_name, namlen);
        *--dirp = '/';

        thisdev = dotdev;
        thisino = dotino;
    }

    if (dirstream && __closedir (dirstream) != 0)
    {
        dirstream = NULL;
        goto lose;
    }

    if (dirp == &dir[allocated - 1])
        *--dirp = '/';

#if ! HAVE_OPENAT_SUPPORT
    if (dotlist != dots)
        free (dotlist);
#endif

    used = dir + allocated - dirp;
    memmove (dir, dirp, used);

    if (size == 0)
        /* Ensure that the buffer is only as large as necessary.  */
        buf = realloc (dir, used);

    if (buf == NULL)
        /* Either buf was NULL all along, or `realloc' failed but
           we still have the original string.  */
        buf = dir;

    return buf;

memory_exhausted:
    __set_errno (ENOMEM);
lose:
    {
        int save = errno;
        if (dirstream)
            __closedir (dirstream);
#if HAVE_OPENAT_SUPPORT
        if (fd_needs_closing)
            close (fd);
#else
        if (dotlist != dots)
            free (dotlist);
#endif
        if (buf == NULL)
            free (dir);
        __set_errno (save);
    }
    return NULL;
}
Ejemplo n.º 7
0
/******************************************************************************
 This function creates a dirctory and file as specified by the input argruments.
 It is used to verify that a file create and delete work as expected.
 The sequence is as follows:
    create directory
    create file in directory
    verify file exists in directory
    remove file
    verify file no longer exists in directory
*******************************************************************************/
int main(int argc, char *argv[])
{
   DIR *dir_ptr;
   struct dirent *file_ptr;
   int dir_status;
   char *path;
   char *filename;
   FILE *test_file_ptr;
   char full_path[128];
   int read_return;
   int dir_remove;
   int return_value=0;


   // Input arguments are directory and filename
   if (argc > 2) {
       path = strdup(argv[1]);
       filename = strdup(argv[2]); 
       sprintf(full_path,"%s/%s",path,filename);
       printf("%s\n", full_path);  
   }
   else {
       printf("ERROR: Path and/or file not specified\n");
       printf("Usage:  ./readdir_test path filename\n");
       return 1;
   }

   // Make the directory
   if ((dir_status=mkdir(path, S_IRWXU))== 0) {
     printf("Directory created\n");
   } 

   // Open the directory
   if ((dir_ptr = opendir(path)) == NULL) {
     printf("Error:  Could not open directory\n");
     return_value=1;
   }
   // Create a file
   else {
     printf("Going to create file %s\n", full_path);
     test_file_ptr = fopen(full_path, "w");
     if (test_file_ptr == NULL) {
        printf("Error:  NULL returned on file create \n");
       return_value=1;
     }    
     else {
       printf("Successfully created file\n");
       // close the directory and file
       fclose(test_file_ptr);
       closedir(dir_ptr);
     }
   }
   // Open the directory again}
   if ((dir_ptr = opendir(path)) == NULL) {
     printf("Error:  Could not open directory\n");
       return_value=1;
   }
   printf("Going to read directory %s to make sure file %s found %s\n", path,filename);
   read_return = read_directory(file_ptr, dir_ptr, filename);
   // File should be found in directory
   if (read_return != 0) {
       printf("Error: expected file %s to be present but was not\n", full_path);  
       return_value=1;
   }
   // Delete the file
   printf("Going to delete %s\n", full_path);
   unlink(full_path);
   printf("Reading directory after deleteing file %s\n", full_path);
   rewinddir(dir_ptr);

   // File should no longer be present
   read_return = read_directory(file_ptr, dir_ptr, filename);
   if (read_return == 0) {
       printf("Error: expected file %s to not be present but was\n", full_path);  
       return_value=1;
   }
   closedir(dir_ptr);
   dir_remove = rmdir(path);
   if (dir_remove != 0) {
      printf("Error: Directoy %s cannot be removed\n",path);
   }    
   return return_value;
}
Ejemplo n.º 8
0
int osd_get_drive_list(struct osd_drive_description **drives, int *num_drives)
{
	struct osd_drive_description *ret = NULL;
	struct dirent *entry;
	int count, fd, type;
	char buf[512];
	char *serial;
	DIR *toplevel;

	/*
	 * Walk through /dev/bsg to find available devices.  Could look
	 * through /sys/class/bsg, but would have to create each device
	 * by hand in /tmp somewhere to use it, or figure out the mapping
	 * in /dev anyway.
	 */
	count = 0;
	toplevel = opendir("/dev/bsg");
	if (!toplevel)
		goto out;

	/* First, get the count */
	while ((entry = readdir(toplevel)))
		++count;

	/* subtract 2 for . and .. */
	count -= 2;

	if (count <= 0)
		goto out;

	ret = malloc(count * sizeof(*ret));
	memset(ret, 0, count * sizeof(*ret));
	rewinddir(toplevel);
	count = 0;
	while ((entry = readdir(toplevel))) {
		if (entry->d_name[0] == '.')
			continue;
		snprintf(buf, sizeof(buf),
		         "/sys/class/scsi_device/%s/device/type",
		         entry->d_name);
		fd = open(buf, O_RDONLY);
		if (fd < 0)
			continue;

		type = 0;
		buf[0] = '\0';
		read(fd, buf, sizeof(buf));
		sscanf(buf, "%d", &type);
		close(fd);

		if (type != 17)  /* TYPE_OSD */
			continue;

		snprintf(buf, sizeof(buf), "/dev/bsg/%s", entry->d_name);

		fd = open(buf, O_RDWR);
		if (fd < 0)
			continue;

		serial = osd_get_drive_serial(fd);
		close(fd);

		if (!serial)
			continue;

		ret[count].targetname = serial;
		ret[count].chardev = strdup(buf);
		++count;
	}

out:
	if (toplevel)
		closedir(toplevel);
	*drives = ret;
	*num_drives = count;
	return 0;
}
Ejemplo n.º 9
0
/**
 * Main method
 */
int main(int argc, char *argv[])
{
	if (argc < 2)
	{
		printf("Usage: mkrcpt <location to watch>\n");
		return -1;
	}
	
	DIR *dp = opendir(argv[1]);
	if (dp == NULL)
	{
		printf("Could not open the directory\n");
		return -1;
	}
	
	char *recpt = malloc(sizeof(char) * 1024);
	snprintf(recpt, 1024, REPOS_ITEM, getenv("HOME"), "test");
			
	FILE *fp = fopen(recpt, "w");
	if (fp == NULL)
	{
		char *repospath = malloc(sizeof(char) * 256);
		snprintf(repospath, 256, REPOS, getenv("HOME"));
		
		// could not open the recipt, try making the directory go again
		DIR *dest = opendir(repospath);
		if (dest == NULL)
		{
			if (mkdir(repospath, 0700) != 0)
			{
				printf("Could not create receipts directory\n");
				free(repospath);
				return -2;
			}
			fp = fopen(recpt, "w");
			if (ferror(fp))
			{
				printf("Failed to create receipt\n");
				free(repospath);
				return -2;
			}
		}
		else
		{
			printf("Failed to create recipt\n");
			free(repospath);
			return -1;
		}
	}
	fwrite(&HEADER, sizeof(HEADER), 1, fp);
	
	time_t install_time;
	assert(time(&install_time) != 0);
	fwrite(&install_time, sizeof(time_t), 1, fp);
	
	fputc('\2', fp);
	
	// open the temporary before list
	int pathsize = strlen(recpt) + 3;
	
	char *temppath = malloc(pathsize * sizeof(char));
	snprintf(temppath, pathsize, "%s.1", recpt);
	FILE *befp = fopen(temppath, "w+");
	record_files(argv[1], dp, befp);
	fputc('\0', befp);
	
	// install
	system("make install");
	
	// open the temporary after list
	rewinddir(dp);
	
	temppath[strlen(temppath) - 1] = '2';
	FILE *affp = fopen(temppath, "w+");
	record_files(argv[1], dp, affp);
	fputc('\0', affp);
	
	// compare the two file lists
	rewind(befp);
	rewind(affp);
	
	compare_records(fp, befp, affp);
	
	fclose(befp);
	fclose(affp);
	
	// remove the two temps
	unlink(temppath);
	temppath[strlen(temppath) - 1] = '1';
	unlink(temppath);
	free(temppath);
	
	// finish cleaning up
	fputc('\0', fp);
	
	fclose(fp);
	closedir(dp);
	
	free(recpt);
	
	return 0;
}
Ejemplo n.º 10
0
/// The real implementation of wildcard expansion is in this function. Other functions are just
/// wrappers around this one.
///
/// This function traverses the relevant directory tree looking for matches, and recurses when
/// needed to handle wildcrards spanning multiple components and recursive wildcards.
///
/// Because this function calls itself recursively with substrings, it's important that the
/// parameters be raw pointers instead of wcstring, which would be too expensive to construct for
/// all substrings.
///
/// Args:
/// base_dir: the "working directory" against which the wildcard is to be resolved
/// wc: the wildcard string itself, e.g. foo*bar/baz (where * is acutally ANY_CHAR)
/// prefix: the string that should be prepended for completions that replace their token.
//    This is usually the same thing as the original wildcard, but for fuzzy matching, we
//    expand intermediate segments. effective_prefix is always either empty, or ends with a slash
//    Note: this is only used when doing completions (EXPAND_FOR_COMPLETIONS is true), not
//    expansions
void wildcard_expander_t::expand(const wcstring &base_dir, const wchar_t *wc,
                                 const wcstring &effective_prefix) {
    assert(wc != NULL);

    if (interrupted()) {
        return;
    }

    // Get the current segment and compute interesting properties about it.
    const size_t wc_len = std::wcslen(wc);
    const wchar_t *const next_slash = std::wcschr(wc, L'/');
    const bool is_last_segment = (next_slash == NULL);
    const size_t wc_segment_len = next_slash ? next_slash - wc : wc_len;
    const wcstring wc_segment = wcstring(wc, wc_segment_len);
    const bool segment_has_wildcards =
        wildcard_has(wc_segment, true /* internal, i.e. look for ANY_CHAR instead of ? */);
    const wchar_t *const wc_remainder = next_slash ? next_slash + 1 : NULL;

    if (wc_segment.empty()) {
        // Handle empty segment.
        assert(!segment_has_wildcards);  //!OCLINT(multiple unary operator)
        if (is_last_segment) {
            this->expand_trailing_slash(base_dir, effective_prefix);
        } else {
            // Multiple adjacent slashes in the wildcard. Just skip them.
            this->expand(base_dir, wc_remainder, effective_prefix + L'/');
        }
    } else if (!segment_has_wildcards && !is_last_segment) {
        // Literal intermediate match. Note that we may not be able to actually read the directory
        // (issue #2099).
        assert(next_slash != NULL);

        // Absolute path of the intermediate directory
        const wcstring intermediate_dirpath = base_dir + wc_segment + L'/';

        // This just trumps everything.
        size_t before = this->resolved_completions->size();
        this->expand(intermediate_dirpath, wc_remainder, effective_prefix + wc_segment + L'/');

        // Maybe try a fuzzy match (#94) if nothing was found with the literal match. Respect
        // EXPAND_NO_DIRECTORY_ABBREVIATIONS (issue #2413).
        // Don't do fuzzy matches if the literal segment was valid (#3211)
        bool allow_fuzzy = (this->flags & (EXPAND_FUZZY_MATCH | EXPAND_NO_FUZZY_DIRECTORIES)) ==
                           EXPAND_FUZZY_MATCH;
        if (allow_fuzzy && this->resolved_completions->size() == before &&
            waccess(intermediate_dirpath, F_OK) != 0) {
            assert(this->flags & EXPAND_FOR_COMPLETIONS);
            DIR *base_dir_fd = open_dir(base_dir);
            if (base_dir_fd != NULL) {
                this->expand_literal_intermediate_segment_with_fuzz(
                    base_dir, base_dir_fd, wc_segment, wc_remainder, effective_prefix);
                closedir(base_dir_fd);
            }
        }
    } else {
        assert(!wc_segment.empty() && (segment_has_wildcards || is_last_segment));
        DIR *dir = open_dir(base_dir);
        if (dir) {
            if (is_last_segment) {
                // Last wildcard segment, nonempty wildcard.
                this->expand_last_segment(base_dir, dir, wc_segment, effective_prefix);
            } else {
                // Not the last segment, nonempty wildcard.
                assert(next_slash != NULL);
                this->expand_intermediate_segment(base_dir, dir, wc_segment, wc_remainder,
                                                  effective_prefix + wc_segment + L'/');
            }

            // Recursive wildcards require special handling.
            size_t asr_idx = wc_segment.find(ANY_STRING_RECURSIVE);
            if (asr_idx != wcstring::npos) {
                // Construct a "head + any" wildcard for matching stuff in this directory, and an
                // "any + tail" wildcard for matching stuff in subdirectories. Note that the
                // ANY_STRING_RECURSIVE character is present in both the head and the tail.
                const wcstring head_any(wc_segment, 0, asr_idx + 1);
                const wchar_t *any_tail = wc + asr_idx;
                assert(head_any.at(head_any.size() - 1) == ANY_STRING_RECURSIVE);
                assert(any_tail[0] == ANY_STRING_RECURSIVE);

                rewinddir(dir);
                this->expand_intermediate_segment(base_dir, dir, head_any, any_tail,
                                                  effective_prefix);
            }
            closedir(dir);
        }
    }
}
Ejemplo n.º 11
0
virNodeParseNode(const char *node,
                 int *sockets,
                 int *cores,
                 int *threads,
                 int *offline)
{
    int ret = -1;
    int processors = 0;
    DIR *cpudir = NULL;
    struct dirent *cpudirent = NULL;
    int sock_max = 0;
    cpu_set_t sock_map;
    int sock;
    cpu_set_t *core_maps = NULL;
    int core;
    size_t i;
    int siblings;
    unsigned int cpu;
    int online;

    *threads = 0;
    *cores = 0;
    *sockets = 0;

    if (!(cpudir = opendir(node))) {
        virReportSystemError(errno, _("cannot opendir %s"), node);
        goto cleanup;
    }

    /* enumerate sockets in the node */
    CPU_ZERO(&sock_map);
    errno = 0;
    while ((cpudirent = readdir(cpudir))) {
        if (sscanf(cpudirent->d_name, "cpu%u", &cpu) != 1)
            continue;

        if ((online = virNodeGetCpuValue(node, cpu, "online", 1)) < 0)
            goto cleanup;

        if (!online)
            continue;

        /* Parse socket */
        if ((sock = virNodeParseSocket(node, cpu)) < 0)
            goto cleanup;
        CPU_SET(sock, &sock_map);

        if (sock > sock_max)
            sock_max = sock;

        errno = 0;
    }

    if (errno) {
        virReportSystemError(errno, _("problem reading %s"), node);
        goto cleanup;
    }

    sock_max++;

    /* allocate cpu maps for each socket */
    if (VIR_ALLOC_N(core_maps, sock_max) < 0)
        goto cleanup;

    for (i = 0; i < sock_max; i++)
        CPU_ZERO(&core_maps[i]);

    /* iterate over all CPU's in the node */
    rewinddir(cpudir);
    errno = 0;
    while ((cpudirent = readdir(cpudir))) {
        if (sscanf(cpudirent->d_name, "cpu%u", &cpu) != 1)
            continue;

        if ((online = virNodeGetCpuValue(node, cpu, "online", 1)) < 0)
            goto cleanup;

        if (!online) {
            (*offline)++;
            continue;
        }

        processors++;

        /* Parse socket */
        if ((sock = virNodeParseSocket(node, cpu)) < 0)
            goto cleanup;
        if (!CPU_ISSET(sock, &sock_map)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("CPU socket topology has changed"));
            goto cleanup;
        }

        /* Parse core */
# if defined(__s390__) || \
    defined(__s390x__)
        /* logical cpu is equivalent to a core on s390 */
        core = cpu;
# else
        core = virNodeGetCpuValue(node, cpu, "topology/core_id", 0);
# endif

        CPU_SET(core, &core_maps[sock]);

        if (!(siblings = virNodeCountThreadSiblings(node, cpu)))
            goto cleanup;

        if (siblings > *threads)
            *threads = siblings;

        errno = 0;
    }

    if (errno) {
        virReportSystemError(errno, _("problem reading %s"), node);
        goto cleanup;
    }

    /* finalize the returned data */
    *sockets = CPU_COUNT(&sock_map);

    for (i = 0; i < sock_max; i++) {
        if (!CPU_ISSET(i, &sock_map))
            continue;

        core = CPU_COUNT(&core_maps[i]);
        if (core > *cores)
            *cores = core;
    }

    ret = processors;

cleanup:
    /* don't shadow a more serious error */
    if (cpudir && closedir(cpudir) < 0 && ret >= 0) {
        virReportSystemError(errno, _("problem closing %s"), node);
        ret = -1;
    }
    VIR_FREE(core_maps);

    return ret;
}
Ejemplo n.º 12
0
static u32
npfs_read_dir(Fid *f, u8* buf, u64 offset, u32 count, int dotu)
{
	int i, n, plen;
	char *dname, *path;
	struct dirent *dirent;
	struct stat st;
	Spwstat wstat;

	if (offset == 0) {
		rewinddir(f->dir);
		f->diroffset = 0;
	}

	plen = strlen(f->path);
	n = 0;
	dirent = NULL;
	dname = f->direntname;
	while (n < count) {
		if (!dname) {
			dirent = readdir(f->dir);
			if (!dirent)
				break;

			if (strcmp(dirent->d_name, ".") == 0
			|| strcmp(dirent->d_name, "..") == 0)
				continue;

			dname = dirent->d_name;
		}

		path = malloc(plen + strlen(dname) + 2);
		sprintf(path, "%s/%s", f->path, dname);
		
		if (lstat(path, &st) < 0) {
			free(path);
			create_rerror(errno);
			return 0;
		}

		ustat2npwstat(path, &st, &wstat, dotu);
		i = sp_serialize_stat(&wstat, buf + n, count - n - 1, dotu);
		free(wstat.extension);
		free(path);
		path = NULL;
		if (i==0)
			break;

		dname = NULL;
		n += i;
	}

	if (f->direntname) {
		free(f->direntname);
		f->direntname = NULL;
	}

	if (dirent)
		f->direntname = strdup(dirent->d_name);

	f->diroffset += n;
	return n;
}
Ejemplo n.º 13
0
static int do_cmd(int cmd, port_addr fd)
{
    switch(cmd)
    {
        case 0:
        {
            // Identify command

            // Read the command crc
            uint32_t ccrc;
            serial_read(fd, &ccrc, 4);
            uint32_t eccrc = crc32((void *)0, 0);
            if(ccrc != eccrc)
                return send_error_msg(fd, CRC_ERROR);

            // Set the response length and error code
            uint32_t resp_length = 12;
            uint32_t error_code = SUCCESS;

            // Build the response crc
            uint32_t crc = crc32_start();
            crc = crc32_append(crc, &magic, 4);
            crc = crc32_append(crc, &resp_length, 4);
            crc = crc32_append(crc, &error_code, 4);
            crc = crc32_append(crc, &server_caps, 4);
            crc = crc32_finish(crc);

            // Send the response
            serial_write(fd, &magic, 4);
            serial_write(fd, &resp_length, 4);
            serial_write(fd, &error_code, 4);
            serial_write(fd, &server_caps, 4);
            serial_write(fd, &crc, 4);

            fprintf(stderr, "Sent CMD0 response\n");

            return 0;
        }

        case 1:
        {
            // Read directory
            uint32_t eccrc = crc32_start();

            // Read the directory name
            uint16_t dir_name_len;
            serial_read(fd, &dir_name_len, 2);
            eccrc = crc32_append(eccrc, &dir_name_len, 2);
            char *dir_name = (char *)malloc((int)dir_name_len + 1);
            memset(dir_name, 0, dir_name_len + 1);
            serial_read(fd, dir_name, (size_t)dir_name_len);
            eccrc = crc32_append(eccrc, dir_name, (size_t)dir_name_len);
            eccrc = crc32_finish(eccrc);

            // Read the command crc
            uint32_t ccrc;
            serial_read(fd, &ccrc, 4);
            if(ccrc != eccrc)
                return send_error_msg(fd, CRC_ERROR);

            // Append the requested dir to the base dir
            int full_dir_len = strlen(base_dir) + 1 + dir_name_len + 1;
            char *full_dir = (char *)malloc(full_dir_len);
            memset(full_dir, 0, full_dir_len);
            strcat(full_dir, base_dir);
            strcat(full_dir, "/");
            strcat(full_dir, dir_name);

            // Try and read the requested directory
            DIR *dirp = opendir(full_dir);
            if(dirp == NULL)
            {
                free(dir_name);
                free(full_dir);
                if((errno == ENOENT) || (errno == ENOTDIR))
                    return send_error_msg(fd, PATH_NOT_FOUND);
                else
                    return send_error_msg(fd, UNKNOWN_ERROR);
            }

            // Count the directory entries
            int byte_count = 0;
            uint32_t entry_count = 0;
            struct dirent *de;
            while((de = readdir(dirp)) != NULL)
            {
                // Add space for byte_size, user_id, group_id
                //  and props fields
                byte_count += 16;

                // Add space for name string
                byte_count += 2;
                byte_count += strlen(de->d_name);

                entry_count++;
            }
            rewinddir(dirp);

            // Allocate the buffer to send
            uint8_t *buf = (uint8_t *)malloc(byte_count);
            int bptr = 0;

            // Fill in the buffer
            uint32_t entries_filled = 0;
            while((de = readdir(dirp)) != NULL)
            {
                // Build a string of the whole filename
                int fname_len = strlen(de->d_name);
                int path_len = full_dir_len + 1 + fname_len + 1;
                char *path = (char *)malloc(path_len);
                memset(path, 0, path_len);
                strcat(path, full_dir);
                strcat(path, "/");
                strcat(path, de->d_name);

                // Get the file stats
                struct stat stat_buf;
                if(stat(path, &stat_buf) != 0)
                {
                    fprintf(stderr, "Error running fstat on %s, errno = %i\n",
                            path, errno);
                    free(path);
                    free(buf);
                    free(full_dir);
                    free(dir_name);
                    return send_error_msg(fd, UNKNOWN_ERROR);
                }

                // Fill in the buffer
                write_word((uint32_t)stat_buf.st_size, buf, bptr);
                write_word((uint32_t)stat_buf.st_uid, buf, bptr + 4);
                write_word((uint32_t)stat_buf.st_gid, buf, bptr + 8);
                write_word((uint32_t)stat_buf.st_mode, buf, bptr + 12);
                bptr += 16;

                // Fill in the name
                write_halfword((uint16_t)dir_name_len, buf, bptr);
                bptr += 2;
                memcpy(&buf[bptr], de->d_name, dir_name_len);
                bptr += dir_name_len;

                free(path);

                entries_filled++;
            }
            if(entries_filled != entry_count)
            {
                // An error has occurred re-parsing the directory
                fprintf(stderr, "entries_filled (%i) != entry_count (%i)\n",
                        entries_filled, entry_count);
                free(buf);
                free(dir_name);
                free(full_dir);
                send_error_msg(fd, UNKNOWN_ERROR);
            }

            fprintf(stderr, "SERVER: %i directory entries, byte_count %i\n", entry_count, byte_count);

            // Set the response length and error code
            uint32_t resp_length = 16 + byte_count;
            uint32_t error_code = SUCCESS;
            uint32_t dir_entry_version = 0;

            // Build the response crc
            uint32_t crc = crc32_start();
            crc = crc32_append(crc, &magic, 4);
            crc = crc32_append(crc, &resp_length, 4);
            crc = crc32_append(crc, &error_code, 4);
            crc = crc32_append(crc, &entry_count, 4);
            crc = crc32_append(crc, &dir_entry_version, 4);
            crc = crc32_append(crc, buf, byte_count);
            crc = crc32_finish(crc);

            // Send the response
            serial_write(fd, &magic, 4);
            serial_write(fd, &resp_length, 4);
            serial_write(fd, &error_code, 4);
            serial_write(fd, &entry_count, 4);
            serial_write(fd, &dir_entry_version, 4);
            serial_write(fd, buf, byte_count);
            serial_write(fd, &crc, 4);

            fprintf(stderr, "Sent CMD1 response\n");

            free(buf);
            free(dir_name);
            free(full_dir);

            return 0;
        }
    }
    (void)fd;
    return 0;
}
Ejemplo n.º 14
0
static int listdir(const char *name, int flags)
{
    char tmp[4096];
    DIR *d;
    struct dirent *de;
    
    d = opendir(name);
    if(d == 0) {
        fprintf(stderr, "opendir failed, %s\n", strerror(errno));
        return -1;
    }

    while((de = readdir(d)) != 0){
        if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
        if(de->d_name[0] == '.' && (flags & LIST_ALL) == 0) continue;

        listfile(name, de->d_name, flags);
    }

    if (flags & LIST_RECURSIVE) {
        rewinddir(d);

        while ((de = readdir(d)) != 0) {
            struct stat s;
            int err;

            if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
                continue;
            if (de->d_name[0] == '.' && (flags & LIST_ALL) == 0)
                continue;

            if (!strcmp(name, "/"))
                snprintf(tmp, sizeof(tmp), "/%s", de->d_name);
            else
                snprintf(tmp, sizeof(tmp), "%s/%s", name, de->d_name);

            /*
             * If the name ends in a '/', use stat() so we treat it like a
             * directory even if it's a symlink.
             */
            if (tmp[strlen(tmp)-1] == '/')
                err = stat(tmp, &s);
            else
                err = lstat(tmp, &s);

            if (err < 0) {
                perror(tmp);
                closedir(d);
                return -1;
            }

            if (S_ISDIR(s.st_mode)) {
                printf("\n%s:\n", tmp);
                listdir(tmp, flags);
            }
        }
    }

    closedir(d);
    return 0;
}
Ejemplo n.º 15
0
BOOL drive_file_query_directory(DRIVE_FILE* file, UINT32 FsInformationClass, BYTE InitialQuery,
	const char* path, wStream* output)
{
	int length;
	BOOL ret;
	WCHAR* ent_path;
	struct STAT st;
	struct dirent* ent;

	DEBUG_SVC("path %s FsInformationClass %d InitialQuery %d", path, FsInformationClass, InitialQuery);

	if (!file->dir)
	{
		Stream_Write_UINT32(output, 0); /* Length */
		Stream_Write_UINT8(output, 0); /* Padding */
		return FALSE;
	}

	if (InitialQuery != 0)
	{
		rewinddir(file->dir);
		free(file->pattern);

		if (path[0])
			file->pattern = _strdup(strrchr(path, '\\') + 1);
		else
			file->pattern = NULL;
	}

	if (file->pattern)
	{
		do
		{
			ent = readdir(file->dir);

			if (ent == NULL)
				continue;

			if (FilePatternMatchA(ent->d_name, file->pattern))
				break;

		}
		while (ent);
	}
	else
	{
		ent = readdir(file->dir);
	}

	if (ent == NULL)
	{
		DEBUG_SVC("  pattern %s not found.", file->pattern);
		Stream_Write_UINT32(output, 0); /* Length */
		Stream_Write_UINT8(output, 0); /* Padding */
		return FALSE;
	}

	memset(&st, 0, sizeof(struct STAT));
	ent_path = (WCHAR*) malloc(strlen(file->fullpath) + strlen(ent->d_name) + 2);
	sprintf((char*) ent_path, "%s/%s", file->fullpath, ent->d_name);

	if (STAT((char*) ent_path, &st) != 0)
	{
		DEBUG_WARN("stat %s failed. errno = %d", (char*) ent_path, errno);
	}

	DEBUG_SVC("  pattern %s matched %s", file->pattern, ent_path);
	free(ent_path);
	ent_path = NULL;

	length = ConvertToUnicode(CP_UTF8, 0, ent->d_name, -1, &ent_path, 0) * 2;

	ret = TRUE;

	switch (FsInformationClass)
	{
		case FileDirectoryInformation:
			/* http://msdn.microsoft.com/en-us/library/cc232097.aspx */
			Stream_Write_UINT32(output, 64 + length); /* Length */
			Stream_EnsureRemainingCapacity(output, 64 + length);
			Stream_Write_UINT32(output, 0); /* NextEntryOffset */
			Stream_Write_UINT32(output, 0); /* FileIndex */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_mtime)); /* CreationTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_atime)); /* LastAccessTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_mtime)); /* LastWriteTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_ctime)); /* ChangeTime */
			Stream_Write_UINT64(output, st.st_size); /* EndOfFile */
			Stream_Write_UINT64(output, st.st_size); /* AllocationSize */
			Stream_Write_UINT32(output, FILE_ATTR_SYSTEM_TO_RDP(file, st)); /* FileAttributes */
			Stream_Write_UINT32(output, length); /* FileNameLength */
			Stream_Write(output, ent_path, length);
			break;

		case FileFullDirectoryInformation:
			/* http://msdn.microsoft.com/en-us/library/cc232068.aspx */
			Stream_Write_UINT32(output, 68 + length); /* Length */
			Stream_EnsureRemainingCapacity(output, 68 + length);
			Stream_Write_UINT32(output, 0); /* NextEntryOffset */
			Stream_Write_UINT32(output, 0); /* FileIndex */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_mtime)); /* CreationTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_atime)); /* LastAccessTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_mtime)); /* LastWriteTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_ctime)); /* ChangeTime */
			Stream_Write_UINT64(output, st.st_size); /* EndOfFile */
			Stream_Write_UINT64(output, st.st_size); /* AllocationSize */
			Stream_Write_UINT32(output, FILE_ATTR_SYSTEM_TO_RDP(file, st)); /* FileAttributes */
			Stream_Write_UINT32(output, length); /* FileNameLength */
			Stream_Write_UINT32(output, 0); /* EaSize */
			Stream_Write(output, ent_path, length);
			break;

		case FileBothDirectoryInformation:
			/* http://msdn.microsoft.com/en-us/library/cc232095.aspx */
			Stream_Write_UINT32(output, 93 + length); /* Length */
			Stream_EnsureRemainingCapacity(output, 93 + length);
			Stream_Write_UINT32(output, 0); /* NextEntryOffset */
			Stream_Write_UINT32(output, 0); /* FileIndex */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_mtime)); /* CreationTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_atime)); /* LastAccessTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_mtime)); /* LastWriteTime */
			Stream_Write_UINT64(output, FILE_TIME_SYSTEM_TO_RDP(st.st_ctime)); /* ChangeTime */
			Stream_Write_UINT64(output, st.st_size); /* EndOfFile */
			Stream_Write_UINT64(output, st.st_size); /* AllocationSize */
			Stream_Write_UINT32(output, FILE_ATTR_SYSTEM_TO_RDP(file, st)); /* FileAttributes */
			Stream_Write_UINT32(output, length); /* FileNameLength */
			Stream_Write_UINT32(output, 0); /* EaSize */
			Stream_Write_UINT8(output, 0); /* ShortNameLength */
			/* Reserved(1), MUST NOT be added! */
			Stream_Zero(output, 24); /* ShortName */
			Stream_Write(output, ent_path, length);
			break;

		case FileNamesInformation:
			/* http://msdn.microsoft.com/en-us/library/cc232077.aspx */
			Stream_Write_UINT32(output, 12 + length); /* Length */
			Stream_EnsureRemainingCapacity(output, 12 + length);
			Stream_Write_UINT32(output, 0); /* NextEntryOffset */
			Stream_Write_UINT32(output, 0); /* FileIndex */
			Stream_Write_UINT32(output, length); /* FileNameLength */
			Stream_Write(output, ent_path, length);
			break;

		default:
			Stream_Write_UINT32(output, 0); /* Length */
			Stream_Write_UINT8(output, 0); /* Padding */
			DEBUG_WARN("invalid FsInformationClass %d", FsInformationClass);
			ret = FALSE;
			break;
	}

	free(ent_path);

	return ret;
}
Ejemplo n.º 16
0
static void local_rewinddir(FsContext *ctx, V9fsFidOpenState *fs)
{
    return rewinddir(fs->dir);
}
Ejemplo n.º 17
0
void msh_auto_complete_path(char *path)
{
    DIR* dir = RT_NULL;
    struct dirent *dirent = RT_NULL;
    char *full_path, *ptr, *index;

    full_path = (char*)rt_malloc(256);
    if (full_path == RT_NULL) return; /* out of memory */

    ptr = full_path;
    if (*path != '/')
    {
        getcwd(full_path, 256);
        if (full_path[rt_strlen(full_path) - 1]  != '/')
            strcat(full_path, "/");
    }
    else *full_path = '\0';

    index = RT_NULL; ptr = path;
    for (;;)
    {
        if (*ptr == '/') index = ptr + 1; if (!*ptr) break; ptr ++;
    }
    if (index == RT_NULL) index = path;

    if (index != RT_NULL)
    {
        char *dest = index;

        /* fill the parent path */
        ptr = full_path;
        while (*ptr) ptr ++;

        for (index = path; index != dest;)
            *ptr++ = *index++;
        *ptr = '\0';

        dir = opendir(full_path);
        if (dir == RT_NULL) /* open directory failed! */
        {
            rt_free(full_path);
            return;
        }

        /* restore the index position */
        index = dest;
    }

    /* auto complete the file or directory name */
    if (*index == '\0') /* display all of files and directories */
    {
        for (;;)
        {
            dirent = readdir(dir);
            if (dirent == RT_NULL) break;

            rt_kprintf("%s\n", dirent->d_name);
        }
    }
    else
    {
        int length, min_length;

        min_length = 0;
        for (;;)
        {
            dirent = readdir(dir);
            if (dirent == RT_NULL) break;

            /* matched the prefix string */
            if (strncmp(index, dirent->d_name, rt_strlen(index)) == 0)
            {
                if (min_length == 0)
                {
                    min_length = rt_strlen(dirent->d_name);
                    /* save dirent name */
                    strcpy(full_path, dirent->d_name);
                }
                
                length = str_common(dirent->d_name, full_path);
                
                if (length < min_length)
                {
                    min_length = length;
                }
            }
        }

        if (min_length)
        {
            if (min_length < rt_strlen(full_path))
            {
                /* list the candidate */
                rewinddir(dir);

                for (;;)
                {
                    dirent = readdir(dir);
                    if (dirent == RT_NULL) break;

                    if (strncmp(index, dirent->d_name, rt_strlen(index)) == 0)
                        rt_kprintf("%s\n", dirent->d_name);
                }
            }
            
            length = index - path;
            memcpy(index, full_path, min_length);
            path[length + min_length] = '\0';
        }
    }

    closedir(dir);
    rt_free(full_path);
}
Ejemplo n.º 18
0
/**
   Directory tree is now
 
     top / topfile
           middle2 /   
           middle1 / bottom1 / absfile
                   / bottom2 / file                -- read-only
 		   / read-only / sub-read-only /
                                 file
 

@SYMTestCaseID          SYSLIB-STDLIB-CT-1050
@SYMTestCaseDesc	    Tests for enumeration on directories 
@SYMTestPriority 	    High
@SYMTestActions  	    Tests by opening directories
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/		
void directory()
	{
	int err, count, i, j, fd;
	DIR *dp;
	struct dirent *ep;
	char name[MAXPATHLEN+1];
	off_t pos;

	test_Next("Enumerating Directories");

	err=chdir(rootpath);
	test(err==0);

	dp=opendir("topfile");
	/* test_errno(dp==0,ENOTDIR); -- not convinced about this anyway */
	test_errno(dp==0,ENOENT);

	dp=opendir("no such file");
	test_errno(dp==0,ENOENT);


	//test something sensible happens if someone uses a WDIR inplace of a DIR
	{
		WDIR *wp = wopendir((wchar_t*)L".");
		test(wp!=0);

		// Test wants a WDIR passed but won't compile under CW.
		// Force the compile by casting. The function will still get a WDIR.
		// DIR inherits from WDIR.
		ep=readdir((DIR*)wp);
		test_errno(ep==0,EINVAL);

		wclosedir(wp);
	}




	dp=opendir(".");
	test(dp!=0);

	count=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count++;
		}
	while (ep!=0);
	test(count==4);

	for (i=0; i<4; i++)
		{
		rewinddir(dp);
		for (j=0; j<=i; j++)
			{
			ep=readdir(dp);
			test(ep!=0);
			}
		strcpy(name,ep->d_name);
		rewinddir(dp);
		for (j=0; j<=i; j++)
			{
			ep=readdir(dp);
			test(ep!=0);
			}
		test(strcmp(name,ep->d_name)==0);
		}

	for (i=0; i<4; i++)
		{
		rewinddir(dp);
		pos=telldir(dp);
		for (j=0; j<=i; j++)
			{
			pos=telldir(dp);
			ep=readdir(dp);
			test(ep!=0);
			}
		strcpy(name,ep->d_name);
		rewinddir(dp);
		seekdir(dp, pos);
		ep=readdir(dp);
		test(ep!=0);
		test(strcmp(name,ep->d_name)==0);
		}

	err=closedir(dp);
	test(err==0);

	dp=opendir("middle2");
	test(dp!=0);

	count=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count++;
		}
	while (ep!=0);
	test(count==0);	/* empty directory */

	rewinddir(dp);

	fd = open("middle2/extrafile",O_RDWR+O_CREAT,0777);
	test(fd>=0);

	err=close(fd);
	test(err==0);

	count=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count++;
		}
	while (ep!=0);
	test(count==0);	/* shouldn't have noticed the change */

	rewinddir(dp);	/* and spot the new file */
	count=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count++;
		}
	while (ep!=0);
	test(count==1);

	closedir(dp);

	dp=opendir("/");
	test(dp!=0);

	count=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count++;
		}
	while (ep!=0);
	test(count>0);

	closedir(dp);
	}
Ejemplo n.º 19
0
static void
ruptime(const char *host, int aflg, int (*cmp)(const void *, const void *))
{
	struct hs *hsp;
	struct whod *wd;
	struct whoent *we;
	struct dirent *dp;
	const char *hostname;
	int fd, i, maxloadav;
	size_t hspace;
	ssize_t cc;

	rewinddir(dirp);
	hsp = NULL;
	maxloadav = -1;
	(void)time(&now);
	for (nhosts = hspace = 0; (dp = readdir(dirp)) != NULL;) {
		if (dp->d_ino == 0 || strncmp(dp->d_name, "whod.", 5) != 0)
			continue;
		if ((fd = open(dp->d_name, O_RDONLY, 0)) < 0) {
			warn("%s", dp->d_name);
			continue;
		}

		if (nhosts == hspace) {
			if ((hs =
			    realloc(hs, (hspace += 40) * sizeof(*hs))) == NULL)
				err(1, NULL);
			hsp = hs + nhosts;
		}

		wd = &hsp->hs_wd;
		cc = read(fd, wd, sizeof(*wd));
		(void)close(fd);
		if (cc < (ssize_t)WHDRSIZE)
			continue;

		if (host != NULL) {
			hostname = wd->wd_hostname;
			if (strcasecmp(hostname, host) != 0)
				continue;
		}
		if (LEFTEARTH(wd->wd_recvtime))
			continue;

		for (i = 0; i < 2; i++)
			if (wd->wd_loadav[i] > maxloadav)
				maxloadav = wd->wd_loadav[i];

		for (hsp->hs_nusers = 0, we = &wd->wd_we[0];
		    (char *)(we + 1) <= (char *)wd + cc; we++)
			if (aflg || we->we_idle < 3600)
				++hsp->hs_nusers;
		++hsp;
		++nhosts;
	}
	if (nhosts == 0) {
		if (host == NULL)
			errx(1, "no hosts in %s", _PATH_RWHODIR);
		else
			warnx("host %s not in %s", host, _PATH_RWHODIR);
	}

	qsort(hs, nhosts, sizeof(hs[0]), cmp);
	for (i = 0; i < (int)nhosts; i++) {
		hsp = &hs[i];
		wd = &hsp->hs_wd;
		if (ISDOWN(hsp)) {
			(void)printf("%-25.25s%s\n", wd->wd_hostname,
			    interval(now - hsp->hs_wd.wd_recvtime, "down"));
			continue;
		}
		(void)printf(
		    "%-25.25s%s,  %4d user%s  load %*.2f, %*.2f, %*.2f\n",
		    wd->wd_hostname,
		    interval((time_t)wd->wd_sendtime -
		        (time_t)wd->wd_boottime, "  up"),
		    hsp->hs_nusers,
		    hsp->hs_nusers == 1 ? ", " : "s,",
		    maxloadav >= 1000 ? 5 : 4,
		        wd->wd_loadav[0] / 100.0,
		    maxloadav >= 1000 ? 5 : 4,
		        wd->wd_loadav[1] / 100.0,
		    maxloadav >= 1000 ? 5 : 4,
		        wd->wd_loadav[2] / 100.0);
	}
	free(hs);
	hs = NULL;
}
Ejemplo n.º 20
0
/**
@SYMTestCaseID          SYSLIB-STDLIB-CT-1054
@SYMTestCaseDesc	    Tests for creation of temporary directory and files in it.
@SYMTestPriority 	    High
@SYMTestActions  	    Tests by creating a temporary directory,files and writing to the files.
                        Check for error codes.
@SYMTestExpectedResults Test must not fail
@SYMREQ                 REQ0000
*/		
void temporary_files()
	{
#define tmpdir        "c:/system/temp"

	int err, count1, count2;
	DIR *dp;
	struct dirent *ep;
	FILE *fp;
	char name[L_tmpnam];
	char name2[L_tmpnam];
	char *p;

	test_Next("Temporary files");

	dp=opendir(tmpdir);
	if (dp==0)
		{
		printf("  Creating the directory %s ...\n", tmpdir);
		err=mkdir("c:/system", 0777);
		test(err==0);
		err=mkdir(tmpdir, 0777);
		test(err==0);
		dp=opendir(tmpdir);
		}
	test(dp!=0);

	count1=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count1++;
		}
	while (ep!=0);

	fp=tmpfile();
	test(fp!=0);

	err=fprintf(fp,"hello");
	test(err==5);

	rewinddir(dp);
	count2=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count2++;
		}
	while (ep!=0);
	test(count2==count1+1);	/* EPOC32 temporary files are visible in file system */
	err=fclose(fp);
	test(err==0);

	rewinddir(dp);
	count2=0;
	do
		{
		ep=readdir(dp);
		if (ep && strcmp(ep->d_name,".")!=0 && strcmp(ep->d_name,"..")!=0)
			count2++;
		}
	while (ep!=0);
	test(count2==count1);		/* should be automatically deleted */

	closedir(dp);

	p=tmpnam(NULL);
	test(p!=0);

	count1=strlen(p);
	test(count1<L_tmpnam);

	p=tmpnam(name);
	test(p==name);

	fp=fopen(name,"wb+");
	test(fp!=0);

	p=tmpnam(name2);
	test(p==name2);

	err=strcmp(name,name2);
	test(err!=0);

	err=fclose(fp);
	test(err==0);

	err=unlink(name);
	test(err==0);

	printf("  Tmpnam suggested %s and %s\n", name, name2);
	}
Ejemplo n.º 21
0
/*--------------------------------------------------------------------
 * rewind
 */
static void readdir_rewind(t_readdir *x)
{
  if (x->x_dir) rewinddir(x->x_dir);
}
Ejemplo n.º 22
0
void test() {
  int err;
  int loc;
  DIR *dir;
  struct dirent *ent;
  struct dirent ent_r;
  struct dirent *result;

  // check bad opendir input
  dir = opendir("noexist");
  assert(!dir);
  assert(errno == ENOENT);
  dir = opendir("nocanread");
  assert(!dir);
  assert(errno == EACCES);
  dir = opendir("foobar/file.txt");
  assert(!dir);
  assert(errno == ENOTDIR);

  // check bad readdir input
  dir = opendir("foobar");
  closedir(dir);
  ent = readdir(dir);
  assert(!ent);
  assert(errno == EBADF);

  // check bad readdir_r input
  dir = opendir("foobar");
  closedir(dir);
  err = readdir_r(dir, NULL, &result);
  assert(err == EBADF);
  
  //
  // do a normal read with readdir
  //
  dir = opendir("foobar");
  assert(dir);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, "."));
  assert(ent->d_type & DT_DIR);
  assert(ent->d_reclen == sizeof(*ent));
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".."));
  assert(ent->d_type & DT_DIR);
  assert(ent->d_reclen == sizeof(*ent));
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, "file.txt"));
  assert(ent->d_type & DT_REG);
  assert(ent->d_reclen == sizeof(*ent));
  ent = readdir(dir);
  assert(!ent);

  // test rewinddir
  rewinddir(dir);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, "."));

  // test seek / tell
  rewinddir(dir);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, "."));
  loc = telldir(dir);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".."));
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, "file.txt"));
  seekdir(dir, loc);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".."));

  //
  // do a normal read with readdir_r
  //
  rewinddir(dir);
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(&ent_r == result);
  assert(!strcmp(ent_r.d_name, "."));
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(&ent_r == result);
  assert(!strcmp(ent_r.d_name, ".."));
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(&ent_r == result);
  assert(!strcmp(ent_r.d_name, "file.txt"));
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(!result);

  err = closedir(dir);
  assert(!err);

  puts("success");
}
Ejemplo n.º 23
0
static void
BroadcastSetThreadSandbox(SandboxType aType)
{
  int signum;
  pid_t pid, tid, myTid;
  DIR *taskdp;
  struct dirent *de;
  SandboxFilter filter(&sSetSandboxFilter, aType,
                       getenv("MOZ_SANDBOX_VERBOSE"));

  static_assert(sizeof(mozilla::Atomic<int>) == sizeof(int),
                "mozilla::Atomic<int> isn't represented by an int");
  pid = getpid();
  myTid = syscall(__NR_gettid);
  taskdp = opendir("/proc/self/task");
  if (taskdp == nullptr) {
    SANDBOX_LOG_ERROR("opendir /proc/self/task: %s\n", strerror(errno));
    MOZ_CRASH();
  }
  signum = FindFreeSignalNumber();
  if (signum == 0) {
    SANDBOX_LOG_ERROR("No available signal numbers!");
    MOZ_CRASH();
  }
  void (*oldHandler)(int);
  oldHandler = signal(signum, SetThreadSandboxHandler);
  if (oldHandler != SIG_DFL) {
    // See the comment on FindFreeSignalNumber about race conditions.
    SANDBOX_LOG_ERROR("signal %d in use by handler %p!\n", signum, oldHandler);
    MOZ_CRASH();
  }

  // In case this races with a not-yet-deprivileged thread cloning
  // itself, repeat iterating over all threads until we find none
  // that are still privileged.
  bool sandboxProgress;
  do {
    sandboxProgress = false;
    // For each thread...
    while ((de = readdir(taskdp))) {
      char *endptr;
      tid = strtol(de->d_name, &endptr, 10);
      if (*endptr != '\0' || tid <= 0) {
        // Not a task ID.
        continue;
      }
      if (tid == myTid) {
        // Drop this thread's privileges last, below, so we can
        // continue to signal other threads.
        continue;
      }
      // Reset the futex cell and signal.
      sSetSandboxDone = 0;
      if (syscall(__NR_tgkill, pid, tid, signum) != 0) {
        if (errno == ESRCH) {
          SANDBOX_LOG_ERROR("Thread %d unexpectedly exited.", tid);
          // Rescan threads, in case it forked before exiting.
          sandboxProgress = true;
          continue;
        }
        SANDBOX_LOG_ERROR("tgkill(%d,%d): %s\n", pid, tid, strerror(errno));
        MOZ_CRASH();
      }
      // It's unlikely, but if the thread somehow manages to exit
      // after receiving the signal but before entering the signal
      // handler, we need to avoid blocking forever.
      //
      // Using futex directly lets the signal handler send the wakeup
      // from an async signal handler (pthread mutex/condvar calls
      // aren't allowed), and to use a relative timeout that isn't
      // affected by changes to the system clock (not possible with
      // POSIX semaphores).
      //
      // If a thread doesn't respond within a reasonable amount of
      // time, but still exists, we crash -- the alternative is either
      // blocking forever or silently losing security, and it
      // shouldn't actually happen.
      static const int crashDelay = 10; // seconds
      struct timespec timeLimit;
      clock_gettime(CLOCK_MONOTONIC, &timeLimit);
      timeLimit.tv_sec += crashDelay;
      while (true) {
        static const struct timespec futexTimeout = { 0, 10*1000*1000 }; // 10ms
        // Atomically: if sSetSandboxDone == 0, then sleep.
        if (syscall(__NR_futex, reinterpret_cast<int*>(&sSetSandboxDone),
                  FUTEX_WAIT, 0, &futexTimeout) != 0) {
          if (errno != EWOULDBLOCK && errno != ETIMEDOUT && errno != EINTR) {
            SANDBOX_LOG_ERROR("FUTEX_WAIT: %s\n", strerror(errno));
            MOZ_CRASH();
          }
        }
        // Did the handler finish?
        if (sSetSandboxDone > 0) {
          if (sSetSandboxDone == 2) {
            sandboxProgress = true;
          }
          break;
        }
        // Has the thread ceased to exist?
        if (syscall(__NR_tgkill, pid, tid, 0) != 0) {
          if (errno == ESRCH) {
            SANDBOX_LOG_ERROR("Thread %d unexpectedly exited.", tid);
          }
          // Rescan threads, in case it forked before exiting.
          // Also, if it somehow failed in a way that wasn't ESRCH,
          // and still exists, that will be handled on the next pass.
          sandboxProgress = true;
          break;
        }
        struct timespec now;
        clock_gettime(CLOCK_MONOTONIC, &now);
        if (now.tv_sec > timeLimit.tv_nsec ||
            (now.tv_sec == timeLimit.tv_nsec &&
             now.tv_nsec > timeLimit.tv_nsec)) {
          SANDBOX_LOG_ERROR("Thread %d unresponsive for %d seconds."
                            "  Killing process.",
                            tid, crashDelay);
          MOZ_CRASH();
        }
      }
    }
    rewinddir(taskdp);
  } while (sandboxProgress);
  oldHandler = signal(signum, SIG_DFL);
  if (oldHandler != SetThreadSandboxHandler) {
    // See the comment on FindFreeSignalNumber about race conditions.
    SANDBOX_LOG_ERROR("handler for signal %d was changed to %p!",
                      signum, oldHandler);
    MOZ_CRASH();
  }
  unused << closedir(taskdp);
  // And now, deprivilege the main thread:
  SetThreadSandbox();
}
Ejemplo n.º 24
0
/**
 * resets the position of the directory stream to the beginning of the directory
 *
 * @param aDir pointer to the directory stream object
 * @return result code
 */
ACP_EXPORT acp_rc_t acpDirRewind(acp_dir_t *aDir)
{
    rewinddir(aDir->mHandle);

    return ACP_RC_SUCCESS;
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
    const struct hwloc_topology_support *support;
    hwloc_topology_t topology;
    hwloc_const_bitmap_t topocpuset;
    hwloc_bitmap_t cpuset;
    unsigned long flags = 0;
    DIR *dir;
    struct dirent *dirent;
    int show_all = 0;
    int show_threads = 0;
    int get_last_cpu_location = 0;
    char *callname;
    char *pidcmd = NULL;
    int err;
    int opt;

    callname = strrchr(argv[0], '/');
    if (!callname)
        callname = argv[0];
    else
        callname++;
    /* skip argv[0], handle options */
    argc--;
    argv++;

    hwloc_utils_check_api_version(callname);

    while (argc >= 1) {
        opt = 0;
        if (!strcmp(argv[0], "-a"))
            show_all = 1;
        else if (!strcmp(argv[0], "-l") || !strcmp(argv[0], "--logical")) {
            logical = 1;
        } else if (!strcmp(argv[0], "-p") || !strcmp(argv[0], "--physical")) {
            logical = 0;
        } else if (!strcmp(argv[0], "-c") || !strcmp(argv[0], "--cpuset")) {
            show_cpuset = 1;
        } else if (!strcmp(argv[0], "-e") || !strncmp(argv[0], "--get-last-cpu-location", 10)) {
            get_last_cpu_location = 1;
        } else if (!strcmp(argv[0], "-t") || !strcmp(argv[0], "--threads")) {
#ifdef HWLOC_LINUX_SYS
            show_threads = 1;
#else
            fprintf (stderr, "Listing threads is currently only supported on Linux\n");
#endif
        } else if (!strcmp (argv[0], "--whole-system")) {
            flags |= HWLOC_TOPOLOGY_FLAG_WHOLE_SYSTEM;
        } else if (!strcmp (argv[0], "--pid-cmd")) {
            if (argc < 2) {
                usage(callname, stdout);
                exit(EXIT_FAILURE);
            }
            pidcmd = argv[1];
            opt = 1;
        } else {
            fprintf (stderr, "Unrecognized option: %s\n", argv[0]);
            usage (callname, stderr);
            exit(EXIT_FAILURE);
        }
        argc -= opt+1;
        argv += opt+1;
    }

    err = hwloc_topology_init(&topology);
    if (err)
        goto out;

    hwloc_topology_set_flags(topology, flags);

    err = hwloc_topology_load(topology);
    if (err)
        goto out_with_topology;

    support = hwloc_topology_get_support(topology);

    if (get_last_cpu_location) {
        if (!support->cpubind->get_proc_last_cpu_location)
            goto out_with_topology;
    } else {
        if (!support->cpubind->get_proc_cpubind)
            goto out_with_topology;
    }

    topocpuset = hwloc_topology_get_topology_cpuset(topology);

    dir  = opendir("/proc");
    if (!dir)
        goto out_with_topology;

    cpuset = hwloc_bitmap_alloc();
    if (!cpuset)
        goto out_with_dir;

    while ((dirent = readdir(dir))) {
        long pid_number;
        hwloc_pid_t pid;
        char pidoutput[1024];
        char *end;
        char name[64] = "";
        /* management of threads */
        unsigned boundthreads = 0, i;
        long *tids = NULL; /* NULL if process is not threaded */
        hwloc_bitmap_t *tidcpusets = NULL;

        pid_number = strtol(dirent->d_name, &end, 10);
        if (*end)
            /* Not a number */
            continue;

        pid = hwloc_pid_from_number(pid_number, 0);

#ifdef HWLOC_LINUX_SYS
        {
            unsigned pathlen = 6 + strlen(dirent->d_name) + 1 + 7 + 1;
            char *path;
            int file;
            ssize_t n;

            path = malloc(pathlen);
            snprintf(path, pathlen, "/proc/%s/cmdline", dirent->d_name);
            file = open(path, O_RDONLY);
            free(path);

            if (file >= 0) {
                n = read(file, name, sizeof(name) - 1);
                close(file);

                if (n <= 0)
                    /* Ignore kernel threads and errors */
                    continue;

                name[n] = 0;
            }
        }
#endif /* HWLOC_LINUX_SYS */

        if (show_threads) {
#ifdef HWLOC_LINUX_SYS
            /* check if some threads must be displayed */
            unsigned pathlen = 6 + strlen(dirent->d_name) + 1 + 4 + 1;
            char *path;
            DIR *taskdir;

            path = malloc(pathlen);
            snprintf(path, pathlen, "/proc/%s/task", dirent->d_name);
            taskdir = opendir(path);
            if (taskdir) {
                struct dirent *taskdirent;
                long tid;
                unsigned n = 0;
                /* count threads */
                while ((taskdirent = readdir(taskdir))) {
                    tid = strtol(taskdirent->d_name, &end, 10);
                    if (*end)
                        /* Not a number */
                        continue;
                    n++;
                }
                if (n > 1) {
                    /* if there's more than one thread, see if some are bound */
                    tids = malloc(n * sizeof(*tids));
                    tidcpusets = calloc(n+1, sizeof(*tidcpusets));
                    if (tids && tidcpusets) {
                        /* reread the directory but gather info now */
                        rewinddir(taskdir);
                        i = 0;
                        while ((taskdirent = readdir(taskdir))) {
                            tid = strtol(taskdirent->d_name, &end, 10);
                            if (*end)
                                /* Not a number */
                                continue;
                            if (get_last_cpu_location) {
                                if (hwloc_linux_get_tid_last_cpu_location(topology, tid, cpuset))
                                    continue;
                            } else {
                                if (hwloc_linux_get_tid_cpubind(topology, tid, cpuset))
                                    continue;
                            }
                            hwloc_bitmap_and(cpuset, cpuset, topocpuset);
                            tids[i] = tid;
                            tidcpusets[i] = hwloc_bitmap_dup(cpuset);
                            i++;
                            if (hwloc_bitmap_iszero(cpuset))
                                continue;
                            if (hwloc_bitmap_isequal(cpuset, topocpuset) && !show_all)
                                continue;
                            boundthreads++;
                        }
                    } else {
                        /* failed to alloc, behave as if there were no threads */
                        free(tids);
                        tids = NULL;
                        free(tidcpusets);
                        tidcpusets = NULL;
                    }
                }
                closedir(taskdir);
            }
#endif /* HWLOC_LINUX_SYS */
        }

        if (get_last_cpu_location) {
            if (hwloc_get_proc_last_cpu_location(topology, pid, cpuset, 0))
                continue;
        } else {
            if (hwloc_get_proc_cpubind(topology, pid, cpuset, 0))
                continue;
        }

        hwloc_bitmap_and(cpuset, cpuset, topocpuset);
        if (hwloc_bitmap_iszero(cpuset))
            continue;

        /* don't print anything if the process isn't bound and if no threads are bound and if not showing all */
        if (hwloc_bitmap_isequal(cpuset, topocpuset) && (!tids || !boundthreads) && !show_all)
            continue;

        pidoutput[0] = '\0';
        if (pidcmd) {
            char *cmd;
            FILE *file;
            cmd = malloc(strlen(pidcmd)+1+5+2+1);
            sprintf(cmd, "%s %u", pidcmd, pid);
            file = popen(cmd, "r");
            if (file) {
                if (fgets(pidoutput, sizeof(pidoutput), file)) {
                    end = strchr(pidoutput, '\n');
                    if (end)
                        *end = '\0';
                }
                pclose(file);
            }
            free(cmd);
        }

        /* print the process */
        print_task(topology, pid_number, name, cpuset, pidoutput[0] == '\0' ? NULL : pidoutput, 0);
        if (tids)
            /* print each tid we found (it's tidcpuset isn't NULL anymore) */
            for(i=0; tidcpusets[i] != NULL; i++) {
                print_task(topology, tids[i], "", tidcpusets[i], NULL, 1);
                hwloc_bitmap_free(tidcpusets[i]);
            }

        /* free threads stuff */
        free(tidcpusets);
        free(tids);
    }

    err = 0;
    hwloc_bitmap_free(cpuset);

out_with_dir:
    closedir(dir);
out_with_topology:
    hwloc_topology_destroy(topology);
out:
    return err;
}
Ejemplo n.º 26
0
static int
thrashdir(
	char *sigdir)
{
	DIR *dirp;
	DIR_BUF *dp;
	char *cwd;
	int safeguard, recurse;
	int c = 0, numentries, pick;
	struct stat st;

	sigfile[0] = '\0';

	if ((dirp = opendir(CURRENTDIR)) == NULL)
		return 1;

	numentries = 0;
	while ((dp = readdir(dirp)) != NULL)
		numentries++;

	/*
	 * consider "." and ".." non-entries
	 * consider all entries starting with "." non-entries
	 */
	cwd = my_malloc(PATH_LEN);
#ifndef M_AMIGA
	if (numentries < 3 || cwd == NULL)
#else
	if (numentries == 0 || cwd == NULL)
#endif /* !M_AMIGA */
	{
		CLOSEDIR(dirp);
		return -1;
	}

	get_cwd(cwd);
	recurse = strcmp(cwd, sigdir);

	/*
	 * If we are using the root sig directory, we don't want
	 * to recurse, or else we might use a custom sig intended
	 * for a specific newsgroup (and not this one).
	 */
	for (safeguard = 0, dp = NULL; safeguard < MAXLOOPS && dp == NULL; safeguard++) {
#ifdef DEBUG
		if (debug == 2)
			error_message("sig loop=[%d] recurse=[%d]", safeguard, recurse);
#endif /* DEBUG */
#ifdef HAVE_REWINDDIR
		rewinddir(dirp);
#else
		CLOSEDIR(dirp);
		if ((dirp = opendir(CURRENTDIR)) == NULL)
			return 1;
#endif /* HAVE_REWINDDIR */
		pick = rand() % numentries + 1;
		while (--pick >= 0) {
			if ((dp = readdir(dirp)) == NULL)
				break;
		}
		if (dp != NULL) {	/* if we could open the dir entry */
			if (!strcmp(dp->d_name, CURRENTDIR) || (dp->d_name[0] == '.'))
				dp = NULL;
			else {	/* if we have a non-dot entry */
				if (stat(dp->d_name, &st) == -1) {
					CLOSEDIR(dirp);
					return 1;
				}
				if (S_ISDIR(st.st_mode)) {
					if (recurse) {
						/*
						 * do subdirectories
						 */
						if ((my_chdir(dp->d_name) < 0) || ((c = thrashdir(sigdir)) == 1)) {
							CLOSEDIR(dirp);
							return 1;
						}
						if (c == -1) {
							/*
							 * the one we picked was an
							 * empty dir so try again.
							 */
							dp = NULL;
							my_chdir(cwd);
						}
					} else
						dp = NULL;
				} else {	/* end dir; we have a file */
					get_cwd(sigfile);
					strcat(sigfile, "/");
					strcat(sigfile, dp->d_name);
#ifdef DEBUG
					if (debug == 2)
						error_message("Found a file=[%s]", sigfile);
#endif /* DEBUG */
				}
			}
		}
	}
	free(cwd);
#ifdef DEBUG
	if (debug == 2)
		error_message("return 0: sigfile=[%s]", sigfile);
#endif /* DEBUG */
	CLOSEDIR(dirp);

	return 0;
}
Ejemplo n.º 27
0
void test() {
  int err;
  long loc;
  DIR *dir;
  struct dirent *ent;
  struct dirent ent_r;
  struct dirent *result;
  int i;

  // check bad opendir input
  dir = opendir("noexist");
  assert(!dir);
  assert(errno == ENOENT);
  dir = opendir("nocanread");
  assert(!dir);
  assert(errno == EACCES);
  dir = opendir("foobar/file.txt");
  assert(!dir);
  assert(errno == ENOTDIR);

  // check bad readdir input
  //dir = opendir("foobar");
  //closedir(dir);
  //ent = readdir(dir);
  //assert(!ent);
  // XXX musl doesn't have enough error handling for this: assert(errno == EBADF);

  // check bad readdir_r input
  //dir = opendir("foobar");
  //closedir(dir);
  //err = readdir_r(dir, NULL, &result);
  // XXX musl doesn't have enough error handling for this: assert(err == EBADF);
  
  //
  // do a normal read with readdir
  //
  dir = opendir("foobar");
  assert(dir);
  int seen[3] = { 0, 0, 0 };
  for (i = 0; i < 3; i++) {
    errno = 0;
    ent = readdir(dir);
    //printf("ent, errno: %p, %d\n", ent, errno);
    assert(ent);
    //printf("%d file: %s (%d : %d)\n", i, ent->d_name, ent->d_reclen, sizeof(*ent));
    assert(ent->d_reclen == sizeof(*ent));
    if (!seen[0] && !strcmp(ent->d_name, ".")) {
      assert(ent->d_type & DT_DIR);
      seen[0] = 1;
      continue;
    }
    if (!seen[1] && !strcmp(ent->d_name, "..")) {
      assert(ent->d_type & DT_DIR);
      seen[1] = 1;
      continue;
    }
    if (!seen[2] && !strcmp(ent->d_name, "file.txt")) {
      assert(ent->d_type & DT_REG);
      seen[2] = 1;
      continue;
    }
    assert(0 && "odd filename");
  }
  ent = readdir(dir);
  if (ent) printf("surprising ent: %p : %s\n", ent, ent->d_name);
  assert(!ent);

  // test rewinddir
  rewinddir(dir);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));

  // test seek / tell
  rewinddir(dir);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));
  char first[1024];
  //printf("first: %s\n", ent->d_name);
  strcpy(first, ent->d_name);
  loc = telldir(dir);
  assert(loc >= 0);
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));
  ent = readdir(dir);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));
  seekdir(dir, loc);
  ent = readdir(dir);
  assert(ent);
  //printf("check: %s / %s\n", ent->d_name, first);
  assert(!strcmp(ent->d_name, first));

  //
  // do a normal read with readdir_r
  //
  rewinddir(dir);
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(&ent_r == result);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(&ent_r == result);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(&ent_r == result);
  assert(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..") || !strcmp(ent->d_name, "file.txt"));
  err = readdir_r(dir, &ent_r, &result);
  assert(!err);
  assert(!result);

  err = closedir(dir);
  assert(!err);

  puts("success");
}
Ejemplo n.º 28
0
static List _get_precs(List task_list, bool pgid_plugin, uint64_t cont_id,
		       jag_callbacks_t *callbacks)
{
	List prec_list = list_create(destroy_jag_prec);
	char	proc_stat_file[256];	/* Allow ~20x extra length */
	char	proc_io_file[256];	/* Allow ~20x extra length */
	static	int	slash_proc_open = 0;
	int i;

	if (!pgid_plugin) {
		pid_t *pids = NULL;
		int npids = 0;
		/* get only the processes in the proctrack container */
		proctrack_g_get_pids(cont_id, &pids, &npids);
		if (!npids) {
			/* update consumed energy even if pids do not exist */
			ListIterator itr = list_iterator_create(task_list);
			struct jobacctinfo *jobacct = NULL;
			if ((jobacct = list_next(itr))) {
				acct_gather_energy_g_get_data(
					energy_profile,
					&jobacct->energy);
				debug2("getjoules_task energy = %u",
				       jobacct->energy.consumed_energy);
			}
			list_iterator_destroy(itr);

			debug4("no pids in this container %"PRIu64"", cont_id);
			goto finished;
		}
		for (i = 0; i < npids; i++) {
			snprintf(proc_stat_file, 256, "/proc/%d/stat", pids[i]);
			snprintf(proc_io_file, 256, "/proc/%d/io", pids[i]);
			_handle_stats(prec_list, proc_stat_file, proc_io_file,
				      callbacks);
		}
		xfree(pids);
	} else {
		struct dirent *slash_proc_entry;
		char  *iptr = NULL, *optr = NULL, *optr2 = NULL;

		if (slash_proc_open) {
			rewinddir(slash_proc);
		} else {
			slash_proc=opendir("/proc");
			if (slash_proc == NULL) {
				perror("opening /proc");
				goto finished;
			}
			slash_proc_open=1;
		}
		strcpy(proc_stat_file, "/proc/");
		strcpy(proc_io_file, "/proc/");

		while ((slash_proc_entry = readdir(slash_proc))) {

			/* Save a few cyles by simulating
			 * strcat(statFileName, slash_proc_entry->d_name);
			 * strcat(statFileName, "/stat");
			 * while checking for a numeric filename (which really
			 * should be a pid). Then do the same for the
			 * /proc/<pid>/io file name.
			 */
			optr = proc_stat_file + sizeof("/proc");
			iptr = slash_proc_entry->d_name;
			i = 0;
			do {
				if ((*iptr < '0') ||
				    ((*optr++ = *iptr++) > '9')) {
					i = -1;
					break;
				}
			} while (*iptr);

			if (i == -1)
				continue;
			iptr = (char*)"/stat";

			do {
				*optr++ = *iptr++;
			} while (*iptr);
			*optr = 0;

			optr2 = proc_io_file + sizeof("/proc");
			iptr = slash_proc_entry->d_name;
			i = 0;
			do {
				if ((*iptr < '0') ||
				    ((*optr2++ = *iptr++) > '9')) {
					i = -1;
					break;
				}
			} while (*iptr);
			if (i == -1)
				continue;
			iptr = (char*)"/io";

			do {
				*optr2++ = *iptr++;
			} while (*iptr);
			*optr2 = 0;

			_handle_stats(prec_list, proc_stat_file, proc_io_file,
				      callbacks);
		}
	}

finished:

	return prec_list;
}
Ejemplo n.º 29
0
sqInt dir_Lookup(char *pathString, sqInt pathStringLength, sqInt index,
/* outputs: */  char *name, sqInt *nameLength, sqInt *creationDate, sqInt *modificationDate,
		sqInt *isDirectory, squeakFileOffsetType *sizeIfFile)
#endif
{
  /* Lookup the index-th entry of the directory with the given path, starting
     at the root of the file system. Set the name, name length, creation date,
     creation time, directory flag, and file size (if the entry is a file).
     Return:	0 	if a entry is found at the given index
     		1	if the directory has fewer than index entries
		2	if the given path has bad syntax or does not reach a directory
  */

  int i;
  int nameLen= 0;
  struct dirent *dirEntry= 0;
  char unixPath[MAXPATHLEN+1];
  struct stat statBuf;

  /* default return values */
  *name             = 0;
  *nameLength       = 0;
  *creationDate     = 0;
  *modificationDate = 0;
  *isDirectory      = false;
  *sizeIfFile       = 0;
#if PharoVM
  *posixPermissions = 0;
  *isSymlink        = false;
#endif

  if ((pathStringLength == 0))
    strcpy(unixPath, ".");
  else if (!sq2uxPath(pathString, pathStringLength, unixPath, MAXPATHLEN, 1))
    return BAD_PATH;

  /* get file or directory info */
  if (!maybeOpenDir(unixPath))
    return BAD_PATH;

  if (++lastIndex == index)
    index= 1;		/* fake that the dir is rewound and we want the first entry */
  else
    {
      rewinddir(openDir);	/* really rewind it, and read to the index */
      lastIndex= index;
    }

  for (i= 0; i < index; i++)
    {
    nextEntry:
      do
	{ 
	  errno= 0; 
	  dirEntry= readdir(openDir);
	}
      while ((dirEntry == 0) && (errno == EINTR));

      if (!dirEntry)
	return NO_MORE_ENTRIES;
      
      nameLen= NAMLEN(dirEntry);

      /* ignore '.' and '..' (these are not *guaranteed* to be first) */
      if (nameLen < 3 && dirEntry->d_name[0] == '.')
	if (nameLen == 1 || dirEntry->d_name[1] == '.')
	  goto nextEntry;
    }

  *nameLength= ux2sqPath(dirEntry->d_name, nameLen, name, MAXPATHLEN, 0);

  {
    char terminatedName[MAXPATHLEN+1];
    if(nameLen > MAXPATHLEN)
      return BAD_PATH;
    strncpy(terminatedName, dirEntry->d_name, nameLen);
    terminatedName[nameLen]= '\0';
    if(strlen(unixPath) + 1 + nameLen > MAXPATHLEN)
      return BAD_PATH;
    strcat(unixPath, "/");
    strcat(unixPath, terminatedName);
    if (stat(unixPath, &statBuf) && lstat(unixPath, &statBuf))
    {
	/* We can't stat the entry, but failing here would invalidate
	   the whole directory --bertf */
      return ENTRY_FOUND;
    }
  }

  /* last change time */
  *creationDate= convertToSqueakTime(statBuf.st_ctime);
  /* modification time */
  *modificationDate= convertToSqueakTime(statBuf.st_mtime);

  if (S_ISDIR(statBuf.st_mode))
    *isDirectory= true;
  else
    *sizeIfFile= statBuf.st_size;

#if PharoVM
  *isSymlink = S_ISLNK(statBuf.st_mode);
  *posixPermissions = statBuf.st_mode & 0777;
#endif

  return ENTRY_FOUND;
}
Ejemplo n.º 30
0
//void rewinddir(DIR *dirp);
void posix_rewinddir(const char *path, DIR *dirp)
{
	rewinddir(dirp);
	logSUCC("rewinddir(dirp=%p) path='%s'",
		dirp, path);
}