- Don't disconnect the same socket multiple times (once per TDI_SEND IRP cancelled...
[reactos.git] / reactos / lib / drivers / ip / transport / tcp / tcp.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS TCP/IP protocol driver
4 * FILE: transport/tcp/tcp.c
5 * PURPOSE: Transmission Control Protocol
6 * PROGRAMMERS: Casper S. Hornstrup (chorns@users.sourceforge.net)
7 * Art Yerkes (arty@users.sf.net)
8 * REVISIONS:
9 * CSH 01/08-2000 Created
10 * arty 12/21/2004 Added accept
11 */
12
13 #include "precomp.h"
14
15 LONG TCP_IPIdentification = 0;
16 static BOOLEAN TCPInitialized = FALSE;
17 static NPAGED_LOOKASIDE_LIST TCPSegmentList;
18 LIST_ENTRY SignalledConnectionsList;
19 KSPIN_LOCK SignalledConnectionsLock;
20 LIST_ENTRY SleepingThreadsList;
21 FAST_MUTEX SleepingThreadsLock;
22 RECURSIVE_MUTEX TCPLock;
23 PORT_SET TCPPorts;
24
25 static VOID HandleSignalledConnection( PCONNECTION_ENDPOINT Connection ) {
26 NTSTATUS Status = STATUS_SUCCESS;
27 PTCP_COMPLETION_ROUTINE Complete;
28 PTDI_BUCKET Bucket;
29 PLIST_ENTRY Entry;
30 PIRP Irp;
31 PMDL Mdl;
32
33 ASSERT_LOCKED(&TCPLock);
34
35 TI_DbgPrint(MID_TRACE,("Handling signalled state on %x (%x)\n",
36 Connection, Connection->SocketContext));
37
38 if( Connection->SignalState & SEL_FIN ) {
39 TI_DbgPrint(DEBUG_TCP, ("EOF From socket\n"));
40
41 while ((Entry = ExInterlockedRemoveHeadList( &Connection->ReceiveRequest,
42 &Connection->Lock )) != NULL)
43 {
44 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
45 Complete = Bucket->Request.RequestNotifyObject;
46
47 Complete( Bucket->Request.RequestContext, STATUS_CANCELLED, 0 );
48
49 exFreePool(Bucket);
50 }
51
52 while ((Entry = ExInterlockedRemoveHeadList( &Connection->SendRequest,
53 &Connection->Lock )) != NULL)
54 {
55 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
56 Complete = Bucket->Request.RequestNotifyObject;
57
58 Complete( Bucket->Request.RequestContext, STATUS_CANCELLED, 0 );
59
60 exFreePool(Bucket);
61 }
62
63 while ((Entry = ExInterlockedRemoveHeadList( &Connection->ListenRequest,
64 &Connection->Lock )) != NULL)
65 {
66 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
67 Complete = Bucket->Request.RequestNotifyObject;
68
69 /* We have to notify oskittcp of the abortion */
70 TCPAbortListenForSocket(Connection->AddressFile->Listener,
71 Connection);
72
73 Complete( Bucket->Request.RequestContext, STATUS_CANCELLED, 0 );
74
75 exFreePool(Bucket);
76 }
77
78 while ((Entry = ExInterlockedRemoveHeadList( &Connection->ConnectRequest,
79 &Connection->Lock )) != NULL)
80 {
81 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
82 Complete = Bucket->Request.RequestNotifyObject;
83
84 Complete( Bucket->Request.RequestContext, STATUS_CANCELLED, 0 );
85
86 exFreePool(Bucket);
87 }
88
89 Connection->SignalState = 0;
90 }
91
92 /* Things that can happen when we try the initial connection */
93 if( Connection->SignalState & SEL_CONNECT ) {
94 while( (Entry = ExInterlockedRemoveHeadList( &Connection->ConnectRequest,
95 &Connection->Lock )) != NULL ) {
96
97 TI_DbgPrint(DEBUG_TCP, ("Connect Event\n"));
98
99 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
100 Complete = Bucket->Request.RequestNotifyObject;
101 TI_DbgPrint(DEBUG_TCP,
102 ("Completing Request %x\n", Bucket->Request.RequestContext));
103
104 Complete( Bucket->Request.RequestContext, STATUS_SUCCESS, 0 );
105
106 /* Frees the bucket allocated in TCPConnect */
107 exFreePool( Bucket );
108 }
109 }
110
111 if( Connection->SignalState & SEL_ACCEPT ) {
112 /* Handle readable on a listening socket --
113 * TODO: Implement filtering
114 */
115
116 TI_DbgPrint(DEBUG_TCP,("Accepting new connection on %x (Queue: %s)\n",
117 Connection,
118 IsListEmpty(&Connection->ListenRequest) ?
119 "empty" : "nonempty"));
120
121 while( (Entry = ExInterlockedRemoveHeadList( &Connection->ListenRequest,
122 &Connection->Lock )) != NULL ) {
123 PIO_STACK_LOCATION IrpSp;
124
125 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
126 Complete = Bucket->Request.RequestNotifyObject;
127
128 Irp = Bucket->Request.RequestContext;
129 IrpSp = IoGetCurrentIrpStackLocation( Irp );
130
131 TI_DbgPrint(DEBUG_TCP,("Getting the socket\n"));
132 Status = TCPServiceListeningSocket
133 ( Connection->AddressFile->Listener,
134 Bucket->AssociatedEndpoint,
135 (PTDI_REQUEST_KERNEL)&IrpSp->Parameters );
136
137 TI_DbgPrint(DEBUG_TCP,("Socket: Status: %x\n"));
138
139 if( Status == STATUS_PENDING ) {
140 ExInterlockedInsertHeadList( &Connection->ListenRequest, &Bucket->Entry, &Connection->Lock );
141 break;
142 } else {
143 Complete( Bucket->Request.RequestContext, Status, 0 );
144 exFreePool( Bucket );
145 }
146 }
147 }
148
149 /* Things that happen after we're connected */
150 if( Connection->SignalState & SEL_READ ) {
151 TI_DbgPrint(DEBUG_TCP,("Readable: irp list %s\n",
152 IsListEmpty(&Connection->ReceiveRequest) ?
153 "empty" : "nonempty"));
154
155 while( (Entry = ExInterlockedRemoveHeadList( &Connection->ReceiveRequest,
156 &Connection->Lock )) != NULL ) {
157 OSK_UINT RecvLen = 0, Received = 0;
158 PVOID RecvBuffer = 0;
159
160 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
161 Complete = Bucket->Request.RequestNotifyObject;
162
163 Irp = Bucket->Request.RequestContext;
164 Mdl = Irp->MdlAddress;
165
166 TI_DbgPrint(DEBUG_TCP,
167 ("Getting the user buffer from %x\n", Mdl));
168
169 NdisQueryBuffer( Mdl, &RecvBuffer, &RecvLen );
170
171 TI_DbgPrint(DEBUG_TCP,
172 ("Reading %d bytes to %x\n", RecvLen, RecvBuffer));
173
174 TI_DbgPrint(DEBUG_TCP, ("Connection: %x\n", Connection));
175 TI_DbgPrint
176 (DEBUG_TCP,
177 ("Connection->SocketContext: %x\n",
178 Connection->SocketContext));
179 TI_DbgPrint(DEBUG_TCP, ("RecvBuffer: %x\n", RecvBuffer));
180
181 Status = TCPTranslateError
182 ( OskitTCPRecv( Connection->SocketContext,
183 RecvBuffer,
184 RecvLen,
185 &Received,
186 0 ) );
187
188 TI_DbgPrint(DEBUG_TCP,("TCP Bytes: %d\n", Received));
189
190 if( Status == STATUS_SUCCESS ) {
191 TI_DbgPrint(DEBUG_TCP,("Received %d bytes with status %x\n",
192 Received, Status));
193
194 Complete( Bucket->Request.RequestContext,
195 STATUS_SUCCESS, Received );
196 exFreePool( Bucket );
197 } else if( Status == STATUS_PENDING ) {
198 ExInterlockedInsertHeadList
199 ( &Connection->ReceiveRequest, &Bucket->Entry, &Connection->Lock );
200 break;
201 } else {
202 TI_DbgPrint(DEBUG_TCP,
203 ("Completing Receive request: %x %x\n",
204 Bucket->Request, Status));
205 Complete( Bucket->Request.RequestContext, Status, 0 );
206 exFreePool( Bucket );
207 }
208 }
209 }
210 if( Connection->SignalState & SEL_WRITE ) {
211 TI_DbgPrint(DEBUG_TCP,("Writeable: irp list %s\n",
212 IsListEmpty(&Connection->SendRequest) ?
213 "empty" : "nonempty"));
214
215 while( (Entry = ExInterlockedRemoveHeadList( &Connection->SendRequest,
216 &Connection->Lock )) != NULL ) {
217 OSK_UINT SendLen = 0, Sent = 0;
218 PVOID SendBuffer = 0;
219
220 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
221 Complete = Bucket->Request.RequestNotifyObject;
222
223 Irp = Bucket->Request.RequestContext;
224 Mdl = Irp->MdlAddress;
225
226 TI_DbgPrint(DEBUG_TCP,
227 ("Getting the user buffer from %x\n", Mdl));
228
229 NdisQueryBuffer( Mdl, &SendBuffer, &SendLen );
230
231 TI_DbgPrint(DEBUG_TCP,
232 ("Writing %d bytes to %x\n", SendLen, SendBuffer));
233
234 TI_DbgPrint(DEBUG_TCP, ("Connection: %x\n", Connection));
235 TI_DbgPrint
236 (DEBUG_TCP,
237 ("Connection->SocketContext: %x\n",
238 Connection->SocketContext));
239
240 Status = TCPTranslateError
241 ( OskitTCPSend( Connection->SocketContext,
242 SendBuffer,
243 SendLen,
244 &Sent,
245 0 ) );
246
247 TI_DbgPrint(DEBUG_TCP,("TCP Bytes: %d\n", Sent));
248
249 if( Status == STATUS_SUCCESS ) {
250 TI_DbgPrint(DEBUG_TCP,("Sent %d bytes with status %x\n",
251 Sent, Status));
252
253 Complete( Bucket->Request.RequestContext,
254 STATUS_SUCCESS, Sent );
255 exFreePool( Bucket );
256 } else if( Status == STATUS_PENDING ) {
257 ExInterlockedInsertHeadList
258 ( &Connection->SendRequest, &Bucket->Entry, &Connection->Lock );
259 break;
260 } else {
261 TI_DbgPrint(DEBUG_TCP,
262 ("Completing Send request: %x %x\n",
263 Bucket->Request, Status));
264 Complete( Bucket->Request.RequestContext, Status, 0 );
265 exFreePool( Bucket );
266 }
267 }
268 }
269
270 Connection->SignalState = 0;
271 Connection->Signalled = FALSE;
272 }
273
274 VOID DrainSignals() {
275 PCONNECTION_ENDPOINT Connection;
276 PLIST_ENTRY ListEntry;
277
278 while( (ListEntry = ExInterlockedRemoveHeadList(&SignalledConnectionsList,
279 &SignalledConnectionsLock)) != NULL) {
280 Connection = CONTAINING_RECORD( ListEntry, CONNECTION_ENDPOINT,
281 SignalList );
282 HandleSignalledConnection( Connection );
283 }
284 }
285
286 PCONNECTION_ENDPOINT TCPAllocateConnectionEndpoint( PVOID ClientContext ) {
287 PCONNECTION_ENDPOINT Connection =
288 exAllocatePool(NonPagedPool, sizeof(CONNECTION_ENDPOINT));
289 if (!Connection)
290 return Connection;
291
292 TI_DbgPrint(DEBUG_CPOINT, ("Connection point file object allocated at (0x%X).\n", Connection));
293
294 RtlZeroMemory(Connection, sizeof(CONNECTION_ENDPOINT));
295
296 /* Initialize spin lock that protects the connection endpoint file object */
297 TcpipInitializeSpinLock(&Connection->Lock);
298 InitializeListHead(&Connection->ConnectRequest);
299 InitializeListHead(&Connection->ListenRequest);
300 InitializeListHead(&Connection->ReceiveRequest);
301 InitializeListHead(&Connection->SendRequest);
302
303 /* Save client context pointer */
304 Connection->ClientContext = ClientContext;
305
306 return Connection;
307 }
308
309 VOID TCPFreeConnectionEndpoint( PCONNECTION_ENDPOINT Connection ) {
310 TI_DbgPrint(DEBUG_TCP, ("Freeing TCP Endpoint\n"));
311 exFreePool( Connection );
312 }
313
314 NTSTATUS TCPSocket( PCONNECTION_ENDPOINT Connection,
315 UINT Family, UINT Type, UINT Proto ) {
316 NTSTATUS Status;
317
318 ASSERT_LOCKED(&TCPLock);
319
320 TI_DbgPrint(DEBUG_TCP,("Called: Connection %x, Family %d, Type %d, "
321 "Proto %d\n",
322 Connection, Family, Type, Proto));
323
324 Status = TCPTranslateError( OskitTCPSocket( Connection,
325 &Connection->SocketContext,
326 Family,
327 Type,
328 Proto ) );
329
330 ASSERT_KM_POINTER(Connection->SocketContext);
331
332 TI_DbgPrint(DEBUG_TCP,("Connection->SocketContext %x\n",
333 Connection->SocketContext));
334
335 return Status;
336 }
337
338 VOID TCPReceive(PIP_INTERFACE Interface, PIP_PACKET IPPacket)
339 /*
340 * FUNCTION: Receives and queues TCP data
341 * ARGUMENTS:
342 * IPPacket = Pointer to an IP packet that was received
343 * NOTES:
344 * This is the low level interface for receiving TCP data
345 */
346 {
347 TI_DbgPrint(DEBUG_TCP,("Sending packet %d (%d) to oskit\n",
348 IPPacket->TotalSize,
349 IPPacket->HeaderSize));
350
351 TcpipRecursiveMutexEnter( &TCPLock, TRUE );
352
353 OskitTCPReceiveDatagram( IPPacket->Header,
354 IPPacket->TotalSize,
355 IPPacket->HeaderSize );
356
357 DrainSignals();
358
359 TcpipRecursiveMutexLeave( &TCPLock );
360 }
361
362 /* event.c */
363 int TCPSocketState( void *ClientData,
364 void *WhichSocket,
365 void *WhichConnection,
366 OSK_UINT NewState );
367
368 int TCPPacketSend( void *ClientData,
369 OSK_PCHAR Data,
370 OSK_UINT Len );
371
372 POSK_IFADDR TCPFindInterface( void *ClientData,
373 OSK_UINT AddrType,
374 OSK_UINT FindType,
375 OSK_SOCKADDR *ReqAddr );
376
377 NTSTATUS TCPMemStartup( void );
378 void *TCPMalloc( void *ClientData,
379 OSK_UINT bytes, OSK_PCHAR file, OSK_UINT line );
380 void TCPFree( void *ClientData,
381 void *data, OSK_PCHAR file, OSK_UINT line );
382 void TCPMemShutdown( void );
383
384 int TCPSleep( void *ClientData, void *token, int priority, char *msg,
385 int tmio );
386
387 void TCPWakeup( void *ClientData, void *token );
388
389 OSKITTCP_EVENT_HANDLERS EventHandlers = {
390 NULL, /* Client Data */
391 TCPSocketState, /* SocketState */
392 TCPPacketSend, /* PacketSend */
393 TCPFindInterface, /* FindInterface */
394 TCPMalloc, /* Malloc */
395 TCPFree, /* Free */
396 TCPSleep, /* Sleep */
397 TCPWakeup /* Wakeup */
398 };
399
400 static KEVENT TimerLoopEvent;
401 static HANDLE TimerThreadHandle;
402
403 /*
404 * We are running 2 timers here, one with a 200ms interval (fast) and the other
405 * with a 500ms interval (slow). So we need to time out at 200, 400, 500, 600,
406 * 800, 1000 and process the "fast" events at 200, 400, 600, 800, 1000 and the
407 * "slow" events at 500 and 1000.
408 */
409 static VOID NTAPI
410 TimerThread(PVOID Context)
411 {
412 LARGE_INTEGER Timeout;
413 NTSTATUS Status;
414 unsigned Current, NextFast, NextSlow, Next;
415
416 Current = 0;
417 Next = 0;
418 NextFast = 0;
419 NextSlow = 0;
420 while ( 1 ) {
421 if (Next == NextFast) {
422 NextFast += 2;
423 }
424 if (Next == NextSlow) {
425 NextSlow += 5;
426 }
427 Next = min(NextFast, NextSlow);
428 Timeout.QuadPart = (LONGLONG) (Next - Current) * -1000000; /* 100 ms */
429 Status = KeWaitForSingleObject(&TimerLoopEvent, Executive, KernelMode,
430 FALSE, &Timeout);
431 if (Status != STATUS_TIMEOUT) {
432 PsTerminateSystemThread(Status);
433 }
434
435 TcpipRecursiveMutexEnter( &TCPLock, TRUE );
436 TimerOskitTCP( Next == NextFast, Next == NextSlow );
437 if (Next == NextSlow) {
438 DrainSignals();
439 }
440 TcpipRecursiveMutexLeave( &TCPLock );
441
442 Current = Next;
443 if (10 <= Current) {
444 Current = 0;
445 Next = 0;
446 NextFast = 0;
447 NextSlow = 0;
448 }
449 }
450 }
451
452 static VOID
453 StartTimer(VOID)
454 {
455 KeInitializeEvent(&TimerLoopEvent, NotificationEvent, FALSE);
456 PsCreateSystemThread(&TimerThreadHandle, THREAD_ALL_ACCESS, 0, 0, 0,
457 TimerThread, NULL);
458 }
459
460
461 NTSTATUS TCPStartup(VOID)
462 /*
463 * FUNCTION: Initializes the TCP subsystem
464 * RETURNS:
465 * Status of operation
466 */
467 {
468 NTSTATUS Status;
469
470 TcpipRecursiveMutexInit( &TCPLock );
471 ExInitializeFastMutex( &SleepingThreadsLock );
472 KeInitializeSpinLock( &SignalledConnectionsLock );
473 InitializeListHead( &SleepingThreadsList );
474 InitializeListHead( &SignalledConnectionsList );
475 Status = TCPMemStartup();
476 if ( ! NT_SUCCESS(Status) ) {
477 return Status;
478 }
479
480 Status = PortsStartup( &TCPPorts, 1, 0xfffe );
481 if( !NT_SUCCESS(Status) ) {
482 TCPMemShutdown();
483 return Status;
484 }
485
486 TcpipRecursiveMutexEnter(&TCPLock, TRUE);
487 RegisterOskitTCPEventHandlers( &EventHandlers );
488 InitOskitTCP();
489 TcpipRecursiveMutexLeave(&TCPLock);
490
491 /* Register this protocol with IP layer */
492 IPRegisterProtocol(IPPROTO_TCP, TCPReceive);
493
494 ExInitializeNPagedLookasideList(
495 &TCPSegmentList, /* Lookaside list */
496 NULL, /* Allocate routine */
497 NULL, /* Free routine */
498 0, /* Flags */
499 sizeof(TCP_SEGMENT), /* Size of each entry */
500 'SPCT', /* Tag */
501 0); /* Depth */
502
503 StartTimer();
504
505 TCPInitialized = TRUE;
506
507 return STATUS_SUCCESS;
508 }
509
510
511 NTSTATUS TCPShutdown(VOID)
512 /*
513 * FUNCTION: Shuts down the TCP subsystem
514 * RETURNS:
515 * Status of operation
516 */
517 {
518 LARGE_INTEGER WaitForThread;
519
520 if (!TCPInitialized)
521 return STATUS_SUCCESS;
522
523 WaitForThread.QuadPart = -2500000; /* 250 ms */
524 KeSetEvent(&TimerLoopEvent, IO_NO_INCREMENT, FALSE);
525 ZwWaitForSingleObject(TimerThreadHandle, FALSE, &WaitForThread);
526
527 /* Deregister this protocol with IP layer */
528 IPRegisterProtocol(IPPROTO_TCP, NULL);
529
530 ExDeleteNPagedLookasideList(&TCPSegmentList);
531
532 TCPInitialized = FALSE;
533
534 DeinitOskitTCP();
535
536 PortsShutdown( &TCPPorts );
537
538 TCPMemShutdown();
539
540 return STATUS_SUCCESS;
541 }
542
543 NTSTATUS TCPTranslateError( int OskitError ) {
544 NTSTATUS Status;
545
546 switch( OskitError ) {
547 case 0: Status = STATUS_SUCCESS; break;
548 case OSK_EADDRNOTAVAIL: Status = STATUS_INVALID_ADDRESS; break;
549 case OSK_EAFNOSUPPORT: Status = STATUS_INVALID_CONNECTION; break;
550 case OSK_ECONNREFUSED:
551 case OSK_ECONNRESET: Status = STATUS_REMOTE_NOT_LISTENING; break;
552 case OSK_EWOULDBLOCK:
553 case OSK_EINPROGRESS: Status = STATUS_PENDING; break;
554 case OSK_EINVAL: Status = STATUS_INVALID_PARAMETER; break;
555 case OSK_ENOMEM:
556 case OSK_ENOBUFS: Status = STATUS_INSUFFICIENT_RESOURCES; break;
557 case OSK_ESHUTDOWN: Status = STATUS_FILE_CLOSED; break;
558 case OSK_EMSGSIZE: Status = STATUS_BUFFER_TOO_SMALL; break;
559 case OSK_ETIMEDOUT: Status = STATUS_TIMEOUT; break;
560 case OSK_ENETUNREACH: Status = STATUS_NETWORK_UNREACHABLE; break;
561 case OSK_EFAULT: Status = STATUS_ACCESS_VIOLATION; break;
562 default:
563 DbgPrint("OskitTCP returned unhandled error code: %d\n", OskitError);
564 Status = STATUS_INVALID_CONNECTION;
565 break;
566 }
567
568 TI_DbgPrint(DEBUG_TCP,("Error %d -> %x\n", OskitError, Status));
569 return Status;
570 }
571
572 NTSTATUS TCPConnect
573 ( PCONNECTION_ENDPOINT Connection,
574 PTDI_CONNECTION_INFORMATION ConnInfo,
575 PTDI_CONNECTION_INFORMATION ReturnInfo,
576 PTCP_COMPLETION_ROUTINE Complete,
577 PVOID Context ) {
578 NTSTATUS Status;
579 SOCKADDR_IN AddressToConnect = { 0 }, AddressToBind = { 0 };
580 IP_ADDRESS RemoteAddress;
581 USHORT RemotePort;
582 PTDI_BUCKET Bucket;
583 PNEIGHBOR_CACHE_ENTRY NCE;
584
585 TI_DbgPrint(DEBUG_TCP,("TCPConnect: Called\n"));
586
587 ASSERT_LOCKED(&TCPLock);
588
589 Status = AddrBuildAddress
590 ((PTRANSPORT_ADDRESS)ConnInfo->RemoteAddress,
591 &RemoteAddress,
592 &RemotePort);
593
594 if (!NT_SUCCESS(Status)) {
595 TI_DbgPrint(DEBUG_TCP, ("Could not AddrBuildAddress in TCPConnect\n"));
596 return Status;
597 }
598
599 if (!(NCE = RouteGetRouteToDestination(&RemoteAddress)))
600 {
601 return STATUS_NETWORK_UNREACHABLE;
602 }
603
604 if (Connection->State & SEL_FIN)
605 {
606 return STATUS_REMOTE_DISCONNECT;
607 }
608
609 /* Freed in TCPSocketState */
610 TI_DbgPrint(DEBUG_TCP,
611 ("Connecting to address %x:%x\n",
612 RemoteAddress.Address.IPv4Address,
613 RemotePort));
614
615 AddressToConnect.sin_family = AF_INET;
616 AddressToBind = AddressToConnect;
617 AddressToBind.sin_addr.s_addr = NCE->Interface->Unicast.Address.IPv4Address;
618
619 Status = TCPTranslateError
620 ( OskitTCPBind( Connection->SocketContext,
621 &AddressToBind,
622 sizeof(AddressToBind) ) );
623
624 if (NT_SUCCESS(Status)) {
625 memcpy( &AddressToConnect.sin_addr,
626 &RemoteAddress.Address.IPv4Address,
627 sizeof(AddressToConnect.sin_addr) );
628 AddressToConnect.sin_port = RemotePort;
629
630 Status = TCPTranslateError
631 ( OskitTCPConnect( Connection->SocketContext,
632 Connection,
633 &AddressToConnect,
634 sizeof(AddressToConnect) ) );
635
636 if (Status == STATUS_PENDING)
637 {
638 Bucket = exAllocatePool( NonPagedPool, sizeof(*Bucket) );
639 if( !Bucket ) return STATUS_NO_MEMORY;
640
641 Bucket->Request.RequestNotifyObject = (PVOID)Complete;
642 Bucket->Request.RequestContext = Context;
643
644 IoMarkIrpPending((PIRP)Context);
645
646 ExInterlockedInsertTailList( &Connection->ConnectRequest, &Bucket->Entry, &Connection->Lock );
647 }
648 }
649
650 return Status;
651 }
652
653 NTSTATUS TCPDisconnect
654 ( PCONNECTION_ENDPOINT Connection,
655 UINT Flags,
656 PTDI_CONNECTION_INFORMATION ConnInfo,
657 PTDI_CONNECTION_INFORMATION ReturnInfo,
658 PTCP_COMPLETION_ROUTINE Complete,
659 PVOID Context ) {
660 NTSTATUS Status = STATUS_INVALID_PARAMETER;
661
662 ASSERT_LOCKED(&TCPLock);
663
664 TI_DbgPrint(DEBUG_TCP,("started\n"));
665
666 if (Flags & TDI_DISCONNECT_RELEASE)
667 Status = TCPTranslateError(OskitTCPDisconnect(Connection->SocketContext));
668
669 if ((Flags & TDI_DISCONNECT_ABORT) || !Flags)
670 Status = TCPTranslateError(OskitTCPShutdown(Connection->SocketContext, FWRITE | FREAD));
671
672 TI_DbgPrint(DEBUG_TCP,("finished %x\n", Status));
673
674 return Status;
675 }
676
677 NTSTATUS TCPClose
678 ( PCONNECTION_ENDPOINT Connection ) {
679 NTSTATUS Status;
680
681 TI_DbgPrint(DEBUG_TCP,("TCPClose started\n"));
682
683 ASSERT_LOCKED(&TCPLock);
684
685 /* Make our code remove all pending IRPs */
686 Connection->State |= SEL_FIN;
687 DrainSignals();
688
689 Status = TCPTranslateError( OskitTCPClose( Connection->SocketContext ) );
690 if (Status == STATUS_SUCCESS)
691 Connection->SocketContext = NULL;
692
693 TI_DbgPrint(DEBUG_TCP,("TCPClose finished %x\n", Status));
694
695 return Status;
696 }
697
698 NTSTATUS TCPReceiveData
699 ( PCONNECTION_ENDPOINT Connection,
700 PNDIS_BUFFER Buffer,
701 ULONG ReceiveLength,
702 PULONG BytesReceived,
703 ULONG ReceiveFlags,
704 PTCP_COMPLETION_ROUTINE Complete,
705 PVOID Context ) {
706 PVOID DataBuffer;
707 UINT DataLen, Received = 0;
708 NTSTATUS Status;
709 PTDI_BUCKET Bucket;
710
711 TI_DbgPrint(DEBUG_TCP,("Called for %d bytes (on socket %x)\n",
712 ReceiveLength, Connection->SocketContext));
713
714 ASSERT_LOCKED(&TCPLock);
715
716 ASSERT_KM_POINTER(Connection->SocketContext);
717
718 /* Closing */
719 if (Connection->State & SEL_FIN)
720 {
721 *BytesReceived = 0;
722 return STATUS_REMOTE_DISCONNECT;
723 }
724
725 NdisQueryBuffer( Buffer, &DataBuffer, &DataLen );
726
727 TI_DbgPrint(DEBUG_TCP,("TCP>|< Got an MDL %x (%x:%d)\n", Buffer, DataBuffer, DataLen));
728
729 Status = TCPTranslateError
730 ( OskitTCPRecv
731 ( Connection->SocketContext,
732 DataBuffer,
733 DataLen,
734 &Received,
735 ReceiveFlags ) );
736
737 TI_DbgPrint(DEBUG_TCP,("OskitTCPReceive: %x, %d\n", Status, Received));
738
739 /* Keep this request around ... there was no data yet */
740 if( Status == STATUS_PENDING ) {
741 /* Freed in TCPSocketState */
742 Bucket = exAllocatePool( NonPagedPool, sizeof(*Bucket) );
743 if( !Bucket ) {
744 TI_DbgPrint(DEBUG_TCP,("Failed to allocate bucket\n"));
745 return STATUS_NO_MEMORY;
746 }
747
748 Bucket->Request.RequestNotifyObject = Complete;
749 Bucket->Request.RequestContext = Context;
750 *BytesReceived = 0;
751
752 IoMarkIrpPending((PIRP)Context);
753
754 ExInterlockedInsertTailList( &Connection->ReceiveRequest, &Bucket->Entry, &Connection->Lock );
755 TI_DbgPrint(DEBUG_TCP,("Queued read irp\n"));
756 } else {
757 TI_DbgPrint(DEBUG_TCP,("Got status %x, bytes %d\n", Status, Received));
758 *BytesReceived = Received;
759 }
760
761 TI_DbgPrint(DEBUG_TCP,("Status %x\n", Status));
762
763 return Status;
764 }
765
766 NTSTATUS TCPSendData
767 ( PCONNECTION_ENDPOINT Connection,
768 PCHAR BufferData,
769 ULONG SendLength,
770 PULONG BytesSent,
771 ULONG Flags,
772 PTCP_COMPLETION_ROUTINE Complete,
773 PVOID Context ) {
774 UINT Sent = 0;
775 NTSTATUS Status;
776 PTDI_BUCKET Bucket;
777
778 ASSERT_LOCKED(&TCPLock);
779
780 TI_DbgPrint(DEBUG_TCP,("Called for %d bytes (on socket %x)\n",
781 SendLength, Connection->SocketContext));
782
783 ASSERT_KM_POINTER(Connection->SocketContext);
784
785 TI_DbgPrint(DEBUG_TCP,("Connection = %x\n", Connection));
786 TI_DbgPrint(DEBUG_TCP,("Connection->SocketContext = %x\n",
787 Connection->SocketContext));
788
789 /* Closing */
790 if (Connection->State & SEL_FIN)
791 {
792 *BytesSent = 0;
793 return STATUS_REMOTE_DISCONNECT;
794 }
795
796 Status = TCPTranslateError
797 ( OskitTCPSend( Connection->SocketContext,
798 (OSK_PCHAR)BufferData, SendLength,
799 &Sent, 0 ) );
800
801 TI_DbgPrint(DEBUG_TCP,("OskitTCPSend: %x, %d\n", Status, Sent));
802
803 /* Keep this request around ... there was no data yet */
804 if( Status == STATUS_PENDING ) {
805 /* Freed in TCPSocketState */
806 Bucket = exAllocatePool( NonPagedPool, sizeof(*Bucket) );
807 if( !Bucket ) {
808 TI_DbgPrint(DEBUG_TCP,("Failed to allocate bucket\n"));
809 return STATUS_NO_MEMORY;
810 }
811
812 Bucket->Request.RequestNotifyObject = Complete;
813 Bucket->Request.RequestContext = Context;
814 *BytesSent = 0;
815
816 IoMarkIrpPending((PIRP)Context);
817
818 ExInterlockedInsertTailList( &Connection->SendRequest, &Bucket->Entry, &Connection->Lock );
819 TI_DbgPrint(DEBUG_TCP,("Queued write irp\n"));
820 } else {
821 TI_DbgPrint(DEBUG_TCP,("Got status %x, bytes %d\n", Status, Sent));
822 *BytesSent = Sent;
823 }
824
825 TI_DbgPrint(DEBUG_TCP,("Status %x\n", Status));
826
827 return Status;
828 }
829
830 VOID TCPTimeout(VOID) {
831 /* Now handled by TimerThread */
832 }
833
834 UINT TCPAllocatePort( UINT HintPort ) {
835 if( HintPort ) {
836 if( AllocatePort( &TCPPorts, HintPort ) ) return HintPort;
837 else {
838 TI_DbgPrint
839 (MID_TRACE,("We got a hint port but couldn't allocate it\n"));
840 return (UINT)-1;
841 }
842 } else return AllocatePortFromRange( &TCPPorts, 1024, 5000 );
843 }
844
845 VOID TCPFreePort( UINT Port ) {
846 DeallocatePort( &TCPPorts, Port );
847 }
848
849 NTSTATUS TCPGetSockAddress
850 ( PCONNECTION_ENDPOINT Connection,
851 PTRANSPORT_ADDRESS Address,
852 BOOLEAN GetRemote ) {
853 OSK_UINT LocalAddress, RemoteAddress;
854 OSK_UI16 LocalPort, RemotePort;
855 PTA_IP_ADDRESS AddressIP = (PTA_IP_ADDRESS)Address;
856 NTSTATUS Status;
857
858 ASSERT_LOCKED(&TCPLock);
859
860 Status = TCPTranslateError(OskitTCPGetAddress(Connection->SocketContext,
861 &LocalAddress, &LocalPort,
862 &RemoteAddress, &RemotePort));
863 if (!NT_SUCCESS(Status))
864 return Status;
865
866 AddressIP->TAAddressCount = 1;
867 AddressIP->Address[0].AddressLength = TDI_ADDRESS_LENGTH_IP;
868 AddressIP->Address[0].AddressType = TDI_ADDRESS_TYPE_IP;
869 AddressIP->Address[0].Address[0].sin_port = GetRemote ? RemotePort : LocalPort;
870 AddressIP->Address[0].Address[0].in_addr = GetRemote ? RemoteAddress : LocalAddress;
871
872 return Status;
873 }
874
875 VOID TCPRemoveIRP( PCONNECTION_ENDPOINT Endpoint, PIRP Irp ) {
876 PLIST_ENTRY Entry;
877 PLIST_ENTRY ListHead[4];
878 KIRQL OldIrql;
879 PTDI_BUCKET Bucket;
880 UINT i = 0;
881
882 ListHead[0] = &Endpoint->SendRequest;
883 ListHead[1] = &Endpoint->ReceiveRequest;
884 ListHead[2] = &Endpoint->ConnectRequest;
885 ListHead[3] = &Endpoint->ListenRequest;
886
887 TcpipAcquireSpinLock( &Endpoint->Lock, &OldIrql );
888
889 for( i = 0; i < 4; i++ )
890 {
891 for( Entry = ListHead[i]->Flink;
892 Entry != ListHead[i];
893 Entry = Entry->Flink )
894 {
895 Bucket = CONTAINING_RECORD( Entry, TDI_BUCKET, Entry );
896 if( Bucket->Request.RequestContext == Irp )
897 {
898 RemoveEntryList( &Bucket->Entry );
899 exFreePool( Bucket );
900 break;
901 }
902 }
903 }
904
905 TcpipReleaseSpinLock( &Endpoint->Lock, OldIrql );
906 }
907
908 /* EOF */