MythTV master
mediamonitor-unix.cpp
Go to the documentation of this file.
1// -*- Mode: c++ -*-
2
3#include "mediamonitor-unix.h"
4#include "mediamonitor.h"
5#include "libmythbase/mythconfig.h"
6
7// Standard C headers
8#include <cstdio>
9#include <thread>
10
11// POSIX headers
12#include <dirent.h>
13#include <unistd.h>
14#include <fcntl.h>
15#if HAVE_FSTAB_H
16#include <fstab.h>
17#endif
18
19// UNIX System headers
20#include <sys/file.h>
21#include <sys/types.h>
22#include <sys/stat.h>
23#include <sys/wait.h>
24#include <sys/param.h>
25
26// Qt headers
27#include <QtGlobal>
28#if CONFIG_QTDBUS
29#include <QDBusConnection>
30#include <QDBusInterface>
31#include <QDBusPendingReply>
32#include <QDBusReply>
33#include <QVersionNumber>
34#include <QXmlStreamReader>
35#endif
36#include <QList>
37#include <QTextStream>
38#include <QDir>
39#include <QRegularExpression>
40
41// MythTV headers
45#include "libmythbase/mythhdd.h"
48
49#if HAVE_LIBUDEV
50extern "C" {
51 #include <libudev.h>
52}
53#endif
54
55
56#if HAVE_FSTAB_H
57#ifndef MNTTYPE_ISO9660
58# ifdef Q_OS_LINUX
59 static constexpr const char* MNTTYPE_ISO9660 { "iso9660" };
60# elif defined(Q_OS_BSD4)
61 static constexpr const char* MNTTYPE_ISO9660 { "cd9660" };
62# endif
63#endif
64
65#ifndef MNTTYPE_UDF
66static constexpr const char* MNTTYPE_UDF { "udf" };
67#endif
68
69#ifndef MNTTYPE_AUTO
70static constexpr const char* MNTTYPE_AUTO { "auto" };
71#endif
72
73#ifndef MNTTYPE_SUPERMOUNT
74static constexpr const char* MNTTYPE_SUPERMOUNT { "supermount" };
75#endif
76static const std::string kSuperOptDev { "dev=" };
77#endif // !Q_OS_ANDROID
78
79#if CONFIG_QTDBUS
80// DBus UDisks2 service - https://udisks.freedesktop.org/
81static constexpr const char* UDISKS2_SVC { "org.freedesktop.UDisks2" };
82static constexpr const char* UDISKS2_SVC_DRIVE { "org.freedesktop.UDisks2.Drive" };
83static constexpr const char* UDISKS2_SVC_BLOCK { "org.freedesktop.UDisks2.Block" };
84static constexpr const char* UDISKS2_SVC_FILESYSTEM { "org.freedesktop.UDisks2.Filesystem" };
85static constexpr const char* UDISKS2_SVC_MANAGER { "org.freedesktop.UDisks2.Manager" };
86static constexpr const char* UDISKS2_PATH { "/org/freedesktop/UDisks2" };
87static constexpr const char* UDISKS2_PATH_MANAGER { "/org/freedesktop/UDisks2/Manager" };
88static constexpr const char* UDISKS2_PATH_BLOCK_DEVICES { "/org/freedesktop/UDisks2/block_devices" };
89static constexpr const char* UDISKS2_MIN_VERSION { "2.7.3" };
90#endif
91
92
93// Some helpers for debugging:
94
95static const QString LOC = QString("MMUnix:");
96
97#if HAVE_FSTAB_H
98// TODO: are these used?
99static void fstabError(const QString &methodName)
100{
101 LOG(VB_GENERAL, LOG_ALERT,
102 LOC + methodName + " Error: failed to open " + _PATH_FSTAB +
103 " for reading, " + ENO);
104}
105#endif
106
107static void statError(const QString &methodName, const QString &devPath)
108{
109 LOG(VB_GENERAL, LOG_ALERT,
110 LOC + methodName + " Error: failed to stat " + devPath +
111 ", " + ENO);
112}
113
115// MediaMonitor
116
117
119 unsigned long interval, bool allowEject)
120 : MediaMonitor(par, interval, allowEject)
121{
123 if (!gCoreContext->GetBoolSetting("MonitorDrives", false)) {
124 LOG(VB_GENERAL, LOG_NOTICE, "MediaMonitor disabled by user setting.");
125 }
126 else
127 {
129 }
130
131 LOG(VB_MEDIA, LOG_INFO, LOC +"Initial device list...\n" + listDevices());
132}
133
134
135#if !CONFIG_QTDBUS
137{
138 if (m_fifo >= 0)
139 {
140 close(m_fifo);
141 m_fifo = -1;
142 unlink(kUDEV_FIFO);
143 }
145}
146#endif // !CONFIG_QTDBUS
147
148
149// Loop through the file system table and add any supported devices.
150// NOLINTNEXTLINE(readability-convert-member-functions-to-static)
152{
153#if HAVE_FSTAB_H
154 struct fstab * mep = nullptr;
155
156 // Attempt to open the file system descriptor entry.
157 if (!setfsent())
158 {
159 fstabError(":CheckFileSystemTable()");
160 return false;
161 }
162
163 // Add all the entries
164 while ((mep = getfsent()) != nullptr)
165 AddDevice(mep);
166
167 endfsent();
168
169 return !m_devices.isEmpty();
170#else
171 return false;
172#endif
173}
174
175#if CONFIG_QTDBUS
176// Get a device property by name
177static QVariant DriveProperty(const QDBusObjectPath& o, const std::string& kszProperty)
178{
179 QVariant v;
180 QDBusInterface iface(UDISKS2_SVC, o.path(), UDISKS2_SVC_DRIVE,
181 QDBusConnection::systemBus() );
182 if (iface.isValid())
183 {
184 v = iface.property(kszProperty.c_str());
185 LOG(VB_MEDIA, LOG_DEBUG, LOC +
186 "Udisks2:Drive:" + kszProperty.c_str() + " : " +
187 (v.canConvert<QStringList>() ? v.toStringList().join(", ") : v.toString()) );
188 }
189 return v;
190}
191
192// Uses a QDBusObjectPath for a block device as input parameter
193static bool DetectDevice(const QDBusObjectPath& entry, MythUdisksDevice& device,
194 QString& desc, QString& dev)
195{
196 QDBusInterface block(UDISKS2_SVC, entry.path(), UDISKS2_SVC_BLOCK,
197 QDBusConnection::systemBus() );
198
199 if (!block.property("HintSystem").toBool() &&
200 !block.property("HintIgnore").toBool())
201 {
202 dev = block.property("Device").toString();
203 LOG(VB_MEDIA, LOG_DEBUG, LOC +
204 "DetectDevice: Device found: " + dev);
205
206 // ignore floppies, too slow
207 if (dev.startsWith("/dev/fd"))
208 return false;
209
210 // Check if device has partitions
211 QDBusInterface properties(UDISKS2_SVC, entry.path(),
212 "org.freedesktop.DBus.Properties", QDBusConnection::systemBus());
213
214 auto mountpointscall = properties.call("Get", UDISKS2_SVC_FILESYSTEM,
215 "MountPoints");
216 bool isfsmountable = (properties.lastError().type() == QDBusError::NoError);
217
218 LOG(VB_MEDIA, LOG_DEBUG, LOC +
219 QString(" DetectDevice:Entry:isfsmountable : %1").arg(isfsmountable));
220
221 // Get properties of the corresponding drive
222 // Note: the properties 'Optical' and 'OpticalBlank' needs a medium inserted
223 auto drivePath = block.property("Drive").value<QDBusObjectPath>();
224 desc = DriveProperty(drivePath, "Vendor").toString();
225 if (!desc.isEmpty())
226 desc += " ";
227 desc += DriveProperty(drivePath, "Model").toString();
228 LOG(VB_MEDIA, LOG_DEBUG, LOC +
229 QString("DetectDevice: Found drive '%1'").arg(desc));
230 const auto media = DriveProperty(drivePath, "MediaCompatibility").toStringList();
231 const bool isOptical = !media.filter("optical", Qt::CaseInsensitive).isEmpty();
232
233 if (DriveProperty(drivePath, "Removable").toBool())
234 {
235 if (isOptical)
236 {
237 device = UDisks2DVD;
238 return true;
239 }
240 if (isfsmountable)
241 {
242 device = UDisks2HDD;
243 return true;
244 }
245 }
246 }
247 return false;
248}
249#endif // CONFIG_QTDBUS
250
251
264{
265#if CONFIG_QTDBUS
266 for (int i = 0; i < 10; ++i, std::this_thread::sleep_for(500ms))
267 {
268 // Connect to UDisks2. This can sometimes fail if mythfrontend
269 // is started during system init
270 QDBusInterface ifacem(UDISKS2_SVC, UDISKS2_PATH_MANAGER,
271 UDISKS2_SVC_MANAGER, QDBusConnection::systemBus() );
272
273 if (ifacem.isValid())
274 {
275 if (!ifacem.property("Version").toString().isEmpty())
276 {
277 // Minimal supported UDisk2 version: UDISKS2_MIN_VERSION
278 QString mversion = ifacem.property("Version").toString();
279 QVersionNumber this_version = QVersionNumber::fromString(mversion);
280 QVersionNumber min_version = QVersionNumber::fromString(UDISKS2_MIN_VERSION);
281 LOG(VB_MEDIA, LOG_DEBUG, LOC + "Using UDisk2 version " + mversion);
282
283 if (QVersionNumber::compare(this_version, min_version) < 0)
284 {
285 LOG(VB_GENERAL, LOG_ERR, LOC +
286 "CheckMountable: UDisks2 version too old: " + mversion);
287 return false;
288 }
289 }
290 else
291 {
292 LOG(VB_GENERAL, LOG_ERR, LOC +
293 "Cannot retrieve UDisks2 version, stopping device discovery");
294 return false;
295 }
296 }
297 else
298 {
299 LOG(VB_GENERAL, LOG_WARNING, LOC +
300 "Cannot interface to UDisks2, will retry");
301 continue;
302 }
303
304 // Get device paths
305 using QDBusObjectPathList = QList<QDBusObjectPath>;
306 QDBusPendingReply<QDBusObjectPathList> reply = ifacem.call("GetBlockDevices",
307 QVariantMap{});
308 reply.waitForFinished();
309 if (!reply.isValid())
310 {
311 LOG(VB_GENERAL, LOG_ALERT, LOC +
312 "CheckMountable DBus GetBlockDevices error: " +
313 reply.error().message() );
314 continue;
315 }
316
317 LOG(VB_MEDIA, LOG_DEBUG, LOC +
318 "CheckMountable: Start listening on UDisks2 DBus");
319
320 // Listen on DBus for UDisk add/remove device messages
321 (void)QDBusConnection::systemBus().connect(UDISKS2_SVC, UDISKS2_PATH,
322 "org.freedesktop.DBus.ObjectManager", "InterfacesAdded",
323 this, SLOT(deviceAdded(QDBusObjectPath,QMap<QString,QVariant>)) );
324 (void)QDBusConnection::systemBus().connect(UDISKS2_SVC, UDISKS2_PATH,
325 "org.freedesktop.DBus.ObjectManager", "InterfacesRemoved",
326 this, SLOT(deviceRemoved(QDBusObjectPath,QStringList)) );
327
328 // Parse the returned device array
329 const QDBusObjectPathList& list(reply.value());
330 for (const auto& entry : std::as_const(list))
331 {
332 // Create the MythMediaDevice
333 MythMediaDevice* pDevice = nullptr;
334 MythUdisksDevice mythdevice = UDisks2INVALID;
335 QString description;
336 QString path;
337
338 if (DetectDevice(entry, mythdevice, description, path))
339 {
340 if (mythdevice == UDisks2DVD)
341 {
342 pDevice = MythCDROM::get(this, path.toLatin1(), false, m_allowEject);
343 LOG(VB_MEDIA, LOG_DEBUG, LOC +
344 "deviceAdded: Added MythCDROM: " + path);
345 }
346 else if (mythdevice == UDisks2HDD)
347 {
348 pDevice = MythHDD::Get(this, path.toLatin1().constData(), false, false);
349 LOG(VB_MEDIA, LOG_DEBUG, LOC +
350 "deviceAdded: Added MythHDD: " + path);
351 }
352 }
353 if (pDevice)
354 {
355 // Set the device model and try to add the device
356 pDevice -> setDeviceModel(description.toLatin1().constData());
357 if (!MediaMonitorUnix::AddDevice(pDevice))
358 pDevice->deleteLater();
359 }
360 }
361
362 // Success
363 return true;
364 }
365
366 // Timed out
367 return false;
368
369#elif defined(Q_OS_LINUX)
370 // NB needs script in /etc/udev/rules.d
371 mkfifo(kUDEV_FIFO, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
372 m_fifo = open(kUDEV_FIFO, O_RDONLY | O_NONBLOCK);
373
374 QDir sysfs("/sys/block");
375 sysfs.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
376
377 auto list = sysfs.entryList();
378 for (const auto& device : std::as_const(list))
379 {
380 // ignore floppies, too slow
381 if (device.startsWith("fd"))
382 continue;
383
384 sysfs.cd(device);
385 QString path = sysfs.absolutePath();
386 if (CheckRemovable(path))
387 FindPartitions(path, true);
388 sysfs.cdUp();
389 }
390 return true;
391#else // not CONFIG_QTDBUS and not linux
392 return false;
393#endif
394}
395
396#if !CONFIG_QTDBUS
400bool MediaMonitorUnix::CheckRemovable(const QString &dev)
401{
402#ifdef Q_OS_LINUX
403 QString removablePath = dev + "/removable";
404 QFile removable(removablePath);
405 if (removable.exists() && removable.open(QIODevice::ReadOnly))
406 {
407 char c = 0;
408 QString msg = LOC + ":CheckRemovable(" + dev + ")/removable ";
409 bool ok = removable.getChar(&c);
410 removable.close();
411
412 if (ok)
413 {
414 LOG(VB_MEDIA, LOG_DEBUG, msg + c);
415 if (c == '1')
416 return true;
417 }
418 else
419 {
420 LOG(VB_GENERAL, LOG_ALERT, msg + "failed");
421 }
422 }
423 return false;
424#else // if !linux
425 return false;
426#endif // !linux
427}
428
434QString MediaMonitorUnix::GetDeviceFile(const QString &sysfs)
435{
436 QString msg = LOC + ":GetDeviceFile(" + sysfs + ")";
437 QString ret = sysfs;
438
439 // In case of error, a working default? (device names usually match)
440 ret.replace(QRegularExpression(".*/"), "/dev/");
441
442#ifdef Q_OS_LINUX
443# if HAVE_LIBUDEV
444 // Use libudev to determine the name
445 ret.clear();
446 struct udev *udev = udev_new();
447 if (udev != nullptr)
448 {
449 struct udev_device *device =
450 udev_device_new_from_syspath(udev, sysfs.toLatin1().constData());
451 if (device != nullptr)
452 {
453 const char *name = udev_device_get_devnode(device);
454
455 if (name != nullptr)
456 ret = tr(name);
457 else
458 {
459 // This can happen when udev sends an AddDevice for a block
460 // device with partitions. FindPartition locates a partition
461 // in sysfs but udev hasn't created the devnode for it yet.
462 // Udev will send another AddDevice for the partition later.
463 LOG(VB_MEDIA, LOG_DEBUG, msg + " devnode not (yet) known");
464 }
465
466 udev_device_unref(device);
467 }
468 else
469 {
470 LOG(VB_GENERAL, LOG_ALERT,
471 msg + " udev_device_new_from_syspath returned NULL");
472 ret = "";
473 }
474
475 udev_unref(udev);
476 }
477 else
478 LOG(VB_GENERAL, LOG_ALERT,
479 "MediaMonitorUnix::GetDeviceFile udev_new failed");
480# else // !HAVE_LIBUDEV
481 // Use udevadm info to determine the name
482 QStringList args;
483 args << "info" << "-q" << "name"
484 << "-rp" << sysfs;
485
486 uint flags = kMSStdOut;
487 if (VERBOSE_LEVEL_CHECK(VB_MEDIA, LOG_DEBUG))
488 flags |= kMSStdErr;
489
490 // TODO: change this to a MythSystemLegacy on the stack?
491 auto *udevinfo = new MythSystemLegacy("udevinfo", args, flags);
492 udevinfo->Run(4s);
493 if( udevinfo->Wait() != GENERIC_EXIT_OK )
494 {
495 delete udevinfo;
496 return ret;
497 }
498
499 if (VERBOSE_LEVEL_CHECK(VB_MEDIA, LOG_DEBUG))
500 {
501 QTextStream estream(udevinfo->ReadAllErr());
502 while( !estream.atEnd() )
503 LOG(VB_MEDIA, LOG_DEBUG,
504 msg + " - udevadm info error...\n" + estream.readLine());
505 }
506
507 QTextStream ostream(udevinfo->ReadAll());
508 QString udevLine = ostream.readLine();
509 if (!udevLine.startsWith("device not found in database") )
510 ret = udevLine;
511
512 delete udevinfo;
513# endif // HAVE_LIBUDEV
514#endif // linux
515
516 LOG(VB_MEDIA, LOG_INFO, msg + "->'" + ret + "'");
517 return ret;
518}
519#endif // !CONFIG_QTDBUS
520
521/*
522 * \brief Reads the list devices known to be CD or DVD devices.
523 * \return list of CD and DVD device names.
524 */
525// pure virtual
527{
528 QStringList l;
529
530#if CONFIG_QTDBUS
531 QDBusInterface blocks(UDISKS2_SVC, UDISKS2_PATH_BLOCK_DEVICES,
532 "org.freedesktop.DBus.Introspectable", QDBusConnection::systemBus());
533
534 QDBusReply<QString> reply = blocks.call("Introspect");
535 QXmlStreamReader xml_parser(reply.value());
536
537 while (!xml_parser.atEnd())
538 {
539 xml_parser.readNext();
540
541 if (xml_parser.tokenType() == QXmlStreamReader::StartElement
542 && xml_parser.name().toString() == "node")
543 {
544 const QString &name = xml_parser.attributes().value("name").toString();
545#if 0
546 LOG(VB_MEDIA, LOG_DEBUG, LOC + "GetCDROMBlockDevices: name: " + name);
547#endif
548 if (!name.isEmpty())
549 {
550 QString sbdevices = QString::fromUtf8(UDISKS2_PATH_BLOCK_DEVICES);
551 QDBusObjectPath entry {sbdevices + "/" + name};
552 MythUdisksDevice mythdevice = UDisks2INVALID;
553 QString description;
554 QString dev;
555
556 LOG(VB_MEDIA, LOG_DEBUG, LOC +
557 "GetCDROMBlockDevices: path: " + entry.path());
558
559 if (DetectDevice(entry, mythdevice, description, dev))
560 {
561 if (mythdevice == UDisks2DVD)
562 {
563 LOG(VB_MEDIA, LOG_DEBUG, LOC +
564 "GetCDROMBlockDevices: Added: " + dev);
565
566 if (dev.startsWith("/dev/"))
567 dev.remove(0,5);
568 l.push_back(dev);
569 }
570 }
571 }
572 }
573 }
574
575#elif defined(Q_OS_LINUX)
576 QFile file("/proc/sys/dev/cdrom/info");
577 if (file.open(QIODevice::ReadOnly))
578 {
579 QString line;
580 QTextStream stream(&file);
581 while (!stream.atEnd())
582 {
583 line = stream.readLine();
584 if (line.startsWith("drive name:"))
585 {
586 l = line.split('\t', Qt::SkipEmptyParts);
587 l.pop_front(); // Remove 'drive name:' field
588 break; // file should only contain one drive table?
589 }
590 }
591 file.close();
592 }
593#endif // linux
594
595 LOG(VB_MEDIA, LOG_DEBUG,
596 LOC + ":GetCDROMBlockDevices()->'" + l.join(", ") + "'");
597 return l;
598}
599
600#if !CONFIG_QTDBUS
601static void LookupModel(MythMediaDevice* device)
602{
603 QString desc;
604
605#if defined(Q_OS_LINUX)
606 // Given something like /dev/hda1, extract hda1
607 QString devname = device->getRealDevice().mid(5,5);
608
609 if (devname.startsWith("hd")) // IDE drive
610 {
611 QFile file("/proc/ide/" + devname.left(3) + "/model");
612 if (file.open(QIODevice::ReadOnly))
613 {
614 QTextStream stream(&file);
615
616 desc.append(stream.readLine());
617 file.close();
618 }
619 }
620
621 if (devname.startsWith("scd")) // scd0 doesn't appear in /sys/block,
622 devname.replace("scd", "sr"); // use sr0 instead
623
624 if (devname.startsWith("sd") // SATA/USB/FireWire
625 || devname.startsWith("sr")) // SCSI CD-ROM?
626 {
627 QString path = devname.prepend("/sys/block/");
628 path.append("/device/");
629
630 QFile file(path + "vendor");
631 if (file.open(QIODevice::ReadOnly))
632 {
633 QTextStream stream(&file);
634
635 desc.append(stream.readLine());
636 desc.append(' ');
637 file.close();
638 }
639
640 file.setFileName(path + "model");
641 if (file.open(QIODevice::ReadOnly))
642 {
643 QTextStream stream(&file);
644
645 desc.append(stream.readLine());
646 desc.append(' ');
647 file.close();
648 }
649 }
650#endif
651
652 LOG(VB_MEDIA, LOG_DEBUG, QString("LookupModel '%1' -> '%2'")
653 .arg(device->getRealDevice(), desc) );
654 device->setDeviceModel(desc.toLatin1().constData());
655}
656#endif
657
658
663{
664 if ( ! pDevice )
665 {
666 LOG(VB_GENERAL, LOG_ERR, "MediaMonitorUnix::AddDevice(null)");
667 return false;
668 }
669
670 // If the user doesn't want this device to be monitored, stop now:
671 if (shouldIgnore(pDevice))
672 return false;
673
674 QString path = pDevice->getDevicePath();
675 if (path.isEmpty())
676 {
677 LOG(VB_GENERAL, LOG_ALERT,
678 "MediaMonitorUnix::AddDevice() - empty device path.");
679 return false;
680 }
681
682 struct stat sb {};
683 if (stat(path.toLocal8Bit().constData(), &sb) < 0)
684 {
685 statError(":AddDevice()", path);
686 return false;
687 }
688 dev_t new_rdev = sb.st_rdev;
689
690 //
691 // Check if this is a duplicate of a device we have already added
692 //
693 for (const auto *device : std::as_const(m_devices))
694 {
695 if (stat(device->getDevicePath().toLocal8Bit().constData(), &sb) < 0)
696 {
697 statError(":AddDevice()", device->getDevicePath());
698 return false;
699 }
700
701 if (sb.st_rdev == new_rdev)
702 {
703 LOG(VB_MEDIA, LOG_INFO,
704 LOC + ":AddDevice() - not adding " + path +
705 "\n "
706 "because it appears to be a duplicate of " +
707 device->getDevicePath());
708 return false;
709 }
710 }
711#if !CONFIG_QTDBUS
712 // Device vendor and name already fetched by UDisks2
713 LookupModel(pDevice);
714#endif
715 QMutexLocker locker(&m_devicesLock);
716
717 connect(pDevice, &MythMediaDevice::statusChanged,
719 m_devices.push_back( pDevice );
720 m_useCount[pDevice] = 0;
721 LOG(VB_MEDIA, LOG_INFO, LOC + ":AddDevice() - Added " + path);
722
723 return true;
724}
725
726#if HAVE_FSTAB_H
727// Given a fstab entry to a media device determine what type of device it is
728bool MediaMonitorUnix::AddDevice(struct fstab * mep)
729{
730 if (!mep)
731 return false;
732
733#if 0
734 QString devicePath( mep->fs_spec );
735 LOG(VB_GENERAL, LOG_DEBUG, "AddDevice - " + devicePath);
736#endif
737
738 MythMediaDevice* pDevice = nullptr;
739 struct stat sbuf {};
740
741 bool is_supermount = false;
742 bool is_cdrom = false;
743
744 if (stat(mep->fs_spec, &sbuf) < 0)
745 return false;
746
747 // Can it be mounted?
748 if ( ! ( ((strstr(mep->fs_mntops, "owner") &&
749 (sbuf.st_mode & S_IRUSR)) || strstr(mep->fs_mntops, "user")) &&
750 (strstr(mep->fs_vfstype, MNTTYPE_ISO9660) ||
751 strstr(mep->fs_vfstype, MNTTYPE_UDF) ||
752 strstr(mep->fs_vfstype, MNTTYPE_AUTO)) ) )
753 {
754 if (strstr(mep->fs_mntops, MNTTYPE_ISO9660) &&
755 strstr(mep->fs_vfstype, MNTTYPE_SUPERMOUNT))
756 {
757 is_supermount = true;
758 }
759 else
760 {
761 return false;
762 }
763 }
764
765 if (strstr(mep->fs_mntops, MNTTYPE_ISO9660) ||
766 strstr(mep->fs_vfstype, MNTTYPE_ISO9660) ||
767 strstr(mep->fs_vfstype, MNTTYPE_UDF) ||
768 strstr(mep->fs_vfstype, MNTTYPE_AUTO))
769 {
770 is_cdrom = true;
771#if 0
772 LOG(VB_GENERAL, LOG_DEBUG, "Device is a CDROM");
773#endif
774 }
775
776 if (!is_supermount)
777 {
778 if (is_cdrom)
779 pDevice = MythCDROM::get(this, mep->fs_spec,
780 is_supermount, m_allowEject);
781 }
782 else
783 {
784 QString dev(mep->fs_mntops);
785 int pos = dev.indexOf(QString::fromStdString(kSuperOptDev));
786 if (pos == -1)
787 return false;
788 dev = dev.mid(pos+kSuperOptDev.size());
789 static const QRegularExpression kSeparatorRE { "[, ]" };
790 QStringList parts = dev.split(kSeparatorRE, Qt::SkipEmptyParts);
791 if (parts[0].isEmpty())
792 return false;
793 pDevice = MythCDROM::get(this, dev, is_supermount, m_allowEject);
794 }
795
796 if (pDevice)
797 {
798 pDevice->setMountPath(mep->fs_file);
799 if (pDevice->testMedia() == MEDIAERR_OK)
800 {
801 if (MediaMonitorUnix::AddDevice(pDevice))
802 return true;
803 }
804 pDevice->deleteLater();
805 }
806
807 return false;
808}
809#endif
810
811#if CONFIG_QTDBUS
812/*
813 * DBus UDisk AddDevice handler
814 */
815
816void MediaMonitorUnix::deviceAdded( const QDBusObjectPath& o,
817 const QMap<QString, QVariant> &interfaces)
818{
819 if (!interfaces.contains(QStringLiteral("org.freedesktop.UDisks2.Block")))
820 return;
821
822 LOG(VB_MEDIA, LOG_DEBUG, LOC + ":deviceAdded " + o.path());
823
824 // Create the MythMediaDevice
825 MythMediaDevice* pDevice = nullptr;
826 MythUdisksDevice mythdevice = UDisks2INVALID;
827 QString description;
828 QString path;
829
830 if (DetectDevice(o, mythdevice, description, path))
831 {
832 if (mythdevice == UDisks2DVD)
833 {
834 pDevice = MythCDROM::get(this, path.toLatin1(), false, m_allowEject);
835 LOG(VB_MEDIA, LOG_DEBUG, LOC +
836 "deviceAdded: Added MythCDROM: " + path);
837 }
838 else if (mythdevice == UDisks2HDD)
839 {
840 pDevice = MythHDD::Get(this, path.toLatin1().constData(), false, false);
841 LOG(VB_MEDIA, LOG_DEBUG, LOC +
842 "deviceAdded: Added MythHDD: " + path);
843 }
844 }
845 if (pDevice)
846 {
847 pDevice -> setDeviceModel(description.toLatin1().constData());
848 if (!MediaMonitorUnix::AddDevice(pDevice))
849 pDevice->deleteLater();
850 }
851}
852
853/*
854 * DBus UDisk RemoveDevice handler
855 */
856void MediaMonitorUnix::deviceRemoved(const QDBusObjectPath& o, const QStringList &interfaces)
857{
858 if (!interfaces.contains(QStringLiteral("org.freedesktop.UDisks2.Block")))
859 return;
860
861 LOG(VB_MEDIA, LOG_INFO, LOC + "deviceRemoved " + o.path());
862
863 QString dev = QFileInfo(o.path()).baseName();
864 dev.prepend("/dev/");
865 RemoveDevice(dev);
866}
867
868#else //CONFIG_QTDBUS
869
886bool MediaMonitorUnix::FindPartitions(const QString &dev, bool checkPartitions)
887{
888 LOG(VB_MEDIA, LOG_DEBUG,
889 LOC + ":FindPartitions(" + dev +
890 QString(",%1").arg(checkPartitions ? " true" : " false" ) + ")");
891 MythMediaDevice* pDevice = nullptr;
892
893 if (checkPartitions)
894 {
895 // check for partitions
896 QDir sysfs(dev);
897 sysfs.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
898
899 bool found_partitions = false;
900 QStringList parts = sysfs.entryList();
901 for (const auto& part : std::as_const(parts))
902 {
903 // skip some sysfs dirs that are _not_ sub-partitions
904 if (part == "device" || part == "holders" || part == "queue"
905 || part == "slaves" || part == "subsystem"
906 || part == "bdi" || part == "power")
907 continue;
908
909 found_partitions |= FindPartitions(
910 sysfs.absoluteFilePath(part), false);
911 }
912
913 // no partitions on block device, use main device
914 if (!found_partitions)
915 found_partitions |= FindPartitions(sysfs.absolutePath(), false);
916
917 return found_partitions;
918 }
919
920 QString device_file = GetDeviceFile(dev);
921
922 if (device_file.isEmpty())
923 return false;
924
925 QStringList cdroms = GetCDROMBlockDevices();
926
927 if (cdroms.contains(dev.section('/', -1)))
928 {
929 // found cdrom device
930 pDevice = MythCDROM::get(
931 this, device_file.toLatin1().constData(), false, m_allowEject);
932 }
933 else
934 {
935 // found block or partition device
936 pDevice = MythHDD::Get(
937 this, device_file.toLatin1().constData(), false, false);
938 }
939
940 if (AddDevice(pDevice))
941 return true;
942
943 if (pDevice)
944 pDevice->deleteLater();
945
946 return false;
947}
948
955{
956 std::string buffer(256,'\0');
957 QString qBuffer;
958
959 if (m_fifo == -1)
960 return;
961
962 int size = read(m_fifo, buffer.data(), 255);
963 while (size > 0)
964 {
965 // append buffer to QString
966 buffer[size] = '\0';
967 qBuffer.append(QString::fromStdString(buffer));
968 size = read(m_fifo, buffer.data(), 255);
969 }
970 const QStringList list = qBuffer.split('\n', Qt::SkipEmptyParts);
971 for (const auto& notif : std::as_const(list))
972 {
973 if (notif.startsWith("add"))
974 {
975 QString dev = notif.section(' ', 1, 1);
976 LOG(VB_MEDIA, LOG_INFO, "Udev add " + dev);
977
978 if (CheckRemovable(dev))
979 FindPartitions(dev, true);
980 }
981 else if (notif.startsWith("remove"))
982 {
983 QString dev = notif.section(' ', 2, 2);
984 LOG(VB_MEDIA, LOG_INFO, "Udev remove " + dev);
985 RemoveDevice(dev);
986 }
987 }
988}
989#endif
990
991#if CONFIG_QTDBUS
992#include "moc_mediamonitor-unix.cpp"
993#endif
static bool CheckRemovable(const QString &dev)
Is /sys/block/dev a removable device?
bool AddDevice(MythMediaDevice *pDevice) override
CONFIG_QTDBUS.
MediaMonitorUnix(QObject *par, unsigned long interval, bool allowEject)
bool CheckMountable(void)
Search /sys/block for valid removable media devices.
bool FindPartitions(const QString &dev, bool checkPartitions)
Creates MythMedia instances for sysfs removable media devices.
QStringList GetCDROMBlockDevices(void) override
bool CheckFileSystemTable(void)
void deleteLater(void) override
void CheckDeviceNotifications(void) override
Checks the named pipe, kUDEV_FIFO, for hotplug events from the udev system.
static QString GetDeviceFile(const QString &sysfs)
Returns the device special file associated with the /sys/block node.
static constexpr const char * kUDEV_FIFO
void mediaStatusChanged(MythMediaStatus oldStatus, MythMediaDevice *pMedia) const
Slot which is called when the device status changes and posts a media event to the mainwindow.
bool RemoveDevice(const QString &dev)
Remove a device from the media monitor.
QRecursiveMutex m_devicesLock
Definition: mediamonitor.h:123
bool shouldIgnore(const MythMediaDevice *device)
Check user preferences to see if this device should be monitored.
QList< MythMediaDevice * > m_devices
Definition: mediamonitor.h:124
virtual void deleteLater(void)
QMap< MythMediaDevice *, int > m_useCount
Definition: mediamonitor.h:126
QString listDevices(void)
A string summarising the current devices, for debugging.
static MythCDROM * get(QObject *par, const QString &devicePath, bool SuperMount, bool AllowEject)
Definition: mythcdrom.cpp:44
bool GetBoolSetting(const QString &key, bool defaultval=false)
static MythHDD * Get(QObject *par, const char *devicePath, bool SuperMount, bool AllowEject)
Helper function used to create a new instance of a hard disk device.
Definition: mythhdd.cpp:15
const QString & getRealDevice() const
Definition: mythmedia.h:63
void statusChanged(MythMediaStatus oldStatus, MythMediaDevice *pMedia)
const QString & getDevicePath() const
Definition: mythmedia.h:61
virtual MythMediaError testMedia()
Definition: mythmedia.h:95
void setMountPath(const char *path)
Definition: mythmedia.h:59
void setDeviceModel(const char *model)
Definition: mythmedia.h:68
#define mkfifo(path, mode)
Definition: compat.h:89
#define O_NONBLOCK
Definition: compat.h:139
unsigned int uint
Definition: compat.h:60
#define close
Definition: compat.h:28
@ GENERIC_EXIT_OK
Exited with no error.
Definition: exitcodes.h:13
static void LookupModel(MythMediaDevice *device)
static void statError(const QString &methodName, const QString &devPath)
static const QString LOC
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
static bool VERBOSE_LEVEL_CHECK(uint64_t mask, LogLevel_t level)
Definition: mythlogging.h:29
#define ENO
This can be appended to the LOG args with "+".
Definition: mythlogging.h:74
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
@ MEDIAERR_OK
Definition: mythmedia.h:40
@ kMSStdErr
allow access to stderr
Definition: mythsystem.h:42
@ kMSStdOut
allow access to stdout
Definition: mythsystem.h:41
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:39
def read(device=None, features=[])
Definition: disc.py:35