Exemple #1
0
int
getmntlst(struct statfs **sfsp, int *cntp)
{
	int cnt;
	long bufsize;

	*sfsp = NULL;
	cnt = getfsstat(NULL, 0, MNT_NOWAIT);
	bufsize = cnt * sizeof(**sfsp);
	/*fprintf(stderr, "getmntlst bufsize %ld, cnt %d\n", bufsize, cnt);*/
	*sfsp = malloc(bufsize);
	if (sfsp == NULL)
		goto err;
	cnt = getfsstat(*sfsp, bufsize, MNT_NOWAIT);
	if (cnt == -1)
		goto err;
	*cntp = cnt;
	/*fprintf(stderr, "getmntlst ok, cnt %d\n", cnt);*/
	return (0);
err:
	safe_free(sfsp);
	*sfsp = NULL;
	/*fprintf(stderr, "getmntlst bad\n");*/
	return (-1);
}
Exemple #2
0
int main() 
{
    int fscount, newfscount;
    int i;
    fscount = getfsstat(NULL, 0, 0);
    TEST((fscount != -1));
    printf("Number of filesystems: %d\n", fscount);
    buf = malloc(sizeof(struct statfs) * fscount);
    TEST(buf);
    newfscount = getfsstat(buf, (long) sizeof(struct statfs) * fscount, 0);
    TEST((newfscount != -1));
    TEST((newfscount == fscount));
    printf("Printing filesystem data:\n\n");
    for(i = 0; i < newfscount; i++) 
    {
	printf("Record number:\t\t%d\n", i+1);
	printf("Name:\t\t\t%s\n", buf[i].f_mntonname);
	printf("Fundamental block size:\t%ld\n", buf[i].f_fsize);
	printf("Optimal block size:\t%ld\n", buf[i].f_bsize);
	printf("Number of blocks:\t%ld\n", buf[i].f_blocks);
	printf("Free blocks:\t\t%ld\n", buf[i].f_bfree);
	printf("Available blocks:\t%ld\n", buf[i].f_bavail);
	printf("\n");
    }
    newfscount = getfsstat(buf, 1, 0);
    TEST((newfscount == 0));
    cleanup();
    
    return OK;
}
Exemple #3
0
/*
 * Check if the entry is still/already mounted.
 */
int
is_mounted(char *hostname, char *dirp) {
	struct statfs *mntbuf;
	char name[MNAMELEN + 1];
	size_t bufsize;
	int mntsize, i;

	if (strlen(hostname) + strlen(dirp) >= MNAMELEN)
		return (0);
	snprintf(name, sizeof(name), "%s:%s", hostname, dirp);
	mntsize = getfsstat(NULL, 0, MNT_NOWAIT);
	if (mntsize <= 0)
		return (0);
	bufsize = (mntsize + 1) * sizeof(struct statfs);
	if ((mntbuf = malloc(bufsize)) == NULL)
		err(1, "malloc");
	mntsize = getfsstat(mntbuf, (long)bufsize, MNT_NOWAIT);
	for (i = mntsize - 1; i >= 0; i--) {
		if (strcmp(mntbuf[i].f_mntfromname, name) == 0) {
			free(mntbuf);
			return (1);
		}
	}
	free(mntbuf);
	return (0);
}
Exemple #4
0
char *mount_get_mountpoint(const char *device_path)
{
    struct stat st;
    if (stat (device_path, &st) ) {
        return str_dup(device_path);
    }

    /* If it's a directory, all is good */
    if (S_ISDIR(st.st_mode)) {
        return str_dup(device_path);
    }

    struct statfs mbuf[128];
    int fs_count;

    if ( (fs_count = getfsstat (NULL, 0, MNT_NOWAIT)) != -1 ) {

        getfsstat (mbuf, fs_count * sizeof(mbuf[0]), MNT_NOWAIT);

        for ( int i = 0; i < fs_count; ++i) {
            if (!strcmp (mbuf[i].f_mntfromname, device_path)) {
                return str_dup (mbuf[i].f_mntonname);
            }
        }
    }

    return str_dup (device_path);
}
static int
statfs_init(void)
{
	struct statfs *sfs;
	int error;

	if (gsfs != NULL) {
		free(gsfs);
		gsfs = NULL;
	}
	allfs = getfsstat(NULL, 0, MNT_WAIT);
	if (allfs == -1)
		goto fail;
	gsfs = malloc(sizeof(gsfs[0]) * allfs * 2);
	if (gsfs == NULL)
		goto fail;
	allfs = getfsstat(gsfs, (long)(sizeof(gsfs[0]) * allfs * 2),
	    MNT_WAIT);
	if (allfs == -1)
		goto fail;
	sfs = realloc(gsfs, allfs * sizeof(gsfs[0]));
	if (sfs != NULL)
		gsfs = sfs;
	return (0);
fail:
	error = errno;
	if (gsfs != NULL)
		free(gsfs);
	gsfs = NULL;
	allfs = 0;
	return (error);
}
/*
 * Return information about mounted filesystems.
 */
int
getmntinfo(struct statfs12 **mntbufp, int flags)
{
	static struct statfs12 *mntbuf;
	static int mntsize;
	static size_t bufsize;

	_DIAGASSERT(mntbufp != NULL);

	if (mntsize <= 0 &&
	    (mntsize = getfsstat(NULL, 0L, MNT_NOWAIT)) == -1)
		return (0);
	if (bufsize > 0 &&
	    (mntsize = getfsstat(mntbuf, (long)bufsize, flags)) == -1)
		return (0);
	while (bufsize <= mntsize * sizeof(struct statfs12)) {
		if (mntbuf)
			free(mntbuf);
		bufsize = (mntsize + 1) * sizeof(struct statfs12);
		if ((mntbuf = malloc(bufsize)) == NULL)
			return (0);
		if ((mntsize = getfsstat(mntbuf, (long)bufsize, flags)) == -1)
			return (0);
	}
	*mntbufp = mntbuf;
	return (mntsize);
}
/*
 * File system functions
 */
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) {
    int fs_count = getfsstat(NULL, 0, MNT_NOWAIT);
    if (fs_count < 0) {
        mark_failed_with_errno(env, "could not stat file systems", result);
        return;
    }

    size_t len = fs_count * sizeof(struct statfs);
    struct statfs* buf = (struct statfs*)malloc(len);
    if (getfsstat(buf, len, MNT_NOWAIT) < 0 ) {
        mark_failed_with_errno(env, "could not stat file systems", result);
        free(buf);
        return;
    }

    jclass info_class = env->GetObjectClass(info);
    jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V");

    for (int i = 0; i < fs_count; i++) {
        jboolean caseSensitive = JNI_TRUE;
        jboolean casePreserving = JNI_TRUE;

        jstring mount_point = char_to_java(env, buf[i].f_mntonname, result);
        jstring file_system_type = char_to_java(env, buf[i].f_fstypename, result);
        jstring device_name = char_to_java(env, buf[i].f_mntfromname, result);
        jboolean remote = (buf[i].f_flags & MNT_LOCAL) == 0;
        env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, remote, caseSensitive, casePreserving);
    }
    free(buf);
}
Exemple #8
0
int
nix_bsd_getfsstat(struct nix_statfs *buf, size_t bufsiz, int flags,
	nix_env_t *env)
{
#ifdef HAVE_GETFSSTAT
	struct statfs *nfs;
	int            n, maxcount;
	int            nflags = 0;
	int            count = 0;

#ifdef MNT_NOWAIT
	if (flags == NIX_MNT_NOWAIT)
		nflags = MNT_NOWAIT;
#endif
  
	if (buf == NULL) {
		count = getfsstat(NULL, 0, nflags);
		if (count < 0) {
			nix_env_set_errno(env, errno);
			return (-1);
		}
      
		return (count);
	}

	maxcount = bufsiz / sizeof(struct nix_statfs);
	if (maxcount == 0) {
		nix_env_set_errno(env, EINVAL);
		return (-1);
	}
  
	nfs = xec_mem_alloc_ntype(struct statfs, maxcount, 0);
	if (nfs == NULL) {
		nix_env_set_errno(env, ENOMEM);
		return (-1);
	}

	if ((count = getfsstat(nfs, maxcount * sizeof(struct statfs),
		  nflags)) < 0) {
		xec_mem_free(nfs);
		nix_env_set_errno(env, errno);
		return (-1);
	}
  
	for (n = 0; n < count; n++)
		cvt_statfs(&nfs[n], &buf[n]);

	xec_mem_free(nfs);

	return (count);
#else
	return (nix_nosys(env));
#endif
}
Exemple #9
0
size_t
mntinfo(struct statfs **mntbuffer)
{
    static struct statfs *origbuf;
    size_t bufsize;
    int mntsize;

    mntsize = getfsstat(NULL, 0, MNT_NOWAIT);
    if (mntsize <= 0)
	return (0);
    bufsize = (mntsize + 1) * sizeof(struct statfs);
    if ((origbuf = malloc(bufsize)) == NULL)
	err(1, "malloc");
    mntsize = getfsstat(origbuf, (long)bufsize, MNT_NOWAIT);
    *mntbuffer = origbuf;
    return (mntsize);
}
Exemple #10
0
long do_getfsstat(struct statfs * arg1, uint32_t arg2, uint32_t arg3)
{
    long ret;
    DPRINTF("getfsstat(%p, 0x%x, 0x%x)\n", arg1, arg2, arg3);
    ret = get_errno(getfsstat(arg1, arg2, arg3));
    if((!is_error(ret)) && arg1)
        byteswap_statfs(arg1);
    return ret;
}
Exemple #11
0
static FskErr updateStatFS()
{
	FskErr err;

	if (gStatFS != NULL) {
		FskMemPtrDispose(gStatFS);
		gStatFS = NULL;
	}
	if ((gNumStatFS = getfsstat(NULL, 0, MNT_NOWAIT)) < 0)
		return kFskErrOperationFailed;
	if ((err = FskMemPtrNew(sizeof(struct statfs) * gNumStatFS, (FskMemPtr *)&gStatFS)) != kFskErrNone)
		return err;
	if ((gNumStatFS = getfsstat(gStatFS, sizeof(struct statfs) * gNumStatFS, MNT_NOWAIT)) < 0) {
		FskMemPtrDispose(gStatFS);
		gStatFS = NULL;
		return kFskErrOperationFailed;
	}
	return kFskErrNone;
}
Exemple #12
0
/*
 * Return a list of tuples including device, mount point and fs type
 * for all partitions mounted on the system.
 */
