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