示例#1
0
文件: dev.c 项目: dl5rcw/bareos
/*
 * Unmount the device
 * If timeout, wait until the unmount command returns 0.
 * If !timeout, try to unmount the device only once.
 */
bool DEVICE::unmount(DCR *dcr, int timeout)
{
   bool retval = true;
   Dmsg0(100, "Enter unmount\n");

   /*
    * See if the device is mounted.
    */
   if (!is_mounted()) {
      return true;
   }

   /*
    * Before running the unmount program sent a
    * bsdEventDeviceUnmount plugin event so any plugin
    * that want to do something can do things now.
    */
   if (dcr && generate_plugin_event(dcr->jcr, bsdEventDeviceUnmount, dcr) != bRC_OK) {
      retval = false;
      goto bail_out;
   }

   retval = unmount_backend(dcr, timeout);

   /*
    * Mark the device unmounted if we succeed.
    */
   if (retval) {
      clear_mounted();
   }

bail_out:
   return retval;
}
示例#2
0
文件: dev.c 项目: dl5rcw/bareos
/*
 * Mount the device.
 * If timeout, wait until the mount command returns 0.
 * If !timeout, try to mount the device only once.
 */
bool DEVICE::mount(DCR *dcr, int timeout)
{
   bool retval = true;
   Dmsg0(190, "Enter mount\n");

   if (is_mounted()) {
      return true;
   }

   retval = mount_backend(dcr, timeout);

   /*
    * When the mount command succeeded sent a
    * bsdEventDeviceMount plugin event so any plugin
    * that want to do something can do things now.
    */
   if (retval && generate_plugin_event(dcr->jcr, bsdEventDeviceMount, dcr) != bRC_OK) {
      retval = false;
   }

   /*
    * Mark the device mounted if we succeed.
    */
   if (retval) {
      set_mounted();
   }

   return retval;
}
示例#3
0
文件: cryptutil.c 项目: ia/cryptutil
/* decrypt path */
int decrypt(const char *path)
{
	/* validate path argument */
	switch(validation(path, TYPE_ARGUMENT)) {
		case ARG_DIR:
			if (is_mounted(path)) {
				return 1;
			}
			if (!(directory_is_encrypted(path))) {
				printf("%s: %s: directory %s is not encrypted\n", NAME, "ERROR", path);
				return 1;
			}
			decrypt_directory(path);
			break;
		case ARG_PART:
			printf("%s: %s: decrypt partition %s is not implemented yet\n", NAME, "TODO", path);
			break;
		case ARG_DISK:
			printf("%s: %s: decrypt disk %s is not implemented yet\n", NAME, "TODO", path);
			break;
		default:
			printf("%s: %s: file type of %s doesn't support\n", NAME, "ERROR", path);
			break;
	}
	/* exit */
	return 0;
}
示例#4
0
文件: uhvm.c 项目: mjessome/uhvm
static void
deinit(void)
{
    struct device_t *iter, *tmp;

    if (hal_ctx) {
        libhal_ctx_shutdown(hal_ctx, (DBusError *)NULL);
        libhal_ctx_free(hal_ctx);
    }

    dbus_connection_unref(dbus_conn);

    iter = head;

    while (iter) {
        tmp = iter;
        if (!is_mounted(iter))
            /* don't care to check the return values */
            do_umount(iter);
        rmdir(iter->mountp);
        if (iter->should_remove_entry)
            remove_fstab_entry(iter);
        iter = iter->next;
        free_device(tmp);
    }

    if (pid_fd >= 0)
        if (close(pid_fd) < 0) /* releases lock */
            syslog(LOG_ERR, "%s:%d: %s", __FILE__, __LINE__, strerror(errno));
    closelog();
}
示例#5
0
/* 
 * Unmount the device 
 * If timeout, wait until the unmount command returns 0.
 * If !timeout, try to unmount the device only once.
 */
bool DEVICE::unmount(int timeout)
{
   Dmsg0(100, "Enter unmount\n");
   if (is_mounted() && requires_mount() && device->unmount_command) {
      return mount_file(0, timeout);
   } 
   return true;
}
示例#6
0
/* 
 * If timeout, wait until the mount command returns 0.
 * If !timeout, try to mount the device only once.
 */