static PyObject*
get_disk_partitions(PyObject* self, PyObject* args)
{
    int num;
    int i;
    long len;
    struct statfs *fs;
    PyObject* py_retlist = PyList_New(0);
    PyObject* py_tuple;

    // get the number of mount points
    Py_BEGIN_ALLOW_THREADS
    num = getfsstat(NULL, 0, MNT_NOWAIT);
    Py_END_ALLOW_THREADS
    if (num == -1) {
        PyErr_SetFromErrno(0);
        return NULL;
    }

    len = sizeof(*fs) * num;
    fs = malloc(len);

    Py_BEGIN_ALLOW_THREADS
    num = getfsstat(fs, len, MNT_NOWAIT);
    Py_END_ALLOW_THREADS
    if (num == -1) {
        free(fs);
        PyErr_SetFromErrno(0);
        return NULL;
    }

    for (i = 0; i < num; i++) {
        py_tuple = Py_BuildValue("(sss)", fs[i].f_mntfromname,  // device
                                          fs[i].f_mntonname,    // mount point
                                          fs[i].f_fstypename);  // fs type
        PyList_Append(py_retlist, py_tuple);
        Py_XDECREF(py_tuple);
    }

    free(fs);
    return py_retlist;
}
Exemple #13
0
__private_extern__ int ___isautofs( const char * path )
{
    /*
     * Test for the autofs file system.
     */

    struct statfs * mountList;
    int             mountListCount;
    int             mountListIndex;

    mountListCount = getfsstat( NULL, 0, MNT_NOWAIT );

    if ( mountListCount > 0 )
    {
        mountList = malloc( mountListCount * sizeof( struct statfs ) );

        if ( mountList )
        {
            mountListCount = getfsstat( mountList, mountListCount * sizeof( struct statfs ), MNT_NOWAIT );

            if ( mountListCount > 0 )
            {
                for ( mountListIndex = 0; mountListIndex < mountListCount; mountListIndex++ )
                {
                    if ( strcmp( mountList[mountListIndex].f_fstypename, "autofs" ) == 0 )
                    {
                        if ( strncmp( mountList[mountListIndex].f_mntonname, path, strlen( mountList[mountListIndex].f_mntonname ) ) == 0 )
                        {
                            break;
                        }
                    }
                }
            }

            free( mountList );
        }
    }

    return ( mountListIndex < mountListCount );
}
char *device_mountpoint_sysdep(char *dev, char *buf, int buflen) {
        int countfs;

        ASSERT(dev);

        if ((countfs = getfsstat(NULL, 0, MNT_NOWAIT)) != -1) {
                struct statfs *statfs = CALLOC(countfs, sizeof(struct statfs));
                if ((countfs = getfsstat(statfs, countfs * sizeof(struct statfs), MNT_NOWAIT)) != -1) {
                        for (int i = 0; i < countfs; i++) {
                                struct statfs *sfs = statfs + i;
                                if (IS(sfs->f_mntfromname, dev)) {
                                        snprintf(buf, buflen, "%s", sfs->f_mntonname);
                                        FREE(statfs);
                                        return buf;
                                }
                        }
                }
                FREE(statfs);
        }
        LogError("Error getting mountpoint for filesystem '%s' -- %s\n", dev, STRERROR);
        return NULL;
}
Exemple #15
0
/*
 * Get a list of all mount volumes. The calling routine will need to free the memory.
 */
struct statfs *smb_getfsstat(int *fs_cnt)
{
	struct statfs *fs;
	int bufsize = 0;
	
	/* See what we need to allocate */
	*fs_cnt = getfsstat(NULL, bufsize, MNT_NOWAIT);
	if (*fs_cnt <=  0)
		return NULL;
	bufsize = *fs_cnt * (int)sizeof(*fs);
	fs = (struct statfs *)malloc(bufsize);
	if (fs == NULL)
		return NULL;
	
	*fs_cnt = getfsstat(fs, bufsize, MNT_NOWAIT);
	if (*fs_cnt < 0) {
		*fs_cnt = 0;
		free (fs);
		fs = NULL;
	}
	return fs;
}
Exemple #16
0
static PyObject*
usbobserver_get_mounted_filesystems(PyObject *self, PyObject *args) {
    struct statfs *buf, t;
    int num, i;
    PyObject *ans, *key, *val;

    num = getfsstat(NULL, 0, MNT_NOWAIT);
    if (num == -1) {
        PyErr_SetString(PyExc_RuntimeError, "Initial call to getfsstat failed");
        return NULL;
    }
    ans = PyDict_New();
    if (ans == NULL) return PyErr_NoMemory();

    buf = (struct statfs*)calloc(num, sizeof(struct statfs));
    if (buf == NULL) return PyErr_NoMemory();

    num = getfsstat(buf, num*sizeof(struct statfs), MNT_NOWAIT);
    if (num == -1) {
        PyErr_SetString(PyExc_RuntimeError, "Call to getfsstat failed");
        return NULL;
    }

    for (i = 0 ; i < num; i++) {
        t = buf[i];
        key = PyBytes_FromString(t.f_mntfromname);
        val = PyBytes_FromString(t.f_mntonname);
        if (key != NULL && val != NULL) {
            PyDict_SetItem(ans, key, val);
        }
        NUKE(key); NUKE(val);
    }

    free(buf);

    return ans;

}
static void PrintMountedFileSystems(CFArrayRef roots) {
    int fsCount = getfsstat(NULL, 0, MNT_WAIT);
    if (fsCount == -1) return;

    struct statfs fs[fsCount];
    fsCount = getfsstat(fs, sizeof(struct statfs) * fsCount, MNT_NOWAIT);
    if (fsCount == -1) return;

    printf("UNWATCHEABLE\n");

    for (int i = 0; i < fsCount; i++) {
        if ((fs[i].f_flags & FS_FLAGS) != FS_FLAGS) {
            char *mount = fs[i].f_mntonname;
            int mountLen = strlen(mount);

            for (int j = 0; j < CFArrayGetCount(roots); j++) {
                char *root = (char *)CFArrayGetValueAtIndex(roots, j);
                int rootLen = strlen(root);

                if (rootLen >= mountLen && strncmp(root, mount, mountLen) == 0) {
                    // root under mount point
                    if (rootLen == mountLen || root[mountLen] == '/' || strcmp(mount, "/") == 0) {
                        printf("%s\n", root);
                    }
                }
                else if (strncmp(root, mount, rootLen) == 0) {
                    // root over mount point
                    if (strcmp(root, "/") == 0 || mount[rootLen] == '/') {
                        printf("%s\n", mount);
                    }
                }
            }
        }
    }

    printf("#\n");
    fflush(stdout);
}
/*
 * Return information about mounted filesystems.
 */
int
getmntinfo(struct statfs **mntbufp, int flags)
{
	static struct statfs *mntbuf;
	static int mntsize;
	static long bufsize;

	if (mntsize <= 0 && (mntsize = getfsstat(0, 0, MNT_NOWAIT)) < 0)
		return (0);
	if (bufsize > 0 && (mntsize = getfsstat(mntbuf, bufsize, flags)) < 0)
		return (0);
	while (bufsize <= mntsize * sizeof(struct statfs)) {
		if (mntbuf)
			free(mntbuf);
		bufsize = (mntsize + 1) * sizeof(struct statfs);
		if ((mntbuf = (struct statfs *)malloc(bufsize)) == 0)
			return (0);
		if ((mntsize = getfsstat(mntbuf, bufsize, flags)) < 0)
			return (0);
	}
	*mntbufp = mntbuf;
	return (mntsize);
}
Exemple #19
0
/**
 * MacOS X special block device mountpoint method. Filesystem must be mounted.
 * In the case of success, mountpoint is stored in filesystem information
 * structure for later use.
 *
 * @param inf      Information structure where resulting data will be stored
 * @param blockdev Identifies block special device
 * @return         NULL in the case of failure otherwise mountpoint
 */
