forked from python/asyncio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
overlapped.c
1346 lines (1139 loc) · 36.3 KB
/
overlapped.c
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
/*
* Support for overlapped IO
*
* Some code borrowed from Modules/_winapi.c of CPython
*/
/* XXX check overflow and DWORD <-> Py_ssize_t conversions
Check itemsize */
#include "Python.h"
#include "structmember.h"
#define WINDOWS_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#if defined(MS_WIN32) && !defined(MS_WIN64)
# define F_POINTER "k"
# define T_POINTER T_ULONG
#else
# define F_POINTER "K"
# define T_POINTER T_ULONGLONG
#endif
/* Compatibility with Python 3.3 */
#if PY_VERSION_HEX < 0x03040000
# define PyMem_RawMalloc PyMem_Malloc
# define PyMem_RawFree PyMem_Free
#endif
#define F_HANDLE F_POINTER
#define F_ULONG_PTR F_POINTER
#define F_DWORD "k"
#define F_BOOL "i"
#define F_UINT "I"
#define T_HANDLE T_POINTER
enum {TYPE_NONE, TYPE_NOT_STARTED, TYPE_READ, TYPE_WRITE, TYPE_ACCEPT,
TYPE_CONNECT, TYPE_DISCONNECT, TYPE_CONNECT_NAMED_PIPE,
TYPE_WAIT_NAMED_PIPE_AND_CONNECT};
typedef struct {
PyObject_HEAD
OVERLAPPED overlapped;
/* For convenience, we store the file handle too */
HANDLE handle;
/* Error returned by last method call */
DWORD error;
/* Type of operation */
DWORD type;
union {
/* Buffer used for reading: TYPE_READ and TYPE_ACCEPT */
PyObject *read_buffer;
/* Buffer used for writing: TYPE_WRITE */
Py_buffer write_buffer;
};
} OverlappedObject;
/*
* Map Windows error codes to subclasses of OSError
*/
static PyObject *
SetFromWindowsErr(DWORD err)
{
PyObject *exception_type;
if (err == 0)
err = GetLastError();
switch (err) {
case ERROR_CONNECTION_REFUSED:
exception_type = PyExc_ConnectionRefusedError;
break;
case ERROR_CONNECTION_ABORTED:
exception_type = PyExc_ConnectionAbortedError;
break;
default:
exception_type = PyExc_OSError;
}
return PyErr_SetExcFromWindowsErr(exception_type, err);
}
/*
* Some functions should be loaded at runtime
*/
static LPFN_ACCEPTEX Py_AcceptEx = NULL;
static LPFN_CONNECTEX Py_ConnectEx = NULL;
static LPFN_DISCONNECTEX Py_DisconnectEx = NULL;
static BOOL (CALLBACK *Py_CancelIoEx)(HANDLE, LPOVERLAPPED) = NULL;
#define GET_WSA_POINTER(s, x) \
(SOCKET_ERROR != WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, \
&Guid##x, sizeof(Guid##x), &Py_##x, \
sizeof(Py_##x), &dwBytes, NULL, NULL))
static int
initialize_function_pointers(void)
{
GUID GuidAcceptEx = WSAID_ACCEPTEX;
GUID GuidConnectEx = WSAID_CONNECTEX;
GUID GuidDisconnectEx = WSAID_DISCONNECTEX;
HINSTANCE hKernel32;
SOCKET s;
DWORD dwBytes;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
SetFromWindowsErr(WSAGetLastError());
return -1;
}
if (!GET_WSA_POINTER(s, AcceptEx) ||
!GET_WSA_POINTER(s, ConnectEx) ||
!GET_WSA_POINTER(s, DisconnectEx))
{
closesocket(s);
SetFromWindowsErr(WSAGetLastError());
return -1;
}
closesocket(s);
/* On WinXP we will have Py_CancelIoEx == NULL */
hKernel32 = GetModuleHandle("KERNEL32");
*(FARPROC *)&Py_CancelIoEx = GetProcAddress(hKernel32, "CancelIoEx");
return 0;
}
/*
* Completion port stuff
*/
PyDoc_STRVAR(
CreateIoCompletionPort_doc,
"CreateIoCompletionPort(handle, port, key, concurrency) -> port\n\n"
"Create a completion port or register a handle with a port.");
static PyObject *
overlapped_CreateIoCompletionPort(PyObject *self, PyObject *args)
{
HANDLE FileHandle;
HANDLE ExistingCompletionPort;
ULONG_PTR CompletionKey;
DWORD NumberOfConcurrentThreads;
HANDLE ret;
if (!PyArg_ParseTuple(args, F_HANDLE F_HANDLE F_ULONG_PTR F_DWORD,
&FileHandle, &ExistingCompletionPort, &CompletionKey,
&NumberOfConcurrentThreads))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = CreateIoCompletionPort(FileHandle, ExistingCompletionPort,
CompletionKey, NumberOfConcurrentThreads);
Py_END_ALLOW_THREADS
if (ret == NULL)
return SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, ret);
}
PyDoc_STRVAR(
GetQueuedCompletionStatus_doc,
"GetQueuedCompletionStatus(port, msecs) -> (err, bytes, key, address)\n\n"
"Get a message from completion port. Wait for up to msecs milliseconds.");
static PyObject *
overlapped_GetQueuedCompletionStatus(PyObject *self, PyObject *args)
{
HANDLE CompletionPort = NULL;
DWORD NumberOfBytes = 0;
ULONG_PTR CompletionKey = 0;
OVERLAPPED *Overlapped = NULL;
DWORD Milliseconds;
DWORD err;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE F_DWORD,
&CompletionPort, &Milliseconds))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = GetQueuedCompletionStatus(CompletionPort, &NumberOfBytes,
&CompletionKey, &Overlapped, Milliseconds);
Py_END_ALLOW_THREADS
err = ret ? ERROR_SUCCESS : GetLastError();
if (Overlapped == NULL) {
if (err == WAIT_TIMEOUT)
Py_RETURN_NONE;
else
return SetFromWindowsErr(err);
}
return Py_BuildValue(F_DWORD F_DWORD F_ULONG_PTR F_POINTER,
err, NumberOfBytes, CompletionKey, Overlapped);
}
PyDoc_STRVAR(
PostQueuedCompletionStatus_doc,
"PostQueuedCompletionStatus(port, bytes, key, address) -> None\n\n"
"Post a message to completion port.");
static PyObject *
overlapped_PostQueuedCompletionStatus(PyObject *self, PyObject *args)
{
HANDLE CompletionPort;
DWORD NumberOfBytes;
ULONG_PTR CompletionKey;
OVERLAPPED *Overlapped;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE F_DWORD F_ULONG_PTR F_POINTER,
&CompletionPort, &NumberOfBytes, &CompletionKey,
&Overlapped))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = PostQueuedCompletionStatus(CompletionPort, NumberOfBytes,
CompletionKey, Overlapped);
Py_END_ALLOW_THREADS
if (!ret)
return SetFromWindowsErr(0);
Py_RETURN_NONE;
}
/*
* Wait for a handle
*/
struct PostCallbackData {
HANDLE CompletionPort;
LPOVERLAPPED Overlapped;
};
static VOID CALLBACK
PostToQueueCallback(PVOID lpParameter, BOOL TimerOrWaitFired)
{
struct PostCallbackData *p = (struct PostCallbackData*) lpParameter;
PostQueuedCompletionStatus(p->CompletionPort, TimerOrWaitFired,
0, p->Overlapped);
/* ignore possible error! */
PyMem_RawFree(p);
}
PyDoc_STRVAR(
RegisterWaitWithQueue_doc,
"RegisterWaitWithQueue(Object, CompletionPort, Overlapped, Timeout)\n"
" -> WaitHandle\n\n"
"Register wait for Object; when complete CompletionPort is notified.\n");
static PyObject *
overlapped_RegisterWaitWithQueue(PyObject *self, PyObject *args)
{
HANDLE NewWaitObject;
HANDLE Object;
ULONG Milliseconds;
struct PostCallbackData data, *pdata;
if (!PyArg_ParseTuple(args, F_HANDLE F_HANDLE F_POINTER F_DWORD,
&Object,
&data.CompletionPort,
&data.Overlapped,
&Milliseconds))
return NULL;
/* Use PyMem_RawMalloc() rather than PyMem_Malloc(), since
PostToQueueCallback() will call PyMem_Free() from a new C thread
which doesn't hold the GIL. */
pdata = PyMem_RawMalloc(sizeof(struct PostCallbackData));
if (pdata == NULL)
return SetFromWindowsErr(0);
*pdata = data;
if (!RegisterWaitForSingleObject(
&NewWaitObject, Object, (WAITORTIMERCALLBACK)PostToQueueCallback,
pdata, Milliseconds,
WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE))
{
PyMem_RawFree(pdata);
return SetFromWindowsErr(0);
}
return Py_BuildValue(F_HANDLE, NewWaitObject);
}
PyDoc_STRVAR(
UnregisterWait_doc,
"UnregisterWait(WaitHandle) -> None\n\n"
"Unregister wait handle.\n");
static PyObject *
overlapped_UnregisterWait(PyObject *self, PyObject *args)
{
HANDLE WaitHandle;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE, &WaitHandle))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = UnregisterWait(WaitHandle);
Py_END_ALLOW_THREADS
if (!ret)
return SetFromWindowsErr(0);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
UnregisterWaitEx_doc,
"UnregisterWaitEx(WaitHandle, Event) -> None\n\n"
"Unregister wait handle.\n");
static PyObject *
overlapped_UnregisterWaitEx(PyObject *self, PyObject *args)
{
HANDLE WaitHandle, Event;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE F_HANDLE, &WaitHandle, &Event))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = UnregisterWaitEx(WaitHandle, Event);
Py_END_ALLOW_THREADS
if (!ret)
return SetFromWindowsErr(0);
Py_RETURN_NONE;
}
/*
* Event functions -- currently only used by tests
*/
PyDoc_STRVAR(
CreateEvent_doc,
"CreateEvent(EventAttributes, ManualReset, InitialState, Name)"
" -> Handle\n\n"
"Create an event. EventAttributes must be None.\n");
static PyObject *
overlapped_CreateEvent(PyObject *self, PyObject *args)
{
PyObject *EventAttributes;
BOOL ManualReset;
BOOL InitialState;
Py_UNICODE *Name;
HANDLE Event;
if (!PyArg_ParseTuple(args, "O" F_BOOL F_BOOL "Z",
&EventAttributes, &ManualReset,
&InitialState, &Name))
return NULL;
if (EventAttributes != Py_None) {
PyErr_SetString(PyExc_ValueError, "EventAttributes must be None");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
Event = CreateEventW(NULL, ManualReset, InitialState, Name);
Py_END_ALLOW_THREADS
if (Event == NULL)
return SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, Event);
}
PyDoc_STRVAR(
SetEvent_doc,
"SetEvent(Handle) -> None\n\n"
"Set event.\n");
static PyObject *
overlapped_SetEvent(PyObject *self, PyObject *args)
{
HANDLE Handle;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE, &Handle))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = SetEvent(Handle);
Py_END_ALLOW_THREADS
if (!ret)
return SetFromWindowsErr(0);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
ResetEvent_doc,
"ResetEvent(Handle) -> None\n\n"
"Reset event.\n");
static PyObject *
overlapped_ResetEvent(PyObject *self, PyObject *args)
{
HANDLE Handle;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE, &Handle))
return NULL;
Py_BEGIN_ALLOW_THREADS
ret = ResetEvent(Handle);
Py_END_ALLOW_THREADS
if (!ret)
return SetFromWindowsErr(0);
Py_RETURN_NONE;
}
/*
* Bind socket handle to local port without doing slow getaddrinfo()
*/
PyDoc_STRVAR(
BindLocal_doc,
"BindLocal(handle, family) -> None\n\n"
"Bind a socket handle to an arbitrary local port.\n"
"family should AF_INET or AF_INET6.\n");
static PyObject *
overlapped_BindLocal(PyObject *self, PyObject *args)
{
SOCKET Socket;
int Family;
BOOL ret;
if (!PyArg_ParseTuple(args, F_HANDLE "i", &Socket, &Family))
return NULL;
if (Family == AF_INET) {
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = 0;
addr.sin_addr.S_un.S_addr = INADDR_ANY;
ret = bind(Socket, (SOCKADDR*)&addr, sizeof(addr)) != SOCKET_ERROR;
} else if (Family == AF_INET6) {
struct sockaddr_in6 addr;
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_port = 0;
addr.sin6_addr = in6addr_any;
ret = bind(Socket, (SOCKADDR*)&addr, sizeof(addr)) != SOCKET_ERROR;
} else {
PyErr_SetString(PyExc_ValueError, "expected tuple of length 2 or 4");
return NULL;
}
if (!ret)
return SetFromWindowsErr(WSAGetLastError());
Py_RETURN_NONE;
}
/*
* Windows equivalent of os.strerror() -- compare _ctypes/callproc.c
*/
PyDoc_STRVAR(
FormatMessage_doc,
"FormatMessage(error_code) -> error_message\n\n"
"Return error message for an error code.");
static PyObject *
overlapped_FormatMessage(PyObject *ignore, PyObject *args)
{
DWORD code, n;
WCHAR *lpMsgBuf;
PyObject *res;
if (!PyArg_ParseTuple(args, F_DWORD, &code))
return NULL;
n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR) &lpMsgBuf,
0,
NULL);
if (n) {
while (iswspace(lpMsgBuf[n-1]))
--n;
lpMsgBuf[n] = L'\0';
res = Py_BuildValue("u", lpMsgBuf);
} else {
res = PyUnicode_FromFormat("unknown error code %u", code);
}
LocalFree(lpMsgBuf);
return res;
}
/*
* Mark operation as completed - used when reading produces ERROR_BROKEN_PIPE
*/
static void
mark_as_completed(OVERLAPPED *ov)
{
ov->Internal = 0;
if (ov->hEvent != NULL)
SetEvent(ov->hEvent);
}
/*
* A Python object wrapping an OVERLAPPED structure and other useful data
* for overlapped I/O
*/
PyDoc_STRVAR(
Overlapped_doc,
"Overlapped object");
static PyObject *
Overlapped_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
OverlappedObject *self;
HANDLE event = INVALID_HANDLE_VALUE;
static char *kwlist[] = {"event", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|" F_HANDLE, kwlist, &event))
return NULL;
if (event == INVALID_HANDLE_VALUE) {
event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (event == NULL)
return SetFromWindowsErr(0);
}
self = PyObject_New(OverlappedObject, type);
if (self == NULL) {
if (event != NULL)
CloseHandle(event);
return NULL;
}
self->handle = NULL;
self->error = 0;
self->type = TYPE_NONE;
self->read_buffer = NULL;
memset(&self->overlapped, 0, sizeof(OVERLAPPED));
memset(&self->write_buffer, 0, sizeof(Py_buffer));
if (event)
self->overlapped.hEvent = event;
return (PyObject *)self;
}
static void
Overlapped_dealloc(OverlappedObject *self)
{
DWORD bytes;
DWORD olderr = GetLastError();
BOOL wait = FALSE;
BOOL ret;
if (!HasOverlappedIoCompleted(&self->overlapped) &&
self->type != TYPE_NOT_STARTED)
{
if (Py_CancelIoEx && Py_CancelIoEx(self->handle, &self->overlapped))
wait = TRUE;
Py_BEGIN_ALLOW_THREADS
ret = GetOverlappedResult(self->handle, &self->overlapped,
&bytes, wait);
Py_END_ALLOW_THREADS
switch (ret ? ERROR_SUCCESS : GetLastError()) {
case ERROR_SUCCESS:
case ERROR_NOT_FOUND:
case ERROR_OPERATION_ABORTED:
break;
default:
PyErr_Format(
PyExc_RuntimeError,
"%R still has pending operation at "
"deallocation, the process may crash", self);
PyErr_WriteUnraisable(NULL);
}
}
if (self->overlapped.hEvent != NULL)
CloseHandle(self->overlapped.hEvent);
switch (self->type) {
case TYPE_READ:
case TYPE_ACCEPT:
Py_CLEAR(self->read_buffer);
break;
case TYPE_WRITE:
if (self->write_buffer.obj)
PyBuffer_Release(&self->write_buffer);
break;
}
PyObject_Del(self);
SetLastError(olderr);
}
PyDoc_STRVAR(
Overlapped_cancel_doc,
"cancel() -> None\n\n"
"Cancel overlapped operation");
static PyObject *
Overlapped_cancel(OverlappedObject *self)
{
BOOL ret = TRUE;
if (self->type == TYPE_NOT_STARTED
|| self->type == TYPE_WAIT_NAMED_PIPE_AND_CONNECT)
Py_RETURN_NONE;
if (!HasOverlappedIoCompleted(&self->overlapped)) {
Py_BEGIN_ALLOW_THREADS
if (Py_CancelIoEx)
ret = Py_CancelIoEx(self->handle, &self->overlapped);
else
ret = CancelIo(self->handle);
Py_END_ALLOW_THREADS
}
/* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
if (!ret && GetLastError() != ERROR_NOT_FOUND)
return SetFromWindowsErr(0);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
Overlapped_getresult_doc,
"getresult(wait=False) -> result\n\n"
"Retrieve result of operation. If wait is true then it blocks\n"
"until the operation is finished. If wait is false and the\n"
"operation is still pending then an error is raised.");
static PyObject *
Overlapped_getresult(OverlappedObject *self, PyObject *args)
{
BOOL wait = FALSE;
DWORD transferred = 0;
BOOL ret;
DWORD err;
if (!PyArg_ParseTuple(args, "|" F_BOOL, &wait))
return NULL;
if (self->type == TYPE_NONE) {
PyErr_SetString(PyExc_ValueError, "operation not yet attempted");
return NULL;
}
if (self->type == TYPE_NOT_STARTED) {
PyErr_SetString(PyExc_ValueError, "operation failed to start");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
ret = GetOverlappedResult(self->handle, &self->overlapped, &transferred,
wait);
Py_END_ALLOW_THREADS
self->error = err = ret ? ERROR_SUCCESS : GetLastError();
switch (err) {
case ERROR_SUCCESS:
case ERROR_MORE_DATA:
break;
case ERROR_BROKEN_PIPE:
if ((self->type == TYPE_READ || self->type == TYPE_ACCEPT) && self->read_buffer != NULL)
break;
/* fall through */
default:
return SetFromWindowsErr(err);
}
switch (self->type) {
case TYPE_READ:
assert(PyBytes_CheckExact(self->read_buffer));
if (transferred != PyBytes_GET_SIZE(self->read_buffer) &&
_PyBytes_Resize(&self->read_buffer, transferred))
return NULL;
Py_INCREF(self->read_buffer);
return self->read_buffer;
default:
return PyLong_FromUnsignedLong((unsigned long) transferred);
}
}
PyDoc_STRVAR(
Overlapped_ReadFile_doc,
"ReadFile(handle, size) -> Overlapped[message]\n\n"
"Start overlapped read");
static PyObject *
Overlapped_ReadFile(OverlappedObject *self, PyObject *args)
{
HANDLE handle;
DWORD size;
DWORD nread;
PyObject *buf;
BOOL ret;
DWORD err;
if (!PyArg_ParseTuple(args, F_HANDLE F_DWORD, &handle, &size))
return NULL;
if (self->type != TYPE_NONE) {
PyErr_SetString(PyExc_ValueError, "operation already attempted");
return NULL;
}
#if SIZEOF_SIZE_T <= SIZEOF_LONG
size = Py_MIN(size, (DWORD)PY_SSIZE_T_MAX);
#endif
buf = PyBytes_FromStringAndSize(NULL, Py_MAX(size, 1));
if (buf == NULL)
return NULL;
self->type = TYPE_READ;
self->handle = handle;
self->read_buffer = buf;
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(handle, PyBytes_AS_STRING(buf), size, &nread,
&self->overlapped);
Py_END_ALLOW_THREADS
self->error = err = ret ? ERROR_SUCCESS : GetLastError();
switch (err) {
case ERROR_BROKEN_PIPE:
mark_as_completed(&self->overlapped);
return SetFromWindowsErr(err);
case ERROR_SUCCESS:
case ERROR_MORE_DATA:
case ERROR_IO_PENDING:
Py_RETURN_NONE;
default:
self->type = TYPE_NOT_STARTED;
return SetFromWindowsErr(err);
}
}
PyDoc_STRVAR(
Overlapped_WSARecv_doc,
"RecvFile(handle, size, flags) -> Overlapped[message]\n\n"
"Start overlapped receive");
static PyObject *
Overlapped_WSARecv(OverlappedObject *self, PyObject *args)
{
HANDLE handle;
DWORD size;
DWORD flags = 0;
DWORD nread;
PyObject *buf;
WSABUF wsabuf;
int ret;
DWORD err;
if (!PyArg_ParseTuple(args, F_HANDLE F_DWORD "|" F_DWORD,
&handle, &size, &flags))
return NULL;
if (self->type != TYPE_NONE) {
PyErr_SetString(PyExc_ValueError, "operation already attempted");
return NULL;
}
#if SIZEOF_SIZE_T <= SIZEOF_LONG
size = Py_MIN(size, (DWORD)PY_SSIZE_T_MAX);
#endif
buf = PyBytes_FromStringAndSize(NULL, Py_MAX(size, 1));
if (buf == NULL)
return NULL;
self->type = TYPE_READ;
self->handle = handle;
self->read_buffer = buf;
wsabuf.len = size;
wsabuf.buf = PyBytes_AS_STRING(buf);
Py_BEGIN_ALLOW_THREADS
ret = WSARecv((SOCKET)handle, &wsabuf, 1, &nread, &flags,
&self->overlapped, NULL);
Py_END_ALLOW_THREADS
self->error = err = (ret < 0 ? WSAGetLastError() : ERROR_SUCCESS);
switch (err) {
case ERROR_BROKEN_PIPE:
mark_as_completed(&self->overlapped);
return SetFromWindowsErr(err);
case ERROR_SUCCESS:
case ERROR_MORE_DATA:
case ERROR_IO_PENDING:
Py_RETURN_NONE;
default:
self->type = TYPE_NOT_STARTED;
return SetFromWindowsErr(err);
}
}
PyDoc_STRVAR(
Overlapped_WriteFile_doc,
"WriteFile(handle, buf) -> Overlapped[bytes_transferred]\n\n"
"Start overlapped write");
static PyObject *
Overlapped_WriteFile(OverlappedObject *self, PyObject *args)
{
HANDLE handle;
PyObject *bufobj;
DWORD written;
BOOL ret;
DWORD err;
if (!PyArg_ParseTuple(args, F_HANDLE "O", &handle, &bufobj))
return NULL;
if (self->type != TYPE_NONE) {
PyErr_SetString(PyExc_ValueError, "operation already attempted");
return NULL;
}
if (!PyArg_Parse(bufobj, "y*", &self->write_buffer))
return NULL;
#if SIZEOF_SIZE_T > SIZEOF_LONG
if (self->write_buffer.len > (Py_ssize_t)ULONG_MAX) {
PyBuffer_Release(&self->write_buffer);
PyErr_SetString(PyExc_ValueError, "buffer to large");
return NULL;
}
#endif
self->type = TYPE_WRITE;
self->handle = handle;
Py_BEGIN_ALLOW_THREADS
ret = WriteFile(handle, self->write_buffer.buf,
(DWORD)self->write_buffer.len,
&written, &self->overlapped);
Py_END_ALLOW_THREADS
self->error = err = ret ? ERROR_SUCCESS : GetLastError();
switch (err) {
case ERROR_SUCCESS:
case ERROR_IO_PENDING:
Py_RETURN_NONE;
default:
self->type = TYPE_NOT_STARTED;
return SetFromWindowsErr(err);
}
}
PyDoc_STRVAR(
Overlapped_WSASend_doc,
"WSASend(handle, buf, flags) -> Overlapped[bytes_transferred]\n\n"
"Start overlapped send");
static PyObject *
Overlapped_WSASend(OverlappedObject *self, PyObject *args)
{
HANDLE handle;
PyObject *bufobj;
DWORD flags;
DWORD written;
WSABUF wsabuf;
int ret;
DWORD err;
if (!PyArg_ParseTuple(args, F_HANDLE "O" F_DWORD,
&handle, &bufobj, &flags))
return NULL;
if (self->type != TYPE_NONE) {
PyErr_SetString(PyExc_ValueError, "operation already attempted");
return NULL;
}
if (!PyArg_Parse(bufobj, "y*", &self->write_buffer))
return NULL;
#if SIZEOF_SIZE_T > SIZEOF_LONG
if (self->write_buffer.len > (Py_ssize_t)ULONG_MAX) {
PyBuffer_Release(&self->write_buffer);
PyErr_SetString(PyExc_ValueError, "buffer to large");
return NULL;
}
#endif
self->type = TYPE_WRITE;
self->handle = handle;
wsabuf.len = (DWORD)self->write_buffer.len;
wsabuf.buf = self->write_buffer.buf;
Py_BEGIN_ALLOW_THREADS
ret = WSASend((SOCKET)handle, &wsabuf, 1, &written, flags,
&self->overlapped, NULL);
Py_END_ALLOW_THREADS
self->error = err = (ret < 0 ? WSAGetLastError() : ERROR_SUCCESS);
switch (err) {
case ERROR_SUCCESS:
case ERROR_IO_PENDING:
Py_RETURN_NONE;
default:
self->type = TYPE_NOT_STARTED;
return SetFromWindowsErr(err);
}
}
PyDoc_STRVAR(
Overlapped_AcceptEx_doc,
"AcceptEx(listen_handle, accept_handle) -> Overlapped[address_as_bytes]\n\n"
"Start overlapped wait for client to connect");
static PyObject *
Overlapped_AcceptEx(OverlappedObject *self, PyObject *args)
{
SOCKET ListenSocket;
SOCKET AcceptSocket;
DWORD BytesReceived;
DWORD size;
PyObject *buf;
BOOL ret;
DWORD err;
if (!PyArg_ParseTuple(args, F_HANDLE F_HANDLE,
&ListenSocket, &AcceptSocket))
return NULL;
if (self->type != TYPE_NONE) {
PyErr_SetString(PyExc_ValueError, "operation already attempted");
return NULL;
}
size = sizeof(struct sockaddr_in6) + 16;
buf = PyBytes_FromStringAndSize(NULL, size*2);
if (!buf)
return NULL;
self->type = TYPE_ACCEPT;
self->handle = (HANDLE)ListenSocket;
self->read_buffer = buf;
Py_BEGIN_ALLOW_THREADS
ret = Py_AcceptEx(ListenSocket, AcceptSocket, PyBytes_AS_STRING(buf),
0, size, size, &BytesReceived, &self->overlapped);
Py_END_ALLOW_THREADS
self->error = err = ret ? ERROR_SUCCESS : WSAGetLastError();
switch (err) {
case ERROR_SUCCESS:
case ERROR_IO_PENDING:
Py_RETURN_NONE;
default:
self->type = TYPE_NOT_STARTED;
return SetFromWindowsErr(err);
}
}
static int
parse_address(PyObject *obj, SOCKADDR *Address, int Length)
{
char *Host;
unsigned short Port;
unsigned long FlowInfo;
unsigned long ScopeId;
memset(Address, 0, Length);
if (PyArg_ParseTuple(obj, "sH", &Host, &Port))
{
Address->sa_family = AF_INET;
if (WSAStringToAddressA(Host, AF_INET, NULL, Address, &Length) < 0) {
SetFromWindowsErr(WSAGetLastError());
return -1;
}
((SOCKADDR_IN*)Address)->sin_port = htons(Port);
return Length;
}
else if (PyArg_ParseTuple(obj, "sHkk", &Host, &Port, &FlowInfo, &ScopeId))
{
PyErr_Clear();
Address->sa_family = AF_INET6;
if (WSAStringToAddressA(Host, AF_INET6, NULL, Address, &Length) < 0) {
SetFromWindowsErr(WSAGetLastError());
return -1;
}