bool DEVICE::mount(int timeout)
{
   Dmsg0(190, "Enter mount\n");
   if (!is_mounted() && device->mount_command) {
      return mount_file(1, timeout);
   } 
   return true;
}
示例#7
0
void do_bash( char_data* ch, char* argument )
{
  char            arg  [ MAX_INPUT_LENGTH ];
  char_data*   victim;
//  int            door;
  obj_data*     chest;
  obj_data*  bludgeon;

  if(  is_confused_pet( ch )
    || is_mounted( ch )
    || is_entangled( ch, "bash" ) )
    return;

  if( *argument == '\0' ) {
    if( ( victim = opponent( ch ) ) == NULL ) {
      send( ch, "Who or what do you want to bash?\n\r" );
      return;
      }
    char_bash( ch, victim );
    return;
    }

  if( ( victim = get_victim( ch, argument, empty_string ) ) != NULL ) {
    char_bash( ch, victim );
    return;
    }
/*
  if( ( door = find_door( ch, argument, FALSE ) ) >= 0 ) {
    door_bash( ch, door );
    return;
    }

  if( door == -1 ) {
    send( ch, "There isn't a door there for you to bash.\n\r" );
    return;
    }
*/
  argument = one_argument( argument, arg );

  if( ( chest = one_object( ch, arg,
    "bash", ch->array ) ) == NULL )
    return;
  
  if( *argument == '\0' ) {
    send( ch, "With what do you wish to bash %s?\n\r", chest );
    return;
    }

  if( ( bludgeon = one_object( ch, argument,
    "use as a bludgeon", &ch->contents ) ) == NULL )
    return;

  obj_bash( ch, chest, bludgeon );

  return;
}
示例#8
0
bool check_mounted(const char *lower, const char *upper) {
    if (is_mounted(lower, upper)) {
        printf("It is strongly recommended to unmount OverlayFS first. Still continue (not recommended)?: \n");
        int r = getchar();
        if (r != 'Y' && r != 'y') {
            return true;
        }
    }
    return false;
}
int main(int argc, char **argv)
{
	if (argc < 2) {
		fprintf(stderr, "Usage: %s device\n", argv[0]);
		exit(1);
	}

	if (is_mounted(argv[1]))
		printf("\t%s is mounted.\n", argv[1]);
	exit(0);
}
示例#10
0
文件: cdaudio.c 项目: sedwards/xmms3
static void play_file(char *filename)
{
	char *tmp;
	struct driveinfo *drive;
	int track;
	int track_len;

	if ((drive = cdda_find_drive(filename)) == NULL)
		return;

	if (is_mounted(drive->device))
		return;

	tmp = strrchr(filename, '/');
	if (tmp)
		tmp++;
	else
		tmp = filename;

	if (!sscanf(tmp, "Track %d.cda", &track))
		return;
	if (track < 0 || track > 99)
		return;

	if (!cdda_get_toc(&cdda_playing.cd_toc, drive->device) ||
	    cdda_playing.cd_toc.track[track].flags.data_track ||
	    track < cdda_playing.cd_toc.first_track ||
	    track > cdda_playing.cd_toc.last_track)
		return;

	if ((cdda_playing.fd = open(drive->device, CDOPENFLAGS)) == -1)
		return;

	track_len = cdda_calculate_track_length(&cdda_playing.cd_toc, track);
	cdda_ip.set_info(cdda_get_title(&cdda_playing.cd_toc, track),
			 (track_len  * 1000) / 75, 44100 * 2 * 2 * 8, 44100, 2);

	memcpy(&cdda_playing.drive, drive, sizeof (struct driveinfo)); 
#ifndef CDDA_HAS_READAUDIO
	cdda_playing.drive.dae = FALSE;
#endif

	cdda_playing.track = track;

	is_paused = FALSE;
	timeout_remove_for_device(drive->device);

	cdda_playing.playing = TRUE;
	if (drive->dae)
		dae_play();
	else
		seek(0);
}
示例#11
0
文件: io.c 项目: sherpya/nloader
static int unix_open(const char *path, int flags)
{
    if (strcasestr(path, "BOOTEX.LOG"))         /* cruft with log of the scan */
        return open("/dev/null", flags);

    else if (!strncasecmp(path, "Volume{", 7))  /* a device, we need to strip Volume{} */
    {
        size_t len = strlen(path) - 1;

        if (path[len] == '\\')                  /* we don't like Volume{xxxx}\ */
            return -1;

        len -= 6;
        char devpath[len];
        strncpy(devpath, path + 7, len - 1);
        devpath[len - 1] = 0;

        switch (is_mounted(devpath))
        {
            case MTAB_ERROR:
                fprintf(stderr, "unix_open: ERROR: unable to check if mounted\n");
                return -1;
            case MTAB_MOUNTED:
                fprintf(stderr, "unix_open: ERROR: %s is mounted\n", devpath);
                return -1;
            default:
                break;
        }
        return open(devpath, flags);
    }

    /* default or invoked with '*' */
    else if (!strcasecmp(path, "\\??\\Volume{X}\\"))
        return open("disk.img", flags);

    else if (!strcasecmp(path, "disk.img"))     /* our test image */
        return open("disk.img", flags);

    else if (!strncasecmp(path, "\\Device\\KeyboardClass", 21))
    {
        if ((path[22] == 0) && ((path[21] == '0') || (path[21] == '1')))
            return fileno(stdin);
        return -1;
    }

    else if (!strncasecmp(path, "\\Device\\Mailslot", 16))
        return fileno(stdout);

    else if (flags == O_RDONLY)                 /* a generic file only if readonly */
        return open(path, flags);

    return -1;
}
void
zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
    char *pathname, size_t len)
{
	zfs_cmd_t zc = { 0 };
	boolean_t mounted = B_FALSE;
	char *mntpnt = NULL;
	char dsname[MAXNAMELEN];

	if (dsobj == 0) {
		/* special case for the MOS */
		(void) snprintf(pathname, len, "<metadata>:<0x%llx>", obj);
		return;
	}

	/* get the dataset's name */
	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
	zc.zc_obj = dsobj;
	if (ioctl(zhp->zpool_hdl->libzfs_fd,
	    ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
		/* just write out a path of two object numbers */
		(void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
		    dsobj, obj);
		return;
	}
	(void) strlcpy(dsname, zc.zc_value, sizeof (dsname));

	/* find out if the dataset is mounted */
	mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt);

	/* get the corrupted object's path */
	(void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
	zc.zc_obj = obj;
	if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH,
	    &zc) == 0) {
		if (mounted) {
			(void) snprintf(pathname, len, "%s%s", mntpnt,
			    zc.zc_value);
		} else {
			(void) snprintf(pathname, len, "%s:%s",
			    dsname, zc.zc_value);
		}
	} else {
		(void) snprintf(pathname, len, "%s:<0x%llx>", dsname, obj);
	}
	free(mntpnt);
}
示例#13
0
rl_result_t
rl_roll_log(char *bdev)
{
    log_info_t		li;
    rl_result_t		rv = RL_SUCCESS;

    (void) memset((void *)&li, 0, (size_t)sizeof (li));
    if (is_mounted(&li, bdev) == RL_TRUE) {
        rv = rlflush(&li);
    } else {
        /*
         * Device appears not to be mounted.
         * We need to mount the device read only.
         * This automatically causes the log to be rolled, then we can
         * unmount the device again.  To do the mount, we need to
         * create a temporary directory, and then remove it when we
         * are done.
         */
        rv = make_mp(&li);
        switch (rv) {
        case RL_CORRUPT:
            /* corrupt mnttab - the file sys really was mounted */
            rv = rlflush(&li);
            break;
        case RL_SUCCESS:
            rv = rlmount(&li, RLM_RO);
            if (rv == RL_SUCCESS) {
                rv = rlflush(&li);
                if (umount(li.li_blkname) == SYSERR) {
                    (void) fprintf(stderr,
                                   "WARNING: rl_roll_log(): Can't unmount %s\n", li.li_blkname);
                }

            }
            break;
        }
    }
    cleanup(&li);
    return (rv);
}
示例#14
0
void bash_door( char_data* ch, exit_data* exit )
{
  if(  is_mounted( ch )
    || is_entangled( ch, "bash doors" ) )
    return;

  if( !is_set( &exit->exit_info, EX_ISDOOR ) ) {
    send( ch, "There is no door %s and you can't bash an open exit.\n\r",
      dir_table[ exit->direction ].where );
    return;
    }

  if( !is_set( &exit->exit_info, EX_CLOSED ) ) {
    send( ch, "%s isn't closed and thus no point in bashing it.\n\r",
      exit->name );
    return;
    }

  if(  exit->direction  == DIR_UP ||  exit->direction  == DIR_DOWN ) {
    send( ch, "You can't effectively bash doors in the ceiling or\
 ground.\n\r" );
    return;
    }
示例#15
0
/*
 * This is the function that actually installs one volume (usually that's
 * all there is). Upon entry, the extlist is entirely correct:
 *
 *	1. It contains only those files which are to be installed
 *	   from all volumes.
 *	2. The mode bits in the ainfo structure for each file are set
 *	   correctly in accordance with administrative defaults.
 *	3. mstat.setuid/setgid reflect what the status *was* before
 *	   pkgdbmerg() processed compliance.
 */
void
instvol(struct cfextra **extlist, char *srcinst, int part,
	int nparts, VFP_T **a_cfVfp, VFP_T **a_cfTmpVfp,
	char **r_updated, char **r_skipped,
	char *a_zoneName)
{
	FILE		*listfp;
	char		*updated = (char *)NULL;
	char		*skipped = (char *)NULL;
	char		*anyPathLocal = (char *)NULL;
	char		*relocpath = (char *)NULL;
	char		*dstp;
	char		*listfile;
	char		*srcp;
	char		*pspool_loc;
	char		scrpt_dst[PATH_MAX];
	int		count;
	int		entryidx;	/* array of current package objects */
	int		n;
	int		nc = 0;
	int		pass;		/* pass count through the for loop. */
	int		tcount;
	struct cfent	*ept;
	struct cfextra	*ext;
	struct mergstat	*mstat;
	struct reg_files *rfp = NULL;

	/*
	 * r_updated and r_skipped are optional parameters that can be passed in
	 * by the caller if the caller wants to know if any objects are either
	 * updated or skipped. Do not initialize either r_updated or r_skipped;
	 * the call to instvol could be cumulative and any previous update or
	 * skipped indication must not be disturbed - these flags are only set,
	 * they must never be reset. These flags are "char *" pointers so that
	 * the object that was skipped or updated can be displayed in debugging
	 * output.
	 */

	if (part == 1) {
		pkgvolume(&pkgdev, srcinst, part, nparts);
	}

	tcount = 0;
	nc = cl_getn();

	/*
	 * For each class in this volume, install those files.
	 *
	 * NOTE : This loop index may be decremented by code below forcing a
	 * second trip through for the same class. This happens only when a
	 * class is split between an archive and the tree. Examples would be
	 * old WOS packages and the occasional class containing dynamic
	 * libraries which require special treatment.
	 */

	if (is_depend_pkginfo_DB() == B_FALSE) {
	    int		classidx;	/* the current class */

	    for (classidx = 0; classidx < nc; classidx++) {
		int pass_relative = 0;
		int rel_init = 0;

		eocflag = count = pass = 0;
		listfp = (FILE *)0;
		listfile = NULL;

		/* Now what do we pass to the class action script */

		if (cl_pthrel(classidx) == REL_2_CAS) {
			pass_relative = 1;
		}

		for (;;) {
			if (!tcount++) {
				/* first file to install */
				if (a_zoneName == (char *)NULL) {
					echo(MSG_INS_N_N, part, nparts);
				} else {
					echo(MSG_INS_N_N_LZ, part, nparts,
						a_zoneName);
				}
			}

			/*
			 * If there's an install class action script and no
			 * list file has been created yet, create that file
			 * and provide the pointer in listfp.
			 */
			if (cl_iscript(classidx) && !listfp) {
				/* create list file */
				putparam("TMPDIR", tmpdir);
				listfile = tempnam(tmpdir, "list");
				if ((listfp = fopen(listfile, "w")) == NULL) {
					progerr(ERR_WTMPFILE, listfile);
					quit(99);
				}
			}

			/*
			 * The following function goes through the package
			 * object list returning the array index of the next
			 * regular file. If it encounters a directory,
			 * symlink, named pipe or device, it just creates it.
			 */

			entryidx = domerg(extlist, (pass++ ? 0 : part), nparts,
				classidx, &srcp, &dstp, &updated, &skipped,
				&anyPathLocal);

			/* Evaluate the return code */
			if (entryidx == DMRG_DONE) {
				/*
				 * Set ept to the first entry in extlist
				 * which is guaranteed to exist so
				 * later checks against ept->ftype are
				 * not compared to NULL.
				 */
				ext = extlist[0];
				ept = &(ext->cf_ent);
				break; /* no more entries to process */
			}

			ext = extlist[entryidx];
			ept = &(ext->cf_ent);
			mstat = &(ext->mstat);

			/*
			 * If not installing from a partially spooled package
			 * (the "save/pspool" area), and the file contents can
			 * be changed (type is 'e' or 'v'), and the class is not
			 * "none": copy the file from the package (in pristine
			 * state with no actions performed) into the appropriate
			 * location in the packages destination "save/pspool"
			 * area.
			 */

			if ((!is_partial_inst()) &&
				((ept->ftype == 'e') || (ept->ftype == 'v')) &&
				(strcmp(ept->pkg_class, "none") != 0)) {

				if (absolutepath(ext->map_path) == B_TRUE &&
					parametricpath(ext->cf_ent.ainfo.local,
						&relocpath) == B_FALSE) {
					pspool_loc = ROOT;
				} else {
					pspool_loc = RELOC;
				}

				n = snprintf(scrpt_dst, PATH_MAX, "%s/%s/%s",
					saveSpoolInstallDir, pspool_loc,
					relocpath ? relocpath : ext->map_path);

				if (n >= PATH_MAX) {
					progerr(ERR_CREATE_PATH_2,
						saveSpoolInstallDir,
						ext->map_path);
					quit(99);
				}

				/* copy, preserve source file mode */

				if (cppath(MODE_SRC, srcp, scrpt_dst, 0644)) {
					warnflag++;
				}
			}

			/*
			 * If this isn't writeable anyway, it's not going
			 * into the list file. Only count it if it's going
			 * into the list file.
			 */
			if (is_fs_writeable(ext->cf_ent.path,
				&(ext->fsys_value)))
				count++;

			pkgvolume(&pkgdev, srcinst, part, nparts);

			/*
			 * If source verification is OK for this class, make
			 * sure the source we're passing to the class action
			 * script is useable.
			 */
			if (cl_svfy(classidx) != NOVERIFY) {
				if (cl_iscript(classidx) ||
					((ept->ftype == 'e') ||
					(ept->ftype == 'n'))) {
					if (ck_efile(srcp, ept)) {
						progerr(ERR_CORRUPT,
							srcp);
						logerr(getErrbufAddr());
						warnflag++;
						continue;
					}
				}
			}

			/*
			 * If there's a class action script for this class,
			 * just collect names in a temporary file
			 * that will be used as the stdin when the
			 * class action script is invoked.
			 */

			if ((cl_iscript(classidx)) &&
					((is_fs_writeable(ept->path,
						&(ext->fsys_value))))) {
				if (pass_relative) {
					if (!rel_init) {
						(void) fputs(instdir, listfp);
						(void) putc('\n', listfp);
						rel_init++;
					}
					(void) fputs(ext->map_path, listfp);
					(void) putc('\n', listfp);
				} else {
					(void) fputs(srcp ?
						srcp : "/dev/null", listfp);
					(void) putc(' ', listfp);
					(void) fputs(dstp, listfp);
					(void) putc('\n', listfp);
				}
				/*
				 * Note which entries in extlist are regular
				 * files to be installed via the class action
				 * script.
				 */
				if (regfiles_head == NULL) {
					assert(rfp == NULL);
					regfiles_head =
					    malloc(sizeof (struct reg_files));
					if (regfiles_head == NULL) {
						progerr(ERR_MEMORY, errno);
						quit(99);
					}
					regfiles_head->next = NULL;
					regfiles_head->val = entryidx;
					rfp = regfiles_head;
				} else {
					assert(rfp != NULL);
					rfp->next =
					    malloc(sizeof (struct reg_files));
					if (rfp->next == NULL) {
						progerr(ERR_MEMORY, errno);
						quit(99);
					}
					rfp = rfp->next;
					rfp->next = NULL;
					rfp->val = entryidx;
				}

				/*
				 * A warning message about unwritable targets
				 * in a class may be appropriate here.
				 */
				continue;
			}

			/*
			 * If not installing from a partially spooled package
			 * (the "save/pspool" area), and the file contents can
			 * be changed (type is 'e' or 'v') and the class
			 * identifier is not "none": copy the file from the
			 * package (in pristine state with no actions performed)
			 * into the appropriate location in the packages
			 * destination "save/pspool" area.
			 */

			if ((!is_partial_inst()) &&
			    ((ept->ftype == 'e') || (ept->ftype == 'v') &&
			    (strcmp(ept->pkg_class, "none") != 0))) {

				if (absolutepath(ext->map_path) == B_TRUE &&
					parametricpath(ext->cf_ent.ainfo.local,
						&relocpath) == B_FALSE) {
					pspool_loc = ROOT;
				} else {
					pspool_loc = RELOC;
				}

				n = snprintf(scrpt_dst, PATH_MAX, "%s/%s/%s",
					saveSpoolInstallDir, pspool_loc,
					relocpath ? relocpath : ext->map_path);

				if (n >= PATH_MAX) {
					progerr(ERR_CREATE_PATH_2,
						saveSpoolInstallDir,
						ext->map_path);
					quit(99);
				}

				/* copy, preserve source file mode */

				if (cppath(MODE_SRC, srcp, scrpt_dst, 0644)) {
					warnflag++;
				}
			}

			/*
			 * There are several tests here to determine
			 * how we're going to deal with objects
			 * intended for remote read-only filesystems.
			 * We don't use is_served() because this may be
			 * a server. We're actually interested in if
			 * it's *really* remote and *really* not
			 * writeable.
			 */

			n = is_remote_fs(ept->path, &(ext->fsys_value));
			if ((n != 0) &&
				!is_fs_writeable(ept->path,
				&(ext->fsys_value))) {

				/*
				 * Don't change the file, we can't write
				 * to it anyway.
				 */

				mstat->attrchg = 0;
				mstat->contchg = 0;

				/*
				 * If it's currently mounted, we can
				 * at least test it for existence.
				 */

				if (is_mounted(ept->path, &(ext->fsys_value))) {
					if (!isfile(NULL, dstp)) {
						echo(MSG_IS_PRESENT, dstp);
					} else {
						echo(WRN_INSTVOL_NONE, dstp);
					}
				} else {
					char *server_host;

					server_host = get_server_host(
						ext->fsys_value);

					/* If not, we're just stuck. */
					echo(WRN_INSTVOL_NOVERIFY,
						dstp, server_host);
				}

				continue;
			}

			/* echo output destination name */

			echo("%s", dstp);

			/*
			 * if no source then no need to copy/verify
			 */

			if (srcp == (char *)NULL) {
				continue;
			}

			/*
			 * If doing a partial installation (creating a
			 * non-global zone), extra steps need to be taken:
			 *
			 * 1) if the file is not type 'e' and not type 'v' and
			 * the class is "none": then the file must already
			 * exist (as a result of the initial non-global zone
			 * installation which caused all non-e/v files to be
			 * copied from the global zone to the non-global
			 * zone). If this is the case, verify that the file
			 * exists and has the correct attributes.
			 *
			 * 2) if the file is not type 'e' and not type 'v'
			 * and the class is NOT "none", *OR* if the file is
			 * type 'e' or type 'v': then check to see if the
			 * file is located in an area inherited from the
			 * global zone. If so, then there is no ability to
			 * change the file since inherited file systems are
			 * "read only" - just verify that the file exists and
			 * verify attributes only if not 'e' or 'v'.
			 */

			if (is_partial_inst() != 0) {

				/*
				 * determine if the destination package is in an
				 * area inherited from the global zone
				 */

				n = pkgMatchInherited(srcp, dstp,
					get_inst_root(), ept->ainfo.mode,
					ept->cinfo.modtime, ept->ftype,
					ept->cinfo.cksum);

				echoDebug(DBG_INSTVOL_PARTIAL_INST,
					srcp ? srcp : "", dstp ? dstp: "",
					((get_inst_root()) &&
					(strcmp(get_inst_root(), "/") != 0)) ?
					get_inst_root() : "",
					ept->ainfo.mode, ept->cinfo.modtime,
					ept->ftype, ept->cinfo.cksum, n);

				/*
				 * if not type 'e|v' and class 'none', then the
				 * file must already exist.
				 */

				if ((ept->ftype != 'e') &&
					(ept->ftype != 'v') &&
					(strcmp(cl_nam(ept->pkg_class_idx),
								"none") == 0)) {

					/*
					 * if the file is in a space inherited
					 * from the global zone, and if the
					 * contents or attributes are incorrect,
					 * then generate a warning that the
					 * global zone file contents and/or file
					 * attributes have been modified and
					 * that the modifications are extended
					 * to the non-global zone (inherited
					 * from the global zone).
					 */

					if (n == 0) {
						/* is file changed? */
						n = finalck(ept, 1, 1, B_TRUE);

						/* no - ok - continue */
						if (n == 0) {
							continue;
						}

						/* output warning message */
						logerr(NOTE_INSTVOL_FINALCKFAIL,
							pkginst, ext->map_path,
							a_zoneName, ept->path);
						continue;
					} else if (!finalck(ept, 1, 1,
								B_FALSE)) {
						/*
						 * non-e/v file of class "none"
						 * not inherited from the global
						 * zone: verify file already
						 * exists:everything checks here
						 */
						mstat->attrchg = 0;
						mstat->contchg = 0;
					}
					continue;
				}

				/*
				 * non-e/v file with class action script, or
				 * e/v file: if the file is in an area inherited
				 * from the global zone, then no need (or the
				 * ability) to update just accept the file as is
				 */

				if (n == B_TRUE) {
					/*
					 * the object is in an area inherited
					 * from the global zone and the objects
					 * attributes are verified
					 */

					mstat->attrchg = 0;
					mstat->contchg = 0;

					/* NOTE: package object skipped */

					if (skipped == (char *)NULL) {
						skipped = dstp;
					echoDebug(DBG_INSTVOL_OBJ_SKIPPED,
								skipped);
					}
					continue;
				}
			}

			/*
			 * Copy from source media to target path and fix file
			 * mode and permission now in case installation halted.
			 */

			if (z_path_is_inherited(dstp, ept->ftype,
						get_inst_root()) == B_FALSE) {
				n = cppath(MODE_SET|DIR_DISPLAY, srcp, dstp,
						ept->ainfo.mode);
				if (n != 0) {
					warnflag++;
				} else if (!finalck(ept, 1, 1, B_FALSE)) {
					/*
					 * everything checks here
					 */
					mstat->attrchg = 0;
					mstat->contchg = 0;
				}
			}

			/* NOTE: a package object was updated */

			if (updated == (char *)NULL) {
				echoDebug(DBG_INSTVOL_OBJ_UPDATED, dstp);
				updated = dstp;
			}
		}

		/*
		 * We have now completed processing of all pathnames
		 * associated with this volume and class.
		 */
		if (cl_iscript(classidx)) {
			/*
			 * Execute appropriate class action script
			 * with list of source/destination pathnames
			 * as the input to the script.
			 */

			if (chdir(pkgbin)) {
				progerr(ERR_CHGDIR, pkgbin);
				quit(99);
			}

			if (listfp) {
				(void) fclose(listfp);
			}

			/*
			 * if the object associated with the class action script
			 * is in an area inherited from the global zone, then
			 * there is no need to run the class action script -
			 * assume that anything the script would do has already
			 * been done in the area shared from the global zone.
			 */

			/* nothing updated, nothing skipped */

			echoDebug(DBG_INSTVOL_CAS_INFO, is_partial_inst(),
				updated ? updated : "",
				skipped ? skipped : "",
				anyPathLocal ? anyPathLocal : "");

			if ((is_partial_inst() != 0) &&
					(updated == (char *)NULL) &&
					(anyPathLocal == (char *)NULL)) {

				/*
				 * installing in non-global zone, and no object
				 * has been updated (installed/verified in non-
				 * inherited area), and no path delivered by the
				 * package is in an area not inherited from the
				 * global zone (all paths delivered are in
				 * areas inherited from the global zone): do not
				 * run the class action script because the only
				 * affected areas are inherited (read only).
				 */

				echoDebug(DBG_INSTVOL_NOT_RUNNING_CAS,
					a_zoneName ? a_zoneName : "?",
					eocflag ? "ENDOFCLASS" :
							cl_iscript(classidx),
					cl_nam(classidx),
					cl_iscript(classidx));

				if ((r_skipped != (char **)NULL) &&
					(*r_skipped == (char *)NULL) &&
					(skipped == (char *)NULL)) {
					skipped = "postinstall";
					echoDebug(DBG_INSTVOL_OBJ_SKIPPED,
								skipped);
				}
			} else {
				/* run the class action script */

				echoDebug(DBG_INSTVOL_RUNNING_CAS,
					a_zoneName ? a_zoneName : "?",
					eocflag ? "ENDOFCLASS" :
							cl_iscript(classidx),
					cl_nam(classidx),
					cl_iscript(classidx));

				/* Use ULIMIT if supplied. */
				set_ulimit(cl_iscript(classidx), ERR_CASFAIL);

				if (eocflag) {
					/*
					 * end of class detected.
					 * Since there are no more volumes which
					 * contain pathnames associated with
					 * this class, execute class action
					 * script with the ENDOFCLASS argument;
					 * we do this even if none of the path
					 * names associated with this class and
					 * volume needed installation to
					 * guarantee the class action script is
					 * executed at least once during package
					 * installation.
					 */
					if (pkgverbose) {
						n = pkgexecl((listfp ?
							listfile : CAS_STDIN),
							CAS_STDOUT,
							CAS_USER, CAS_GRP,
							SHELL, "-x",
							cl_iscript(classidx),
							"ENDOFCLASS", NULL);
					} else {
						n = pkgexecl(
							(listfp ?
							listfile : CAS_STDIN),
							CAS_STDOUT, CAS_USER,
							CAS_GRP, SHELL,
							cl_iscript(classidx),
							"ENDOFCLASS", NULL);
					}
					ckreturn(n, ERR_CASFAIL);
				} else if (count) {
					/* execute class action script */
					if (pkgverbose) {
						n = pkgexecl(listfile,
							CAS_STDOUT, CAS_USER,
							CAS_GRP, SHELL, "-x",
							cl_iscript(classidx),
							NULL);
					} else {
						n = pkgexecl(listfile,
							CAS_STDOUT, CAS_USER,
							CAS_GRP, SHELL,
							cl_iscript(classidx),
							NULL);
					}
					ckreturn(n, ERR_CASFAIL);
				}

				/*
				 * Ensure the mod times on disk match those
				 * in the pkgmap. In this case, call cverify
				 * with checksumming disabled, since the only
				 * action that needs to be done is to verify
				 * that the attributes are correct.
				 */

				if ((rfp = regfiles_head) != NULL) {
					while (rfp != NULL) {
					    ept = &(extlist[rfp->val]->cf_ent);
					    cverify(1, &ept->ftype, ept->path,
						&ept->cinfo, 0);
					    rfp = rfp->next;
					}
					regfiles_free();
				}

				clr_ulimit();

				if ((r_updated != (char **)NULL) &&
					(*r_updated == (char *)NULL) &&
					(updated == (char *)NULL)) {
					updated = "postinstall";
					echoDebug(DBG_INSTVOL_OBJ_UPDATED,
								updated);
				}
			}
			if (listfile) {
				(void) remove(listfile);
			}
		}

		if (eocflag && (!is_partial_inst() || (is_partial_inst() &&
			strcmp(cl_nam(classidx), "none") != 0))) {
			if (cl_dvfy(classidx) == QKVERIFY && !repl_permitted) {
				/*
				 * The quick verify just fixes everything.
				 * If it returns 0, all is well. If it
				 * returns 1, then the class installation
				 * was incomplete and we retry on the
				 * stuff that failed in the conventional
				 * way (without a CAS). this is primarily
				 * to accomodate old archives such as are
				 * found in pre-2.5 WOS; but, it is also
				 * used when a critical dynamic library
				 * is not archived with its class.
				 */
				if (!fix_attributes(extlist, classidx)) {
					/*
					 * Reset the CAS pointer. If the
					 * function returns 0 then there
					 * was no script there in the first
					 * place and we'll just have to
					 * call this a miss.
					 */
					if (cl_deliscript(classidx))
						/*
						 * Decrement classidx for
						 * next pass.
						 */
						classidx--;
				}
			} else {
				/*
				 * Finalize merge. This checks to make sure
				 * file attributes are correct and any links
				 * specified are created.
				 */
				(void) endofclass(extlist, classidx,
					(cl_iscript(classidx) ? 0 : 1),
					a_cfVfp, a_cfTmpVfp);
			}
		}
	    }
	}

	/*
	 * Instead of creating links back to the GZ files the logic is
	 * to let zdo recreate the files from the GZ then invoke pkgadd to
	 * install the editable files and skip over any 'f'type files.
	 * The commented out block is to create the links which should be
	 * removed once the current code is tested to be correct.
	 */

	/*
	 * Go through extlist creating links for 'f'type files
	 * if we're in a global zone. Note that this code lies
	 * here instead of in the main loop to support CAF packages.
	 * In a CAF package the files are installed by the i.none script
	 * and don't exist until all files are done being processed, thus
	 * the additional loop through extlist.
	 */

	/*
	 * output appropriate completion message
	 */

	if (is_depend_pkginfo_DB() == B_TRUE) {
		/* updating database only (hollow package) */
		if (a_zoneName == (char *)NULL) {
			echo(MSG_DBUPD_N_N, part, nparts);
		} else {
			echo(MSG_DBUPD_N_N_LZ, part, nparts, a_zoneName);
		}
	} else if (tcount == 0) {
		/* updating package (non-hollow package) */
		if (a_zoneName == (char *)NULL) {
			echo(MSG_INST_N_N, part, nparts);
		} else {
			echo(MSG_INST_N_N_LZ, part, nparts, a_zoneName);
		}
	}

	/*
	 * if any package objects were updated (not inherited from the
	 * global zone or otherwise already in existence), set the updated
	 * flag as appropriate
	 */

	if (updated != (char *)NULL) {
		echoDebug(DBG_INSTVOL_OBJ_UPDATED, updated);
		if (r_updated != (char **)NULL) {
			*r_updated = updated;
		}
	}

	/*
	 * if any package objects were skipped (verified inherited from the
	 * global zone), set the skipped flag as appropriate
	 */

	if (skipped != (char *)NULL) {
		echoDebug(DBG_INSTVOL_OBJ_SKIPPED, skipped);
		if (r_skipped != (char **)NULL) {
			*r_skipped = skipped;
		}
	}
}
示例#16
0
rl_result_t
rl_log_control(char *bdev, int request)
{
    log_info_t	li;
    rl_result_t	rv = RL_SUCCESS;
    rl_result_t	alreadymounted;
    int		fd;
    fiolog_t	fl;
    int		logenabled = 0;

    if ((request != _FIOLOGENABLE) && (request != _FIOLOGDISABLE))
        return (RL_FAIL);

    (void) memset((void *)&li, '\0', (size_t)sizeof (li));
    if ((alreadymounted = is_mounted(&li, bdev)) != RL_TRUE) {
        /*
         * Device is not mounted. Need to mount it rw to allow
         * the log to be enabled/disabled. To do the mount, we need
         * to create a temporary directory, and then remove it when
         * we are done.
         */
        if (make_mp(&li) != RL_SUCCESS) {
            cleanup(&li);
            return (RL_FAIL);
        }
        if (rlmount(&li, RLM_RW) != RL_SUCCESS) {
            cleanup(&li);
            return (RL_FAIL);
        }
    }

    if (alreadymounted == RL_TRUE)
        fd = open(li.li_mntpoint, O_RDONLY);
    else
        fd = open(li.li_tmpmp, O_RDONLY);
    if (fd == SYSERR) {
        perror("open");
        rv = RL_SYSERR;
        goto out;
    }

    fl.nbytes_requested = 0;
    fl.nbytes_actual = 0;
    fl.error = FIOLOG_ENONE;

    if (ioctl(fd, request, &fl) == SYSERR) {
        perror("ioctl");
        (void) close(fd);
        rv = RL_SYSERR;
        goto out;
    }
    if (ioctl(fd, _FIOISLOG, &logenabled) == SYSERR) {
        perror("ioctl");
        (void) close(fd);
        rv = RL_SYSERR;
        goto out;
    }
    if (((request == _FIOLOGENABLE) && (!logenabled)) ||
            ((request == _FIOLOGDISABLE) && logenabled))
        rv = RL_FAIL;

    (void) close(fd);
out:
    if (alreadymounted != RL_TRUE)
        (void) rlumount(&li);
    cleanup(&li);
    return (rv);
}
示例#17
0
文件: discofs.c 项目: laevar/discofs
/*! Main
@param argc number of arguments
@param argv arguments
 @return fuse_main()s return value
*/
int main(int argc, char **argv)
{
    /* return value of fuse_main() */
    int ret;

    /* for signal handling */
    struct sigaction sig;

    /* argument handling */
    struct fuse_args args = FUSE_ARGS_INIT(argc, argv);

    /* file name for database */
    char *db_file;


    /*------------------------*
     * install signal handler *
     *------------------------*/

    /* set handling function */
    sig.sa_handler = sig_handler;

    /* set (no) flags */
    sig.sa_flags = 0;

    /* don't ignore any signal */
    sigemptyset(&sig.sa_mask);

    /* install signal handler for USR1 and USR2 */
    sigaction(SIGUSR1, &sig, NULL);
    sigaction(SIGUSR2, &sig, NULL);


    /*------------------*
     * handle arguments *
     *------------------*/

    if (fuse_opt_parse(&args, &discofs_options, discofs_opts, discofs_opt_proc) == -1)
        return EXIT_FAILURE;

    /* after option parsing, remote mount point must be set */
    if (!REMOTE_ROOT)
    {
        fprintf(stderr, "no remote filesystem given\n");
        return EXIT_FAILURE;
    }

    /* a mount point for discofs must also be set */
    if (!discofs_options.discofs_mp)
    {
        fprintf(stderr, "no mount point given\n");
        return EXIT_FAILURE;
    }

    /* add "use_ino" to display inodes in stat(1)*/
    fuse_opt_add_arg(&args, "-ouse_ino");


    /*---------------*
     * set UID / GID *
     *---------------*/

    /* set GID first since permissions might not be
       sufficient if UID was set beforehand */
    if (discofs_options.gid)
    {
        VERBOSE("setting gid to %d\n", discofs_options.gid);
        if (setgid(discofs_options.gid))
        {
            perror("setting gid");
            return EXIT_FAILURE;
        }
    }
    if (discofs_options.uid)
    {
        VERBOSE("setting uid to %d\n", discofs_options.uid);
        if (setuid(discofs_options.uid))
        {
            perror("setting uid");
            return EXIT_FAILURE;
        }
    }


    /*--------------------*
     * initialize logging *
     *--------------------*/

    /* if -d is specified, override logging settings */
    if (discofs_options.debug)
        log_init(LOG_DEBUG, NULL);
    else
        log_init(discofs_options.loglevel, discofs_options.logfile);



    /*=========================*
     * INITIALIZE CACHE AND DB *
     *=========================*/

    /* compute data root if not passed as option */
    if (!discofs_options.data_root)
        discofs_options.data_root = paths_data_root(REMOTE_ROOT);

    if (!is_dir(discofs_options.data_root))
    {
        if (mkdir_rec(discofs_options.data_root))
            FATAL("failed to create data directory %s\n", discofs_options.data_root);
    }


    /*----------------------*
     * initialize cache dir *
     *----------------------*/

    /* set cache dir */
    CACHE_ROOT = join_path(discofs_options.data_root, "cache");

    /* store length of cache root (to save a few hundred strlen() calls)  */
    CACHE_ROOT_LEN = strlen(CACHE_ROOT);

    /* delete cache if "clear" specified */
    if (discofs_options.clear)
    {
        VERBOSE("deleting cache\n");
        rmdir_rec(CACHE_ROOT);
    }

    /* create cache root if needed */
    if (!is_dir(CACHE_ROOT))
    {
        if (mkdir(CACHE_ROOT, S_IRWXU) != 0)
            FATAL("failed to create cache directory %s\n", CACHE_ROOT);
    }


    /*---------------------*
     * initialize database *
     *---------------------*/

    /* set db filename */
    db_file = join_path(discofs_options.data_root, "db.sqlite");

    /* create database file if it doesn't exist  */
    int fd = open(db_file, (O_RDONLY | O_CREAT), (S_IRUSR | S_IWUSR));
    if (fd == -1)
    {
        perror(db_file);
        FATAL("couldn't open or create database file\n");
    }
    close(fd);

    /* initialize tables etc */
    db_init(db_file, discofs_options.clear);

    /* try to load filesystem features from DB */
    if (db_cfg_get_int(CFG_FS_FEATURES, &discofs_options.fs_features))
    {

        /* if loading failed, try to determine them */
        if (is_mounted(REMOTE_ROOT) && is_reachable(discofs_options.host))
        {
            if (test_fs_features(&discofs_options.fs_features))
            {
                ERROR("failed to test remote fs features\n");
                discofs_options.fs_features = 0;
            }
            /* test succeeded, store value for next time */
            else
                db_cfg_set_int(CFG_FS_FEATURES, discofs_options.fs_features);
        }
        /* nag and assume that no features available (but don't save that) */
        else
        {
            ERROR("could not determine remote fs features");
            discofs_options.fs_features = 0;
        }
    }


    /*------------------*
     * initialize stuff *
     *------------------*/
    #define INIT(name)                          \
        if (name ## _init())                    \
            FATAL("error initializing " #name)
    INIT(lock);
    INIT(sync);
    INIT(job);
    #undef INIT


    /*----------------------*
     * print options to log *
     *----------------------*/
    log_options(LOG_VERBOSE, discofs_options);


    /*-----------------*
     * run fuse_main() *
     *-----------------*/
    ret = fuse_main(args.argc, args.argv, &discofs_oper, NULL);


    /*------*
     * exit *
     *------*/

    lock_destroy();
    sync_destroy();
    job_destroy();

    /* free arguments */
    fuse_opt_free_args(&args);

    /* close database connection */
    db_destroy();


    /* end logging */
    INFO("exiting\n");
    log_destroy();


    /* return fuse_main()s return value */
    return ret;
}
示例#18
0
int 
main (int argc, char *argv[])
{
	char *udi;
	char *device_file, *raw_device_file;
	LibHalContext *ctx = NULL;
	DBusError error;
	char *bus;
	char *drive_type;
	int state, last_state;
	char *support_media_changed_str;
	int support_media_changed;
	int fd = -1;

	if ((udi = getenv ("UDI")) == NULL)
		goto out;
	if ((device_file = getenv ("HAL_PROP_BLOCK_DEVICE")) == NULL)
		goto out;
	if ((raw_device_file = getenv ("HAL_PROP_BLOCK_SOLARIS_RAW_DEVICE")) == NULL)
		goto out;
	if ((bus = getenv ("HAL_PROP_STORAGE_BUS")) == NULL)
		goto out;
	if ((drive_type = getenv ("HAL_PROP_STORAGE_DRIVE_TYPE")) == NULL)
		goto out;

	drop_privileges ();

	setup_logger ();

	support_media_changed_str = getenv ("HAL_PROP_STORAGE_CDROM_SUPPORT_MEDIA_CHANGED");
	if (support_media_changed_str != NULL && strcmp (support_media_changed_str, "true") == 0)
		support_media_changed = TRUE;
	else
		support_media_changed = FALSE;

	dbus_error_init (&error);

	if ((ctx = libhal_ctx_init_direct (&error)) == NULL) {
		goto out;
	}
	my_dbus_error_free (&error);

	if (!libhal_device_addon_is_ready (ctx, udi, &error)) {
		goto out;
	}
	my_dbus_error_free (&error);

	printf ("Doing addon-storage for %s (bus %s) (drive_type %s) (udi %s)\n", device_file, bus, drive_type, udi);

	last_state = state = DKIO_NONE;

	/* Linux version of this addon attempts to re-open the device O_EXCL
	 * every 2 seconds, trying to figure out if some other app,
	 * like a cd burner, is using the device. Aside from questionable
	 * value of this (apps should use HAL's locked property or/and
	 * Solaris in_use facility), but also frequent opens/closes
	 * keeps media constantly spun up. All this needs more thought.
	 */
	for (;;) {
		if (is_mounted (device_file)) {
			close_device (&fd);
			sleep (SLEEP_PERIOD);
		} else if ((fd < 0) && ((fd = open (raw_device_file, O_RDONLY | O_NONBLOCK)) < 0)) {
			HAL_DEBUG (("open failed for %s: %s", raw_device_file, strerror (errno)));
			sleep (SLEEP_PERIOD);
		} else {
			/* Check if a disc is in the drive */
			/* XXX initial call always returns inserted
			 * causing unnecessary rescan - optimize?
			 */
			if (ioctl (fd, DKIOCSTATE, &state) == 0) {
				if (state == last_state) {
					HAL_DEBUG (("state has not changed %d %s", state, device_file));
					continue;
				} else {
					HAL_DEBUG (("new state %d %s", state, device_file));
				}

				switch (state) {
				case DKIO_EJECTED:
					HAL_DEBUG (("Media removal detected on %s", device_file));
					last_state = state;

					libhal_device_set_property_bool (ctx, udi, "storage.removable.media_available", FALSE, &error);
					my_dbus_error_free (&error);

					/* attempt to unmount all childs */
					unmount_childs (ctx, udi);

					/* could have a fs on the main block device; do a rescan to remove it */
					libhal_device_rescan (ctx, udi, &error);
					my_dbus_error_free (&error);
					break;

				case DKIO_INSERTED:
					HAL_DEBUG (("Media insertion detected on %s", device_file));
					last_state = state;

					libhal_device_set_property_bool (ctx, udi, "storage.removable.media_available", TRUE, &error);
					my_dbus_error_free (&error);

					/* could have a fs on the main block device; do a rescan to add it */
					libhal_device_rescan (ctx, udi, &error);
					my_dbus_error_free (&error);
					break;

				case DKIO_DEV_GONE:
					HAL_DEBUG (("Device gone detected on %s", device_file));
					last_state = state;

					unmount_childs (ctx, udi);
					close_device (&fd);
					goto out;

				case DKIO_NONE:
				default:
					break;
				}
			} else {
				HAL_DEBUG (("DKIOCSTATE failed: %s\n", strerror(errno)));
				sleep (SLEEP_PERIOD);
			}
		}
	}

out:
	if (ctx != NULL) {
		my_dbus_error_free (&error);
		libhal_ctx_shutdown (ctx, &error);
		libhal_ctx_free (ctx);
	}

	return 0;
}
示例#19
0
文件: bdpoll.c 项目: Audioniek/apps
static bool poll_for_media(const char device_file[], bool is_cdrom, bool support_media_changed)
{
	int fd;
	bool got_media = false;
	bool ret = false;

	if (is_cdrom)
	{
		int drive;

		fd = open(device_file, O_RDONLY | O_NONBLOCK | O_EXCL);
		if (fd < 0 && errno == EBUSY)
		{
			/* this means the disc is mounted or some other app,
			 * like a cd burner, has already opened O_EXCL */

			/* HOWEVER, when starting hald, a disc may be
			 * mounted; so check /etc/mtab to see if it
			 * actually is mounted. If it is we retry to open
			 * without O_EXCL
			 */
			if (!is_mounted(device_file))
				return false;
			fd = open(device_file, O_RDONLY | O_NONBLOCK);
		}
		if (fd < 0)
		{
			err("%s: %s", device_file, strerror(errno));
			return false;
		}

		/* Check if a disc is in the drive
		 *
		 * @todo Use MMC-2 API if applicable
		 */
		drive = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
		switch (drive)
		{
			case CDS_NO_INFO:
			case CDS_NO_DISC:
			case CDS_TRAY_OPEN:
			case CDS_DRIVE_NOT_READY:
				break;

			case CDS_DISC_OK:
				/* some CD-ROMs report CDS_DISK_OK even with an open
				 * tray; if media check has the same value two times in
				 * a row then this seems to be the case and we must not
				 * report that there is a media in it. */
				if (support_media_changed &&
						ioctl(fd, CDROM_MEDIA_CHANGED, CDSL_CURRENT) &&
						ioctl(fd, CDROM_MEDIA_CHANGED, CDSL_CURRENT))
				{
				}
				else
				{
					got_media = true;
				}
				break;

			case -1:
				err("%s: CDROM_DRIVE_STATUS: %s", device_file, strerror(errno));
				break;
		}

		close(fd);
	}
	else
	{
		fd = open(device_file, O_RDONLY);
		if ((fd < 0) && (errno == ENOMEDIUM))
		{
			got_media = false;
		}
		else if (fd >= 0)
		{
			got_media = true;
		}
		else
		{
			err("%s: %s", device_file, strerror(errno));
			return false;
		}
	}

	switch (media_status)
	{
		case MEDIA_STATUS_GOT_MEDIA:
			if (!got_media)
			{
				dbg("Media removal detected on %s\n", device_file);
				ret = true;
				/* have to this to trigger appropriate hotplug events */
				fd = open(device_file, O_RDONLY | O_NONBLOCK);
				if (fd >= 0)
				{
					ioctl(fd, BLKRRPART);
					close(fd);
				}
			}
			break;

		case MEDIA_STATUS_NO_MEDIA:
			if (got_media)
			{
				dbg("Media insertion detected on %s\n", device_file);
				ret = true;
			}
			break;
	}

	/* update our current status */
	if (got_media)
		media_status = MEDIA_STATUS_GOT_MEDIA;
	else
		media_status = MEDIA_STATUS_NO_MEDIA;

	return ret;
}
int main(int argc, char *argv[]) {
    char * bytes_count_str = NULL;
    char * devname;
    reiserfs_filsys_t fs;
    struct reiserfs_super_block * rs;

    int c;
    int error;

    struct reiserfs_super_block *sb_old;

    unsigned long block_count_new;

    print_banner ("resize_reiserfs");

    while ((c = getopt(argc, argv, "fvcqs:")) != EOF) {
        switch (c) {
        case 's' :
            if (!optarg)
                die("%s: Missing argument to -s option", argv[0]);
            bytes_count_str = optarg;
            break;
        case 'f':
            opt_force = 1;
            break;
        case 'v':
            opt_verbose++;
            break;
        case 'n':
            /* no nowrite option at this moment */
            /* opt_nowrite = 1; */
            break;
        case 'c':
            opt_safe = 1;
            break;
        case 'q':
            opt_verbose = 0;
            break;
        default:
            print_usage_and_exit ();
        }
    }

    if (optind == argc )
        print_usage_and_exit();
    devname = argv[optind];

    fs = reiserfs_open(devname, O_RDONLY, &error, 0);
    if (!fs)
        die ("%s: can not open '%s': %s", argv[0], devname, strerror(error));

    if (no_reiserfs_found (fs)) {
        die ("resize_reiserfs: no reiserfs found on the device");
    }
    if (!spread_bitmaps (fs)) {
        die ("resize_reiserfs: cannot resize reiserfs in old (not spread bitmap) format.\n");
    }

    rs = fs->s_rs;

    if(bytes_count_str) {	/* new fs size is specified by user */
        block_count_new = calc_new_fs_size(rs_block_count(rs), fs->s_blocksize, bytes_count_str);
    } else {		/* use whole device */
        block_count_new = count_blocks(devname, fs->s_blocksize, -1);
    }

    if (is_mounted (devname)) {
        reiserfs_close(fs);
        return resize_fs_online(devname, block_count_new);
    }

    if (rs_state(rs) != REISERFS_VALID_FS)
        die ("%s: the file system isn't in valid state\n", argv[0]);

    if(!valid_offset(fs->s_dev, (loff_t) block_count_new * fs->s_blocksize - 1))
        die ("%s: %s too small", argv[0], devname);

    sb_old = 0;		/* Needed to keep idiot compiler from issuing false warning */
    /* save SB for reporting */
    if(opt_verbose) {
        sb_old = getmem(SB_SIZE);
        memcpy(sb_old, SB_DISK_SUPER_BLOCK(fs), SB_SIZE);
    }

    if (block_count_new == SB_BLOCK_COUNT(fs))
        die ("%s: Calculated fs size is the same as the previous one.", argv[0]);

    if (block_count_new > SB_BLOCK_COUNT(fs))
        expand_fs(fs, block_count_new);
    else
        shrink_fs(fs, block_count_new);

    if(opt_verbose) {
        sb_report(rs, sb_old);
        freemem(sb_old);
    }

    set_state (rs, REISERFS_VALID_FS);
    bwrite_cond(SB_BUFFER_WITH_SB(fs));

    if (opt_verbose) {
        printf("\nSyncing..");
        fflush(stdout);
    }
    reiserfs_close (fs);
    if (opt_verbose)
        printf("done\n");

    return 0;
}
示例#21
0
int main (int argc, char ** argv)
{
    uint16_t blocksize, reclen16;
    uint32_t blocknumber32;
    int c;
    char * buf;
    int fd;
    int res;
    struct stat st;
  
    if (argc < 2) {
	printf ("Usage: gunzip -c | unpack [-s][-n] /dev/dest\n");
	return 0;
    }

    while ((c = getopt (argc, argv, "sn")) != EOF) {
	switch (c) {
	case 's': /* skip writing of unformatted nodes */
	    opt_skip_unfms = 1;
	    break;
	case 'n':
	    opt_do_not_write = 1;
	    break;
	default:
	    printf ("Usage: gunzip -c | unpack [-s] /dev/dest\n");
	    return 0;
	}
    }

    /* get file system's block size */
    read (0, &blocksize, sizeof (uint16_t));
    blocksize = ntohs (blocksize);
    fprintf (stderr, "blocksize = %d\n", blocksize);

    buf = (char *)malloc (blocksize);
    if (!buf) {
	perror ("malloc failed");
	return 1;
    }

    /* we need to skip the below:
       reiserfs: read_bitmaps: 0 blocks differ in true and cautious bitmaps
       reiserfs: read_bitmaps: 1 blocks differ in true and cautious bitmaps
    */

/*  
    read (0, buf, strlen ("reiserfs: read_bitmaps: 0 blocks differ in true and cautious bitmaps\n"));
    if (strncmp (buf, "reiserfs", strlen ("reiserfs"))) {
    fprintf (stderr, "Bad signature 1\n");
    return 1;
    }
*/
    /*  
	read (0, buf, strlen ("reiserfs: read_bitmaps: 1 blocks differ in true and cautious bitmaps\n"));
	if (strncmp (buf, "reiserfs", strlen ("reiserfs"))) {
	fprintf (stderr, "Bad signature 2\n");
	return 1;
	}*/

    if (is_mounted (argv[optind])) {
	/* check forced on clean filesystem, maybe we can rebuild it (if it is mounted read-only). Later. */
	die ("unpack: '%s' contains a mounted file system\n", argv[optind]);
    }

    if (stat (argv[optind], &st) == -1)
	die ("unpack: stat failed: %s", strerror (errno));
    if (!S_ISBLK (st.st_mode))
	die ("unpck: %s is not a block device", argv[optind]);

    fd = open (argv[optind], O_CREAT | O_RDWR);
    if (fd == -1) {
	perror ("open failed");
	return 1;
    }

    while ((res = waiting_read (0, (char *)&blocknumber32, sizeof (uint32_t))) == sizeof (uint32_t)) {
	/* read block number from stdin */
/*
  if (blocknumber32 == 0) {
  printf ("exit\n");
  exit (0);
  }
*/
	blocknumber32 = ntohl (blocknumber32);

	/* read 16 bit record length */
	if (waiting_read (0, (char *)&reclen16, sizeof (uint16_t)) != sizeof (uint16_t)) {
	    perror ("read reclen failed");
	    return 1;
	}
	reclen16 = ntohs (reclen16);

	fprintf (stderr, "%d reclen %d\n", blocknumber32, reclen16);

	/* read the record itself */
	if ((res = waiting_read (0, buf, reclen16)) != reclen16) {
	    fprintf (stderr, "read record failed (%d %d)\n", res, reclen16);
	    return 1;
	}


	/* the only one requirement to this block: does not look like
           leaf node. If you unpacked damaged partition already you
           might consider using -s to save time */
	if ((opt_skip_unfms && reclen16 == 2) || opt_do_not_write == 1)
	    continue;


	/* write to argv[1] */
	if (reiserfs_llseek (fd, (loff_t)blocknumber32 * (loff_t)blocksize, SEEK_SET) == (loff_t)-1) {
	    perror ("llseek failed");
	    return 1;
	}
	if (write (fd, buf, reclen16) != reclen16) {
	    perror ("write failed");
	    return 1;
	}
    }

    fprintf (stderr, "done\n");
    return 0;
}
示例#22
0
/* Check all file systems, using the /etc/fstab table. */
static int check_all(NOARGS)
{
	struct fs_info *fs = NULL;
	int status = EXIT_OK;
	int not_done_yet = 1;
	int passno = 1;
	int pass_done;

	if (verbose)
		fputs(_("Checking all file systems.\n"), stdout);

	/*
	 * Do an initial scan over the filesystem; mark filesystems
	 * which should be ignored as done, and resolve any "auto"
	 * filesystem types (done as a side-effect of calling ignore()).
	 */
	for (fs = filesys_info; fs; fs = fs->next) {
		if (ignore(fs))
			fs->flags |= FLAG_DONE;
	}

	/*
	 * Find and check the root filesystem.
	 */
	if (!parallel_root) {
		for (fs = filesys_info; fs; fs = fs->next) {
			if (!strcmp(fs->mountpt, "/"))
				break;
		}
		if (fs) {
			if (!skip_root && !ignore(fs) &&
			    !(ignore_mounted && is_mounted(fs->device))) {
				fsck_device(fs, 1);
				status |= wait_many(FLAG_WAIT_ALL);
				if (status > EXIT_NONDESTRUCT)
					return status;
			}
			fs->flags |= FLAG_DONE;
		}
	}
	/*
	 * This is for the bone-headed user who enters the root
	 * filesystem twice.  Skip root will skep all root entries.
	 */
	if (skip_root)
		for (fs = filesys_info; fs; fs = fs->next)
			if (!strcmp(fs->mountpt, "/"))
				fs->flags |= FLAG_DONE;

	while (not_done_yet) {
		not_done_yet = 0;
		pass_done = 1;

		for (fs = filesys_info; fs; fs = fs->next) {
			if (cancel_requested)
				break;
			if (fs->flags & FLAG_DONE)
				continue;
			/*
			 * If the filesystem's pass number is higher
			 * than the current pass number, then we don't
			 * do it yet.
			 */
			if (fs->passno > passno) {
				not_done_yet++;
				continue;
			}
			if (ignore_mounted && is_mounted(fs->device)) {
				fs->flags |= FLAG_DONE;
				continue;
			}
			/*
			 * If a filesystem on a particular device has
			 * already been spawned, then we need to defer
			 * this to another pass.
			 */
			if (device_already_active(fs->device)) {
				pass_done = 0;
				continue;
			}
			/*
			 * Spawn off the fsck process
			 */
			fsck_device(fs, serialize);
			fs->flags |= FLAG_DONE;

			/*
			 * Only do one filesystem at a time, or if we
			 * have a limit on the number of fsck's extant
			 * at one time, apply that limit.
			 */
			if (serialize ||
			    (max_running && (num_running >= max_running))) {
				pass_done = 0;
				break;
			}
		}
		if (cancel_requested)
			break;
		if (verbose > 1)
			printf(_("--waiting-- (pass %d)\n"), passno);
		status |= wait_many(pass_done ? FLAG_WAIT_ALL :
				    FLAG_WAIT_ATLEAST_ONE);
		if (pass_done) {
			if (verbose > 1)
				printf("----------------------------------\n");
			passno++;
		} else
			not_done_yet++;
	}
	if (cancel_requested && !kill_sent) {
		kill_all(SIGTERM);
		kill_sent++;
	}
	status |= wait_many(FLAG_WAIT_ATLEAST_ONE);
	return status;
}
示例#23
0
int main(int argc, char *argv[])
{
	int i, status = 0;
	int interactive = 0;
	char *oldpath = getenv("PATH");
	const char *fstab;
	struct fs_info *fs;

	setvbuf(stdout, NULL, _IONBF, BUFSIZ);
	setvbuf(stderr, NULL, _IONBF, BUFSIZ);

#ifdef ENABLE_NLS
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");
	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
	textdomain(NLS_CAT_NAME);
#endif
	blkid_get_cache(&cache, NULL);
	PRS(argc, argv);

	if (!notitle)
		printf("fsck %s (%s)\n", E2FSPROGS_VERSION, E2FSPROGS_DATE);

	fstab = getenv("FSTAB_FILE");
	if (!fstab)
		fstab = _PATH_MNTTAB;
	load_fs_info(fstab);

	/* Update our search path to include uncommon directories. */
	if (oldpath) {
		fsck_path = malloc (strlen (fsck_prefix_path) + 1 +
				    strlen (oldpath) + 1);
		if (!fsck_path) {
			fprintf(stderr, "%s: Unable to allocate memory for fsck_path\n", progname);
			exit(EXIT_ERROR);
		}
		strcpy (fsck_path, fsck_prefix_path);
		strcat (fsck_path, ":");
		strcat (fsck_path, oldpath);
	} else {
		fsck_path = string_copy(fsck_prefix_path);
	}

	if ((num_devices == 1) || (serialize))
		interactive = 1;

	/* If -A was specified ("check all"), do that! */
	if (doall)
		return check_all();

	if (num_devices == 0) {
		serialize++;
		interactive++;
		return check_all();
	}
	for (i = 0 ; i < num_devices; i++) {
		if (cancel_requested) {
			if (!kill_sent) {
				kill_all(SIGTERM);
				kill_sent++;
			}
			break;
		}
		fs = lookup(devices[i]);
		if (!fs) {
			fs = create_fs_device(devices[i], 0, "auto",
					      0, -1, -1);
			if (!fs)
				continue;
		}
		if (ignore_mounted && is_mounted(fs->device))
			continue;
		fsck_device(fs, interactive);
		if (serialize ||
		    (max_running && (num_running >= max_running))) {
			struct fsck_instance *inst;

			inst = wait_one(0);
			if (inst) {
				status |= inst->exit_status;
				free_instance(inst);
			}
			if (verbose > 1)
				printf("----------------------------------\n");
		}
	}
	status |= wait_many(FLAG_WAIT_ALL);
	free(fsck_path);
	blkid_put_cache(cache);
	return status;
}
/* returns: whether the state changed */
static gboolean
poll_for_media_force (void)
{
        int fd;
        int got_media;
        int old_media_status;

	got_media = FALSE;

        old_media_status = media_status;
	if (is_cdrom) {
		int drive;
		
		fd = open (device_file, O_RDONLY | O_NONBLOCK | O_EXCL);
		
		if (fd < 0 && errno == EBUSY) {
			/* this means the disc is mounted or some other app,
			 * like a cd burner, has already opened O_EXCL */
			
			/* HOWEVER, when starting hald, a disc may be
			 * mounted; so check /etc/mtab to see if it
			 * actually is mounted. If it is we retry to open
			 * without O_EXCL
			 */
			if (!is_mounted (device_file)) {
                                if (!is_locked_via_o_excl) {
                                        is_locked_via_o_excl = TRUE;
                                        update_proc_title ();
                                } else {
                                        is_locked_via_o_excl = TRUE;
                                }
				goto skip_check;
                        }
			
			fd = open (device_file, O_RDONLY | O_NONBLOCK);
		}
		
		if (fd < 0) {
			HAL_ERROR (("open failed for %s: %s", device_file, strerror (errno))); 
			goto skip_check;
		}

                if (is_locked_via_o_excl) {
                        is_locked_via_o_excl = FALSE;
                        update_proc_title ();
                }
		
		
		/* Check if a disc is in the drive
		 *
		 * @todo Use MMC-2 API if applicable
		 */
		drive = ioctl (fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
		switch (drive) {
		case CDS_NO_INFO:
		case CDS_NO_DISC:
		case CDS_TRAY_OPEN:
		case CDS_DRIVE_NOT_READY:
			break;
			
		case CDS_DISC_OK:
			/* some CD-ROMs report CDS_DISK_OK even with an open
			 * tray; if media check has the same value two times in
			 * a row then this seems to be the case and we must not
			 * report that there is a media in it. */
			if (support_media_changed &&
			    ioctl (fd, CDROM_MEDIA_CHANGED, CDSL_CURRENT) && 
			    ioctl (fd, CDROM_MEDIA_CHANGED, CDSL_CURRENT)) {
			} else {
				got_media = TRUE;
			}
			break;
			
		case -1:
			HAL_ERROR (("CDROM_DRIVE_STATUS failed: %s\n", strerror(errno)));
			break;
			
		default:
			break;
		}
		
		/* check if eject button was pressed */
		if (got_media) {
			unsigned char cdb[10] = { 0x4a, 1, 0, 0, 16, 0, 0, 0, 8, 0};
			unsigned char buffer[8];
			struct sg_io_hdr sg_h;
			int retval;
			
			memset(buffer, 0, sizeof(buffer));
			memset(&sg_h, 0, sizeof(struct sg_io_hdr));
			sg_h.interface_id = 'S';
			sg_h.cmd_len = sizeof(cdb);
			sg_h.dxfer_direction = SG_DXFER_FROM_DEV;
			sg_h.dxfer_len = sizeof(buffer);
			sg_h.dxferp = buffer;
			sg_h.cmdp = cdb;
			sg_h.timeout = 5000;
			retval = ioctl(fd, SG_IO, &sg_h);
			if (retval == 0 && sg_h.status == 0 && (buffer[4] & 0x0f) == 0x01) {
				DBusError error;
				
				/* emit signal from drive device object */
				dbus_error_init (&error);
				libhal_device_emit_condition (ctx, udi, "EjectPressed", "", &error);
				LIBHAL_FREE_DBUS_ERROR (&error);
			}
		}
		close (fd);
	} else {
		fd = open (device_file, O_RDONLY);
		if (fd < 0 && errno == ENOMEDIUM) {
			got_media = FALSE;
		} else if (fd >= 0) {
			got_media = TRUE;
			close (fd);
		} else {
			HAL_ERROR (("open failed for %s: %s", device_file, strerror (errno))); 
			goto skip_check;
		}
	}
	
	/* set correct state on startup, this avoid endless loops if there was a media in the device on startup */
	if (media_status == MEDIA_STATUS_UNKNOWN) {
		if (got_media) 
			media_status = MEDIA_STATUS_NO_MEDIA;
		else 
			media_status = MEDIA_STATUS_GOT_MEDIA;	
	}

	switch (media_status) {
	case MEDIA_STATUS_GOT_MEDIA:
		if (!got_media) {
			DBusError error;
			
			HAL_DEBUG (("Media removal detected on %s", device_file));
			libhal_device_set_property_bool (ctx, udi, "storage.removable.media_available", FALSE, NULL);
			libhal_device_set_property_string (ctx, udi, "storage.partitioning_scheme", "", NULL);
			
			
			/* attempt to unmount all childs */
			unmount_childs (ctx, udi);
			
			/* could have a fs on the main block device; do a rescan to remove it */
			dbus_error_init (&error);
			libhal_device_rescan (ctx, udi, &error);
			LIBHAL_FREE_DBUS_ERROR (&error);
			
			/* have to this to trigger appropriate hotplug events */
			fd = open (device_file, O_RDONLY | O_NONBLOCK);
			if (fd >= 0) {
				ioctl (fd, BLKRRPART);
				close (fd);
			}
		}
		break;
		
	case MEDIA_STATUS_NO_MEDIA:
		if (got_media) {
			DBusError error;
			
			HAL_DEBUG (("Media insertion detected on %s", device_file));
			
			/* our probe will trigger the appropriate hotplug events */
			libhal_device_set_property_bool (
				ctx, udi, "storage.removable.media_available", TRUE, NULL);
			
			/* could have a fs on the main block device; do a rescan to add it */
			dbus_error_init (&error);
			libhal_device_rescan (ctx, udi, &error);
			LIBHAL_FREE_DBUS_ERROR (&error);
		}
		break;
		
	case MEDIA_STATUS_UNKNOWN:
	default:
		break;
	}
	
	/* update our current status */
	if (got_media)
		media_status = MEDIA_STATUS_GOT_MEDIA;
	else
		media_status = MEDIA_STATUS_NO_MEDIA;
	
	/*HAL_DEBUG (("polling %s; got media=%d", device_file, got_media));*/
	
skip_check:
	return old_media_status != media_status;
}
示例#25
0
int
main(int argc, char **argv) {
	struct stat statbuf;
	struct swap_header_v1_2 *hdr;
	int c;
	unsigned long long maxpages;
	unsigned long long goodpages;
	unsigned long long sz;
	off_t offset;
	int force = 0;
	int version = 1;
	char *block_count = 0;
	char *opt_label = NULL;
	unsigned char *uuid = NULL;
#ifdef HAVE_LIBUUID
	const char *opt_uuid = NULL;
	uuid_t uuid_dat;
#endif
	static const struct option longopts[] = {
		{ "check",       no_argument,       0, 'c' },
		{ "force",       no_argument,       0, 'f' },
		{ "pagesize",    required_argument, 0, 'p' },
		{ "label",       required_argument, 0, 'L' },
		{ "swapversion", required_argument, 0, 'v' },
		{ "uuid",        required_argument, 0, 'U' },
		{ "version",     no_argument,       0, 'V' },
		{ "help",        no_argument,       0, 'h' },
		{ NULL,          0, 0, 0 }
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while((c = getopt_long(argc, argv, "cfp:L:v:U:Vh", longopts, NULL)) != -1) {
		switch (c) {
		case 'c':
			check=1;
			break;
		case 'f':
			force=1;
			break;
		case 'p':
			user_pagesize = strtou32_or_err(optarg, _("parsing page size failed"));
			break;
		case 'L':
			opt_label = optarg;
			break;
		case 'v':
			version = strtos32_or_err(optarg, _("parsing version number failed"));
			break;
		case 'U':
#ifdef HAVE_LIBUUID
			opt_uuid = optarg;
#else
			warnx(_("warning: ignoring -U (UUIDs are unsupported by %s)"),
				program_invocation_short_name);
#endif
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			exit(EXIT_SUCCESS);
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}
	}
	if (optind < argc)
		device_name = argv[optind++];
	if (optind < argc)
		block_count = argv[optind++];
	if (optind != argc) {
		warnx(_("only one device argument is currently supported"));
		usage(stderr);
	}

	if (version != 1)
		errx(EXIT_FAILURE,
			_("swapspace version %d is not supported"), version);

#ifdef HAVE_LIBUUID
	if(opt_uuid) {
		if (uuid_parse(opt_uuid, uuid_dat) != 0)
			errx(EXIT_FAILURE, _("error: parsing UUID failed"));
	} else
		uuid_generate(uuid_dat);
	uuid = uuid_dat;
#endif

	init_signature_page();	/* get pagesize */

	if (!device_name) {
		warnx(_("error: Nowhere to set up swap on?"));
		usage(stderr);
	}
	if (block_count) {
		/* this silly user specified the number of blocks explicitly */
		uint64_t blks = strtou64_or_err(block_count,
					_("invalid block count argument"));
		PAGES = blks / (pagesize / 1024);
	}
	sz = get_size(device_name);
	if (!PAGES)
		PAGES = sz;
	else if (PAGES > sz && !force) {
		errx(EXIT_FAILURE,
			_("error: "
			  "size %llu KiB is larger than device size %llu KiB"),
			PAGES*(pagesize/1024), sz*(pagesize/1024));
	}

	if (PAGES < MIN_GOODPAGES) {
		warnx(_("error: swap area needs to be at least %ld KiB"),
			(long)(MIN_GOODPAGES * pagesize/1024));
		usage(stderr);
	}

#ifdef __linux__
	if (get_linux_version() >= KERNEL_VERSION(2,3,4))
		maxpages = UINT_MAX + 1ULL;
	else if (get_linux_version() >= KERNEL_VERSION(2,2,1))
		maxpages = V1_MAX_PAGES;
	else
#endif
		maxpages = V1_OLD_MAX_PAGES;

	if (PAGES > maxpages) {
		PAGES = maxpages;
		warnx(_("warning: truncating swap area to %llu KiB"),
			PAGES * pagesize / 1024);
	}

	if (is_mounted(device_name))
		errx(EXIT_FAILURE, _("error: "
			"%s is mounted; will not make swapspace"),
			device_name);

	if (stat(device_name, &statbuf) < 0) {
		perror(device_name);
		exit(EXIT_FAILURE);
	}
	if (S_ISBLK(statbuf.st_mode))
		DEV = open(device_name, O_RDWR | O_EXCL);
	else
		DEV = open(device_name, O_RDWR);

	if (DEV < 0) {
		perror(device_name);
		exit(EXIT_FAILURE);
	}

	if (!S_ISBLK(statbuf.st_mode))
		check=0;
	else if (blkdev_is_misaligned(DEV))
		warnx(_("warning: %s is misaligned"), device_name);

	if (check)
		check_blocks();

	wipe_device(DEV, device_name, force);

	hdr = (struct swap_header_v1_2 *) signature_page;
	hdr->version = 1;
	hdr->last_page = PAGES - 1;
	hdr->nr_badpages = badpages;

	if (badpages > PAGES - MIN_GOODPAGES)
		errx(EXIT_FAILURE, _("Unable to set up swap-space: unreadable"));

	goodpages = PAGES - badpages - 1;
	printf(_("Setting up swapspace version 1, size = %llu KiB\n"),
		goodpages * pagesize / 1024);

	write_signature("SWAPSPACE2");
	write_uuid_and_label(uuid, opt_label);

	offset = 1024;
	if (lseek(DEV, offset, SEEK_SET) != offset)
		errx(EXIT_FAILURE, _("unable to rewind swap-device"));
	if (write_all(DEV, (char *) signature_page + offset,
				    pagesize - offset) == -1)
		err(EXIT_FAILURE,
			_("%s: unable to write signature page"),
			device_name);

#ifdef HAVE_LIBSELINUX
	if (S_ISREG(statbuf.st_mode) && is_selinux_enabled() > 0) {
		security_context_t context_string;
		security_context_t oldcontext;
		context_t newcontext;

		if (fgetfilecon(DEV, &oldcontext) < 0) {
			if (errno != ENODATA)
				err(EXIT_FAILURE,
					_("%s: unable to obtain selinux file label"),
					device_name);
			if (matchpathcon(device_name, statbuf.st_mode, &oldcontext))
				errx(EXIT_FAILURE, _("unable to matchpathcon()"));
		}
		if (!(newcontext = context_new(oldcontext)))
			errx(EXIT_FAILURE, _("unable to create new selinux context"));
		if (context_type_set(newcontext, SELINUX_SWAPFILE_TYPE))
			errx(EXIT_FAILURE, _("couldn't compute selinux context"));

		context_string = context_str(newcontext);

		if (strcmp(context_string, oldcontext)!=0) {
			if (fsetfilecon(DEV, context_string))
				err(EXIT_FAILURE, _("unable to relabel %s to %s"),
						device_name, context_string);
		}
		context_free(newcontext);
		freecon(oldcontext);
	}
#endif
	/*
	 * A subsequent swapon() will fail if the signature
	 * is not actually on disk. (This is a kernel bug.)
	 * The fsync() in close_fd() will take care of writing.
	 */
	if (close_fd(DEV) != 0)
		err(EXIT_FAILURE, _("write failed"));
	return EXIT_SUCCESS;
}
示例#26
0
int main(int argc, char *argv[])
{
	struct udev *udev;
	static const struct option options[] = {
		{ "export", no_argument, NULL, 'x' },
		{ "debug", no_argument, NULL, 'd' },
		{ "help", no_argument, NULL, 'h' },
		{}
	};
	const char *node = NULL;
	int export = 0;
	int fd = -1;
	int cnt;
	int rc = 0;

	udev = udev_new();
	if (udev == NULL)
		goto exit;

	udev_log_init("cdrom_id");
	udev_set_log_fn(udev, log_fn);

	while (1) {
		int option;

		option = getopt_long(argc, argv, "dxh", options, NULL);
		if (option == -1)
			break;

		switch (option) {
		case 'd':
			debug = 1;
			if (udev_get_log_priority(udev) < LOG_INFO)
				udev_set_log_priority(udev, LOG_INFO);
			break;
		case 'x':
			export = 1;
			break;
		case 'h':
			printf("Usage: cdrom_id [options] <device>\n"
			       "  --export        export key/value pairs\n"
			       "  --debug         debug to stderr\n"
			       "  --help          print this help text\n\n");
			goto exit;
		default:
			rc = 1;
			goto exit;
		}
	}

	node = argv[optind];
	if (!node) {
		err(udev, "no device\n");
		fprintf(stderr, "no device\n");
		rc = 1;
		goto exit;
	}

	srand((unsigned int)getpid());
	for (cnt = 20; cnt > 0; cnt--) {
		struct timespec duration;

		fd = open(node, O_RDONLY|O_NONBLOCK|(is_mounted(node) ? 0 : O_EXCL));
		if (fd >= 0 || errno != EBUSY)
			break;
		duration.tv_sec = 0;
		duration.tv_nsec = (100 * 1000 * 1000) + (rand() % 100 * 1000 * 1000);
		nanosleep(&duration, NULL);
	}
	if (fd < 0) {
		info(udev, "unable to open '%s'\n", node);
		fprintf(stderr, "unable to open '%s'\n", node);
		rc = 1;
		goto exit;
	}
	info(udev, "probing: '%s'\n", node);

	/* same data as original cdrom_id */
	if (cd_capability_compat(udev, fd) < 0) {
		rc = 1;
		goto exit;
	}

	/* check for media - don't bail if there's no media as we still need to
         * to read profiles */
	cd_media_compat(udev, fd);

	/* check if drive talks MMC */
	if (cd_inquiry(udev, fd) < 0)
		goto print;

	/* read drive and possibly current profile */
	if (cd_profiles(udev, fd) < 0)
		goto print;

	/* get session/track info */
	cd_media_toc(udev, fd);

	/* get writable media state */
	cd_media_info(udev, fd);

print:
	printf("ID_CDROM=1\n");
	if (cd_cd_rom)
		printf("ID_CDROM_CD=1\n");
	if (cd_cd_r)
		printf("ID_CDROM_CD_R=1\n");
	if (cd_cd_rw)
		printf("ID_CDROM_CD_RW=1\n");
	if (cd_dvd_rom)
		printf("ID_CDROM_DVD=1\n");
	if (cd_dvd_r)
		printf("ID_CDROM_DVD_R=1\n");
	if (cd_dvd_rw)
		printf("ID_CDROM_DVD_RW=1\n");
	if (cd_dvd_ram)
		printf("ID_CDROM_DVD_RAM=1\n");
	if (cd_dvd_plus_r)
		printf("ID_CDROM_DVD_PLUS_R=1\n");
	if (cd_dvd_plus_rw)
		printf("ID_CDROM_DVD_PLUS_RW=1\n");
	if (cd_dvd_plus_r_dl)
		printf("ID_CDROM_DVD_PLUS_R_DL=1\n");
	if (cd_dvd_plus_rw_dl)
		printf("ID_CDROM_DVD_PLUS_RW_DL=1\n");
	if (cd_bd)
		printf("ID_CDROM_BD=1\n");
	if (cd_bd_r)
		printf("ID_CDROM_BD_R=1\n");
	if (cd_bd_re)
		printf("ID_CDROM_BD_RE=1\n");
	if (cd_hddvd)
		printf("ID_CDROM_HDDVD=1\n");
	if (cd_hddvd_r)
		printf("ID_CDROM_HDDVD_R=1\n");
	if (cd_hddvd_rw)
		printf("ID_CDROM_HDDVD_RW=1\n");
	if (cd_mo)
		printf("ID_CDROM_MO=1\n");
	if (cd_mrw)
		printf("ID_CDROM_MRW=1\n");
	if (cd_mrw_w)
		printf("ID_CDROM_MRW_W=1\n");

	if (cd_media)
		printf("ID_CDROM_MEDIA=1\n");
	if (cd_media_mo)
		printf("ID_CDROM_MEDIA_MO=1\n");
	if (cd_media_mrw)
		printf("ID_CDROM_MEDIA_MRW=1\n");
	if (cd_media_mrw_w)
		printf("ID_CDROM_MEDIA_MRW_W=1\n");
	if (cd_media_cd_rom)
		printf("ID_CDROM_MEDIA_CD=1\n");
	if (cd_media_cd_r)
		printf("ID_CDROM_MEDIA_CD_R=1\n");
	if (cd_media_cd_rw)
		printf("ID_CDROM_MEDIA_CD_RW=1\n");
	if (cd_media_dvd_rom)
		printf("ID_CDROM_MEDIA_DVD=1\n");
	if (cd_media_dvd_r)
		printf("ID_CDROM_MEDIA_DVD_R=1\n");
	if (cd_media_dvd_ram)
		printf("ID_CDROM_MEDIA_DVD_RAM=1\n");
	if (cd_media_dvd_rw)
		printf("ID_CDROM_MEDIA_DVD_RW=1\n");
	if (cd_media_dvd_plus_r)
		printf("ID_CDROM_MEDIA_DVD_PLUS_R=1\n");
	if (cd_media_dvd_plus_rw)
		printf("ID_CDROM_MEDIA_DVD_PLUS_RW=1\n");
	if (cd_media_dvd_plus_rw_dl)
		printf("ID_CDROM_MEDIA_DVD_PLUS_RW_DL=1\n");
	if (cd_media_dvd_plus_r_dl)
		printf("ID_CDROM_MEDIA_DVD_PLUS_R_DL=1\n");
	if (cd_media_bd)
		printf("ID_CDROM_MEDIA_BD=1\n");
	if (cd_media_bd_r)
		printf("ID_CDROM_MEDIA_BD_R=1\n");
	if (cd_media_bd_re)
		printf("ID_CDROM_MEDIA_BD_RE=1\n");
	if (cd_media_hddvd)
		printf("ID_CDROM_MEDIA_HDDVD=1\n");
	if (cd_media_hddvd_r)
		printf("ID_CDROM_MEDIA_HDDVD_R=1\n");
	if (cd_media_hddvd_rw)
		printf("ID_CDROM_MEDIA_HDDVD_RW=1\n");

	if (cd_media_state != NULL)
		printf("ID_CDROM_MEDIA_STATE=%s\n", cd_media_state);
	if (cd_media_session_next > 0)
		printf("ID_CDROM_MEDIA_SESSION_NEXT=%d\n", cd_media_session_next);
	if (cd_media_session_count > 0)
		printf("ID_CDROM_MEDIA_SESSION_COUNT=%d\n", cd_media_session_count);
	if (cd_media_session_count > 1 && cd_media_session_last_offset > 0)
		printf("ID_CDROM_MEDIA_SESSION_LAST_OFFSET=%llu\n", cd_media_session_last_offset);
	if (cd_media_track_count > 0)
		printf("ID_CDROM_MEDIA_TRACK_COUNT=%d\n", cd_media_track_count);
	if (cd_media_track_count_audio > 0)
		printf("ID_CDROM_MEDIA_TRACK_COUNT_AUDIO=%d\n", cd_media_track_count_audio);
	if (cd_media_track_count_data > 0)
		printf("ID_CDROM_MEDIA_TRACK_COUNT_DATA=%d\n", cd_media_track_count_data);
exit:
	if (fd >= 0)
		close(fd);
	udev_unref(udev);
	udev_log_close();
	return rc;
}
示例#27
0
boolean_t
zfs_is_mounted(zfs_handle_t *zhp, char **where)
{
	return (is_mounted(zhp->zfs_hdl, zfs_get_name(zhp), where));
}
示例#28
0
int main(int argc, char **argv)
{
	struct mkswap_control ctl = { .fd = -1 };
	int c;
	uint64_t sz;
	int version = SWAP_VERSION;
	char *block_count = NULL, *strsz = NULL;
#ifdef HAVE_LIBUUID
	const char *opt_uuid = NULL;
	uuid_t uuid_dat;
#endif
	static const struct option longopts[] = {
		{ "check",       no_argument,       0, 'c' },
		{ "force",       no_argument,       0, 'f' },
		{ "pagesize",    required_argument, 0, 'p' },
		{ "label",       required_argument, 0, 'L' },
		{ "swapversion", required_argument, 0, 'v' },
		{ "uuid",        required_argument, 0, 'U' },
		{ "version",     no_argument,       0, 'V' },
		{ "help",        no_argument,       0, 'h' },
		{ NULL,          0, 0, 0 }
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while((c = getopt_long(argc, argv, "cfp:L:v:U:Vh", longopts, NULL)) != -1) {
		switch (c) {
		case 'c':
			ctl.check = 1;
			break;
		case 'f':
			ctl.force = 1;
			break;
		case 'p':
			ctl.user_pagesize = strtou32_or_err(optarg, _("parsing page size failed"));
			break;
		case 'L':
			ctl.opt_label = optarg;
			break;
		case 'v':
			version = strtos32_or_err(optarg, _("parsing version number failed"));
			if (version != SWAP_VERSION)
				errx(EXIT_FAILURE,
					_("swapspace version %d is not supported"), version);
			break;
		case 'U':
#ifdef HAVE_LIBUUID
			opt_uuid = optarg;
#else
			warnx(_("warning: ignoring -U (UUIDs are unsupported by %s)"),
				program_invocation_short_name);
#endif
			break;
		case 'V':
			printf(UTIL_LINUX_VERSION);
			exit(EXIT_SUCCESS);
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}
	}

	if (optind < argc)
		ctl.devname = argv[optind++];
	if (optind < argc)
		block_count = argv[optind++];
	if (optind != argc) {
		warnx(_("only one device argument is currently supported"));
		usage(stderr);
	}

#ifdef HAVE_LIBUUID
	if(opt_uuid) {
		if (uuid_parse(opt_uuid, uuid_dat) != 0)
			errx(EXIT_FAILURE, _("error: parsing UUID failed"));
	} else
		uuid_generate(uuid_dat);
	ctl.uuid = uuid_dat;
#endif

	init_signature_page(&ctl);	/* get pagesize and allocate signature page */

	if (!ctl.devname) {
		warnx(_("error: Nowhere to set up swap on?"));
		usage(stderr);
	}
	if (block_count) {
		/* this silly user specified the number of blocks explicitly */
		uint64_t blks = strtou64_or_err(block_count,
					_("invalid block count argument"));
		ctl.npages = blks / (ctl.pagesize / 1024);
	}

	sz = get_size(&ctl);
	if (!ctl.npages)
		ctl.npages = sz;
	else if (ctl.npages > sz && !ctl.force)
		errx(EXIT_FAILURE,
			_("error: "
			  "size %llu KiB is larger than device size %ju KiB"),
			ctl.npages * (ctl.pagesize / 1024), sz * (ctl.pagesize / 1024));

	if (ctl.npages < MIN_GOODPAGES)
		errx(EXIT_FAILURE,
		     _("error: swap area needs to be at least %ld KiB"),
		     (long)(MIN_GOODPAGES * ctl.pagesize / 1024));
	if (ctl.npages > UINT32_MAX) {
		/* true when swap is bigger than 17.59 terabytes */
		ctl.npages = UINT32_MAX;
		warnx(_("warning: truncating swap area to %llu KiB"),
			ctl.npages * ctl.pagesize / 1024);
	}

	if (is_mounted(ctl.devname))
		errx(EXIT_FAILURE, _("error: "
			"%s is mounted; will not make swapspace"),
			ctl.devname);

	open_device(&ctl);

	if (ctl.check)
		check_blocks(&ctl);

	wipe_device(&ctl);

	assert(ctl.hdr);
	ctl.hdr->version = version;
	ctl.hdr->last_page = ctl.npages - 1;
	ctl.hdr->nr_badpages = ctl.nbadpages;

	if ((ctl.npages - MIN_GOODPAGES) < ctl.nbadpages)
		errx(EXIT_FAILURE, _("Unable to set up swap-space: unreadable"));

	sz = (ctl.npages - ctl.nbadpages - 1) * ctl.pagesize;
	strsz = size_to_human_string(SIZE_SUFFIX_SPACE | SIZE_SUFFIX_3LETTER, sz);

	printf(_("Setting up swapspace version %d, size = %s (%ju bytes)\n"),
		version, strsz, sz);
	free(strsz);

	set_signature(&ctl);
	set_uuid_and_label(&ctl);

	write_header_to_device(&ctl);

	deinit_signature_page(&ctl);

#ifdef HAVE_LIBSELINUX
	if (S_ISREG(ctl.devstat.st_mode) && is_selinux_enabled() > 0) {
		security_context_t context_string;
		security_context_t oldcontext;
		context_t newcontext;

		if (fgetfilecon(ctl.fd, &oldcontext) < 0) {
			if (errno != ENODATA)
				err(EXIT_FAILURE,
					_("%s: unable to obtain selinux file label"),
					ctl.devname);
			if (matchpathcon(ctl.devname, ctl.devstat.st_mode, &oldcontext))
				errx(EXIT_FAILURE, _("unable to matchpathcon()"));
		}
		if (!(newcontext = context_new(oldcontext)))
			errx(EXIT_FAILURE, _("unable to create new selinux context"));
		if (context_type_set(newcontext, SELINUX_SWAPFILE_TYPE))
			errx(EXIT_FAILURE, _("couldn't compute selinux context"));

		context_string = context_str(newcontext);

		if (strcmp(context_string, oldcontext)!=0) {
			if (fsetfilecon(ctl.fd, context_string))
				err(EXIT_FAILURE, _("unable to relabel %s to %s"),
						ctl.devname, context_string);
		}
		context_free(newcontext);
		freecon(oldcontext);
	}
#endif
	/*
	 * A subsequent swapon() will fail if the signature
	 * is not actually on disk. (This is a kernel bug.)
	 * The fsync() in close_fd() will take care of writing.
	 */
	if (close_fd(ctl.fd) != 0)
		err(EXIT_FAILURE, _("write failed"));
	return EXIT_SUCCESS;
}
示例#29
0
int
main(int argc, char **argv) {
	int ch, keep, success, pathlen;
	time_t expire, now;
	char *host, *path;
	struct mtablist *mtab;

	expire = 0;
	host = path = NULL;
	success = keep = verbose = 0;
	while ((ch = getopt(argc, argv, "h:kp:ve:")) != -1)
		switch (ch) {
		case 'h':
			host = optarg;
			break;
		case 'e':
			expire = atoi(optarg);
			break;
		case 'k':
			keep = 1;
			break;
		case 'p':
			path = optarg;
			break;
		case 'v':
			verbose = 1;
			break;
		case '?':
			usage();
		default:
			break;
		}
	argc -= optind;
	argv += optind;

	/* Default expiretime is one day */
	if (expire == 0)
		expire = 86400;
	time(&now);

	/* Read PATH_MOUNTTAB. */
	if (!read_mtab()) {
		if (verbose)
			warnx("no mounttab entries (%s does not exist)",
			    PATH_MOUNTTAB);
		mtabhead = NULL;
	}

	if (host == NULL && path == NULL) {
		/* Check each entry and do any necessary unmount RPCs. */
		for (mtab = mtabhead; mtab != NULL; mtab = mtab->mtab_next) {
			if (*mtab->mtab_host == '\0')
				continue;
			if (mtab->mtab_time + expire < now) {
				/* Clear expired entry. */
				if (verbose)
					warnx("remove expired entry %s:%s",
					    mtab->mtab_host, mtab->mtab_dirp);
				bzero(mtab->mtab_host,
				    sizeof(mtab->mtab_host));
				continue;
			}
			if (keep && is_mounted(mtab->mtab_host,
			    mtab->mtab_dirp)) {
				if (verbose)
					warnx("skip entry %s:%s",
					    mtab->mtab_host, mtab->mtab_dirp);
				continue;
			}
			if (do_umount(mtab->mtab_host, mtab->mtab_dirp)) {
				if (verbose)
					warnx("umount RPC for %s:%s succeeded",
					    mtab->mtab_host, mtab->mtab_dirp);
				/* Remove all entries for this host + path. */
				clean_mtab(mtab->mtab_host, mtab->mtab_dirp,
				    verbose);
			}
		}
		success = 1;
	} else {
		if (host == NULL && path != NULL)
			/* Missing hostname. */
			usage();
		if (path == NULL) {
			/* Do a RPC UMNTALL for this specific host */
			success = do_umntall(host);
			if (verbose && success)
				warnx("umntall RPC for %s succeeded", host);
		} else {
			/* Do a RPC UMNTALL for this specific mount */
			for (pathlen = strlen(path);
			    pathlen > 1 && path[pathlen - 1] == '/'; pathlen--)
				path[pathlen - 1] = '\0';
			success = do_umount(host, path);
			if (verbose && success)
				warnx("umount RPC for %s:%s succeeded", host,
				    path);
		}
		/* If successful, remove any corresponding mounttab entries. */
		if (success)
			clean_mtab(host, path, verbose);
	}
	/* Write and unlink PATH_MOUNTTAB if necessary */
	if (success)
		success = write_mtab(verbose);
	free_mtab();
	exit (success ? 0 : 1);
}
示例#30
0
int main(int argc, char *argv[]) {
        struct udev *udev;
        static const struct option options[] = {
                { "lock-media", no_argument, NULL, 'l' },
                { "unlock-media", no_argument, NULL, 'u' },
                { "eject-media", no_argument, NULL, 'e' },
                { "debug", no_argument, NULL, 'd' },
                { "help", no_argument, NULL, 'h' },
                {}
        };
        bool eject = false;
        bool lock = false;
        bool unlock = false;
        const char *node = NULL;
        int fd = -1;
        int cnt;
        int rc = 0;

        log_set_target(LOG_TARGET_AUTO);
        udev_parse_config();
        log_parse_environment();
        log_open();

        udev = udev_new();
        if (udev == NULL)
                goto exit;

        for (;;) {
                int option;

                option = getopt_long(argc, argv, "deluh", options, NULL);
                if (option == -1)
                        break;

                switch (option) {
                case 'l':
                        lock = true;
                        break;
                case 'u':
                        unlock = true;
                        break;
                case 'e':
                        eject = true;
                        break;
                case 'd':
                        log_set_target(LOG_TARGET_CONSOLE);
                        log_set_max_level(LOG_DEBUG);
                        log_open();
                        break;
                case 'h':
                        printf("Usage: cdrom_id [options] <device>\n"
                               "  -l,--lock-media    lock the media (to enable eject request events)\n"
                               "  -u,--unlock-media  unlock the media\n"
                               "  -e,--eject-media   eject the media\n"
                               "  -d,--debug         debug to stderr\n"
                               "  -h,--help          print this help text\n\n");
                        goto exit;
                default:
                        rc = 1;
                        goto exit;
                }
        }

        node = argv[optind];
        if (!node) {
                log_error("no device");
                fprintf(stderr, "no device\n");
                rc = 1;
                goto exit;
        }

        initialize_srand();
        for (cnt = 20; cnt > 0; cnt--) {
                struct timespec duration;

                fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|(is_mounted(node) ? 0 : O_EXCL));
                if (fd >= 0 || errno != EBUSY)
                        break;
                duration.tv_sec = 0;
                duration.tv_nsec = (100 * 1000 * 1000) + (rand() % 100 * 1000 * 1000);
                nanosleep(&duration, NULL);
        }
        if (fd < 0) {
                log_debug("unable to open '%s'", node);
                fprintf(stderr, "unable to open '%s'\n", node);
                rc = 1;
                goto exit;
        }
        log_debug("probing: '%s'", node);

        /* same data as original cdrom_id */
        if (cd_capability_compat(udev, fd) < 0) {
                rc = 1;
                goto exit;
        }

        /* check for media - don't bail if there's no media as we still need to
         * to read profiles */
        cd_media_compat(udev, fd);

        /* check if drive talks MMC */
        if (cd_inquiry(udev, fd) < 0)
                goto work;

        /* read drive and possibly current profile */
        if (cd_profiles(udev, fd) != 0)
                goto work;

        /* at this point we are guaranteed to have media in the drive - find out more about it */

        /* get session/track info */
        cd_media_toc(udev, fd);

        /* get writable media state */
        cd_media_info(udev, fd);

work:
        /* lock the media, so we enable eject button events */
        if (lock && cd_media) {
                log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (lock)");
                media_lock(udev, fd, true);
        }

        if (unlock && cd_media) {
                log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (unlock)");
                media_lock(udev, fd, false);
        }

        if (eject) {
                log_debug("PREVENT_ALLOW_MEDIUM_REMOVAL (unlock)");
                media_lock(udev, fd, false);
                log_debug("START_STOP_UNIT (eject)");
                media_eject(udev, fd);
        }

        printf("ID_CDROM=1\n");
        if (cd_cd_rom)
                printf("ID_CDROM_CD=1\n");
        if (cd_cd_r)
                printf("ID_CDROM_CD_R=1\n");
        if (cd_cd_rw)
                printf("ID_CDROM_CD_RW=1\n");
        if (cd_dvd_rom)
                printf("ID_CDROM_DVD=1\n");
        if (cd_dvd_r)
                printf("ID_CDROM_DVD_R=1\n");
        if (cd_dvd_rw)
                printf("ID_CDROM_DVD_RW=1\n");
        if (cd_dvd_ram)
                printf("ID_CDROM_DVD_RAM=1\n");
        if (cd_dvd_plus_r)
                printf("ID_CDROM_DVD_PLUS_R=1\n");
        if (cd_dvd_plus_rw)
                printf("ID_CDROM_DVD_PLUS_RW=1\n");
        if (cd_dvd_plus_r_dl)
                printf("ID_CDROM_DVD_PLUS_R_DL=1\n");
        if (cd_dvd_plus_rw_dl)
                printf("ID_CDROM_DVD_PLUS_RW_DL=1\n");
        if (cd_bd)
                printf("ID_CDROM_BD=1\n");
        if (cd_bd_r)
                printf("ID_CDROM_BD_R=1\n");
        if (cd_bd_re)
                printf("ID_CDROM_BD_RE=1\n");
        if (cd_hddvd)
                printf("ID_CDROM_HDDVD=1\n");
        if (cd_hddvd_r)
                printf("ID_CDROM_HDDVD_R=1\n");
        if (cd_hddvd_rw)
                printf("ID_CDROM_HDDVD_RW=1\n");
        if (cd_mo)
                printf("ID_CDROM_MO=1\n");
        if (cd_mrw)
                printf("ID_CDROM_MRW=1\n");
        if (cd_mrw_w)
                printf("ID_CDROM_MRW_W=1\n");

        if (cd_media)
                printf("ID_CDROM_MEDIA=1\n");
        if (cd_media_mo)
                printf("ID_CDROM_MEDIA_MO=1\n");
        if (cd_media_mrw)
                printf("ID_CDROM_MEDIA_MRW=1\n");
        if (cd_media_mrw_w)
                printf("ID_CDROM_MEDIA_MRW_W=1\n");
        if (cd_media_cd_rom)
                printf("ID_CDROM_MEDIA_CD=1\n");
        if (cd_media_cd_r)
                printf("ID_CDROM_MEDIA_CD_R=1\n");
        if (cd_media_cd_rw)
                printf("ID_CDROM_MEDIA_CD_RW=1\n");
        if (cd_media_dvd_rom)
                printf("ID_CDROM_MEDIA_DVD=1\n");
        if (cd_media_dvd_r)
                printf("ID_CDROM_MEDIA_DVD_R=1\n");
        if (cd_media_dvd_ram)
                printf("ID_CDROM_MEDIA_DVD_RAM=1\n");
        if (cd_media_dvd_rw)
                printf("ID_CDROM_MEDIA_DVD_RW=1\n");
        if (cd_media_dvd_plus_r)
                printf("ID_CDROM_MEDIA_DVD_PLUS_R=1\n");
        if (cd_media_dvd_plus_rw)
                printf("ID_CDROM_MEDIA_DVD_PLUS_RW=1\n");
        if (cd_media_dvd_plus_rw_dl)
                printf("ID_CDROM_MEDIA_DVD_PLUS_RW_DL=1\n");
        if (cd_media_dvd_plus_r_dl)
                printf("ID_CDROM_MEDIA_DVD_PLUS_R_DL=1\n");
        if (cd_media_bd)
                printf("ID_CDROM_MEDIA_BD=1\n");
        if (cd_media_bd_r)
                printf("ID_CDROM_MEDIA_BD_R=1\n");
        if (cd_media_bd_re)
                printf("ID_CDROM_MEDIA_BD_RE=1\n");
        if (cd_media_hddvd)
                printf("ID_CDROM_MEDIA_HDDVD=1\n");
        if (cd_media_hddvd_r)
                printf("ID_CDROM_MEDIA_HDDVD_R=1\n");
        if (cd_media_hddvd_rw)
                printf("ID_CDROM_MEDIA_HDDVD_RW=1\n");

        if (cd_media_state != NULL)
                printf("ID_CDROM_MEDIA_STATE=%s\n", cd_media_state);
        if (cd_media_session_next > 0)
                printf("ID_CDROM_MEDIA_SESSION_NEXT=%u\n", cd_media_session_next);
        if (cd_media_session_count > 0)
                printf("ID_CDROM_MEDIA_SESSION_COUNT=%u\n", cd_media_session_count);
        if (cd_media_session_count > 1 && cd_media_session_last_offset > 0)
                printf("ID_CDROM_MEDIA_SESSION_LAST_OFFSET=%llu\n", cd_media_session_last_offset);
        if (cd_media_track_count > 0)
                printf("ID_CDROM_MEDIA_TRACK_COUNT=%u\n", cd_media_track_count);
        if (cd_media_track_count_audio > 0)
                printf("ID_CDROM_MEDIA_TRACK_COUNT_AUDIO=%u\n", cd_media_track_count_audio);
        if (cd_media_track_count_data > 0)
                printf("ID_CDROM_MEDIA_TRACK_COUNT_DATA=%u\n", cd_media_track_count_data);
exit:
        if (fd >= 0)
                close(fd);
        udev_unref(udev);
        log_close();
        return rc;
}