-
Notifications
You must be signed in to change notification settings - Fork 286
/
win32.d
1529 lines (1291 loc) · 42.5 KB
/
win32.d
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
/**
Win32 driver implementation using WSAAsyncSelect
Copyright: © 2012-2014 Sönke Ludwig
Authors: Sönke Ludwig, Leonid Kramer
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
*/
module vibe.core.drivers.win32;
version(VibeWin32Driver)
{
import vibe.core.core;
import vibe.core.driver;
import vibe.core.drivers.timerqueue;
import vibe.core.drivers.utils;
import vibe.core.log;
import vibe.inet.url;
import vibe.internal.win32;
import vibe.utils.array;
import vibe.utils.hashmap;
import core.atomic;
import core.sync.mutex;
import core.sys.windows.windows;
import core.time;
import core.thread;
import std.algorithm;
import std.conv;
import std.c.windows.windows;
import std.c.windows.winsock;
import std.datetime;
import std.exception;
import std.string : lastIndexOf;
import std.typecons;
import std.utf;
enum WM_USER_SIGNAL = WM_USER+101;
enum WM_USER_SOCKET = WM_USER+102;
pragma(lib, "wsock32");
pragma(lib, "ws2_32");
/******************************************************************************/
/* class Win32EventDriver */
/******************************************************************************/
final class Win32EventDriver : EventDriver {
import std.container : Array, BinaryHeap, heapify;
import std.datetime : Clock;
private {
HWND m_hwnd;
DWORD m_tid;
DriverCore m_core;
bool m_exit = false;
SocketEventHandler[SOCKET] m_socketHandlers;
HANDLE[] m_registeredEvents;
HANDLE m_fileCompletionEvent;
bool[Win32TCPConnection] m_fileWriters;
TimerQueue!TimerInfo m_timers;
}
this(DriverCore core)
{
setupWindowClass();
m_core = core;
m_tid = GetCurrentThreadId();
m_hwnd = CreateWindowA("VibeWin32MessageWindow", "VibeWin32MessageWindow", 0, 0,0,0,0, HWND_MESSAGE,null,null,null);
SetWindowLongPtrA(m_hwnd, GWLP_USERDATA, cast(ULONG_PTR)cast(void*)this);
assert( cast(Win32EventDriver)cast(void*)GetWindowLongPtrA(m_hwnd, GWLP_USERDATA) == this );
WSADATA wd;
enforce(WSAStartup(0x0202, &wd) == 0, "Failed to initialize WinSock");
m_fileCompletionEvent = CreateEventW(null, false, false, null);
m_registeredEvents ~= m_fileCompletionEvent;
}
void dispose()
{
// DestroyWindow(m_hwnd);
}
int runEventLoop()
{
m_exit = false;
while( !m_exit && haveEvents() )
runEventLoopOnce();
return 0;
}
int runEventLoopOnce()
{
doProcessEvents(INFINITE);
return 0;
}
bool processEvents()
{
return doProcessEvents(0);
}
bool doProcessEvents(uint timeout_msecs)
{
assert(m_tid == GetCurrentThreadId());
waitForEvents(timeout_msecs);
processTimers();
MSG msg;
//uint cnt = 0;
while (PeekMessageW(&msg, null, 0, 0, PM_REMOVE)) {
if( msg.message == WM_QUIT ) return false;
if( msg.message == WM_USER_SIGNAL )
msg.hwnd = m_hwnd;
TranslateMessage(&msg);
DispatchMessageW(&msg);
// process timers every now and then so that they don't get stuck
//if (++cnt % 10 == 0) processTimers();
}
if (timeout_msecs != 0) m_core.notifyIdle();
return true;
}
private bool haveEvents()
{
version(VibePartialAutoExit)
return !m_fileWriters.byKey.empty || !m_socketHandlers.byKey.empty;
else return true;
}
private void waitForEvents(uint timeout_msecs)
{
// if timers are pending, limit the wait time to the first timer timeout
auto next_timer = m_timers.getFirstTimeout();
if (timeout_msecs > 0 && next_timer != SysTime.max) {
auto now = Clock.currStdTime();
auto timer_timeout = (next_timer.stdTime - now) / 10_000;
if (timeout_msecs == INFINITE || timer_timeout < timeout_msecs)
timeout_msecs = cast(uint)(timer_timeout < 0 ? 0 : timer_timeout > uint.max ? uint.max : timer_timeout);
}
auto ret = MsgWaitForMultipleObjectsEx(cast(DWORD)m_registeredEvents.length, m_registeredEvents.ptr, timeout_msecs, QS_ALLEVENTS, MWMO_ALERTABLE|MWMO_INPUTAVAILABLE);
if( ret == WAIT_OBJECT_0 ){
Win32TCPConnection[] to_remove;
foreach( fw; m_fileWriters.byKey )
if( fw.testFileWritten() )
to_remove ~= fw;
foreach( fw; to_remove )
m_fileWriters.remove(fw);
}
}
private void processTimers()
{
if (!m_timers.anyPending) return;
// process all timers that have expired up to now
auto now = Clock.currTime(UTC());
m_timers.consumeTimeouts(now, (timer, periodic, ref data) {
Task owner = data.owner;
auto callback = data.callback;
if (!periodic) releaseTimer(timer);
if (owner && owner.running) m_core.resumeTask(owner);
if (callback) runTask(callback);
});
}
void exitEventLoop()
{
m_exit = true;
PostThreadMessageW(m_tid, WM_QUIT, 0, 0);
}
Win32FileStream openFile(Path path, FileMode mode)
{
assert(m_tid == GetCurrentThreadId());
return new Win32FileStream(m_core, path, mode);
}
DirectoryWatcher watchDirectory(Path path, bool recursive)
{
assert(m_tid == GetCurrentThreadId());
return new Win32DirectoryWatcher(m_core, path, recursive);
}
NetworkAddress resolveHost(string host, ushort family = AF_UNSPEC, bool use_dns = true)
{
static immutable ushort[] addrfamilies = [AF_INET, AF_INET6];
NetworkAddress addr;
foreach( af; addrfamilies ){
if( family != af && family != AF_UNSPEC ) continue;
addr.family = af;
INT addrlen = addr.sockAddrLen;
auto ret = WSAStringToAddressW(toUTFz!(immutable(wchar)*)(host), af, null, addr.sockAddr, &addrlen);
if( ret != 0 ) continue;
assert(addrlen == addr.sockAddrLen);
return addr;
}
enforce(use_dns, "Invalid IP address string: "~host);
LookupStatus status;
status.task = Task.getThis();
status.driver = this;
status.finished = false;
WSAOVERLAPPEDX overlapped;
overlapped.Internal = 0;
overlapped.InternalHigh = 0;
overlapped.hEvent = cast(HANDLE)cast(void*)&status;
version(none){ // Windows 8+
void* aif;
ADDRINFOEXW addr_hint;
ADDRINFOEXW* addr_ret;
addr_hint.ai_family = family;
addr_hint.ai_socktype = SOCK_STREAM;
addr_hint.ai_protocol = IPPROTO_TCP;
enforce(GetAddrInfoExW(toUTFz!(immutable(wchar)*)(host), null, NS_DNS, null, &addr_hint, &addr_ret, null, &overlapped, &onDnsResult, null) == 0, "Failed to lookup host");
while( !status.finished ) m_core.yieldForEvent();
enforce(!status.error, "Failed to lookup host: "~to!string(status.error));
aif = addr_ret;
addr.family = cast(ubyte)addr_ret.ai_family;
switch(addr.family){
default: assert(false, "Invalid address family returned from host lookup.");
case AF_INET: addr.sockAddrInet4 = *cast(sockaddr_in*)addr_ret.ai_addr; break;
case AF_INET6: addr.sockAddrInet6 = *cast(sockaddr_in6*)addr_ret.ai_addr; break;
}
FreeAddrInfoExW(addr_ret);
} else {
auto he = gethostbyname(toUTFz!(immutable(char)*)(host));
socketEnforce(he !is null, "Failed to look up host "~host);
addr.family = he.h_addrtype;
switch(addr.family){
default: assert(false, "Invalid address family returned from host lookup.");
case AF_INET: addr.sockAddrInet4.sin_addr = *cast(in_addr*)he.h_addr_list[0]; break;
case AF_INET6: addr.sockAddrInet6.sin6_addr = *cast(in6_addr*)he.h_addr_list[0]; break;
}
}
return addr;
}
Win32TCPConnection connectTCP(NetworkAddress addr)
{
assert(m_tid == GetCurrentThreadId());
auto sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, null, 0, WSA_FLAG_OVERLAPPED);
socketEnforce(sock != INVALID_SOCKET, "Failed to create socket");
NetworkAddress bind_addr;
bind_addr.family = addr.family;
if (addr.family == AF_INET) bind_addr.sockAddrInet4.sin_addr.s_addr = 0;
else bind_addr.sockAddrInet6.sin6_addr.s6_addr[] = 0;
socketEnforce(bind(sock, bind_addr.sockAddr, bind_addr.sockAddrLen) == 0, "Failed to bind socket");
auto conn = new Win32TCPConnection(this, sock, addr);
conn.connect(addr);
return conn;
}
Win32TCPListener listenTCP(ushort port, void delegate(TCPConnection conn) conn_callback, string bind_address, TCPListenOptions options)
{
assert(m_tid == GetCurrentThreadId());
auto addr = resolveHost(bind_address);
addr.port = port;
auto sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, null, 0, WSA_FLAG_OVERLAPPED);
socketEnforce(sock != INVALID_SOCKET, "Failed to create socket");
socketEnforce(bind(sock, addr.sockAddr, addr.sockAddrLen) == 0,
"Failed to bind listening socket");
socketEnforce(listen(sock, 128) == 0,
"Failed to listen");
// TODO: support TCPListenOptions.distribute
return new Win32TCPListener(this, sock, conn_callback, options);
}
Win32UDPConnection listenUDP(ushort port, string bind_address = "0.0.0.0")
{
assert(m_tid == GetCurrentThreadId());
/*auto addr = resolveHost(bind_address);
addr.port = port;*/
assert(false);
}
Win32ManualEvent createManualEvent()
{
assert(m_tid == GetCurrentThreadId());
return new Win32ManualEvent(this);
}
FileDescriptorEvent createFileDescriptorEvent(int file_descriptor, FileDescriptorEvent.Trigger events)
{
assert(false, "Not implemented.");
}
size_t createTimer(void delegate() callback) { return m_timers.create(TimerInfo(callback)); }
void acquireTimer(size_t timer_id) { m_timers.getUserData(timer_id).refCount++; }
void releaseTimer(size_t timer_id)
{
if (!--m_timers.getUserData(timer_id).refCount)
m_timers.destroy(timer_id);
}
bool isTimerPending(size_t timer_id) { return m_timers.isPending(timer_id); }
void rearmTimer(size_t timer_id, Duration dur, bool periodic)
{
if (!m_timers.isPending(timer_id))
acquireTimer(timer_id);
m_timers.schedule(timer_id, dur, periodic);
}
void stopTimer(size_t timer_id)
{
if (m_timers.isPending(timer_id))
releaseTimer(timer_id);
m_timers.unschedule(timer_id);
}
void waitTimer(size_t timer_id)
{
while (true) {
auto data = &m_timers.getUserData(timer_id);
assert(data.owner == Task.init, "Waiting for the same timer from multiple tasks is not supported.");
if (!m_timers.isPending(timer_id)) return;
data.owner = Task.getThis();
scope (exit) m_timers.getUserData(timer_id).owner = Task.init;
m_core.yieldForEvent();
}
}
static struct LookupStatus {
Task task;
DWORD error;
bool finished;
Win32EventDriver driver;
}
private static nothrow extern(System)
void onDnsResult(DWORD dwError, DWORD /*dwBytes*/, WSAOVERLAPPEDX* lpOverlapped)
{
auto stat = cast(LookupStatus*)cast(void*)lpOverlapped.hEvent;
stat.error = dwError;
stat.finished = true;
if( stat.task )
try stat.driver.m_core.resumeTask(stat.task);
catch (UncaughtException th) logWarn("Resuming task for DNS lookup has thrown: %s", th.msg);
}
private static nothrow extern(System)
LRESULT onMessage(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
auto driver = cast(Win32EventDriver)cast(void*)GetWindowLongPtrA(wnd, GWLP_USERDATA);
switch(msg){
default: break;
case WM_USER_SIGNAL:
auto sig = cast(Win32ManualEvent)cast(void*)lparam;
Win32EventDriver[Task] lst;
try {
synchronized(sig.m_mutex) lst = sig.m_listeners.dup;
foreach( task, tid; lst )
if( tid is driver && task )
driver.m_core.resumeTask(task);
} catch(UncaughtException th){
logWarn("Failed to resume signal listeners: %s", th.msg);
return 0;
}
return 0;
case WM_USER_SOCKET:
SOCKET sock = cast(SOCKET)wparam;
auto evt = LOWORD(lparam);
auto err = HIWORD(lparam);
auto ph = sock in driver.m_socketHandlers;
if( ph is null ){
logWarn("Socket %s has no associated handler for event %s/%s", sock, evt, err);
} else ph.notifySocketEvent(sock, evt, err);
return 0;
}
return DefWindowProcA(wnd, msg, wparam, lparam);
}
}
interface SocketEventHandler {
SOCKET socket() nothrow;
void notifySocketEvent(SOCKET sock, WORD event, WORD error) nothrow;
}
private struct TimerInfo {
size_t refCount = 1;
void delegate() callback;
Task owner;
this(void delegate() callback) { this.callback = callback; }
}
/******************************************************************************/
/* class Win32ManualEvent */
/******************************************************************************/
final class Win32ManualEvent : ManualEvent {
private {
core.sync.mutex.Mutex m_mutex;
Win32EventDriver m_driver;
Win32EventDriver[Task] m_listeners;
shared int m_emitCount = 0;
Task m_waiter;
bool m_timedOut;
}
this(Win32EventDriver driver)
{
m_mutex = new core.sync.mutex.Mutex;
m_driver = driver;
}
void emit()
{
/*auto newcnt =*/ atomicOp!"+="(m_emitCount, 1);
bool[Win32EventDriver] threads;
synchronized(m_mutex)
{
foreach( th; m_listeners )
threads[th] = true;
}
foreach( th, _; threads )
if( !PostMessageW(th.m_hwnd, WM_USER_SIGNAL, 0, cast(LPARAM)cast(void*)this) )
logWarn("Failed to post thread message.");
}
void wait()
{
wait(emitCount);
}
int wait(int reference_emit_count)
{
//logDebugV("Signal %s wait enter %s", cast(void*)this, reference_emit_count);
acquire();
scope(exit) release();
auto ec = atomicLoad(m_emitCount);
while( ec == reference_emit_count ){
m_driver.m_core.yieldForEvent();
ec = atomicLoad(m_emitCount);
}
//logDebugV("Signal %s wait leave %s", cast(void*)this, ec);
return ec;
}
int wait(Duration timeout, int reference_emit_count = emitCount)
{
acquire();
scope(exit) release();
auto ec = atomicLoad(m_emitCount);
m_timedOut = false;
m_waiter = Task.getThis();
auto timer = m_driver.createTimer(null);
scope(exit) m_driver.releaseTimer(timer);
m_driver.m_timers.getUserData(timer).owner = Task.getThis();
m_driver.rearmTimer(timer, timeout, false);
while (ec == reference_emit_count && !m_driver.isTimerPending(timer)) {
m_driver.m_core.yieldForEvent();
ec = atomicLoad(m_emitCount);
}
return ec;
}
void acquire()
{
synchronized(m_mutex)
{
m_listeners[Task.getThis()] = cast(Win32EventDriver)getEventDriver();
}
}
void release()
{
auto self = Task.getThis();
synchronized(m_mutex)
{
if( self in m_listeners )
m_listeners.remove(self);
}
}
bool amOwner()
{
synchronized(m_mutex)
{
return (Task.getThis() in m_listeners) !is null;
}
}
@property int emitCount() const { return atomicLoad(m_emitCount); }
}
/******************************************************************************/
/* class Win32FileStream */
/******************************************************************************/
final class Win32FileStream : FileStream {
private {
Path m_path;
HANDLE m_handle;
FileMode m_mode;
DriverCore m_driver;
Task m_task;
ulong m_size;
ulong m_ptr = 0;
DWORD m_bytesTransferred;
}
this(DriverCore driver, Path path, FileMode mode)
{
m_path = path;
m_mode = mode;
m_driver = driver;
auto access = m_mode == FileMode.readWrite ? (GENERIC_WRITE | GENERIC_READ) :
(m_mode == FileMode.createTrunc || m_mode == FileMode.append)? GENERIC_WRITE : GENERIC_READ;
auto shareMode = m_mode == FileMode.read? FILE_SHARE_READ : 0;
auto creation = m_mode == FileMode.createTrunc? CREATE_ALWAYS : m_mode == FileMode.append? OPEN_ALWAYS : OPEN_EXISTING;
m_handle = CreateFileW(
toUTF16z(m_path.toNativeString()),
access,
shareMode,
null,
creation,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
null);
auto errorcode = GetLastError();
enforce(m_handle != INVALID_HANDLE_VALUE, "Failed to open "~path.toNativeString()~": "~to!string(errorcode));
if(mode == FileMode.createTrunc && errorcode == ERROR_ALREADY_EXISTS)
{
// truncate file
// TODO: seek to start pos?
BOOL ret = SetEndOfFile(m_handle);
errorcode = GetLastError();
enforce(ret, "Failed to call SetFileEndPos for path "~path.toNativeString()~", Error: " ~ to!string(errorcode));
}
long size;
auto succeeded = GetFileSizeEx(m_handle, &size);
enforce(succeeded);
m_size = size;
}
~this()
{
close();
}
void release()
{
assert(m_task == Task.getThis(), "Releasing FileStream that is not owned by the calling task.");
m_task = Task();
}
void acquire()
{
assert(m_task == Task(), "Acquiring FileStream that is already owned.");
m_task = Task.getThis();
}
bool amOwner()
{
return m_task == Task.getThis();
}
void close()
{
if(m_handle == INVALID_HANDLE_VALUE)
return;
CloseHandle(m_handle);
m_handle = INVALID_HANDLE_VALUE;
}
ulong tell() { return m_ptr; }
@property Path path() const { return m_path; }
@property bool isOpen() const { return m_handle != INVALID_HANDLE_VALUE; }
@property ulong size() const { return m_size; }
@property bool readable()
const {
return m_mode != FileMode.append;
}
@property bool writable()
const {
return m_mode == FileMode.append || m_mode == FileMode.createTrunc || m_mode == FileMode.readWrite;
}
void seek(ulong offset)
{
m_ptr = offset;
}
@property bool empty() const { assert(this.readable); return m_ptr >= m_size; }
@property ulong leastSize() const { assert(this.readable); return m_size - m_ptr; }
@property bool dataAvailableForRead(){
return leastSize() > 0;
}
const(ubyte)[] peek(){
assert(false);
}
void read(ubyte[] dst)
{
assert(this.readable);
acquire();
scope(exit) release();
while( dst.length > 0 ){
enforce(dst.length <= leastSize);
OVERLAPPED overlapped;
overlapped.Internal = 0;
overlapped.InternalHigh = 0;
overlapped.Offset = cast(uint)(m_ptr & 0xFFFFFFFF);
overlapped.OffsetHigh = cast(uint)(m_ptr >> 32);
overlapped.hEvent = cast(HANDLE)cast(void*)this;
m_bytesTransferred = 0;
auto to_read = min(dst.length, DWORD.max);
// request to write the data
ReadFileEx(m_handle, cast(void*)dst, to_read, &overlapped, &onIOCompleted);
// yield until the data is read
while( !m_bytesTransferred ) m_driver.yieldForEvent();
assert(m_bytesTransferred <= to_read, "More bytes read than requested!?");
dst = dst[m_bytesTransferred .. $];
m_ptr += m_bytesTransferred;
}
}
void write(in ubyte[] bytes_)
{
assert(this.writable);
acquire();
scope(exit) release();
const(ubyte)[] bytes = bytes_;
while( bytes.length > 0 ){
OVERLAPPED overlapped;
overlapped.Internal = 0;
overlapped.InternalHigh = 0;
overlapped.Offset = cast(uint)(m_ptr & 0xFFFFFFFF);
overlapped.OffsetHigh = cast(uint)(m_ptr >> 32);
overlapped.hEvent = cast(HANDLE)cast(void*)this;
m_bytesTransferred = 0;
auto to_write = min(bytes.length, DWORD.max);
// request to write the data
WriteFileEx(m_handle, cast(void*)bytes, to_write, &overlapped, &onIOCompleted);
// yield until the data is written
while( !m_bytesTransferred ) m_driver.yieldForEvent();
assert(m_bytesTransferred <= to_write, "More bytes written than requested!?");
bytes = bytes[m_bytesTransferred .. $];
m_ptr += m_bytesTransferred;
}
if(m_ptr > m_size) m_size = m_ptr;
}
void flush(){}
void finalize(){}
void write(InputStream stream, ulong nbytes = 0)
{
writeDefault(stream, nbytes);
}
private static extern(System) nothrow
void onIOCompleted(DWORD dwError, DWORD cbTransferred, OVERLAPPED* overlapped)
{
try {
auto fileStream = cast(Win32FileStream)(overlapped.hEvent);
fileStream.m_bytesTransferred = cbTransferred;
if( fileStream.m_task ){
Exception ex;
if( dwError != 0 ) ex = new Exception("File I/O error: "~to!string(dwError));
if( fileStream.m_task ) fileStream.m_driver.resumeTask(fileStream.m_task, ex);
}
} catch( UncaughtException e ){
logWarn("Exception while handling file I/O: %s", e.msg);
}
}
}
/******************************************************************************/
/* class Win32Directory Watcher */
/******************************************************************************/
final class Win32DirectoryWatcher : DirectoryWatcher {
private {
Path m_path;
bool m_recursive;
HANDLE m_handle;
DWORD m_bytesTransferred;
DriverCore m_core;
ubyte[16384] m_buffer;
UINT m_notifications = FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|
FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE;
Task m_task;
}
this(DriverCore core, Path path, bool recursive)
{
m_core = core;
m_path = path;
m_recursive = recursive;
m_task = Task.getThis();
auto pstr = m_path.toString();
m_handle = CreateFileW(toUTFz!(const(wchar)*)(pstr),
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
null,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
null);
}
~this()
{
CloseHandle(m_handle);
}
@property Path path() const { return m_path; }
@property bool recursive() const { return m_recursive; }
void release()
{
assert(m_task == Task.getThis(), "Releasing FileStream that is not owned by the calling task.");
m_task = Task();
}
void acquire()
{
assert(m_task == Task(), "Acquiring FileStream that is already owned.");
m_task = Task.getThis();
}
bool amOwner()
{
return m_task == Task.getThis();
}
bool readChanges(ref DirectoryChange[] dst, Duration timeout)
{
OVERLAPPED overlapped;
overlapped.Internal = 0;
overlapped.InternalHigh = 0;
overlapped.Offset = 0;
overlapped.OffsetHigh = 0;
overlapped.hEvent = cast(HANDLE)cast(void*)this;
m_bytesTransferred = 0;
DWORD bytesReturned;
if( !ReadDirectoryChangesW(m_handle, m_buffer.ptr, m_buffer.length, m_recursive,
m_notifications, &bytesReturned, &overlapped, &onIOCompleted) )
{
logError("Failed to read directory changes in '%s'", m_path);
return false;
}
// FIXME: obey timeout!
assert(timeout.isNegative());
while( !m_bytesTransferred ) m_core.yieldForEvent();
ubyte[] result = m_buffer[0 .. m_bytesTransferred];
do {
assert(result.length >= FILE_NOTIFY_INFORMATION.sizeof);
auto fni = cast(FILE_NOTIFY_INFORMATION*)result.ptr;
DirectoryChangeType kind;
switch( fni.Action ){
default: kind = DirectoryChangeType.modified; break;
case 0x1: kind = DirectoryChangeType.added; break;
case 0x2: kind = DirectoryChangeType.removed; break;
case 0x3: kind = DirectoryChangeType.modified; break;
case 0x4: kind = DirectoryChangeType.removed; break;
case 0x5: kind = DirectoryChangeType.added; break;
}
string filename = to!string(fni.FileName.ptr[0 .. fni.FileNameLength/2]);
dst ~= DirectoryChange(kind, Path(filename));
//logTrace("File changed: %s", fni.FileName.ptr[0 .. fni.FileNameLength/2]);
if( fni.NextEntryOffset == 0 ) break;
result = result[fni.NextEntryOffset .. $];
} while(result.length > 0);
return true;
}
static nothrow extern(System)
{
void onIOCompleted(DWORD dwError, DWORD cbTransferred, OVERLAPPED* overlapped)
{
try {
auto watcher = cast(Win32DirectoryWatcher)overlapped.hEvent;
watcher.m_bytesTransferred = cbTransferred;
if( watcher.m_task ){
Exception ex;
if( dwError != 0 ) ex = new Exception("Diretory watcher error: "~to!string(dwError));
if( watcher.m_task ) watcher.m_core.resumeTask(watcher.m_task, ex);
}
} catch( UncaughtException th ){
logWarn("Exception in directory watcher callback: %s", th.msg);
}
}
}
}
/******************************************************************************/
/* class Win32UDPConnection */
/******************************************************************************/
final class Win32UDPConnection : UDPConnection, SocketEventHandler {
private {
Task m_task;
Win32EventDriver m_driver;
SOCKET m_socket;
NetworkAddress m_bindAddress;
bool m_canBroadcast;
}
this(Win32EventDriver driver, SOCKET sock, NetworkAddress bind_addr)
{
m_driver = driver;
m_socket = sock;
m_bindAddress = bind_addr;
WSAAsyncSelect(sock, m_driver.m_hwnd, WM_USER_SOCKET, FD_READ|FD_WRITE|FD_CLOSE);
//bind...
}
@property SOCKET socket() { return m_socket; }
@property string bindAddress() const {
// NOTE: using WSAAddressToStringW instead of inet_ntop because that is only available from Vista up
wchar[64] buf;
DWORD buf_len = 64;
WSAAddressToStringW(m_bindAddress.sockAddr, m_bindAddress.sockAddrLen, null, buf.ptr, &buf_len);
auto ret = to!string(buf[0 .. buf_len]);
ret = ret[0 .. ret.lastIndexOf(':')]; // strip the port number
return ret;
}
@property NetworkAddress localAddress() const { return m_bindAddress; }
@property bool canBroadcast() const { return m_canBroadcast; }
@property void canBroadcast(bool val)
{
int tmp_broad = val;
socketEnforce(setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, &tmp_broad, tmp_broad.sizeof) == 0,
"Failed to change the socket broadcast flag");
m_canBroadcast = val;
}
void close()
{
if (m_socket == INVALID_SOCKET) return;
closesocket(m_socket);
m_socket = INVALID_SOCKET;
}
bool amOwner() {
return m_task != Task() && m_task == Task.getThis();
}
void acquire()
{
assert(m_task == Task(), "Trying to acquire a TCP connection that is currently owned.");
m_task = Task.getThis();
}
void release()
{
assert(m_task != Task(), "Trying to release a TCP connection that is not owned.");
assert(m_task == Task.getThis(), "Trying to release a foreign TCP connection.");
m_task = Task();
}
void connect(string host, ushort port)
{
NetworkAddress addr = m_driver.resolveHost(host, m_bindAddress.family);
addr.port = port;
connect(addr);
}
void connect(NetworkAddress addr)
{
socketEnforce(.connect(m_socket, addr.sockAddr, addr.sockAddrLen) == 0, "Failed to connect UDP socket");
}
void send(in ubyte[] data, in NetworkAddress* peer_address = null)
{
assert(data.length <= int.max);
sizediff_t ret;
if( peer_address ){
ret = .sendto(m_socket, data.ptr, cast(int)data.length, 0, peer_address.sockAddr, peer_address.sockAddrLen);
} else {
ret = .send(m_socket, data.ptr, cast(int)data.length, 0);
}
logTrace("send ret: %s, %s", ret, WSAGetLastError());
socketEnforce(ret >= 0, "Error sending UDP packet");
enforce(ret == data.length, "Unable to send full packet.");
}
ubyte[] recv(ubyte[] buf = null, NetworkAddress* peer_address = null)
{
return recv(Duration.max, buf, peer_address);
}
ubyte[] recv(Duration timeout, ubyte[] buf = null, NetworkAddress* peer_address = null)
{
size_t tm;
if (timeout != Duration.max && timeout > 0.seconds) {
tm = m_driver.createTimer(null);
m_driver.rearmTimer(tm, timeout, false);
m_driver.acquireTimer(tm);
}
acquire();
scope(exit) {
release();
if (tm != size_t.max) m_driver.releaseTimer(tm);
}
assert(buf.length <= int.max);
if( buf.length == 0 ) buf.length = 65507;
NetworkAddress from;
from.family = m_bindAddress.family;
while(true){
socklen_t addr_len = from.sockAddrLen;
auto ret = .recvfrom(m_socket, buf.ptr, cast(int)buf.length, 0, from.sockAddr, &addr_len);
if( ret > 0 ){
if( peer_address ) *peer_address = from;
return buf[0 .. ret];
}
if( ret < 0 ){
auto err = WSAGetLastError();
logDebug("UDP recv err: %s", err);
socketEnforce(err == WSAEWOULDBLOCK, "Error receiving UDP packet");
if (timeout != Duration.max) {
enforce(timeout > 0.seconds && m_driver.isTimerPending(tm), "UDP receive timeout.");
}
}
m_driver.m_core.yieldForEvent();
}
}
void notifySocketEvent(SOCKET sock, WORD event, WORD error)
{
assert(false);
}
private static nothrow extern(C) void onUDPRead(SOCKET sockfd, short evts, void* arg)
{
/*auto ctx = cast(TCPContext*)arg;
logTrace("udp socket %d read event!", ctx.socketfd);