Repository navigation
Expand file tree
/
Copy pathwpdplug.cpp
More file actions
3607 lines (3424 loc) · 106 KB
/
Copy pathwpdplug.cpp
File metadata and controls
3607 lines (3424 loc) · 106 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
// wpdplug.cpp : Definiert den Einstiegspunkt f�r die DLL-Anwendung.
//
#include <PortableDeviceApi.h>
#include <PortableDevice.h>
#include <new>
#include <stdio.h>
#include <wchar.h>
#include <Dbt.h>
#include <GdiPlus.h>
#include "wpdplug.h"
#include "cunicode.h"
#include "fsplugin.h"
#include "utils.h"
#include "connectionsettings.h"
#include "wpdplug_int.h"
#include "apple_md.h"
#define DefPluginTitle PLUGIN_DISPLAY_NAME
CRITICAL_SECTION g_cs;
static BOOL g_csInit=FALSE;
volatile LONG g_abort=0;
volatile LONG g_contentStop=0;
TransferScope* TransferScope::s_head=NULL;
CRITICAL_SECTION TransferScope::s_cs;
WCHAR DefaultIniNameW[MAX_PATH];
HINSTANCE hInst;
tProgressProc ProgressProc;
tLogProc LogProc;
tRequestProc RequestProc;
tProgressProcW ProgressProcW;
tLogProcW LogProcW;
tRequestProcW RequestProcW;
int PluginNumber;
BOOL connected=false;
BOOL DeviceEventReceived=false; // if true, we need to re-scan all devices
volatile LONG g_cacheDirty=0;
void MarkObjectCacheDirty(void)
{
InterlockedExchange(&g_cacheDirty, 1);
}
#define NUM_OBJECTS_TO_REQUEST 128
BOOL LoadAllDevices();
void FreeAllDevices();
void FreeDeviceList();
void LogWpdError(LPCWSTR context, HRESULT hr);
ULONG_PTR GdiPlusToken=0;
BOOL GdiPlusInitialize()
{
if (GdiPlusToken)
return true;
Gdiplus::GdiplusStartupInput Gsi;
memset(&Gsi,0,sizeof(Gsi));
Gsi.GdiplusVersion=1;
if (Gdiplus::GdiplusStartup(&GdiPlusToken,&Gsi,NULL)!=0)
GdiPlusToken=0;
return (GdiPlusToken!=0);
}
void ShutdownGdiPlus() // do NOT call this from DLL_PROCESS_DETACH!
{
if (GdiPlusToken) {
Gdiplus::GdiplusShutdown(GdiPlusToken);
GdiPlusToken=0;
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
hInst=(HINSTANCE)hModule;
InitializeCriticalSection(&g_cs);
g_csInit=TRUE;
TransferScope::Init();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
TransferScope::Uninit();
/* g_cs deleted in FsContentPluginUnloading */
break;
}
return TRUE;
}
// maxlen is the destination buffer size including the terminating 0
char* strlcpy(char* p,const char* p2,int maxlen)
{
if (!p || maxlen<=0)
return p;
if (!p2) {
p[0]=0;
return p;
}
strncpy_s(p,maxlen,p2,_TRUNCATE);
return p;
}
char* strlcat(char* p,const char* p2,int maxlen)
{
if (!p || !p2 || maxlen<=0)
return p;
strncat_s(p,maxlen,p2,_TRUNCATE);
return p;
}
typedef struct {
WCHAR Path[wdirtypemax];
WCHAR LastFoundName[wdirtypemax];
IEnumPortableDeviceObjectIDs* pEnumObjectIDs;
IPortableDeviceKeyCollection* pPropertiesToRead;
IPortableDeviceProperties* pProperties;
DWORD pPnpDeviceLastRead;
LPWSTR szObjectIDArray[NUM_OBJECTS_TO_REQUEST];
IPortableDeviceValues* szObjectValues[NUM_OBJECTS_TO_REQUEST];
DWORD szObjectIDsFetched;
DWORD szObjectIDLastRead;
int LocalTime;
DWORD listedCount;
int listKind;
HANDLE appleFind;
} tLastFindStuct,*pLastFindStuct;
BOOL initialized=FALSE;
BOOL firstinitialized=FALSE;
BOOL weInitializedCOM=FALSE;
IPortableDeviceManager* pDevMgr=NULL;
PWSTR* StoredPnpDeviceIDs=NULL; // keep them globally!
PWSTR* StoredPnPFriendlyNames=NULL;
IPortableDevice** StoredDevices=NULL;
LPWSTR* StoredEventCookies=NULL;
static LONG* StoredDeviceBusy=NULL;
DWORD StoredNumIds=0;
static __declspec(thread) int t_pluginLockHeld=0;
PWSTR FindPnpIdByPath(LPCWSTR path)
{
if (!path)
return NULL;
WCHAR name[MAX_PATH];
const WCHAR* p=path;
if (p[0]=='\\')
p++;
wcslcpy(name,p,MAX_PATH-1);
WCHAR* slash=wcschr(name,'\\');
if (slash)
slash[0]=0;
for (DWORD i=0;i<StoredNumIds;i++) {
if (StoredPnPFriendlyNames[i] && wcscmp(StoredPnPFriendlyNames[i],name)==0)
return StoredPnpDeviceIDs[i];
}
return NULL;
}
HANDLE hDevNotify=NULL;
HWND hWndNotify=NULL;
void LockPlugin(void)
{
if (!g_csInit)
return;
EnterCriticalSection(&g_cs);
t_pluginLockHeld++;
}
void UnlockPlugin(void)
{
if (!g_csInit)
return;
t_pluginLockHeld--;
LeaveCriticalSection(&g_cs);
}
static DWORD FindStoredDeviceIndexByPath(LPCWSTR path)
{
if (!path || !StoredPnPFriendlyNames)
return (DWORD)-1;
WCHAR name[MAX_PATH];
const WCHAR* p=path;
if (p[0]=='\\')
p++;
wcslcpy(name,p,MAX_PATH-1);
WCHAR* slash=wcschr(name,'\\');
if (slash)
slash[0]=0;
for (DWORD i=0;i<StoredNumIds;i++) {
if (StoredPnPFriendlyNames[i] && wcscmp(StoredPnPFriendlyNames[i],name)==0)
return i;
}
return (DWORD)-1;
}
static void TransferBegin(DWORD idx)
{
if (idx!=(DWORD)-1 && StoredDeviceBusy)
InterlockedIncrement(&StoredDeviceBusy[idx]);
}
static void TransferEnd(DWORD idx)
{
if (idx!=(DWORD)-1 && StoredDeviceBusy)
InterlockedDecrement(&StoredDeviceBusy[idx]);
}
static void WaitDeviceTransfersIdle(void)
{
for (;;) {
BOOL busy=FALSE;
if (StoredDeviceBusy) {
for (DWORD i=0;i<StoredNumIds;i++) {
if (InterlockedCompareExchange(&StoredDeviceBusy[i],0,0)!=0) {
busy=TRUE;
break;
}
}
}
if (!busy)
return;
LeaveCriticalSection(&g_cs);
Sleep(10);
EnterCriticalSection(&g_cs);
}
}
static __declspec(thread) int t_comDepth=0;
static __declspec(thread) BOOL t_comInitedByUs=FALSE;
static __declspec(thread) BOOL t_comOwnedByPlugin=FALSE;
BOOL EnsureComApartment(void)
{
HRESULT hr=CoInitialize(NULL);
if (hr==S_OK) {
t_comInitedByUs=TRUE;
t_comDepth++;
return TRUE;
}
if (hr==S_FALSE) {
t_comDepth++;
return TRUE;
}
return FALSE;
}
void UninitComApartment(void)
{
if (t_comDepth>0)
t_comDepth--;
if (t_comDepth==0 && t_comInitedByUs && !t_comOwnedByPlugin) {
CoUninitialize();
t_comInitedByUs=FALSE;
}
}
ComApartmentGuard::ComApartmentGuard()
{
m_ok=EnsureComApartment();
}
ComApartmentGuard::~ComApartmentGuard()
{
UninitComApartment();
}
void TransferScope::Init(void)
{
InitializeCriticalSection(&s_cs);
s_head=NULL;
}
void TransferScope::Uninit(void)
{
DeleteCriticalSection(&s_cs);
}
TransferScope::TransferScope(IPortableDevice* device)
{
InterlockedExchange(&m_abort,0);
m_device=NULL;
m_next=NULL;
if (device) {
device->AddRef();
m_device=device;
}
EnterCriticalSection(&s_cs);
m_next=s_head;
s_head=this;
LeaveCriticalSection(&s_cs);
}
TransferScope::~TransferScope()
{
IPortableDevice* d=NULL;
EnterCriticalSection(&s_cs);
TransferScope** pp=&s_head;
while (*pp) {
if (*pp==this) {
*pp=m_next;
break;
}
pp=&(*pp)->m_next;
}
d=m_device;
m_device=NULL;
m_next=NULL;
LeaveCriticalSection(&s_cs);
if (d)
d->Release();
}
BOOL TransferScope::aborted() const
{
return InterlockedCompareExchange(&m_abort,0,0)!=0;
}
void TransferScope::AbortAll(void)
{
IPortableDevice* toCancel[16];
int n=0;
EnterCriticalSection(&s_cs);
for (TransferScope* c=s_head;c;c=c->m_next) {
InterlockedExchange(&c->m_abort,1);
if (c->m_device && n<16) {
c->m_device->AddRef();
toCancel[n++]=c->m_device;
}
}
LeaveCriticalSection(&s_cs);
for (int i=0;i<n;i++) {
toCancel[i]->Cancel();
toCancel[i]->Release();
}
}
IPortableDevice* FindStoredDeviceByPath(LPCWSTR path)
{
if (!path || path[0]==0)
return NULL;
WCHAR name[MAX_PATH];
const WCHAR* p=path;
if (p[0]=='\\')
p++;
wcslcpy(name,p,MAX_PATH-1);
WCHAR* slash=wcschr(name,'\\');
if (slash)
slash[0]=0;
for (DWORD i=0;i<StoredNumIds;i++) {
if (StoredPnPFriendlyNames[i] && wcscmp(StoredPnPFriendlyNames[i],name)==0)
return StoredDevices[i];
}
return NULL;
}
void RequestAbort(void)
{
InterlockedExchange(&g_abort,1);
TransferScope::AbortAll();
}
void ResetAbort(void)
{
InterlockedExchange(&g_abort,0);
}
BOOL IsAbortRequested(void)
{
return InterlockedCompareExchange(&g_abort,0,0)!=0;
}
void SetContentStop(BOOL stop)
{
InterlockedExchange(&g_contentStop, stop ? 1 : 0);
}
BOOL IsContentStop(void)
{
return InterlockedCompareExchange(&g_contentStop,0,0)!=0;
}
int ProgressCheck(WCHAR* src, WCHAR* dst, int percent)
{
BOOL held=t_pluginLockHeld>0;
if (held)
LeaveCriticalSection(&g_cs);
int err=ProgressProcT(PluginNumber,src,dst,percent);
if (held)
EnterCriticalSection(&g_cs);
if (err)
RequestAbort();
return err;
}
static BOOL IsWpdFolderContentType(REFGUID contentType)
{
return IsEqualGUID(contentType, WPD_CONTENT_TYPE_FOLDER)
|| IsEqualGUID(contentType, WPD_CONTENT_TYPE_FUNCTIONAL_OBJECT)
|| IsEqualGUID(contentType, WPD_CONTENT_TYPE_AUDIO_ALBUM)
|| IsEqualGUID(contentType, WPD_CONTENT_TYPE_IMAGE_ALBUM)
|| IsEqualGUID(contentType, WPD_CONTENT_TYPE_VIDEO_ALBUM)
|| IsEqualGUID(contentType, WPD_CONTENT_TYPE_MIXED_CONTENT_ALBUM);
}
static ULONGLONG MakeU64(DWORD low, DWORD high)
{
return ((ULONGLONG)high << 32) | (ULONGLONG)low;
}
static BOOL IsWpdFolderObject(IPortableDeviceValues* pObjectProperties)
{
if (!pObjectProperties)
return TRUE; // same fallback as before: treat unknown as a folder
GUID contentType=GUID_NULL;
HRESULT hr=pObjectProperties->GetGuidValue(WPD_OBJECT_CONTENT_TYPE,&contentType);
if (FAILED(hr))
return TRUE;
return IsWpdFolderContentType(contentType);
}
void LogWpdError(LPCWSTR context, HRESULT hr)
{
WCHAR buf[512];
buf[0]=0;
if (hr==HRESULT_FROM_WIN32(ERROR_BUSY) || hr==HRESULT_FROM_WIN32(ERROR_SHARING_VIOLATION)) {
swprintf_s(buf, L"%s failed (0x%08X): device is in use by Explorer, Phone Link or another program. Close that access and retry.",
context ? context : L"WPD", hr);
} else if (hr==HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED) || hr==E_ACCESSDENIED) {
swprintf_s(buf, L"%s failed (0x%08X): access denied. The device may be locked, in charging-only mode, or MTP may be disabled.",
context ? context : L"WPD", hr);
} else if (hr==HRESULT_FROM_WIN32(ERROR_NOT_READY) || hr==HRESULT_FROM_WIN32(ERROR_NOT_FOUND)) {
swprintf_s(buf, L"%s failed (0x%08X): device not ready or not found. Unlock the phone and set USB to File transfer (MTP).",
context ? context : L"WPD", hr);
} else {
swprintf_s(buf, L"%s failed (0x%08X).", context ? context : L"WPD", hr);
}
LogProcT(PluginNumber, MSGTYPE_IMPORTANTERROR, buf);
}
static HRESULT CreateWpdClientInfo(IPortableDeviceValues** ppClientInfo, DWORD desiredAccess)
{
if (!ppClientInfo)
return E_POINTER;
*ppClientInfo=NULL;
IPortableDeviceValues* info=NULL;
HRESULT hr=CoCreateInstance(CLSID_PortableDeviceValues, NULL, CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues, (VOID**)&info);
if (FAILED(hr))
return hr;
info->SetStringValue(WPD_CLIENT_NAME, PLUGIN_WPD_CLIENT_NAME);
info->SetUnsignedIntegerValue(WPD_CLIENT_MAJOR_VERSION, PLUGIN_VERSION_MAJOR);
info->SetUnsignedIntegerValue(WPD_CLIENT_MINOR_VERSION, PLUGIN_VERSION_MINOR);
info->SetUnsignedIntegerValue(WPD_CLIENT_REVISION, PLUGIN_VERSION_REV);
info->SetUnsignedIntegerValue(WPD_CLIENT_SECURITY_QUALITY_OF_SERVICE, SECURITY_IMPERSONATION);
info->SetUnsignedIntegerValue(WPD_CLIENT_DESIRED_ACCESS, desiredAccess);
info->SetUnsignedIntegerValue(WPD_CLIENT_SHARE_MODE, FILE_SHARE_READ | FILE_SHARE_WRITE);
// Same cookie Explorer uses. Without it, WUDFHost rebuilds its MTP cache
// inside IPortableDeviceContent::Delete and the call never finishes.
info->SetStringValue(WPD_CLIENT_EVENT_COOKIE, L"{35786D3C-B075-49B9-88DD-029876E11C01}");
*ppClientInfo=info;
return S_OK;
}
static HRESULT OpenWpdDevice(LPCWSTR deviceId, IPortableDevice** ppDevice)
{
if (!ppDevice)
return E_POINTER;
*ppDevice=NULL;
if (!deviceId)
return E_INVALIDARG;
IPortableDeviceValues* client=NULL;
HRESULT hr=CreateWpdClientInfo(&client, GENERIC_READ | GENERIC_WRITE);
if (FAILED(hr))
return hr;
IPortableDevice* dev=NULL;
hr=CoCreateInstance(CLSID_PortableDevice, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDevice, (VOID**)&dev);
if (SUCCEEDED(hr))
hr=dev->Open(deviceId, client);
if (FAILED(hr)) {
LogWpdError(L"Open(read-write)", hr);
SAFE_RELEASE(dev);
client->SetUnsignedIntegerValue(WPD_CLIENT_DESIRED_ACCESS, GENERIC_READ);
HRESULT hr2=CoCreateInstance(CLSID_PortableDevice, NULL, CLSCTX_INPROC_SERVER, IID_IPortableDevice, (VOID**)&dev);
if (SUCCEEDED(hr2)) {
hr2=dev->Open(deviceId, client);
if (SUCCEEDED(hr2))
hr=hr2;
else {
LogWpdError(L"Open(read-only)", hr2);
SAFE_RELEASE(dev);
hr=hr2;
}
} else
hr=hr2;
}
SAFE_RELEASE(client);
*ppDevice=dev;
return hr;
}
static void SanitizeFriendlyName(LPWSTR name)
{
if (!name)
return;
for (WCHAR* p=name; *p; p++) {
WCHAR ch=*p;
if (ch==L'\\' || ch==L'/' || ch==L'*' || ch==L'?' ||
ch==L'<' || ch==L'>' || ch==L':' || ch==L'"' || ch==L'|')
*p=L'_';
}
wcutlastbackslash(name);
}
static void MakeFriendlyNameUnique(DWORD index)
{
if (!StoredPnPFriendlyNames || !StoredPnPFriendlyNames[index])
return;
WCHAR base[256];
wcslcpy(base, StoredPnPFriendlyNames[index], 256);
int n=2;
for (;;) {
BOOL clash=FALSE;
for (DWORD k=0; k<index; k++) {
if (StoredPnPFriendlyNames[k] && wcscmp(StoredPnPFriendlyNames[index], StoredPnPFriendlyNames[k])==0) {
clash=TRUE;
break;
}
}
if (!clash)
break;
WCHAR tmp[280];
swprintf_s(tmp, L"%s (%d)", base, n++);
CoTaskMemFree(StoredPnPFriendlyNames[index]);
StoredPnPFriendlyNames[index]=wstrnew(tmp);
if (!StoredPnPFriendlyNames[index])
break;
}
}
BOOL InitFunctionsIfNeeded(BOOL trueconnect)
{
HRESULT hr;
BOOL result=false;
if (!firstinitialized) {
HRESULT cohr=CoInitialize(NULL);
firstinitialized=true;
if (cohr==S_OK) {
weInitializedCOM=TRUE;
t_comOwnedByPlugin=TRUE;
t_comInitedByUs=TRUE;
t_comDepth++;
} else if (cohr==S_FALSE) {
weInitializedCOM=TRUE;
t_comOwnedByPlugin=TRUE;
}
}
if (!initialized) {
initialized=true;
hr = CoCreateInstance(CLSID_PortableDeviceManager, NULL, CLSCTX_INPROC_SERVER,
IID_IPortableDeviceManager, (VOID**) &pDevMgr);
if SUCCEEDED(hr) {
result=true;
} else {
LogWpdError(L"CoCreateInstance(PortableDeviceManager)", hr);
MessageBoxA(GetActiveWindow(),
"Windows Portable Devices (WPD) is not available.\nThis plugin requires Windows Vista or later with WPD support.",
PLUGIN_DISPLAY_NAME, MB_ICONSTOP);
result=false;
}
} else
result=true;
AppleMdInit();
if (result && pDevMgr && StoredNumIds==0)
LoadAllDevices();
return (result && StoredNumIds>0) || AppleMdCount()>0 || result;
}
// From: http://blogs.msdn.com/b/wpdblog/archive/2007/03/17/how-to-receive-wpd-device-arrival-events.aspx
#define WPD_DEVINTERFACE L"{6ac27878-a6fa-4155-ba85-f98f491d4f33}"
#define szWindowClass "PnpNotificationListener"
GUID guidDevInterface=GUID_NULL;
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_CREATE:
{
DEV_BROADCAST_DEVICEINTERFACE db = {0};
db.dbcc_size = sizeof(db);
db.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
CLSIDFromString(WPD_DEVINTERFACE, &guidDevInterface);
db.dbcc_classguid = guidDevInterface;
hDevNotify = RegisterDeviceNotificationW(hWnd, &db, DEVICE_NOTIFY_WINDOW_HANDLE);
return 1;
}
case WM_DEVICECHANGE:
switch(wParam)
{
case DBT_DEVICEARRIVAL:
case DBT_DEVICEREMOVECOMPLETE:
{
PDEV_BROADCAST_HDR pdbh = (PDEV_BROADCAST_HDR)lParam;
if (pdbh != NULL && pdbh->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
PDEV_BROADCAST_DEVICEINTERFACE pdbi = (PDEV_BROADCAST_DEVICEINTERFACE)lParam;
if (IsEqualGUID(pdbi->dbcc_classguid, guidDevInterface))
{
DeviceEventReceived=true;
}
}
}
break;
} // switch (wParam)
return 0;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
} // switch (uMsg)
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASS wc;
memset(&wc,0,sizeof(wc));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = szWindowClass;
return RegisterClass(&wc);
}
BOOL RegisterForEventNotifications(void)
{
if (!hWndNotify) {
HINSTANCE hInstance=GetModuleHandle(NULL);
MyRegisterClass(hInstance);
hWndNotify=CreateWindow(szWindowClass, szWindowClass, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
}
return hWndNotify!=NULL;
}
void UnregisterNotification(void) {
if (hDevNotify) {
UnregisterDeviceNotification(hDevNotify);
hDevNotify=NULL;
}
if (hWndNotify) {
DestroyWindow(hWndNotify);
hWndNotify=NULL;
}
}
#define CACHESIZE 32
LPWSTR CachedDirs[CACHESIZE]={0};
DWORD CachedDirLens[CACHESIZE]={0};
LPWSTR CachedObjectIds[CACHESIZE]={0};
DWORD CachedLastUsedTimes[CACHESIZE]={0};
void ClearCache() {
for (int i=0;i<CACHESIZE;i++) {
if (CachedDirs[i]!=NULL)
CoTaskMemFree(CachedDirs[i]);
if (CachedObjectIds[i]!=NULL)
CoTaskMemFree(CachedObjectIds[i]);
}
memset(&CachedDirs,0,sizeof(CachedDirs));
memset(&CachedDirLens,0,sizeof(CachedDirLens));
memset(&CachedObjectIds,0,sizeof(CachedObjectIds));
memset(&CachedLastUsedTimes,0,sizeof(CachedLastUsedTimes));
}
void RemoveNameFromCache(LPWSTR pdir) {
WCHAR fulldir[1024];
wcslcpy(fulldir,pdir,1022);
wcslcatbackslash(fulldir,1023);
DWORD len=(DWORD)wcslen(fulldir);
if (len<=1)
return;
// look whether the dir or any subdir in it is already in the cache
for (int i=0;i<CACHESIZE;i++) {
if (CachedDirLens[i]>=len && wcsncmp(fulldir,CachedDirs[i],len)==0) {
CoTaskMemFree(CachedDirs[i]);
CachedDirs[i]=NULL;
CoTaskMemFree(CachedObjectIds[i]);
CachedObjectIds[i]=NULL;
CachedDirLens[i]=0;
CachedLastUsedTimes[i]=0;
}
}
}
void RemoveFullPathFromCache(LPWSTR pdir) {
if (!pdir || wcslen(pdir)<2)
return;
if (pdir[0]=='\\')
RemoveNameFromCache(pdir+1);
else
RemoveNameFromCache(pdir);
}
void AddNameToCache(LPWSTR deviceName,LPWSTR pdir,LPWSTR pObjectId,DWORD time) {
WCHAR fulldir[1024];
if (!deviceName || !deviceName[0])
return;
wcslcpy(fulldir,deviceName,1022);
wcslcatbackslash(fulldir,1023);
if (pdir && pdir[0])
wcslcat(fulldir,pdir,1022);
wcslcatbackslash(fulldir,1023);
DWORD len=(DWORD)wcslen(fulldir);
if (len<=1)
return;
// first, look whether the dir is already in the cache
for (int i=0;i<CACHESIZE;i++) {
if (CachedDirLens[i]==len && wcscmp(fulldir,CachedDirs[i])==0)
return;
}
// second, look for a free space
int lastmatch=-1;
for (int i=0;i<CACHESIZE;i++) {
if (CachedDirs[i]==0) {
lastmatch=i;
break;
}
}
// third, look for the one with the oldest timestamp
if (lastmatch<0) {
DWORD oldesttime=0xFFFFFFFF;
for (int i=0;i<CACHESIZE;i++) {
if (CachedLastUsedTimes[i]<oldesttime) {
oldesttime=CachedLastUsedTimes[i];
lastmatch=i;
}
}
if (lastmatch>=0) {
CoTaskMemFree(CachedDirs[lastmatch]);
CoTaskMemFree(CachedObjectIds[lastmatch]);
}
}
CachedDirs[lastmatch]=wstrnew(fulldir);
CachedDirLens[lastmatch]=len;
CachedObjectIds[lastmatch]=wstrnew(pObjectId);
CachedLastUsedTimes[lastmatch]=time;
}
BOOL FindNameInCache(LPWSTR deviceName,LPWSTR pdir,LPWSTR* returnedObjectId,LPWSTR* pdirsubstart) {
WCHAR fulldir[1024];
if (!deviceName || !deviceName[0])
return false;
wcslcpy(fulldir,deviceName,1022);
wcslcatbackslash(fulldir,1023);
DWORD devicePartLen=(DWORD)wcslen(fulldir);
if (pdir && pdir[0])
wcslcat(fulldir,pdir,1022);
wcslcatbackslash(fulldir,1023);
DWORD maxmatchlen=0;
int lastmatch=-1;
// find longest match!
for (int i=0;i<CACHESIZE;i++) {
if (CachedDirs[i]) {
if (CachedDirLens[i]>maxmatchlen) {
if (wcsncmp(CachedDirs[i],fulldir,CachedDirLens[i])==0) {
lastmatch=i;
maxmatchlen=CachedDirLens[i];
}
}
}
}
if (lastmatch>=0) {
DWORD matchedSubLen=(maxmatchlen>devicePartLen) ? (maxmatchlen-devicePartLen) : 0;
if (pdir && wcslen(pdir)>matchedSubLen)
*pdirsubstart=pdir+matchedSubLen;
else if (pdir)
*pdirsubstart=pdir+wcslen(pdir); // full match
else
*pdirsubstart=pdir;
*returnedObjectId=CachedObjectIds[lastmatch];
return true;
}
return false;
}
static void PickObjectDisplayName(IPortableDeviceValues* v, WCHAR* out, DWORD cch);
HRESULT GetFolderIDFromPathName(LPWSTR pPath,IEnumPortableDeviceObjectIDs** pEnumObjectIDsRetVal,
IPortableDeviceProperties** pPropertiesRetVal,IPortableDeviceContent** pDeviceContent,LPWSTR* pStorageIDRetVal)
{
if (StoredPnPFriendlyNames==NULL || StoredPnpDeviceIDs==NULL)
return E_FAIL;
// wsSearch has form \Devicename\path1\path2
// First, get Device
IPortableDevice* pDevice=NULL;
IPortableDeviceContent* pContent=NULL;
IEnumPortableDeviceObjectIDs* pEnumObjectIDs=NULL;
IPortableDeviceProperties* pProperties=NULL;
IPortableDeviceKeyCollection* pPropertiesToRead=NULL;
WCHAR *pname,*pnext,*pdirstart,*pdirsubstart;
HRESULT hr;
WCHAR wcSearch[1024];
wcslcpy(wcSearch,pPath+1,1023);
pdirstart=wcschr(wcSearch,'\\');
if (pdirstart) {
pdirstart[0]=0;
pdirstart++;
} else {
pdirstart=wcSearch+wcslen(wcSearch); // "\Device" with no trailing slash
}
if (wcSearch[0]==0)
return E_FAIL;
// Find the right device, p points to it!
WCHAR* DeviceID=NULL;
DWORD DeviceIndex=0;
for (DeviceIndex=0;DeviceIndex<StoredNumIds;DeviceIndex++) {
if (wcscmp((const wchar_t *)StoredPnPFriendlyNames[DeviceIndex],wcSearch)==0) {
DeviceID=StoredPnpDeviceIDs[DeviceIndex];
pDevice=StoredDevices[DeviceIndex];
break;
}
}
if (DeviceID==NULL) {
LogProc(PluginNumber,MSGTYPE_OPERATIONCOMPLETE,"Device not found!");
return E_FAIL;
}
if (pDevice==NULL) {
hr = OpenWpdDevice(DeviceID, &pDevice);
if (SUCCEEDED(hr))
StoredDevices[DeviceIndex]=pDevice;
else
return hr;
} else
hr=S_OK;
if (SUCCEEDED(hr)) {
hr = pDevice->Content(&pContent);
if (FAILED(hr)) {
LogProc(PluginNumber,MSGTYPE_OPERATIONCOMPLETE,"No content on Device!");
return hr;
}
}
PWSTR returnedObjectId=NULL;
pdirsubstart=pdirstart;
if (!FindNameInCache(wcSearch,pdirstart,&returnedObjectId,&pdirsubstart))
returnedObjectId=WPD_DEVICE_OBJECT_ID;
if (pdirsubstart[0]==NULL) { // device root
if (pEnumObjectIDsRetVal) {
hr = pContent->EnumObjects(0, // Flags are unused
returnedObjectId, // Starting from the passed in object
NULL, // Filter is unused
&pEnumObjectIDs);
*pEnumObjectIDsRetVal=pEnumObjectIDs;
} else
hr=S_OK;
if (pPropertiesRetVal)
pContent->Properties(pPropertiesRetVal);
if (pDeviceContent)
*pDeviceContent=pContent;
else
SAFE_RELEASE(pContent);
if (pStorageIDRetVal)
*pStorageIDRetVal=wstrnew(returnedObjectId);
return hr;
}
// ShowSupportedFormats(pIDevice);
if (SUCCEEDED(hr))
hr = pContent->Properties(&pProperties);
if (SUCCEEDED(hr))
hr = CoCreateInstance(CLSID_PortableDeviceKeyCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceKeyCollection,
(VOID**) &pPropertiesToRead);
if (SUCCEEDED(hr)) {
pPropertiesToRead->Add(WPD_OBJECT_NAME);
pPropertiesToRead->Add(WPD_OBJECT_ORIGINAL_FILE_NAME);
pPropertiesToRead->Add(WPD_STORAGE_DESCRIPTION);
pPropertiesToRead->Add(WPD_FUNCTIONAL_OBJECT_CATEGORY);
}
LPWSTR LastParentName=wstrnew(WPD_DEVICE_OBJECT_ID);
if (SUCCEEDED(hr))
hr = pContent->EnumObjects(0, // Flags are unused
returnedObjectId, // Starting from the passed in object
NULL, // Filter is unused
&pEnumObjectIDs);
if (FAILED(hr)) {
SAFE_RELEASE(pPropertiesToRead);
SAFE_RELEASE(pProperties);
SAFE_RELEASE(pEnumObjectIDs);
SAFE_RELEASE(pContent);
return hr;
}
pname=pdirsubstart;
pnext=wcschr(pname,'\\');
if (pnext)
pnext[0]=0;
DWORD cFetched=0;
DWORD time=GetTickCount();
while (SUCCEEDED(hr)) {
PWSTR szObjectIDArray[NUM_OBJECTS_TO_REQUEST];
hr = pEnumObjectIDs->Next(NUM_OBJECTS_TO_REQUEST, // Number of objects to request on each NEXT call
szObjectIDArray, // Array of PWSTR array which will be populated on each NEXT call
&cFetched); // Number of objects written to the PWSTR array
DWORD i=0;
if (cFetched==0)
hr=E_FAIL;
while (SUCCEEDED(hr) && i<cFetched) {
IPortableDeviceValues* pObjectProperties=NULL;
HRESULT hr2=pProperties->GetValues(szObjectIDArray[i],
pPropertiesToRead, // The properties we want to read
&pObjectProperties); // Driver supplied property values for the specified object
if (SUCCEEDED(hr2) && pObjectProperties) {
WCHAR showname[MAX_PATH];
PickObjectDisplayName(pObjectProperties, showname, MAX_PATH);
SAFE_RELEASE(pObjectProperties);
if (wcscmp(showname,pname)==0) { //found!!
AddNameToCache(wcSearch,pdirstart,szObjectIDArray[i],time);
SAFE_RELEASE(pEnumObjectIDs);
CoTaskMemFree(LastParentName);
LastParentName=wstrnew(szObjectIDArray[i]);
for (i=0;i<cFetched;i++)
CoTaskMemFree(szObjectIDArray[i]);
cFetched=0;
pname=pnext;
if (pname) {
pname[0]='\\';
pname++;
pnext=wcschr(pname,'\\');
if (pnext)
pnext[0]=0;
if (pname[0]==0)
pname=NULL;
}
if (pname || pEnumObjectIDsRetVal) {
hr = pContent->EnumObjects(0, // Flags are unused
LastParentName, // Subitem
NULL, // Filter is unused
&pEnumObjectIDs);
if (!SUCCEEDED(hr)) // a file?
pEnumObjectIDs=NULL;
}
if (!pname) { //we are done!
if (pEnumObjectIDsRetVal)
*pEnumObjectIDsRetVal=pEnumObjectIDs;
if (pPropertiesRetVal)
*pPropertiesRetVal=pProperties;
else
SAFE_RELEASE(pProperties);
if (pDeviceContent)
*pDeviceContent=pContent;
else
SAFE_RELEASE(pContent);
if (pStorageIDRetVal)
*pStorageIDRetVal=LastParentName;
else
CoTaskMemFree(LastParentName);
SAFE_RELEASE(pPropertiesToRead);
return S_OK;
}
}
}
i++;
}
for (i=0;i<cFetched;i++)
CoTaskMemFree(szObjectIDArray[i]);
}
SAFE_RELEASE(pPropertiesToRead);
SAFE_RELEASE(pProperties);
SAFE_RELEASE(pEnumObjectIDs);
SAFE_RELEASE(pContent);
if (LastParentName)
CoTaskMemFree(LastParentName);
return E_FAIL;
}
static BOOL NameContainsI(LPCWSTR hay, LPCWSTR needle)
{
if (!hay || !needle || !needle[0])