char *device_mountpoint_sysdep(Info_T inf, char *blockdev) {
  int countfs;

  ASSERT(inf);
  ASSERT(blockdev);

  if ((countfs = getfsstat(NULL, 0, MNT_NOWAIT)) != -1) {
    struct statfs *statfs = xcalloc(countfs, sizeof(struct statfs));
    if ((countfs = getfsstat(statfs, countfs * sizeof(struct statfs), MNT_NOWAIT)) != -1) {
      int i;
      for (i = 0; i < countfs; i++) {
        struct statfs *sfs = statfs + i;
        if (IS(sfs->f_mntfromname, blockdev)) {
          inf->priv.filesystem.mntpath = xstrdup(sfs->f_mntonname);
          FREE(statfs);
          return inf->priv.filesystem.mntpath;
        }
      }
    }
    FREE(statfs);
  }
  LogError("%s: Error getting mountpoint for filesystem '%s' -- %s\n", prog, blockdev, STRERROR);
  return NULL;
}
Exemple #20
0
static dvd_reader_t *DVDOpenCommon( const char *ppath,
                                    void *stream,
                                    dvd_reader_stream_cb *stream_cb )
{
  struct stat fileinfo;
  int ret, have_css, retval, cdir = -1;
  dvd_reader_t *ret_val = NULL;
  char *dev_name = NULL;
  char *path = NULL, *new_path = NULL, *path_copy = NULL;

#if defined(_WIN32) || defined(__OS2__)
      int len;
#endif

  /* Try to open DVD using stream_cb functions */
  if( stream != NULL && stream_cb != NULL )
  {
    have_css = dvdinput_setup( "" );
    return DVDOpenImageFile( NULL, stream, stream_cb, have_css );
  }

  if( ppath == NULL )
    goto DVDOpen_error;

  path = strdup(ppath);
  if( path == NULL )
    goto DVDOpen_error;

  /* Try to open libdvdcss or fall back to standard functions */
  have_css = dvdinput_setup(path);

#if defined(_WIN32) || defined(__OS2__)
  /* Strip off the trailing \ if it is not a drive */
  len = strlen(path);
  if ((len > 1) &&
      (path[len - 1] == '\\')  &&
      (path[len - 2] != ':'))
  {
    path[len-1] = '\0';
  }
#endif

  ret = mythfile_stat( path, &fileinfo );

  if( ret < 0 ) {

    /* maybe "host:port" url? try opening it with acCeSS library */
    if( strchr(path,':') ) {
      ret_val = DVDOpenImageFile( path, NULL, NULL, have_css );
      free(path);
      return ret_val;
    }

    /* If we can't stat the file, give up */
    fprintf( stderr, "libdvdread: Can't stat %s\n", path );
    perror("");
    goto DVDOpen_error;
  }

  /* First check if this is a block/char device or a file*/
  if( S_ISBLK( fileinfo.st_mode ) ||
      S_ISCHR( fileinfo.st_mode ) ||
      S_ISREG( fileinfo.st_mode ) ) {

    /**
     * Block devices and regular files are assumed to be DVD-Video images.
     */
    dvd_reader_t *dvd = NULL;
#if defined(__sun)
    dev_name = sun_block2char( path );
#elif defined(SYS_BSD)
    dev_name = bsd_block2char( path );
#else
    dev_name = strdup( path );
#endif
    if(!dev_name)
        goto DVDOpen_error;
    dvd = DVDOpenImageFile( dev_name, NULL, NULL, have_css );
    free( dev_name );
    free(path);
    return dvd;
  } else if( S_ISDIR( fileinfo.st_mode ) ) {
    dvd_reader_t *auth_drive = 0;
#if defined(SYS_BSD)
    struct fstab* fe;
#elif defined(__sun) || defined(__linux__)
    FILE *mntfile;
#endif

    /* XXX: We should scream real loud here. */
    if( !(path_copy = strdup( path ) ) )
      goto DVDOpen_error;

#ifndef WIN32 /* don't have fchdir, and getcwd( NULL, ... ) is strange */
              /* Also WIN32 does not have symlinks, so we don't need this bit of code. */

    /* Resolve any symlinks and get the absolute dir name. */
    if (!strncmp(path, "myth://", 7))
        dev_name = strdup( path );
    else
    {
      if( ( cdir  = open( ".", O_RDONLY ) ) >= 0 ) {
        if( chdir( path_copy ) == -1 ) {
          goto DVDOpen_error;
        }
        new_path = malloc(PATH_MAX+1);
        if(!new_path) {
          goto DVDOpen_error;
        }
        if( getcwd( new_path, PATH_MAX ) == NULL ) {
          goto DVDOpen_error;
        }
        retval = fchdir( cdir );
        close( cdir );
        cdir = -1;
        if( retval == -1 ) {
          goto DVDOpen_error;
        }
        free(path_copy);
        path_copy = new_path;
        new_path = NULL;
      }
    }
#endif

    /**
     * If we're being asked to open a directory, check if that directory
     * is the mount point for a DVD-ROM which we can use instead.
     */

    if( strlen( path_copy ) > 1 ) {
      if( path_copy[ strlen( path_copy ) - 1 ] == '/' ) {
        path_copy[ strlen( path_copy ) - 1 ] = '\0';
      }
    }

#if defined(_WIN32) || defined(__OS2__)
    if( strlen( path_copy ) > 9 ) {
      if( !strcasecmp( &(path_copy[ strlen( path_copy ) - 9 ]),
                       "\\video_ts"))
        path_copy[ strlen( path_copy ) - (9-1) ] = '\0';
    }
#endif
    if( strlen( path_copy ) > 9 ) {
      if( !strcasecmp( &(path_copy[ strlen( path_copy ) - 9 ]),
                       "/video_ts" ) ) {
        path_copy[ strlen( path_copy ) - 9 ] = '\0';
      }
    }

    if(path_copy[0] == '\0') {
      free( path_copy );
      if( !(path_copy = strdup( "/" ) ) )
        goto DVDOpen_error;
    }

#if defined(__APPLE__)
    struct statfs s[128];
    int r = getfsstat(NULL, 0, MNT_NOWAIT);
    if (r > 0) {
        if (r > 128)
            r = 128;
        r = getfsstat(s, r * sizeof(s[0]), MNT_NOWAIT);
        int i;
        for (i=0; i<r; i++) {
            if (!strcmp(path_copy, s[i].f_mntonname)) {
                dev_name = bsd_block2char(s[i].f_mntfromname);
                fprintf( stderr,
                        "libdvdread: Attempting to use device %s"
                        " mounted on %s for CSS authentication\n",
                        dev_name,
                        s[i].f_mntonname);
                auth_drive = DVDOpenImageFile( dev_name, NULL, NULL, have_css );
                break;
            }
        }
    }
#elif defined(SYS_BSD)
    if( ( fe = getfsfile( path_copy ) ) ) {
      dev_name = bsd_block2char( fe->fs_spec );
      fprintf( stderr,
               "libdvdread: Attempting to use device %s"
               " mounted on %s for CSS authentication\n",
               dev_name,
               fe->fs_file );
      auth_drive = DVDOpenImageFile( dev_name, NULL, NULL, have_css );
    }
#elif defined(__sun)
    mntfile = fopen( MNTTAB, "r" );
    if( mntfile ) {
      struct mnttab mp;
      int res;

      while( ( res = getmntent( mntfile, &mp ) ) != -1 ) {
        if( res == 0 && !strcmp( mp.mnt_mountp, path_copy ) ) {
          dev_name = sun_block2char( mp.mnt_special );
          fprintf( stderr,
                   "libdvdread: Attempting to use device %s"
                   " mounted on %s for CSS authentication\n",
                   dev_name,
                   mp.mnt_mountp );
          auth_drive = DVDOpenImageFile( dev_name, NULL, NULL, have_css );
          break;
        }
      }
      fclose( mntfile );
    }
#elif defined(__linux__)
    mntfile = fopen( _PATH_MOUNTED, "r" );
    if( mntfile ) {
      struct mntent *me;

      while( ( me = getmntent( mntfile ) ) ) {
        if( !strcmp( me->mnt_dir, path_copy ) ) {
          fprintf( stderr,
                   "libdvdread: Attempting to use device %s"
                   " mounted on %s for CSS authentication\n",
                   me->mnt_fsname,
                   me->mnt_dir );
          auth_drive = DVDOpenImageFile( me->mnt_fsname, NULL, NULL, have_css );
          dev_name = strdup(me->mnt_fsname);
          break;
        }
      }
      fclose( mntfile );
    }
#elif defined(_WIN32) || defined(__OS2__)
#ifdef __OS2__
    /* Use DVDOpenImageFile() only if it is a drive */
    if(isalpha(path[0]) && path[1] == ':' &&
        ( !path[2] ||
          ((path[2] == '\\' || path[2] == '/') && !path[3])))
#endif
    auth_drive = DVDOpenImageFile( path, NULL, NULL, have_css );
#endif

#if !defined(_WIN32) && !defined(__OS2__)
    if( !dev_name ) {
      fprintf( stderr, "libdvdread: Couldn't find device name.\n" );
    } else if( !auth_drive ) {
      fprintf( stderr, "libdvdread: Device %s inaccessible, "
               "CSS authentication not available.\n", dev_name );
    }
#else
    if( !auth_drive ) {
        fprintf( stderr, "libdvdread: Device %s inaccessible, "
                 "CSS authentication not available.\n", path );
    }
#endif

    free( dev_name );
    dev_name = NULL;
    free( path_copy );
    path_copy = NULL;

    /**
     * If we've opened a drive, just use that.
     */
    if( auth_drive ) {
      free(path);
      return auth_drive;
    }
    /**
     * Otherwise, we now try to open the directory tree instead.
     */
    ret_val = DVDOpenPath( path );
      free( path );
      return ret_val;
  }

DVDOpen_error:
  /* If it's none of the above, screw it. */
  fprintf( stderr, "libdvdread: Could not open %s\n", path );
  free( path );
  free( path_copy );
  if ( cdir >= 0 )
    close( cdir );
  free( new_path );
  return NULL;
}
Exemple #21
0
int
ipoddisk_init_ipods (void)
{
	int                  i;
        int                  fsnr;
	struct statfs        *stats = NULL;

	fsnr = getfsstat(NULL, 0, MNT_NOWAIT);
	if (fsnr <= 0)
		return ENOENT;

	stats = g_malloc0(fsnr * sizeof(struct statfs));
        if (stats == NULL)
                return ENOMEM;

	fsnr = getfsstat(stats, fsnr * sizeof(struct statfs), MNT_NOWAIT);
	if (fsnr <= 0) {
		g_free(stats);
		return ENOENT;
        }

        ipoddisk_tree = ipoddisk_new_node(NULL, NULL, IPODDISK_NODE_ROOT);

        for (i = 0, ipodnr = 0; i < fsnr && ipodnr < IPODDISK_MAX_IPOD; i++) {
                gchar                *dbpath;
                gchar                *ipodname;
                struct ipoddisk_node *node;

                if (strncasecmp(stats[i].f_mntfromname,
                                CONST_STR_LEN("/dev/disk")))
                        continue;  /* fs not disk-based */

                if (!strcmp(stats[i].f_mntonname, "/"))
                        continue;  /* skip root fs */

                dbpath = g_strconcat(stats[i].f_mntonname,
                                     "/iPod_Control/iTunes/iTunesDB", NULL);

                if (strlen(dbpath) >= MAXPATHLEN ||
                    !g_file_test(dbpath, G_FILE_TEST_EXISTS) ||
                    !g_file_test(dbpath, G_FILE_TEST_IS_REGULAR)) {
                        g_free(dbpath);
                        continue;
                }

                node = ipoddisk_init_one_ipod(dbpath);
                if (node == NULL) {
                        g_free(dbpath);
                        continue;
                }

                ipodname = g_path_get_basename(stats[i].f_mntonname);
                ipoddisk_add_child(ipoddisk_tree, node, ipodname);
                node->nd_data.ipod.ipod_mp = g_strdup(stats[i].f_mntonname);

                ipods[ipodnr] = node;
                ipodnr++;
                
                g_free(dbpath);
                g_free(ipodname);
        }

        g_free(stats);

        if (ipodnr == 0)
                return ENOENT;

        if (ipodnr == 1) {
                ipoddisk_tree = ipods[0];
                ipoddisk_tree->nd_type = IPODDISK_NODE_ROOT;
        }

        return 0;
}
Exemple #22
0
int statfs_32bit_inode_tests( void * the_argp )
{
	int					my_err, my_count, i;
	int					my_buffer_size;
	int					my_fd = -1;
	int					is_ufs = 0;
	void *				my_bufferp = NULL;
	struct statfs *		my_statfsp;
	long				my_io_size;
	fsid_t				my_fsid;
	struct attrlist		my_attrlist;
	vol_attr_buf		my_attr_buf;
	kern_return_t		my_kr;

	my_buffer_size = (sizeof(struct statfs) * 10);
        my_kr = vm_allocate((vm_map_t) mach_task_self(), (vm_address_t*)&my_bufferp, my_buffer_size, VM_FLAGS_ANYWHERE);
        if(my_kr != KERN_SUCCESS){
                printf( "vm_allocate failed with error %d - \"%s\" \n", errno, strerror( errno) );
                goto test_failed_exit;
        }

	my_statfsp = (struct statfs *) my_bufferp;
	my_err = statfs( "/", my_statfsp );
	if ( my_err == -1 ) {
		printf( "statfs call failed.  got errno %d - %s. \n", errno, strerror( errno ) );
		goto test_failed_exit;
	}
	if ( memcmp( &my_statfsp->f_fstypename[0], "ufs", 3 ) == 0 ) {
		is_ufs = 1;
	}
	
	my_count = getfsstat( (struct statfs *)my_bufferp, my_buffer_size, MNT_NOWAIT );
	if ( my_count == -1 ) {
		printf( "getfsstat call failed.  got errno %d - %s. \n", errno, strerror( errno ) );
		goto test_failed_exit;
	}

	/* validate results */
	my_statfsp = (struct statfs *) my_bufferp;
	for ( i = 0; i < my_count; i++, my_statfsp++ ) {
		if ( memcmp( &my_statfsp->f_fstypename[0], "hfs", 3 ) == 0 ||
			 memcmp( &my_statfsp->f_fstypename[0], "ufs", 3 ) == 0 ||
			 memcmp( &my_statfsp->f_fstypename[0], "devfs", 5 ) == 0 ||
			 memcmp( &my_statfsp->f_fstypename[0], "volfs", 5 ) == 0 ) {
			/* found a valid entry */
			break;
		}
	}
	if ( i >= my_count ) {
		printf( "getfsstat call failed.  could not find valid f_fstypename! \n" );
		goto test_failed_exit;
	}

	/* set up to validate results via multiple sources.  we use getattrlist to get volume
	 * related attributes to verify against results from fstatfs and statfs - but only if
	 * we are not targeting ufs volume since it doesn't support getattr calls
	 */
	if ( is_ufs == 0 ) {
		memset( &my_attrlist, 0, sizeof(my_attrlist) );
		my_attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
		my_attrlist.volattr = (ATTR_VOL_SIZE | ATTR_VOL_IOBLOCKSIZE);
		my_err = getattrlist( "/", &my_attrlist, &my_attr_buf, sizeof(my_attr_buf), 0 );
		if ( my_err != 0 ) {
			printf( "getattrlist call failed.  got errno %d - %s. \n", errno, strerror( errno ) );
			goto test_failed_exit;
		}
	}
	
	/* open kernel to use as test file for fstatfs */
 	my_fd = open( "/mach_kernel", O_RDONLY, 0 );
	if ( my_fd == -1 ) {
		printf( "open call failed.  got errno %d - %s. \n", errno, strerror( errno ) );
		goto test_failed_exit;
	}
	
	/* testing fstatfs */
	my_statfsp = (struct statfs *) my_bufferp;
	my_err = fstatfs( my_fd, my_statfsp );
	if ( my_err == -1 ) {
		printf( "fstatfs call failed.  got errno %d - %s. \n", errno, strerror( errno ) );
		goto test_failed_exit;
	}
	
	/* validate results */
	if ( !(memcmp( &my_statfsp->f_fstypename[0], "hfs", 3 ) == 0 ||
		   memcmp( &my_statfsp->f_fstypename[0], "ufs", 3 ) == 0) ) {
		printf( "fstatfs call failed.  could not find valid f_fstypename! \n" );
		goto test_failed_exit;
	}
	my_io_size = my_statfsp->f_iosize;
	my_fsid = my_statfsp->f_fsid;
	if ( is_ufs == 0 && my_statfsp->f_iosize != my_attr_buf.io_blksize ) {
		printf( "fstatfs and getattrlist results do not match for volume block size  \n" );
		goto test_failed_exit;
	} 

	/* try again with statfs */
	my_err = statfs( "/mach_kernel", my_statfsp );
	if ( my_err == -1 ) {
		printf( "statfs call failed.  got errno %d - %s. \n", errno, strerror( errno ) );
		goto test_failed_exit;
	}

	/* validate resutls */
	if ( my_io_size != my_statfsp->f_iosize || my_fsid.val[0] != my_statfsp->f_fsid.val[0] ||
		 my_fsid.val[1] != my_statfsp->f_fsid.val[1] ) {
		printf( "statfs call failed.  wrong f_iosize or f_fsid! \n" );
		goto test_failed_exit;
	}
	if ( is_ufs == 0 && my_statfsp->f_iosize != my_attr_buf.io_blksize ) {
		printf( "statfs and getattrlist results do not match for volume block size  \n" );
		goto test_failed_exit;
	} 

	/* We passed the test */
	my_err = 0;

test_failed_exit:
	if(my_err != 0)
		my_err = -1;
	
test_passed_exit:
	if ( my_fd != -1 )
		close( my_fd );
	if ( my_bufferp != NULL ) {
		vm_deallocate(mach_task_self(), (vm_address_t)my_bufferp, my_buffer_size);	
	}
	 
	return( my_err );
}
Exemple #23
0
static PyObject *
psutil_proc_open_files(PyObject *self, PyObject *args) {
    long pid;
    int i, cnt;
    struct kinfo_file *freep = NULL;
    struct kinfo_file *kif;
    kinfo_proc kipp;
    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;

    if (py_retlist == NULL)
        return NULL;
    if (! PyArg_ParseTuple(args, "l", &pid))
        goto error;
    if (psutil_kinfo_proc(pid, &kipp) == -1)
        goto error;

    freep = kinfo_getfile(pid, &cnt);
    if (freep == NULL) {
        psutil_raise_ad_or_nsp(pid);
        goto error;
    }

    for (i = 0; i < cnt; i++) {
        kif = &freep[i];
#ifdef __FreeBSD__
        if ((kif->kf_type == KF_TYPE_VNODE) &&
                (kif->kf_vnode_type == KF_VTYPE_VREG))
        {
            py_tuple = Py_BuildValue("(si)", kif->kf_path, kif->kf_fd);
#elif defined(__OpenBSD__)
        if ((kif->f_type == DTYPE_VNODE) &&
                (kif->v_type == VREG))
        {
            py_tuple = Py_BuildValue("(si)", "", kif->fd_fd);
#elif defined(__NetBSD__)
        if ((kif->ki_ftype == DTYPE_VNODE) &&
                (kif->ki_vtype == VREG))
        {
            py_tuple = Py_BuildValue("(si)", "", kif->ki_fd);
#endif
            if (py_tuple == NULL)
                goto error;
            if (PyList_Append(py_retlist, py_tuple))
                goto error;
            Py_DECREF(py_tuple);
        }
    }
    free(freep);
    return py_retlist;

error:
    Py_XDECREF(py_tuple);
    Py_DECREF(py_retlist);
    if (freep != NULL)
        free(freep);
    return NULL;
}
#endif


/*
 * Return a list of tuples including device, mount point and fs type
 * for all partitions mounted on the system.
 */
static PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
    int num;
    int i;
    long len;
    uint64_t flags;
    char opts[200];
#if defined(__NetBSD__)
    struct statvfs *fs = NULL;
#else
    struct statfs *fs = NULL;
#endif
    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;

    if (py_retlist == NULL)
        return NULL;

    // get the number of mount points
    Py_BEGIN_ALLOW_THREADS
#if defined(__NetBSD__)
    num = getvfsstat(NULL, 0, MNT_NOWAIT);
#else
    num = getfsstat(NULL, 0, MNT_NOWAIT);
#endif
    Py_END_ALLOW_THREADS
    if (num == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    len = sizeof(*fs) * num;
    fs = malloc(len);
    if (fs == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    Py_BEGIN_ALLOW_THREADS
#if defined(__NetBSD__)
    num = getvfsstat(fs, len, MNT_NOWAIT);
#else
    num = getfsstat(fs, len, MNT_NOWAIT);
#endif
    Py_END_ALLOW_THREADS
    if (num == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    for (i = 0; i < num; i++) {
        py_tuple = NULL;
        opts[0] = 0;
#if defined(__NetBSD__)
        flags = fs[i].f_flag;
#else
        flags = fs[i].f_flags;
#endif

        // see sys/mount.h
        if (flags & MNT_RDONLY)
            strlcat(opts, "ro", sizeof(opts));
        else
            strlcat(opts, "rw", sizeof(opts));
        if (flags & MNT_SYNCHRONOUS)
            strlcat(opts, ",sync", sizeof(opts));
        if (flags & MNT_NOEXEC)
            strlcat(opts, ",noexec", sizeof(opts));
        if (flags & MNT_NOSUID)
            strlcat(opts, ",nosuid", sizeof(opts));
        if (flags & MNT_ASYNC)
            strlcat(opts, ",async", sizeof(opts));
        if (flags & MNT_NOATIME)
            strlcat(opts, ",noatime", sizeof(opts));
        if (flags & MNT_SOFTDEP)
            strlcat(opts, ",softdep", sizeof(opts));
#ifdef __FreeBSD__
        if (flags & MNT_UNION)
            strlcat(opts, ",union", sizeof(opts));
        if (flags & MNT_SUIDDIR)
            strlcat(opts, ",suiddir", sizeof(opts));
        if (flags & MNT_SOFTDEP)
            strlcat(opts, ",softdep", sizeof(opts));
        if (flags & MNT_NOSYMFOLLOW)
            strlcat(opts, ",nosymfollow", sizeof(opts));
        if (flags & MNT_GJOURNAL)
            strlcat(opts, ",gjournal", sizeof(opts));
        if (flags & MNT_MULTILABEL)
            strlcat(opts, ",multilabel", sizeof(opts));
        if (flags & MNT_ACLS)
            strlcat(opts, ",acls", sizeof(opts));
        if (flags & MNT_NOCLUSTERR)
            strlcat(opts, ",noclusterr", sizeof(opts));
        if (flags & MNT_NOCLUSTERW)
            strlcat(opts, ",noclusterw", sizeof(opts));
        if (flags & MNT_NFS4ACLS)
            strlcat(opts, ",nfs4acls", sizeof(opts));
#elif __NetBSD__
        if (flags & MNT_NODEV)
            strlcat(opts, ",nodev", sizeof(opts));
        if (flags & MNT_UNION)
            strlcat(opts, ",union", sizeof(opts));
        if (flags & MNT_NOCOREDUMP)
            strlcat(opts, ",nocoredump", sizeof(opts));
        if (flags & MNT_RELATIME)
            strlcat(opts, ",relatime", sizeof(opts));
        if (flags & MNT_IGNORE)
            strlcat(opts, ",ignore", sizeof(opts));
#if defined(MNT_DISCARD)
        if (flags & MNT_DISCARD)
            strlcat(opts, ",discard", sizeof(opts));
#endif
        if (flags & MNT_EXTATTR)
            strlcat(opts, ",extattr", sizeof(opts));
        if (flags & MNT_LOG)
            strlcat(opts, ",log", sizeof(opts));
        if (flags & MNT_SYMPERM)
            strlcat(opts, ",symperm", sizeof(opts));
        if (flags & MNT_NODEVMTIME)
            strlcat(opts, ",nodevmtime", sizeof(opts));
#endif
        py_tuple = Py_BuildValue("(ssss)",
                                 fs[i].f_mntfromname,  // device
                                 fs[i].f_mntonname,    // mount point
                                 fs[i].f_fstypename,   // fs type
                                 opts);                // options
        if (!py_tuple)
            goto error;
        if (PyList_Append(py_retlist, py_tuple))
            goto error;
        Py_DECREF(py_tuple);
    }

    free(fs);
    return py_retlist;

error:
    Py_XDECREF(py_tuple);
    Py_DECREF(py_retlist);
    if (fs != NULL)
        free(fs);
    return NULL;
}


/*
 * Return a Python list of named tuples with overall network I/O information
 */
static PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args) {
    char *buf = NULL, *lim, *next;
    struct if_msghdr *ifm;
    int mib[6];
    size_t len;
    PyObject *py_retdict = PyDict_New();
    PyObject *py_ifc_info = NULL;
    if (py_retdict == NULL)
        return NULL;

    mib[0] = CTL_NET;          // networking subsystem
    mib[1] = PF_ROUTE;         // type of information
    mib[2] = 0;                // protocol (IPPROTO_xxx)
    mib[3] = 0;                // address family
    mib[4] = NET_RT_IFLIST;   // operation
    mib[5] = 0;

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    buf = malloc(len);
    if (buf == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    lim = buf + len;

    for (next = buf; next < lim; ) {
        py_ifc_info = NULL;
        ifm = (struct if_msghdr *)next;
        next += ifm->ifm_msglen;

        if (ifm->ifm_type == RTM_IFINFO) {
            struct if_msghdr *if2m = (struct if_msghdr *)ifm;
            struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
            char ifc_name[32];

            strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
            ifc_name[sdl->sdl_nlen] = 0;
            // XXX: ignore usbus interfaces:
            // http://lists.freebsd.org/pipermail/freebsd-current/
            //     2011-October/028752.html
            // 'ifconfig -a' doesn't show them, nor do we.
            if (strncmp(ifc_name, "usbus", 5) == 0)
                continue;

            py_ifc_info = Py_BuildValue("(kkkkkkki)",
                                        if2m->ifm_data.ifi_obytes,
                                        if2m->ifm_data.ifi_ibytes,
                                        if2m->ifm_data.ifi_opackets,
                                        if2m->ifm_data.ifi_ipackets,
                                        if2m->ifm_data.ifi_ierrors,
                                        if2m->ifm_data.ifi_oerrors,
                                        if2m->ifm_data.ifi_iqdrops,
                                        0);  // dropout not supported
            if (!py_ifc_info)
                goto error;
            if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info))
                goto error;
            Py_DECREF(py_ifc_info);
        }
        else {
            continue;
        }
    }

    free(buf);
    return py_retdict;

error:
    Py_XDECREF(py_ifc_info);
    Py_DECREF(py_retdict);
    if (buf != NULL)
        free(buf);
    return NULL;
}
Exemple #24
0
/*
 * Return a list of tuples including device, mount point and fs type
 * for all partitions mounted on the system.
 */
static PyObject*
get_disk_partitions(PyObject* self, PyObject* args)
{
    int num;
    int i;
    long len;
    uint64_t flags;
    char opts[200];
    struct statfs *fs;
    PyObject* py_retlist = PyList_New(0);
    PyObject* py_tuple;

    // get the number of mount points
    Py_BEGIN_ALLOW_THREADS
    num = getfsstat(NULL, 0, MNT_NOWAIT);
    Py_END_ALLOW_THREADS
    if (num == -1) {
        PyErr_SetFromErrno(0);
        return NULL;
    }

    len = sizeof(*fs) * num;
    fs = malloc(len);

    Py_BEGIN_ALLOW_THREADS
    num = getfsstat(fs, len, MNT_NOWAIT);
    Py_END_ALLOW_THREADS
    if (num == -1) {
        free(fs);
        PyErr_SetFromErrno(0);
        return NULL;
    }

    for (i = 0; i < num; i++) {
        opts[0] = 0;
        flags = fs[i].f_flags;

        // see sys/mount.h
        if (flags & MNT_RDONLY)
            strlcat(opts, "rdonly", sizeof(opts));
        else
            strlcat(opts, "rw", sizeof(opts));
        if (flags & MNT_SYNCHRONOUS)
            strlcat(opts, ",sync", sizeof(opts));
        if (flags & MNT_NOEXEC)
            strlcat(opts, ",noexec", sizeof(opts));
        if (flags & MNT_NOSUID)
            strlcat(opts, ",nosuid", sizeof(opts));
        if (flags & MNT_NODEV)
            strlcat(opts, ",nodev", sizeof(opts));
        if (flags & MNT_ASYNC)
            strlcat(opts, ",async", sizeof(opts));
        if (flags & MNT_SOFTDEP)
            strlcat(opts, ",softdep", sizeof(opts));
        if (flags & MNT_NOATIME)
            strlcat(opts, ",noatime", sizeof(opts));

        py_tuple = Py_BuildValue("(ssss)", fs[i].f_mntfromname,  // device
                                           fs[i].f_mntonname,    // mount point
                                           fs[i].f_fstypename,   // fs type
                                           opts);                // options
        PyList_Append(py_retlist, py_tuple);
        Py_XDECREF(py_tuple);
    }

    free(fs);
    return py_retlist;
}
Exemple #25
0
/**
 * Query the underlaying OS for the mounted file systems
 * anf fill in the respective lists (for hrStorageTable and for hrFSTable)
 */
static void
storage_OS_get_fs(void)
{
	struct storage_entry *entry;
	uint64_t size, used;
	int i, mounted_fs_count, units;
	char fs_string[SE_DESC_MLEN];

	if ((mounted_fs_count = getfsstat(NULL, 0, MNT_NOWAIT)) < 0) {
		syslog(LOG_ERR, "hrStorageTable: getfsstat() failed: %m");
		return; /* out of luck this time */
	}

	if (mounted_fs_count != (int)fs_buf_count || fs_buf == NULL) {
		fs_buf_count = mounted_fs_count;
		fs_buf = reallocf(fs_buf, fs_buf_count * sizeof(struct statfs));
		if (fs_buf == NULL) {
			fs_buf_count = 0;
			assert(0);
			return;
		}
	}

	if ((mounted_fs_count = getfsstat(fs_buf,
	    fs_buf_count * sizeof(struct statfs), MNT_NOWAIT)) < 0) {
		syslog(LOG_ERR, "hrStorageTable: getfsstat() failed: %m");
		return; /* out of luck this time */
	}

	HRDBG("got %d mounted FS", mounted_fs_count);

	fs_tbl_pre_refresh();

	for (i = 0; i < mounted_fs_count; i++) {
		snprintf(fs_string, sizeof(fs_string),
		    "%s, type: %s, dev: %s", fs_buf[i].f_mntonname,
		    fs_buf[i].f_fstypename, fs_buf[i].f_mntfromname);

		entry = storage_find_by_name(fs_string);
		if (entry == NULL)
			entry = storage_entry_create(fs_string);

		assert (entry != NULL);
		if (entry == NULL)
			return; /* Out of luck */

		entry->flags |= HR_STORAGE_FOUND;
		entry->type = fs_get_type(&fs_buf[i]); /*XXX - This is wrong*/

		units = fs_buf[i].f_bsize;
		size = fs_buf[i].f_blocks;
		used = fs_buf[i].f_blocks - fs_buf[i].f_bfree;
		while (size > INT_MAX) {
			units <<= 1;
			size >>= 1;
			used >>= 1;
		}
		entry->allocationUnits = units;
		entry->size = size;
		entry->used = used;

		entry->allocationFailures = 0;

		/* take care of hrFSTable */
		fs_tbl_process_statfs_entry(&fs_buf[i], entry->index);
	}

	fs_tbl_post_refresh();
}
void MemoryCardDriverThreaded_MacOSX::GetUSBStorageDevices( vector<UsbStorageDevice>& vDevicesOut )
{
	LockMut( m_ChangedLock );
	// First, get all device paths
	struct statfs *fs;
	int num = getfsstat( NULL, 0, MNT_NOWAIT );
	
	fs = new struct statfs[num];
	
	num = getfsstat( fs, num * sizeof(struct statfs), MNT_NOWAIT );
	ASSERT( num != -1 );
	
	for( int i = 0; i < num; ++i )
	{
		if( strncmp(fs[i].f_mntfromname, _PATH_DEV, strlen(_PATH_DEV)) )
			continue;
		
		const RString& sDevicePath = fs[i].f_mntfromname;
		const RString& sDisk = Basename( sDevicePath ); // disk#[[s#] ...]
		
		// Now that we have the disk name, look up the IOServices associated with it.
		CFMutableDictionaryRef dict;
		
		if( !(dict = IOBSDNameMatching(kIOMasterPortDefault, 0, sDisk)) )
			continue;
		
		// Look for certain properties: Leaf, Ejectable, Writable.
		CFDictionarySetValue( dict, CFSTR(kIOMediaLeafKey), kCFBooleanTrue );
		CFDictionarySetValue( dict, CFSTR(kIOMediaEjectableKey), kCFBooleanTrue );
		CFDictionarySetValue( dict, CFSTR(kIOMediaWritableKey), kCFBooleanTrue );
		
		// Get the matching iterator. As always, this consumes a reference to dict.
		io_iterator_t iter;
		kern_return_t ret = IOServiceGetMatchingServices( kIOMasterPortDefault, dict, &iter );
		
		if( ret != KERN_SUCCESS || iter == 0 )
			continue;
		
		// I'm not quite sure what it means to have two services with this device.
		// Iterate over them all. If one contains what we want, stop.
		io_registry_entry_t device; // This is the same as an io_object_t.
		
		while( (device = IOIteratorNext(iter)) )
		{
			// Look at the parent of the device until we see an IOUSBMassStorageClass
			while( device != MACH_PORT_NULL && !IOObjectConformsTo(device, "IOUSBMassStorageClass") )
			{
				io_registry_entry_t entry;
				ret = IORegistryEntryGetParentEntry( device, kIOServicePlane, &entry );
				IOObjectRelease( device );
				device = ret == KERN_SUCCESS? entry:MACH_PORT_NULL;
			}
			// Now look for the corresponding IOUSBDevice, it's likely 2 up the tree
			while( device != MACH_PORT_NULL && !IOObjectConformsTo(device, "IOUSBDevice") )
			{
				io_registry_entry_t entry;
				ret = IORegistryEntryGetParentEntry( device, kIOServicePlane, &entry );
				IOObjectRelease( device );
				device = ret == KERN_SUCCESS? entry:MACH_PORT_NULL;
			}
			if( device == MACH_PORT_NULL )
				continue;
			
			// At this point, it is pretty safe to say that we've found a USB device.
			vDevicesOut.push_back( UsbStorageDevice() );
			UsbStorageDevice& usbd = vDevicesOut.back();
			
			LOG->Trace( "Found memory card at path: %s.", fs[i].f_mntonname );
			usbd.SetOsMountDir( fs[i].f_mntonname );
			usbd.iVolumeSizeMB = int( (uint64_t(fs[i].f_blocks) * fs[i].f_bsize) >> 20 );
		
			// Now we can get some more information from the registry tree.
			usbd.iBus = GetIntProperty( device, CFSTR("USB Address") );
			usbd.iPort = GetIntProperty( device, CFSTR("PortNum") );
			// usbd.iLevel ?
			usbd.sSerial = GetStringProperty( device, CFSTR("USB Serial Number") );
			usbd.sDevice = fs[i].f_mntfromname;
			usbd.idVendor = GetIntProperty( device, CFSTR(kUSBVendorID) );
			usbd.idProduct = GetIntProperty( device, CFSTR(kUSBProductID) );
			usbd.sVendor = GetStringProperty( device, CFSTR("USB Vendor Name") );
			usbd.sProduct = GetStringProperty( device, CFSTR("USB Product Name") );
			IOObjectRelease( device );
			break; // We found what we wanted
		}
		IOObjectRelease( iter );
	}
	m_bChanged = false;
	delete[] fs;
}
Exemple #27
0
/* Function to detect the MB of diskspace on a path */
int detect_diskspace(const char *path)
{
	long long avail = 0LL;

	if ( path[0] == '/' ) {
#ifdef HAVE_SYS_STATVFS_H
		struct statvfs fs;
#else
		struct statfs fs;
#endif
		char buf[PATH_MAX], *cp;

		strcpy(buf, path);
        cp = buf+strlen(buf);
        while ( buf[0] && (access(buf, F_OK) < 0) ) {
            while ( (cp > (buf+1)) && (*cp != '/') ) {
                --cp;
            }
            *cp = '\0';
        }
		if ( buf[0] ) {
#ifdef HAVE_SYS_STATVFS_H
			if ( statvfs(buf, &fs) ) {
#else
			if ( statfs(buf, &fs) ) {
#endif
				perror("statfs");
				return 0;
			}
			avail = fs.f_bsize;
			avail *= fs.f_bavail;
		}
	}
	return avail / (1024*1024LL);
}

int detect_and_mount_cdrom(char *path[SETUP_MAX_DRIVES])
{
	int num_cdroms = 0;

#ifdef __FreeBSD__
	int mounted;
    struct fstab *fstab;

    /* Try to mount unmounted CDROM filesystems */
    while( (fstab = getfsent()) != NULL ){
        if ( !strcmp(fstab->fs_vfstype, MNTTYPE_CDROM)) {
            if ( !is_fs_mounted(fstab->fs_spec)) {
                if ( ! run_command(NULL, MOUNT_PATH, fstab->fs_spec, 1) ) {
                    add_mounted_entry(fstab->fs_spec, fstab->fs_file);
                    log_normal(_("Mounted device %s"), fstab->fs_spec);
                }
            }
        }
    }
    endfsent();

    mounted = getfsstat(NULL, 0, MNT_WAIT);
    if ( mounted > 0 ) {
        int i;
		struct statfs *mnts = (struct statfs *)malloc(sizeof(struct statfs) * mounted);

		mounted = getfsstat(mnts, mounted * sizeof(struct statfs), MNT_WAIT);
		for ( i = 0; i < mounted && num_cdroms < SETUP_MAX_DRIVES; ++ i ) {
			if ( ! strcmp(mnts[i].f_fstypename, MNTTYPE_CDROM) ) {
				path[num_cdroms ++] = strdup(mnts[i].f_mntonname);
			}
		}
		
		free(mnts);
    }
#elif defined(darwin)
{
    const char *devPrefix = "/dev/";
    int prefixLen = strlen(devPrefix);
    mach_port_t masterPort = 0;
    struct statfs *mntbufp;
    int i, mounts;

    if (IOMasterPort(MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
    {
        mounts = getmntinfo(&mntbufp, MNT_WAIT);  /* NOT THREAD SAFE! */
        for (i = 0; i < mounts && num_cdroms < SETUP_MAX_DRIVES; i++)
        {
            char *dev = mntbufp[i].f_mntfromname;
            char *mnt = mntbufp[i].f_mntonname;
            if (strncmp(dev, devPrefix, prefixLen) != 0)  /* virtual device? */
                continue;

            /* darwinIsMountedDisc needs to skip "/dev/" part of string... */
            if (darwinIsMountedDisc(dev + prefixLen, masterPort))
            {
                strcpy(darwinEjectThisCDDevice, dev + prefixLen);
                path[num_cdroms ++] = strdup(mnt);
            }
        }
    }
}
#elif defined(sco)
	/* Quite horrible. We have to parse mount's output :( */
	/* And of course, we can't try to mount unmounted filesystems */
	FILE *cmd = popen("/etc/mount", "r");
	if ( cmd ) {
		char device[32] = "", mountp[PATH_MAX] = "";
		while ( fscanf(cmd, "%s on %32s %*[^\n]", mountp, device) > 0 ) {
			if ( !strncmp(device, "/dev/cd", 7) ) {
				path[num_cdroms ++] = strdup(mountp);
				break;
			}
		}
		pclose(cmd);
	}

#elif defined(hpux)
    char mntdevpath[PATH_MAX];
    FILE *mountfp;
    struct mntent *mntent;
    const char *fstab, *mtab, *mount_cmd, *mnttype;

    /* HPUX: We need to support PFS */
    if ( !access("/etc/pfs_fstab", F_OK) ) {
		fstab = "/etc/pfs_fstab";
		mtab = "/etc/pfs_mtab";
		mount_cmd = "/usr/sbin/pfs_mount";
		mnttype = "pfs-rrip";
    } else {
		fstab = SETUP_FSTAB;
		mtab = MOUNTS_FILE;
		mnttype = MNTTYPE_CDROM;
		mount_cmd = MOUNT_PATH;
    }

    /* Try to mount unmounted CDROM filesystems */
    mountfp = setmntent( fstab, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL ){
            if ( !strcmp(mntent->mnt_type, mnttype) ) {
                char *fsname = strdup(mntent->mnt_fsname);
                char *dir = strdup(mntent->mnt_dir);
                if ( !is_fs_mounted(fsname)) {
                    if ( ! run_command(NULL, mount_cmd, fsname, 1) ) {
                        add_mounted_entry(fsname, dir);
                        log_normal(_("Mounted device %s"), fsname);
                    }
                }
                free(fsname);
                free(dir);
            }
        }
        endmntent(mountfp);
    }
    
    mountfp = setmntent(mtab, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL && num_cdroms < SETUP_MAX_DRIVES){
            char mntdev[1024], mnt_type[32];

            strcpy(mntdev, mntent->mnt_fsname);
            strcpy(mnt_type, mntent->mnt_type);
            if( strncmp(mntdev, "/dev", 4) || 
                realpath(mntdev, mntdevpath) == NULL ) {
                continue;
            }
            if ( strcmp(mnt_type, mnttype) == 0 ) {
				path[num_cdroms ++] = strdup(mntent->mnt_dir);
            }
        }
        endmntent( mountfp );
    }
#elif defined(__svr4__)
	struct mnttab mnt;

	FILE *fstab = fopen(SETUP_FSTAB, "r");
	if ( fstab != NULL ) {
		while ( getmntent(fstab, &mnt)==0 ) {
			if ( !strcmp(mnt.mnt_fstype, MNTTYPE_CDROM) ) {
                char *fsname = strdup(mnt.mnt_special);
                char *dir = strdup(mnt.mnt_mountp);
                if ( !is_fs_mounted(fsname)) {
                    if ( ! run_command(NULL, MOUNT_PATH, fsname, 1) ) {
                        add_mounted_entry(fsname, dir);
                        log_normal(_("Mounted device %s"), fsname);
                    }
                }
                free(fsname);
                free(dir);
				break;
			}
		}
		fclose(fstab);
		fstab = fopen(MOUNTS_FILE, "r");
		if (fstab) {
			while ( getmntent(fstab, &mnt)==0 && num_cdroms < SETUP_MAX_DRIVES) {
				if ( !strcmp(mnt.mnt_fstype, MNTTYPE_CDROM) ) {
					path[num_cdroms ++] = strdup(mnt.mnt_mountp);
				}
			}
			fclose(fstab);
		}
	}
    
#else
//#ifndef darwin
    char mntdevpath[PATH_MAX];
    FILE *mountfp;
    struct mntent *mntent;

    /* Try to mount unmounted CDROM filesystems */
    mountfp = setmntent( SETUP_FSTAB, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL ){
            if ( (!strcmp(mntent->mnt_type, MNTTYPE_CDROM) 
#ifdef sgi
				 || !strcmp(mntent->mnt_type, "cdfs")
				 || !strcmp(mntent->mnt_type, "efs")
#endif
				 || !strcmp(mntent->mnt_type, "auto"))
				 && strncmp(mntent->mnt_fsname, DEVICE_FLOPPY, strlen(DEVICE_FLOPPY)) ) {
                char *fsname = strdup(mntent->mnt_fsname);
                char *dir = strdup(mntent->mnt_dir);
                if ( !is_fs_mounted(fsname)) {
                    if ( ! run_command(NULL, MOUNT_PATH, fsname, 1) ) {
                        add_mounted_entry(fsname, dir);
                        log_normal(_("Mounted device %s"), fsname);
                    }
                }
                free(fsname);
                free(dir);
            }
        }
        endmntent(mountfp);
    }
    
    mountfp = setmntent(MOUNTS_FILE, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL && num_cdroms < SETUP_MAX_DRIVES){
            char *tmp, mntdev[1024], mnt_type[32];

			if ( strncmp(mntent->mnt_fsname, DEVICE_FLOPPY, strlen(DEVICE_FLOPPY)) == 0)
				continue;

            strcpy(mntdev, mntent->mnt_fsname);
            strcpy(mnt_type, mntent->mnt_type);
            if ( strcmp(mnt_type, MNTTYPE_SUPER) == 0 ) {
                tmp = strstr(mntent->mnt_opts, "fs=");
                if ( tmp ) {
                    strcpy(mnt_type, tmp+strlen("fs="));
                    tmp = strchr(mnt_type, ',');
                    if ( tmp ) {
                        *tmp = '\0';
                    }
                }
		tmp = strstr(mntent->mnt_opts, "dev=");
		if ( tmp ) {
                    strcpy(mntdev, tmp+strlen("dev="));
                    tmp = strchr(mntdev, ',');
                    if ( tmp ) {
                        *tmp = '\0';
                    }
                }
            }
            if( strncmp(mntdev, "/dev", 4) || 
                realpath(mntdev, mntdevpath) == NULL ) {
                continue;
            }
            if ( strcmp(mnt_type, MNTTYPE_CDROM) == 0 ) {
	        path[num_cdroms ++] = strdup(mntent->mnt_dir);
            } else if ( strcmp(mnt_type, "auto") == 0 &&
			strncmp(mntdev, DEVICE_FLOPPY, strlen(DEVICE_FLOPPY))) {
	        path[num_cdroms ++] = strdup(mntent->mnt_dir);		
	    }
#ifdef sgi
            else if ( strcmp(mnt_type, "cdfs") == 0 ||
                      strcmp(mnt_type, "efs")  == 0 ) {
	      path[num_cdroms ++] = strdup(mntent->mnt_dir);
            }
#endif
        }
        endmntent( mountfp );
    }
//#endif
#endif
	return num_cdroms;
}
Exemple #28
0
/*
 * Return a list of tuples including device, mount point and fs type
 * for all partitions mounted on the system.
 */
static PyObject*
get_disk_partitions(PyObject* self, PyObject* args)
{
    int num;
    int i;
    long len;
    uint64_t flags;
    char opts[400];
    struct statfs *fs;
    PyObject* py_retlist = PyList_New(0);
    PyObject* py_tuple;

    // get the number of mount points
    Py_BEGIN_ALLOW_THREADS
    num = getfsstat(NULL, 0, MNT_NOWAIT);
    Py_END_ALLOW_THREADS
    if (num == -1) {
        PyErr_SetFromErrno(0);
        return NULL;
    }

    len = sizeof(*fs) * num;
    fs = malloc(len);

    Py_BEGIN_ALLOW_THREADS
    num = getfsstat(fs, len, MNT_NOWAIT);
    Py_END_ALLOW_THREADS
    if (num == -1) {
        free(fs);
        PyErr_SetFromErrno(0);
        return NULL;
    }

    for (i = 0; i < num; i++) {
        opts[0] = 0;
        flags = fs[i].f_flags;

        // see sys/mount.h
        if (flags & MNT_RDONLY)
            strlcat(opts, "ro", sizeof(opts));
        else
            strlcat(opts, "rw", sizeof(opts));
        if (flags & MNT_SYNCHRONOUS)
            strlcat(opts, ",sync", sizeof(opts));
        if (flags & MNT_NOEXEC)
            strlcat(opts, ",noexec", sizeof(opts));
        if (flags & MNT_NOSUID)
            strlcat(opts, ",nosuid", sizeof(opts));
        if (flags & MNT_UNION)
            strlcat(opts, ",union", sizeof(opts));
        if (flags & MNT_ASYNC)
            strlcat(opts, ",async", sizeof(opts));
        if (flags & MNT_EXPORTED)
            strlcat(opts, ",exported", sizeof(opts));
        if (flags & MNT_QUARANTINE)
            strlcat(opts, ",quarantine", sizeof(opts));
        if (flags & MNT_LOCAL)
            strlcat(opts, ",local", sizeof(opts));
        if (flags & MNT_QUOTA)
            strlcat(opts, ",quota", sizeof(opts));
        if (flags & MNT_ROOTFS)
            strlcat(opts, ",rootfs", sizeof(opts));
        if (flags & MNT_DOVOLFS)
            strlcat(opts, ",dovolfs", sizeof(opts));
        if (flags & MNT_DONTBROWSE)
            strlcat(opts, ",dontbrowse", sizeof(opts));
        if (flags & MNT_IGNORE_OWNERSHIP)
            strlcat(opts, ",ignore-ownership", sizeof(opts));
        if (flags & MNT_AUTOMOUNTED)
            strlcat(opts, ",automounted", sizeof(opts));
        if (flags & MNT_JOURNALED)
            strlcat(opts, ",journaled", sizeof(opts));
        if (flags & MNT_NOUSERXATTR)
            strlcat(opts, ",nouserxattr", sizeof(opts));
        if (flags & MNT_DEFWRITE)
            strlcat(opts, ",defwrite", sizeof(opts));
        if (flags & MNT_MULTILABEL)
            strlcat(opts, ",multilabel", sizeof(opts));
        if (flags & MNT_NOATIME)
            strlcat(opts, ",noatime", sizeof(opts));
        if (flags & MNT_UPDATE)
            strlcat(opts, ",update", sizeof(opts));
        if (flags & MNT_RELOAD)
            strlcat(opts, ",reload", sizeof(opts));
        if (flags & MNT_FORCE)
            strlcat(opts, ",force", sizeof(opts));
        if (flags & MNT_CMDFLAGS)
            strlcat(opts, ",cmdflags", sizeof(opts));

        py_tuple = Py_BuildValue("(ssss)", fs[i].f_mntfromname,  // device
                                           fs[i].f_mntonname,    // mount point
                                           fs[i].f_fstypename,   // fs type
                                           opts);                // options
        PyList_Append(py_retlist, py_tuple);
        Py_XDECREF(py_tuple);
    }

    free(fs);
    return py_retlist;
}
Exemple #29
0
struct mount_entry *
read_file_system_list (bool need_fs_type)
{
  struct mount_entry *mount_list;
  struct mount_entry *me;
  struct mount_entry **mtail = &mount_list;

#ifdef MOUNTED_LISTMNTENT
  {
    struct tabmntent *mntlist, *p;
    struct mntent *mnt;
    struct mount_entry *me;

    /* the third and fourth arguments could be used to filter mounts,
       but Crays doesn't seem to have any mounts that we want to
       remove. Specifically, automount create normal NFS mounts.
       */

    if (listmntent (&mntlist, KMTAB, NULL, NULL) < 0)
      return NULL;
    for (p = mntlist; p; p = p->next) {
      mnt = p->ment;
      me = xmalloc (sizeof *me);
      me->me_devname = xstrdup (mnt->mnt_fsname);
      me->me_mountdir = xstrdup (mnt->mnt_dir);
      me->me_type = xstrdup (mnt->mnt_type);
      me->me_type_malloced = 1;
      me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
      me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
      me->me_dev = -1;
      *mtail = me;
      mtail = &me->me_next;
    }
    freemntlist (mntlist);
  }
#endif

#ifdef MOUNTED_GETMNTENT1	/* 4.3BSD, SunOS, HP-UX, Dynix, Irix.  */
  {
    struct mntent *mnt;
    char *table = MOUNTED;
    FILE *fp;
    char *devopt;

    fp = setmntent (table, "r");
    if (fp == NULL)
      return NULL;

    while ((mnt = getmntent (fp)))
      {
	me = xmalloc (sizeof *me);
	me->me_devname = xstrdup (mnt->mnt_fsname);
	me->me_mountdir = xstrdup (mnt->mnt_dir);
	me->me_type = xstrdup (mnt->mnt_type);
	me->me_type_malloced = 1;
	me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
#if ! (__CYGWIN__ || __MSYS__)
	me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
#else
      me->me_remote = cygremote (me->me_devname, &me->me_type);
#endif
	devopt = strstr (mnt->mnt_opts, "dev=");
	if (devopt)
	  me->me_dev = strtoul (devopt + 4, NULL, 16);
	else
	  me->me_dev = (dev_t) -1;	/* Magic; means not known yet. */

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }

    if (endmntent (fp) == 0)
      goto free_then_fail;
  }
#endif /* MOUNTED_GETMNTENT1. */

#ifdef MOUNTED_GETMNTINFO	/* 4.4BSD.  */
  {
    struct statfs *fsp;
    int entries;

    entries = getmntinfo (&fsp, MNT_NOWAIT);
    if (entries < 0)
      return NULL;
    for (; entries-- > 0; fsp++)
      {
	char *fs_type = fsp_to_string (fsp);

	me = xmalloc (sizeof *me);
	me->me_devname = xstrdup (fsp->f_mntfromname);
	me->me_mountdir = xstrdup (fsp->f_mntonname);
	me->me_type = fs_type;
	me->me_type_malloced = 0;
	me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
	me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
	me->me_dev = (dev_t) -1;	/* Magic; means not known yet. */

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }
  }
#endif /* MOUNTED_GETMNTINFO */

#ifdef MOUNTED_GETMNT		/* Ultrix.  */
  {
    int offset = 0;
    int val;
    struct fs_data fsd;

    while (errno = 0,
	   0 < (val = getmnt (&offset, &fsd, sizeof (fsd), NOSTAT_MANY,
			      (char *) 0)))
      {
	me = xmalloc (sizeof *me);
	me->me_devname = xstrdup (fsd.fd_req.devname);
	me->me_mountdir = xstrdup (fsd.fd_req.path);
	me->me_type = gt_names[fsd.fd_req.fstype];
	me->me_type_malloced = 0;
	me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
	me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
	me->me_dev = fsd.fd_req.dev;

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }
    if (val < 0)
      goto free_then_fail;
  }
#endif /* MOUNTED_GETMNT. */

#if defined MOUNTED_FS_STAT_DEV /* BeOS */
  {
    /* The next_dev() and fs_stat_dev() system calls give the list of
       all file systems, including the information returned by statvfs()
       (fs type, total blocks, free blocks etc.), but without the mount
       point. But on BeOS all file systems except / are mounted in the
       rootfs, directly under /.
       The directory name of the mount point is often, but not always,
       identical to the volume name of the device.
       We therefore get the list of subdirectories of /, and the list
       of all file systems, and match the two lists.  */

    DIR *dirp;
    struct rootdir_entry
      {
	char *name;
	dev_t dev;
	ino_t ino;
	struct rootdir_entry *next;
      };
    struct rootdir_entry *rootdir_list;
    struct rootdir_entry **rootdir_tail;
    int32 pos;
    dev_t dev;
    fs_info fi;

    /* All volumes are mounted in the rootfs, directly under /. */
    rootdir_list = NULL;
    rootdir_tail = &rootdir_list;
    dirp = opendir ("/");
    if (dirp)
      {
	struct dirent *d;

	while ((d = readdir (dirp)) != NULL)
	  {
	    char *name;
	    struct stat statbuf;

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

	    if (strcmp (d->d_name, ".") == 0)
	      name = xstrdup ("/");
	    else
	      {
		name = xmalloc (1 + strlen (d->d_name) + 1);
		name[0] = '/';
		strcpy (name + 1, d->d_name);
	      }

	    if (lstat (name, &statbuf) >= 0 && S_ISDIR (statbuf.st_mode))
	      {
		struct rootdir_entry *re = xmalloc (sizeof *re);
		re->name = name;
		re->dev = statbuf.st_dev;
		re->ino = statbuf.st_ino;

		/* Add to the linked list.  */
		*rootdir_tail = re;
		rootdir_tail = &re->next;
	      }
	    else
	      free (name);
	  }
	closedir (dirp);
      }
    *rootdir_tail = NULL;

    for (pos = 0; (dev = next_dev (&pos)) >= 0; )
      if (fs_stat_dev (dev, &fi) >= 0)
	{
	  /* Note: fi.dev == dev. */
	  struct rootdir_entry *re;

	  for (re = rootdir_list; re; re = re->next)
	    if (re->dev == fi.dev && re->ino == fi.root)
	      break;

	  me = xmalloc (sizeof *me);
	  me->me_devname = xstrdup (fi.device_name[0] != '\0' ? fi.device_name : fi.fsh_name);
	  me->me_mountdir = xstrdup (re != NULL ? re->name : fi.fsh_name);
	  me->me_type = xstrdup (fi.fsh_name);
	  me->me_type_malloced = 1;
	  me->me_dev = fi.dev;
	  me->me_dummy = 0;
	  me->me_remote = (fi.flags & B_FS_IS_SHARED) != 0;

	  /* Add to the linked list. */
	  *mtail = me;
	  mtail = &me->me_next;
	}
    *mtail = NULL;

    while (rootdir_list != NULL)
      {
	struct rootdir_entry *re = rootdir_list;
	rootdir_list = re->next;
	free (re->name);
	free (re);
      }
  }
#endif /* MOUNTED_FS_STAT_DEV */

#if defined MOUNTED_GETFSSTAT	/* __alpha running OSF_1 */
  {
    int numsys, counter;
    size_t bufsize;
    struct statfs *stats;

    numsys = getfsstat ((struct statfs *)0, 0L, MNT_NOWAIT);
    if (numsys < 0)
      return (NULL);
    if (SIZE_MAX / sizeof *stats <= numsys)
      xalloc_die ();

    bufsize = (1 + numsys) * sizeof *stats;
    stats = xmalloc (bufsize);
    numsys = getfsstat (stats, bufsize, MNT_NOWAIT);

    if (numsys < 0)
      {
	free (stats);
	return (NULL);
      }

    for (counter = 0; counter < numsys; counter++)
      {
	me = xmalloc (sizeof *me);
	me->me_devname = xstrdup (stats[counter].f_mntfromname);
	me->me_mountdir = xstrdup (stats[counter].f_mntonname);
	me->me_type = xstrdup (FS_TYPE (stats[counter]));
	me->me_type_malloced = 1;
	me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
	me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
	me->me_dev = (dev_t) -1;	/* Magic; means not known yet. */

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }

    free (stats);
  }
#endif /* MOUNTED_GETFSSTAT */

#if defined MOUNTED_FREAD || defined MOUNTED_FREAD_FSTYP /* SVR[23].  */
  {
    struct mnttab mnt;
    char *table = "/etc/mnttab";
    FILE *fp;

    fp = fopen (table, "r");
    if (fp == NULL)
      return NULL;

    while (fread (&mnt, sizeof mnt, 1, fp) > 0)
      {
	me = xmalloc (sizeof *me);
# ifdef GETFSTYP			/* SVR3.  */
	me->me_devname = xstrdup (mnt.mt_dev);
# else
	me->me_devname = xmalloc (strlen (mnt.mt_dev) + 6);
	strcpy (me->me_devname, "/dev/");
	strcpy (me->me_devname + 5, mnt.mt_dev);
# endif
	me->me_mountdir = xstrdup (mnt.mt_filsys);
	me->me_dev = (dev_t) -1;	/* Magic; means not known yet. */
	me->me_type = "";
	me->me_type_malloced = 0;
# ifdef GETFSTYP			/* SVR3.  */
	if (need_fs_type)
	  {
	    struct statfs fsd;
	    char typebuf[FSTYPSZ];

	    if (statfs (me->me_mountdir, &fsd, sizeof fsd, 0) != -1
		&& sysfs (GETFSTYP, fsd.f_fstyp, typebuf) != -1)
	      {
		me->me_type = xstrdup (typebuf);
		me->me_type_malloced = 1;
	      }
	  }
# endif
	me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
	me->me_remote = ME_REMOTE (me->me_devname, me->me_type);

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }

    if (ferror (fp))
      {
	/* The last fread() call must have failed.  */
	int saved_errno = errno;
	fclose (fp);
	errno = saved_errno;
	goto free_then_fail;
      }

    if (fclose (fp) == EOF)
      goto free_then_fail;
  }
#endif /* MOUNTED_FREAD || MOUNTED_FREAD_FSTYP.  */

#ifdef MOUNTED_GETMNTTBL	/* DolphinOS goes it's own way */
  {
    struct mntent **mnttbl = getmnttbl (), **ent;
    for (ent=mnttbl;*ent;ent++)
      {
	me = xmalloc (sizeof *me);
	me->me_devname = xstrdup ( (*ent)->mt_resource);
	me->me_mountdir = xstrdup ( (*ent)->mt_directory);
	me->me_type = xstrdup ((*ent)->mt_fstype);
	me->me_type_malloced = 1;
	me->me_dummy = ME_DUMMY (me->me_devname, me->me_type);
	me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
	me->me_dev = (dev_t) -1;	/* Magic; means not known yet. */

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }
    endmnttbl ();
  }
#endif

#ifdef MOUNTED_GETMNTENT2	/* SVR4.  */
  {
    struct mnttab mnt;
    char *table = MNTTAB;
    FILE *fp;
    int ret;
    int lockfd = -1;

# if defined F_RDLCK && defined F_SETLKW
    /* MNTTAB_LOCK is a macro name of our own invention; it's not present in
       e.g. Solaris 2.6.  If the SVR4 folks ever define a macro
       for this file name, we should use their macro name instead.
       (Why not just lock MNTTAB directly?  We don't know.)  */
#  ifndef MNTTAB_LOCK
#   define MNTTAB_LOCK "/etc/.mnttab.lock"
#  endif
    lockfd = open (MNTTAB_LOCK, O_RDONLY);
    if (0 <= lockfd)
      {
	struct flock flock;
	flock.l_type = F_RDLCK;
	flock.l_whence = SEEK_SET;
	flock.l_start = 0;
	flock.l_len = 0;
	while (fcntl (lockfd, F_SETLKW, &flock) == -1)
	  if (errno != EINTR)
	    {
	      int saved_errno = errno;
	      close (lockfd);
	      errno = saved_errno;
	      return NULL;
	    }
      }
    else if (errno != ENOENT)
      return NULL;
# endif

    errno = 0;
    fp = fopen (table, "r");
    if (fp == NULL)
      ret = errno;
    else
      {
	while ((ret = getmntent (fp, &mnt)) == 0)
	  {
	    me = xmalloc (sizeof *me);
	    me->me_devname = xstrdup (mnt.mnt_special);
	    me->me_mountdir = xstrdup (mnt.mnt_mountp);
	    me->me_type = xstrdup (mnt.mnt_fstype);
	    me->me_type_malloced = 1;
	    me->me_dummy = MNT_IGNORE (&mnt) != 0;
	    me->me_remote = ME_REMOTE (me->me_devname, me->me_type);
	    me->me_dev = (dev_t) -1;	/* Magic; means not known yet. */

	    /* Add to the linked list. */
	    *mtail = me;
	    mtail = &me->me_next;
	  }

	ret = fclose (fp) == EOF ? errno : 0 < ret ? 0 : -1;
      }

    if (0 <= lockfd && close (lockfd) != 0)
      ret = errno;

    if (0 <= ret)
      {
	errno = ret;
	goto free_then_fail;
      }
  }
#endif /* MOUNTED_GETMNTENT2.  */

#ifdef MOUNTED_VMOUNT		/* AIX.  */
  {
    int bufsize;
    char *entries, *thisent;
    struct vmount *vmp;
    int n_entries;
    int i;

    /* Ask how many bytes to allocate for the mounted file system info.  */
    if (mntctl (MCTL_QUERY, sizeof bufsize, (struct vmount *) &bufsize) != 0)
      return NULL;
    entries = xmalloc (bufsize);

    /* Get the list of mounted file systems.  */
    n_entries = mntctl (MCTL_QUERY, bufsize, (struct vmount *) entries);
    if (n_entries < 0)
      {
	int saved_errno = errno;
	free (entries);
	errno = saved_errno;
	return NULL;
      }

    for (i = 0, thisent = entries;
	 i < n_entries;
	 i++, thisent += vmp->vmt_length)
      {
	char *options, *ignore;

	vmp = (struct vmount *) thisent;
	me = xmalloc (sizeof *me);
	if (vmp->vmt_flags & MNT_REMOTE)
	  {
	    char *host, *dir;

	    me->me_remote = 1;
	    /* Prepend the remote dirname.  */
	    host = thisent + vmp->vmt_data[VMT_HOSTNAME].vmt_off;
	    dir = thisent + vmp->vmt_data[VMT_OBJECT].vmt_off;
	    me->me_devname = xmalloc (strlen (host) + strlen (dir) + 2);
	    strcpy (me->me_devname, host);
	    strcat (me->me_devname, ":");
	    strcat (me->me_devname, dir);
	  }
	else
	  {
	    me->me_remote = 0;
	    me->me_devname = xstrdup (thisent +
				      vmp->vmt_data[VMT_OBJECT].vmt_off);
	  }
	me->me_mountdir = xstrdup (thisent + vmp->vmt_data[VMT_STUB].vmt_off);
	me->me_type = xstrdup (fstype_to_string (vmp->vmt_gfstype));
	me->me_type_malloced = 1;
	options = thisent + vmp->vmt_data[VMT_ARGS].vmt_off;
	ignore = strstr (options, "ignore");
	me->me_dummy = (ignore
			&& (ignore == options || ignore[-1] == ',')
			&& (ignore[sizeof "ignore" - 1] == ','
			    || ignore[sizeof "ignore" - 1] == '\0'));
	me->me_dev = (dev_t) -1; /* vmt_fsid might be the info we want.  */

	/* Add to the linked list. */
	*mtail = me;
	mtail = &me->me_next;
      }
    free (entries);
  }
#endif /* MOUNTED_VMOUNT. */

  *mtail = NULL;
  return mount_list;


 free_then_fail:
  {
    int saved_errno = errno;
    *mtail = NULL;

    while (mount_list)
      {
	me = mount_list->me_next;
	free (mount_list->me_devname);
	free (mount_list->me_mountdir);
	if (mount_list->me_type_malloced)
	  free (mount_list->me_type);
	free (mount_list);
	mount_list = me;
      }

    errno = saved_errno;
    return NULL;
  }
}
Exemple #30
0
/**
 * OS specific function to load the different mntents into the cache.
 * This function should be called with a write lock on the mntent_cache.
 */
static void refresh_mount_cache(mntent_cache_entry_t *handle_entry(uint32_t dev,
                                                                   const char *special,
                                                                   const char *mountpoint,
                                                                   const char *fstype,
                                                                   const char *mntopts))
{
#if defined(HAVE_GETMNTENT)
   FILE *fp;
   struct stat st;
#if defined(HAVE_LINUX_OS) || \
    defined(HAVE_HPUX_OS) || \
    defined(HAVE_IRIX_OS) || \
    defined(HAVE_AIX_OS) || \
    defined(HAVE_HURD_OS)
   struct mntent *mnt;

#if defined(HAVE_LINUX_OS)
   if ((fp = setmntent("/proc/mounts", "r")) == (FILE *)NULL) {
      if ((fp = setmntent(_PATH_MOUNTED, "r")) == (FILE *)NULL) {
         return;
      }
   }
#elif defined(HAVE_HPUX_OS)
   if ((fp = fopen(MNT_MNTTAB, "r")) == (FILE *)NULL) {
      return;
   }
#elif defined(HAVE_IRIX_OS)
   if ((fp = setmntent(MOUNTED, "r")) == (FILE *)NULL) {
      return;
   }
#elif defined(HAVE_AIX_OS)
   if ((fp = setmntent(MNTTAB, "r")) == (FILE *)NULL) {
      return;
   }
#elif defined(HAVE_HURD_OS)
   if ((fp = setmntent(_PATH_MNTTAB, "r")) == (FILE *)NULL) {
      return;
   }
#endif

   while ((mnt = getmntent(fp)) != (struct mntent *)NULL) {
      if (skip_fstype(mnt->mnt_type)) {
         continue;
      }

      if (stat(mnt->mnt_dir, &st) < 0) {
         continue;
      }

      handle_entry(st.st_dev,
                   mnt->mnt_fsname,
                   mnt->mnt_dir,
                   mnt->mnt_type,
                   mnt->mnt_opts);
   }

   endmntent(fp);
#elif defined(HAVE_SUN_OS)
   struct mnttab mnt;

   if ((fp = fopen(MNTTAB, "r")) == (FILE *)NULL)
      return;

   while (getmntent(fp, &mnt) == 0) {
      if (skip_fstype(mnt.mnt_fstype)) {
         continue;
      }

      if (stat(mnt.mnt_mountp, &st) < 0) {
         continue;
      }

      handle_entry(st.st_dev,
                   mnt.mnt_special,
                   mnt.mnt_mountp,
                   mnt.mnt_fstype,
                   mnt.mnt_mntopts);
   }

   fclose(fp);
#endif /* HAVE_SUN_OS */
#elif defined(HAVE_GETMNTINFO)
   int cnt;
   struct stat st;
#if defined(HAVE_NETBSD_OS)
   struct statvfs *mntinfo;
#else
   struct statfs *mntinfo;
#endif
#if defined(ST_NOWAIT)
   int flags = ST_NOWAIT;
#elif defined(MNT_NOWAIT)
   int flags = MNT_NOWAIT;
#else
   int flags = 0;
#endif

   if ((cnt = getmntinfo(&mntinfo, flags)) > 0) {
      while (cnt > 0) {
         if (!skip_fstype(mntinfo->f_fstypename) &&
             stat(mntinfo->f_mntonname, &st) == 0) {
            handle_entry(st.st_dev,
                         mntinfo->f_mntfromname,
                         mntinfo->f_mntonname,
                         mntinfo->f_fstypename,
                         NULL);
         }
         mntinfo++;
         cnt--;
      }
   }
#elif defined(HAVE_AIX_OS)
   int bufsize;
   char *entries, *current;
   struct vmount *vmp;
   struct stat st;
   struct vfs_ent *ve;
   int n_entries, cnt;

   if (mntctl(MCTL_QUERY, sizeof(bufsize), (struct vmount *)&bufsize) != 0) {
      return;
   }

   entries = malloc(bufsize);
   if ((n_entries = mntctl(MCTL_QUERY, bufsize, (struct vmount *) entries)) < 0) {
      free(entries);
      return;
   }

   cnt = 0;
   current = entries;
   while (cnt < n_entries) {
      vmp = (struct vmount *)current;

      if (skip_fstype(ve->vfsent_name)) {
         continue;
      }

      if (stat(current + vmp->vmt_data[VMT_STUB].vmt_off, &st) < 0) {
         continue;
      }

      ve = getvfsbytype(vmp->vmt_gfstype);
      if (ve && ve->vfsent_name) {
         handle_entry(st.st_dev,
                      current + vmp->vmt_data[VMT_OBJECT].vmt_off,
                      current + vmp->vmt_data[VMT_STUB].vmt_off,
                      ve->vfsent_name,
                      current + vmp->vmt_data[VMT_ARGS].vmt_off);
      }
      current = current + vmp->vmt_length;
      cnt++;
   }
   free(entries);
#elif defined(HAVE_OSF1_OS)
   struct statfs *entries, *current;
   struct stat st;
   int n_entries, cnt;
   int size;

   if ((n_entries = getfsstat((struct statfs *)0, 0L, MNT_NOWAIT)) < 0) {
      return;
   }

   size = (n_entries + 1) * sizeof(struct statfs);
   entries = malloc(size);

   if ((n_entries = getfsstat(entries, size, MNT_NOWAIT)) < 0) {
      free(entries);
      return;
   }

   cnt = 0;
   current = entries;
   while (cnt < n_entries) {
      if (skip_fstype(current->f_fstypename)) {
         continue;
      }

      if (stat(current->f_mntonname, &st) < 0) {
         continue;
      }
      handle_entry(st.st_dev,
                   current->f_mntfromname,
                   current->f_mntonname,
                   current->f_fstypename,
                   NULL);
      current++;
      cnt++;
   }
   free(stats);
#endif
}