Repository navigation
Expand file tree
/
Copy paththreadscan.cpp
More file actions
1597 lines (1351 loc) · 61.5 KB
/
Copy paththreadscan.cpp
File metadata and controls
1597 lines (1351 loc) · 61.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ****************************************************************************
// Project: GUYMAGER
// ****************************************************************************
// Programmer: Guy Voncken
// Police Grand-Ducale
// Service de Police Judiciaire
// Section Nouvelles Technologies
// ****************************************************************************
// Module: Thread for scanning the connected devices
// ****************************************************************************
// Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
// 2018, 2019, 2020
// Guy Voncken
//
// This file is part of Guymager.
//
// Guymager is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Guymager is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Guymager. If not, see <http://www.gnu.org/licenses/>.
#include <QtCore>
#include <QtDBus/QtDBus>
#include <dlfcn.h>
#include <unistd.h>
#include <libudev.h>
#include "toolconstants.h"
#include "common.h"
#include "config.h"
#include "device.h"
#include "qtutil.h"
#include "media.h"
#include "dlgmessage.h"
#include "threadscan.h"
// --------------------------
// Constants
// --------------------------
//#define DEBUG_SERNR
#ifdef DEBUG_SERNR
#warning "DEBUG_SERNR must be switched off for final release"
#endif
const int THREADSCAN_WAIT_MAX = 30000;
const int THREADSCAN_WAIT_GRANULARITY = 100;
const QString ThreadScanLibSearchDirs = "/lib,/usr/lib,/usr/lib64,/usr/local/lib"; // Separate directories by commas
const int ThreadScanLibSearchMaxDepth = 1; // Max. depth for recursing into directories indicated under
// ThreadScanLibPartedSearchDirs, 0=only directory indicated, 1=also descend 1 below, ...
const QString ThreadScanLibPartedSearchPattern = "libparted*.so*";
const QString ThreadScanLibUdevSearchPattern = "libudev*.so*";
// -----------------------------------
// Worker base class
// -----------------------------------
t_ThreadScanWorker::t_ThreadScanWorker (t_ThreadScan *pThreadScan)
{
poThreadScan = pThreadScan;
}
// -----------------------------------
// Utility functions used by workers
// -----------------------------------
static bool ThreadScanDeviceIsListed (QStringList *pList, t_pDevice pDevice)
{
bool Listed=false;
if (CONFIG(LocalHiddenDevicesUseRegExp))
{
QRegExp RegExp;
RegExp.setCaseSensitivity(Qt::CaseInsensitive);
foreach (QString Str, *pList)
{
RegExp.setPattern (Str);
Listed = (RegExp.indexIn(pDevice->SerialNumber) != -1) ||
(RegExp.indexIn(pDevice->LinuxDevice ) != -1) ||
(RegExp.indexIn(pDevice->Model ) != -1) ||
(RegExp.indexIn(pDevice->NativePath ) != -1) ||
(RegExp.indexIn(pDevice->ByPath ) != -1) ||
(RegExp.indexIn(pDevice->Interface ) != -1);
if (Listed)
break;
}
}
else
{
Listed = pList->contains (pDevice->SerialNumber, Qt::CaseInsensitive) ||
pList->contains (pDevice->LinuxDevice , Qt::CaseInsensitive) ||
pList->contains (pDevice->Model , Qt::CaseInsensitive) ||
pList->contains (pDevice->NativePath , Qt::CaseInsensitive) ||
pList->contains (pDevice->ByPath , Qt::CaseInsensitive) ||
pList->contains (pDevice->Interface , Qt::CaseInsensitive);
}
return Listed;
}
static APIRET ThreadScanSetLocal (t_pDevice pDevice)
{
QStringList *pLocalDevices;
CHK_EXIT (CfgGetLocalDevices (&pLocalDevices))
pDevice->Local = ThreadScanDeviceIsListed (pLocalDevices, pDevice);
return NO_ERROR;
}
static bool ThreadScanIsHidden (t_pDevice pDevice)
{
QStringList *pHiddenDevices;
bool Hidden;
CHK_EXIT (CfgGetHiddenDevices (&pHiddenDevices))
Hidden = ThreadScanDeviceIsListed (pHiddenDevices, pDevice);
return Hidden;
}
static APIRET ThreadScanGetAddStateInfo (t_pDevice pDevice)
{
QString Command;
APIRET rc;
QString StateInfo;
QStringList StateInfoList;
Command = CONFIG (CommandGetAddStateInfo);
if (!Command.isEmpty())
{
Command.replace ("%dev" , pDevice->LinuxDevice , Qt::CaseInsensitive);
Command.replace ("%local", pDevice->Local ? "1":"0", Qt::CaseInsensitive);
rc = QtUtilProcessCommand (Command, &StateInfo);
if (rc == ERROR_QTUTIL_COMMAND_TIMEOUT)
{
LOG_INFO ("Timeout while trying to get additional state information for %s, additional state info will be ignored", QSTR_TO_PSZ(pDevice->LinuxDevice))
return NO_ERROR;
}
CHK(rc)
StateInfoList = StateInfo.split("\n");
if (StateInfoList.count() > 0) pDevice->AddStateInfo.Info = StateInfoList[0].trimmed();
if (StateInfoList.count() > 1) pDevice->AddStateInfo.CanBeAcquired = (StateInfoList[1].trimmed() != "0");
if (StateInfoList.count() > 2) pDevice->AddStateInfo.Color = StateInfoList[2].trimmed().toInt();
}
return NO_ERROR;
}
// --------------------------
// t_ThreadScanWorkerParted
// --------------------------
// Scan the devices using libparted and bash command to gather device info
typedef void (*t_pFnLibPartedProbeAll) (void) ;
typedef PedDevice* (*t_pFnLibPartedGetNext ) (const PedDevice* pDev);
typedef void (*t_pFnLibPartedFreeAll ) (void);
class t_ThreadScanWorkerPartedLocal
{
public:
t_ThreadScanWorkerPartedLocal ()
:LibPartedLoaded (false), pLibPartedHandle (nullptr),
pFnLibPartedProbeAll (nullptr) ,
pFnLibPartedGetNext (nullptr) ,
pFnLibPartedFreeAll (nullptr)
{
}
public:
bool LibPartedLoaded;
void *pLibPartedHandle;
t_pFnLibPartedProbeAll pFnLibPartedProbeAll;
t_pFnLibPartedGetNext pFnLibPartedGetNext;
t_pFnLibPartedFreeAll pFnLibPartedFreeAll;
};
static APIRET ThreadScanGetSerialNumber (char const *pcDeviceName, QString &SerialNumber)
{
QString Command;
APIRET rc;
Command = CONFIG (CommandGetSerialNumber);
Command.replace ("%dev", pcDeviceName, Qt::CaseInsensitive);
rc = QtUtilProcessCommand (Command, &SerialNumber);
if (rc == ERROR_QTUTIL_COMMAND_TIMEOUT)
return rc;
CHK(rc)
SerialNumber = SerialNumber.trimmed();
return NO_ERROR;
}
static APIRET ThreadScanCheckForceSerialNumber (char const *pcDeviceName, QVariant *pSerialNumber)
{
if (CONFIG(ForceCommandGetSerialNumber))
{
QString SN;
APIRET rc;
rc = ThreadScanGetSerialNumber (pcDeviceName, SN);
if (rc == ERROR_QTUTIL_COMMAND_TIMEOUT)
{
LOG_INFO ("Timeout while trying to get serial number for %s", pcDeviceName)
SN.clear();
}
else
{
CHK_EXIT (rc)
}
pSerialNumber->setValue(SN);
}
return NO_ERROR;
}
static APIRET ThreadScanFindLib0 (const QString &Path, QStringList &Files, const QString &SearchPattern, int RecurseLevel=0)
{
QStringList SearchDirs;
QFileInfoList ItemList;
// static int DirCount=0;
// Search for files in current dir
// -------------------------------
// printf ("%d / %d - Into %s\n", RecurseLevel, DirCount++, QSTR_TO_PSZ(Path));
QDir SearchDir(Path);
ItemList = SearchDir.entryInfoList (QStringList(SearchPattern), QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name);
foreach (const QFileInfo &Item, ItemList)
{
if (Item.isDir())
{
if (RecurseLevel<ThreadScanLibSearchMaxDepth)
{
CHK (ThreadScanFindLib0 (Item.absoluteFilePath(), Files, SearchPattern, ++RecurseLevel)) // Recurse into subdirs (must be pre-increment!)
RecurseLevel--;
}
}
else
{
LOG_INFO ("lib for '%s' found: %s", QSTR_TO_PSZ(SearchPattern), QSTR_TO_PSZ(Item.absoluteFilePath()));
Files += Item.absoluteFilePath();
}
}
return NO_ERROR;
}
static APIRET ThreadScanFindLib (QStringList &Files, const QString &SearchPattern)
{
QStringList SearchDirs;
int i;
SearchDirs = ThreadScanLibSearchDirs.split(",");
for (i=0; i<SearchDirs.size(); i++)
CHK (ThreadScanFindLib0 (SearchDirs[i], Files, SearchPattern))
if (Files.empty())
LOG_INFO ("No libparted could be found")
return NO_ERROR;
}
t_ThreadScanWorkerParted::t_ThreadScanWorkerParted (t_ThreadScan *pThreadScan, APIRET &rc)
:t_ThreadScanWorker (pThreadScan)
{
QStringList FilenameList;
QString Filename;
char *pErrStr;
int i;
bool Found = false;
rc = ERROR_THREADSCAN_LIBPARTED_NOTWORKING;
pOwn = new t_ThreadScanWorkerPartedLocal();
CHK_EXIT (ThreadScanFindLib (FilenameList, ThreadScanLibPartedSearchPattern))
for (i=0; (i<FilenameList.size()) && (!Found); i++)
{
Filename = FilenameList[i];
pOwn->pLibPartedHandle = dlopen (QSTR_TO_PSZ(Filename), RTLD_NOW);
if (pOwn->pLibPartedHandle == nullptr)
{
LOG_INFO ("Trying %s -- dlopen returns (%s)", QSTR_TO_PSZ(Filename), dlerror())
continue;
}
LOG_INFO ("Trying %s -- dlopen ok", QSTR_TO_PSZ(Filename))
// GETFN: See dlsym documentation concerning the usage of dlerror for error checking
#define GETFN(pFn, Type, pFnName) \
dlerror(); \
pFn = (Type)dlsym (pOwn->pLibPartedHandle, pFnName); \
pErrStr = dlerror(); \
if (pErrStr) \
{ \
LOG_INFO ("Trying %s -- dlsym for %s returns (%s)", QSTR_TO_PSZ(Filename), pFnName, dlerror()); \
dlclose (pOwn->pLibPartedHandle); \
pOwn->pLibPartedHandle = nullptr; \
pOwn->pFnLibPartedProbeAll= nullptr; \
pOwn->pFnLibPartedGetNext = nullptr; \
pOwn->pFnLibPartedFreeAll = nullptr; \
continue; \
} \
else \
{ \
LOG_INFO ("Trying %s -- dlsym for %s ok", QSTR_TO_PSZ(Filename), pFnName); \
}
GETFN (pOwn->pFnLibPartedProbeAll, t_pFnLibPartedProbeAll, "ped_device_probe_all")
GETFN (pOwn->pFnLibPartedGetNext , t_pFnLibPartedGetNext , "ped_device_get_next" )
GETFN (pOwn->pFnLibPartedFreeAll , t_pFnLibPartedFreeAll , "ped_device_free_all" )
#undef GETFN
Found = true;
}
if (Found)
rc = NO_ERROR;
}
t_ThreadScanWorkerParted::~t_ThreadScanWorkerParted (void)
{
int rc;
if (pOwn->pLibPartedHandle)
{
rc = dlclose (pOwn->pLibPartedHandle);
if (rc)
LOG_INFO ("dlclose returned %d (%s).", rc, dlerror());
}
delete pOwn;
}
void t_ThreadScanWorkerParted::SlotRescan (void)
{
t_pDeviceList pDeviceList;
t_pDevice pDevice;
PedDevice *pPedDev;
QString SerialNumber;
APIRET rc;
emit (SignalScanStarted ());
LOG_INFO ("Rescanning devices")
CHK_EXIT (poThreadScan->SetDebugMessage ("SlotRescan called (parted)"))
pOwn->pFnLibPartedProbeAll ();
pDeviceList = new t_DeviceList;
pPedDev = nullptr;
while ((pPedDev = pOwn->pFnLibPartedGetNext (pPedDev))) //lint !e820
{
rc = ThreadScanGetSerialNumber (pPedDev->path, SerialNumber);
if (rc == ERROR_QTUTIL_COMMAND_TIMEOUT)
{
LOG_INFO ("Device scan aborted due to timeout while trying to get serial number for %s", pPedDev->path)
pOwn->pFnLibPartedFreeAll ();
delete pDeviceList;
return;
}
#ifdef DEBUG_SERNR
printf ("\n----- libparted device info ---------");
printf ("\nPath: [%s]", pPedDev->path );
printf ("\nModel: [%s]", pPedDev->model);
printf ("\nSectorSize: %lld", pPedDev->sector_size);
printf ("\nSectorSizePhys: %lld", pPedDev->phys_sector_size);
printf ("\nLength (Sectors): %lld", pPedDev->length);
printf ("\nSerial number: [%s] -- read out by command %s" , QSTR_TO_PSZ(SerialNumber), CONFIG (CommandGetSerialNumber));
printf ("\n");
#endif
pDevice = new t_Device (SerialNumber, pPedDev);
if (ThreadScanIsHidden(pDevice))
{
delete pDevice;
}
else
{
pDeviceList->append (pDevice);
if (pDevice->LinuxDevice.startsWith ("/dev/fd", Qt::CaseSensitive)) // Not a good way for checking this, but I don't know how to extract the information from
pDevice->Removable = true; // PedDevice. BTW, this won't work with other removable devices, for instance memory sticks.
CHK_EXIT (ThreadScanSetLocal (pDevice));
CHK_EXIT (ThreadScanGetAddStateInfo (pDevice));
}
}
pOwn->pFnLibPartedFreeAll ();
emit (SignalScanFinished (pDeviceList));
CHK_EXIT (poThreadScan->SetDebugMessage ("Leaving SlotRescan (parted)"))
}
// ------------------------
// t_ThreadScanWorkerUdev
// ------------------------
#define THREADSCAN_UDEV_PATH_RAM "/sys/devices/virtual/block/ram"
#define THREADSCAN_UDEV_PATH_LOOP "/sys/devices/virtual/block/loop"
typedef struct udev * (*t_pFnLibUdev_udev_new) (void);
typedef struct udev * (*t_pFnLibUdev_udev_unref) (struct udev *udev);
typedef void (*t_pFnLibUdev_udev_device_unref) (struct udev_device *udev_device);
typedef struct udev_enumerate * (*t_pFnLibUdev_udev_enumerate_new) (struct udev *udev);
typedef struct udev_enumerate * (*t_pFnLibUdev_udev_enumerate_unref) (struct udev_enumerate *udev_enumerate);
typedef int (*t_pFnLibUdev_udev_enumerate_add_match_subsystem) (struct udev_enumerate *udev_enumerate, const char *subsystem);
typedef int (*t_pFnLibUdev_udev_enumerate_add_match_property) (struct udev_enumerate *udev_enumerate, const char *property, const char *value);
typedef int (*t_pFnLibUdev_udev_enumerate_scan_devices) (struct udev_enumerate *udev_enumerate);
typedef struct udev_list_entry * (*t_pFnLibUdev_udev_enumerate_get_list_entry) (struct udev_enumerate *udev_enumerate);
typedef const char * (*t_pFnLibUdev_udev_list_entry_get_name) (struct udev_list_entry *list_entry);
typedef struct udev_device * (*t_pFnLibUdev_udev_device_new_from_syspath) (struct udev *udev, const char *syspath);
typedef const char * (*t_pFnLibUdev_udev_device_get_property_value) (struct udev_device *udev_device, const char *key);
typedef struct udev_list_entry * (*t_pFnLibUdev_udev_list_entry_get_next) (struct udev_list_entry *list_entry);
#define LibUdevListEntryForEach(list_entry, first_entry) \
for (list_entry = first_entry; \
list_entry != nullptr; \
list_entry = pOwn->pFnLibUdev_udev_list_entry_get_next(list_entry))
#pragma GCC diagnostic ignored "-Wunused-result"
class t_ThreadScanWorkerUdevLocal
{
public:
t_ThreadScanWorkerUdevLocal ()
:LibUdevLoaded (false),
pLibUdevHandle (nullptr)
{
ClearFnPointers();
}
void ClearFnPointers (void)
{
pFnLibUdev_udev_new = nullptr;
pFnLibUdev_udev_unref = nullptr;
pFnLibUdev_udev_device_unref = nullptr;
pFnLibUdev_udev_enumerate_new = nullptr;
pFnLibUdev_udev_enumerate_unref = nullptr;
pFnLibUdev_udev_enumerate_add_match_subsystem = nullptr;
pFnLibUdev_udev_enumerate_add_match_property = nullptr;
pFnLibUdev_udev_enumerate_scan_devices = nullptr;
pFnLibUdev_udev_enumerate_get_list_entry = nullptr;
pFnLibUdev_udev_list_entry_get_name = nullptr;
pFnLibUdev_udev_device_new_from_syspath = nullptr;
pFnLibUdev_udev_device_get_property_value = nullptr;
pFnLibUdev_udev_list_entry_get_next = nullptr;
}
// GetFileContents; Join both path parts and read file contents into ppData.
// ppData is allocated by GetFileContents and must be freed by caller
// (only in case of successful call).
// Return values: 0=ok, 1=Error.
int GetFileContents (const char *pPath, const char *pSubPath, char **ppData)
{
const size_t MaxSize = 65536; // If the file is bigger than this then there's surely something wrong
char *pFullPath = nullptr;
FILE *pFile = nullptr;
size_t Read;
size_t Size;
*ppData = nullptr;
// Open file
// ---------
(void) asprintf (&pFullPath, "%s/%s", pPath, pSubPath);
if (!pFullPath)
goto Err;
pFile = fopen(pFullPath, "rb");
if (!pFile)
goto Err;
// Get and check file size
// -----------------------
if (fseek (pFile, 0, SEEK_END))
goto Err;
Size = ftell (pFile);
if (Size >= MaxSize)
goto Err;
if (fseek (pFile, 0, SEEK_SET))
goto Err;
// Read data
// ---------
*ppData = (char *) malloc(Size);
if (!*ppData)
goto Err;
Read = fread (*ppData, 1, Size, pFile);
if ((Read==0) || (Read >= MaxSize))
goto Err;
(*ppData)[Read-1] = '\0';
// Free resources
// --------------
fclose (pFile);
free (pFullPath);
return 0;
Err:
if (pFullPath) free (pFullPath);
if (*ppData) free (*ppData);
if (pFile) fclose (pFile);
return 1;
}
// GetFileContentsNum: See GetFileContents.
// Expects the file to start with a numerical value. If not, an error is returned.
// Same error codes as GetFileContents.
int GetFileContentsNum (const char *pPath, const char *pSubPath, long long *pVal)
{
char *pData;
char *pTail;
int rc;
rc = GetFileContents (pPath, pSubPath, &pData);
if (rc)
return rc;
*pVal = strtoll (pData, &pTail, 10);
free (pData);
if (pTail == pData) // Nothing converted?
return 1;
return 0;
}
int GetUdevDevicePropertyNum (struct udev_device *pUdevDevice, const char *pProperty, long long *pVal)
{
const char *pStr;
char *pTail;
pStr = pFnLibUdev_udev_device_get_property_value (pUdevDevice, pProperty);
if (!pStr)
return 1;
*pVal = strtoll (pStr, &pTail, 10);
if (pTail == pStr) // Nothing converted?
return 1;
return 0;
}
public:
bool LibUdevLoaded;
void *pLibUdevHandle;
t_pFnLibUdev_udev_new pFnLibUdev_udev_new;
t_pFnLibUdev_udev_unref pFnLibUdev_udev_unref;
t_pFnLibUdev_udev_device_unref pFnLibUdev_udev_device_unref;
t_pFnLibUdev_udev_enumerate_new pFnLibUdev_udev_enumerate_new;
t_pFnLibUdev_udev_enumerate_unref pFnLibUdev_udev_enumerate_unref;
t_pFnLibUdev_udev_enumerate_add_match_subsystem pFnLibUdev_udev_enumerate_add_match_subsystem;
t_pFnLibUdev_udev_enumerate_add_match_property pFnLibUdev_udev_enumerate_add_match_property;
t_pFnLibUdev_udev_enumerate_scan_devices pFnLibUdev_udev_enumerate_scan_devices;
t_pFnLibUdev_udev_enumerate_get_list_entry pFnLibUdev_udev_enumerate_get_list_entry;
t_pFnLibUdev_udev_list_entry_get_name pFnLibUdev_udev_list_entry_get_name;
t_pFnLibUdev_udev_device_new_from_syspath pFnLibUdev_udev_device_new_from_syspath;
t_pFnLibUdev_udev_device_get_property_value pFnLibUdev_udev_device_get_property_value;
t_pFnLibUdev_udev_list_entry_get_next pFnLibUdev_udev_list_entry_get_next;
};
t_ThreadScanWorkerUdev::t_ThreadScanWorkerUdev (t_ThreadScan *pThreadScan, APIRET &rc)
:t_ThreadScanWorker (pThreadScan)
{
QStringList FilenameList;
QString Filename;
char *pErrStr;
int i;
bool Found = false;
rc = ERROR_THREADSCAN_LIBUDEV_NOTWORKING;
pOwn = new t_ThreadScanWorkerUdevLocal();
CHK_EXIT (ThreadScanFindLib (FilenameList, ThreadScanLibUdevSearchPattern))
for (i=0; (i<FilenameList.size()) && (!Found); i++)
{
Filename = FilenameList[i];
pOwn->pLibUdevHandle = dlopen (QSTR_TO_PSZ(Filename), RTLD_NOW);
if (pOwn->pLibUdevHandle == nullptr)
{
LOG_INFO ("Trying %s -- dlopen returns (%s)", QSTR_TO_PSZ(Filename), dlerror())
continue;
}
LOG_INFO ("Trying %s -- dlopen ok", QSTR_TO_PSZ(Filename))
// GETFN: See dlsym documentation concerning the usage of dlerror for error checking
#define GETFN(pFn, Type, pFnName) \
dlerror(); \
pFn = (Type)dlsym (pOwn->pLibUdevHandle, pFnName); \
pErrStr = dlerror(); \
if (pErrStr) \
{ \
LOG_INFO ("Trying %s -- dlsym for %s returns (%s)", QSTR_TO_PSZ(Filename), pFnName, dlerror()); \
dlclose (pOwn->pLibUdevHandle); \
pOwn->pLibUdevHandle = nullptr; \
pOwn->ClearFnPointers(); \
continue; \
} \
else \
{ \
LOG_INFO ("Trying %s -- dlsym for %s ok", QSTR_TO_PSZ(Filename), pFnName); \
}
GETFN (pOwn->pFnLibUdev_udev_new , t_pFnLibUdev_udev_new , "udev_new")
GETFN (pOwn->pFnLibUdev_udev_unref , t_pFnLibUdev_udev_unref , "udev_unref")
GETFN (pOwn->pFnLibUdev_udev_device_unref , t_pFnLibUdev_udev_device_unref , "udev_device_unref")
GETFN (pOwn->pFnLibUdev_udev_enumerate_new , t_pFnLibUdev_udev_enumerate_new , "udev_enumerate_new")
GETFN (pOwn->pFnLibUdev_udev_enumerate_unref , t_pFnLibUdev_udev_enumerate_unref , "udev_enumerate_unref")
GETFN (pOwn->pFnLibUdev_udev_enumerate_add_match_subsystem, t_pFnLibUdev_udev_enumerate_add_match_subsystem, "udev_enumerate_add_match_subsystem")
GETFN (pOwn->pFnLibUdev_udev_enumerate_add_match_property , t_pFnLibUdev_udev_enumerate_add_match_property , "udev_enumerate_add_match_property")
GETFN (pOwn->pFnLibUdev_udev_enumerate_scan_devices , t_pFnLibUdev_udev_enumerate_scan_devices , "udev_enumerate_scan_devices")
GETFN (pOwn->pFnLibUdev_udev_enumerate_get_list_entry , t_pFnLibUdev_udev_enumerate_get_list_entry , "udev_enumerate_get_list_entry")
GETFN (pOwn->pFnLibUdev_udev_list_entry_get_name , t_pFnLibUdev_udev_list_entry_get_name , "udev_list_entry_get_name")
GETFN (pOwn->pFnLibUdev_udev_device_new_from_syspath , t_pFnLibUdev_udev_device_new_from_syspath , "udev_device_new_from_syspath")
GETFN (pOwn->pFnLibUdev_udev_device_get_property_value , t_pFnLibUdev_udev_device_get_property_value , "udev_device_get_property_value")
GETFN (pOwn->pFnLibUdev_udev_list_entry_get_next , t_pFnLibUdev_udev_list_entry_get_next , "udev_list_entry_get_next")
#undef GETFN
Found = true;
}
if (Found)
rc = NO_ERROR;
}
t_ThreadScanWorkerUdev::~t_ThreadScanWorkerUdev (void)
{
int rc;
if (pOwn->pLibUdevHandle)
{
rc = dlclose (pOwn->pLibUdevHandle);
if (rc)
LOG_INFO ("dlclose returned %d (%s).", rc, dlerror());
}
delete pOwn;
}
#define CHK_UDEV(x) \
{ \
int rc = (x); \
if (rc<0) \
{ \
LOG_ERROR ("Error in udev call (rc=%d), aborting device scan",rc); \
goto End; \
} \
}
void t_ThreadScanWorkerUdev::SlotRescan (void)
{
t_pDeviceList pDeviceList;
t_pDevice pDevice;
struct udev *pUdev = nullptr;
struct udev_enumerate *pUdevEnum = nullptr;
struct udev_device *pUdevDevice = nullptr;
struct udev_list_entry *pUdevList;
struct udev_list_entry *pUdevEntry;
const char *pPath;
const char *pLinuxDevice;
const char *pSerial;
const char *pVendor;
const char *pModel;
const char *pRaidUuid;
const char *pRaidLevel;
char *pLoopBacking = nullptr;
int rc;
long long int IsRemovable;
long long int IsCD;
long long int HasMedia;
long long int SectorSize;
long long int Size;
QString Model;
emit (SignalScanStarted ());
LOG_INFO ("Rescanning devices")
CHK_EXIT (poThreadScan->SetDebugMessage ("SlotRescan called (udev)"))
pDeviceList = new t_DeviceList;
pUdev = pOwn->pFnLibUdev_udev_new();
if (!pUdev)
goto End;
pUdevEnum = pOwn->pFnLibUdev_udev_enumerate_new (pUdev);
if (!pUdevEnum)
goto End;
CHK_UDEV (pOwn->pFnLibUdev_udev_enumerate_add_match_subsystem (pUdevEnum, "block"))
CHK_UDEV (pOwn->pFnLibUdev_udev_enumerate_add_match_property (pUdevEnum, "DEVTYPE", "disk"))
CHK_UDEV (pOwn->pFnLibUdev_udev_enumerate_scan_devices (pUdevEnum))
pUdevList = pOwn->pFnLibUdev_udev_enumerate_get_list_entry (pUdevEnum);
if (pUdevList == nullptr)
{
LOG_ERROR ("No disk block devices found.");
goto End;
}
// Loop trough result set
LibUdevListEntryForEach (pUdevEntry, pUdevList)
{
pPath = pOwn->pFnLibUdev_udev_list_entry_get_name (pUdevEntry);
if (!pPath)
continue;
if (pUdevDevice)
pOwn->pFnLibUdev_udev_device_unref (pUdevDevice);
pUdevDevice = pOwn->pFnLibUdev_udev_device_new_from_syspath (pUdev, pPath);
if (!pUdevDevice)
continue;
if (strncmp (pPath, THREADSCAN_UDEV_PATH_RAM, strlen (THREADSCAN_UDEV_PATH_RAM)) == 0) // Ignore RAM devices
continue;
pLinuxDevice = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "DEVNAME"); // Ignore devices without standard Linux /dev/xxx path
if (!pLinuxDevice)
continue;
pVendor = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "ID_VENDOR" );
pModel = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "ID_MODEL" );
pRaidUuid = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "MD_UUID" );
pSerial = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "ID_SERIAL_SHORT");
if (!pSerial)
pSerial = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "ID_SERIAL");
if (!pSerial)
pSerial = pRaidUuid; // Take UUID for md arrays (if it exists)
if (strncmp (pPath, THREADSCAN_UDEV_PATH_LOOP, strlen (THREADSCAN_UDEV_PATH_LOOP)) == 0) // Ignore non-mounted loop devices
{ // Gather extra info for mounted loop devices
rc = pOwn->GetFileContents (pPath, "loop/backing_file", &pLoopBacking);
if (rc)
continue;
pModel = basename (pLoopBacking); // Take mounted filename as model
}
HasMedia=1;
if (pOwn->GetFileContentsNum (pPath, "removable", &IsRemovable) == 0) // Check drives with removable media, ignore those where no media is inserted.
{ // If it's a CD/DVD/BR then there should be property ID_CDROM_MEDIA to check if
if (IsRemovable) // a disc is inserted. This is not the case for floppy drives. Floppy drive do have
{ // property ID_FLOPPY but there is not property for telling us if a floppy disc is
rc = pOwn->GetUdevDevicePropertyNum (pUdevDevice, "ID_CDROM", &IsCD); // inserted or not. However, the size switches to 0 if the drive is empty.
if ((rc==0) && IsCD) // Tested with external USB floppy drive "SmartDisk FDUSB-B2"
{
HasMedia=0;
rc = pOwn->GetUdevDevicePropertyNum (pUdevDevice, "ID_CDROM_MEDIA", &HasMedia);
}
}
}
else
{
IsRemovable=0;
}
if (pOwn->GetFileContentsNum (pPath, "queue/hw_sector_size", &SectorSize))
SectorSize = 512; // not always available, set to 512 in that case
if (pOwn->GetFileContentsNum (pPath, "size", &Size)) // An alternative would be to get sysattr 'size',
Size = 0; // but this is the way it is done by udisks
Size *= 512; // Do not multiply by SectorSize, multiply by 512!
if (HasMedia && Size)
{
Model.clear();
if (pModel)
{
Model = pModel;
}
else
{
if (pRaidUuid)
{
pRaidLevel = pOwn->pFnLibUdev_udev_device_get_property_value (pUdevDevice, "MD_LEVEL");
Model = QString ("Linux SW ") + (pRaidLevel ? pRaidLevel : "raid");
}
}
if (!Model.contains (pVendor, Qt::CaseInsensitive))
Model = QString(pVendor) + " " + Model;
pDevice = new t_Device (pSerial ? pSerial : QString(), pLinuxDevice, Model, SectorSize, SectorSize, Size);
if (ThreadScanIsHidden(pDevice))
{
delete pDevice;
}
else
{
pDevice->Removable = IsRemovable ? true : false;
if (CONFIG(QueryDeviceMediaInfo))
CHK_EXIT (pDevice->MediaInfo.QueryDevice(pLinuxDevice))
CHK_EXIT (ThreadScanSetLocal (pDevice));
CHK_EXIT (ThreadScanGetAddStateInfo (pDevice));
pDeviceList->append (pDevice);
}
}
if (pLoopBacking)
{
free (pLoopBacking);
pLoopBacking = nullptr;
}
}
End:
if (pUdevDevice) pOwn->pFnLibUdev_udev_device_unref (pUdevDevice);
if (pUdevEnum) pOwn->pFnLibUdev_udev_enumerate_unref (pUdevEnum);
if (pUdev) pOwn->pFnLibUdev_udev_unref (pUdev);
emit (SignalScanFinished (pDeviceList));
CHK_EXIT (poThreadScan->SetDebugMessage ("Leaving SlotRescan (parted)"))
}
// --------------------------
// t_ThreadScanWorkerHAL
// --------------------------
// Scan the devices using DBUS/HAL
#define HAL_SERVICE "org.freedesktop.Hal"
#define HAL_MANAGER_PATH "/org/freedesktop/Hal/Manager"
#define HAL_MANAGER_IF "org.freedesktop.Hal.Manager"
#define HAL_DEVICE_IF "org.freedesktop.Hal.Device"
class t_ThreadScanWorkerHALLocal
{
public:
t_ThreadScanWorkerHALLocal (void)
{
pDBusConnection = new QDBusConnection (QDBusConnection::systemBus());
pDBusInterface = nullptr;
}
~t_ThreadScanWorkerHALLocal ()
{
QDBusConnection::disconnectFromBus (pDBusConnection->baseService());
delete pDBusConnection;
pDBusConnection = nullptr;
pDBusInterface = nullptr;
}
public:
QDBusConnection *pDBusConnection;
QDBusConnectionInterface *pDBusInterface;
};
t_ThreadScanWorkerHAL::t_ThreadScanWorkerHAL (t_ThreadScan *pThreadScan, APIRET &rc)
:t_ThreadScanWorker (pThreadScan)
{
pOwn = new t_ThreadScanWorkerHALLocal;
if (!pOwn->pDBusConnection->isConnected())
{
LOG_INFO ("DBus connection failed")
rc = ERROR_THREADSCAN_DBUSHAL_NOTWORKING;
return;
}
pOwn->pDBusInterface = pOwn->pDBusConnection->interface();
if (!pOwn->pDBusInterface->isServiceRegistered (HAL_SERVICE))
{
LOG_INFO ("HAL not registered")
rc = ERROR_THREADSCAN_DBUSHAL_NOTWORKING;
return;
}
rc = NO_ERROR;
}
t_ThreadScanWorkerHAL::~t_ThreadScanWorkerHAL (void)
{
delete pOwn;
}
QList<QVariant> t_ThreadScanWorkerHAL::CallMethod (const QString &Device, const QString &Method, const QString &Argument)
{
QList<QVariant> Args;
QDBusMessage Message = QDBusMessage::createMethodCall (HAL_SERVICE, Device, HAL_DEVICE_IF, Method);
QDBusMessage Reply;
Args += Argument;
Message.setArguments (Args);
Reply = pOwn->pDBusConnection->call (Message);
if (Reply.type() == QDBusMessage::ErrorMessage)
{
LOG_ERROR ("DBus returned '%s' for method %s on device %s", QSTR_TO_PSZ (Reply.errorName()),
QSTR_TO_PSZ (Method),
QSTR_TO_PSZ (Device))
return QList<QVariant>(); // return empty list
}
return Reply.arguments();
}
QVariant t_ThreadScanWorkerHAL::CallMethodSingle (const QString &Device, const QString &Method, const QString &Argument)
{
QList<QVariant> Results;
Results = CallMethod (Device, Method, Argument);
if (Results.first().isNull())
return QVariant();
return Results.first();
}
APIRET t_ThreadScanWorkerHAL::GetProperty (const QString &Device, const QString &Property, QList<QVariant> &VarList)
{
QVariant Exists;
Exists = CallMethodSingle (Device, "PropertyExists", Property);
if (Exists.toBool())
VarList = CallMethod (Device, "GetProperty", Property);
else VarList = QList<QVariant>(); // Construct an empty, invalid list to show that the property doesn't exist
return NO_ERROR;
}
APIRET t_ThreadScanWorkerHAL::GetPropertySingle (const QString &Device, const QString &Property, QVariant &Var)
{
Var = CallMethodSingle (Device, "PropertyExists", Property);
if (Var.toBool())
Var = CallMethodSingle (Device, "GetProperty", Property);
else Var = QVariant(); // Construct an empty, invalid QVariant to show that the property doesn't exist
return NO_ERROR;
}
bool t_ThreadScanWorkerHAL::PropertyContains (const QString &Device, const QString &Property, const QString &Str)
{
QList<QVariant> PropertyElements;
bool Found = false;
CHK_EXIT (GetProperty (Device, Property, PropertyElements))
foreach (QVariant Element, PropertyElements)
{
if (Element.isValid())
{
switch (Element.type())
{
case QVariant::String : Found = (Element.toString() == Str); break;
case QVariant::StringList: Found = Element.toStringList().contains (Str, Qt::CaseInsensitive); break;
default : break;
}
}
if (Found)
break;
}
return Found;
}
void t_ThreadScanWorkerHAL::SlotRescan (void)
{
t_pDeviceList pDeviceList=nullptr;
t_pDevice pDevice;
QDBusMessage Message;
QDBusMessage Reply;
QStringList DeviceList;
QVariant Category;
QVariant SerialNumber;
QVariant LinuxDevice;
QVariant Vendor;
QVariant Product;
QVariant Size;
QVariant Removable;
QVariant RemovableAvailable;
QString Model;
CHK_EXIT (poThreadScan->SetDebugMessage ("SlotRescan called (HAL)"))
if (thread() != QThread::currentThread())
CHK_EXIT (ERROR_THREADSCAN_CALLED_FROM_WRONG_THREAD) // As Qt's DBus system is quite sensible to this kind of
// mistake (resulting in many QTimer "cannot be stopped/started
// from another thread) we prefer to do the check here!
emit (SignalScanStarted ());
LOG_INFO ("Device scan started")
Message = QDBusMessage::createMethodCall (HAL_SERVICE, HAL_MANAGER_PATH, HAL_MANAGER_IF, "GetAllDevices");
Reply = pOwn->pDBusConnection->call (Message);
if (Reply.type() == QDBusMessage::ErrorMessage)