- use InterlockedExchange for setting shutdown flag
[reactos.git] / reactos / services / tcpsvcs / echo.c
1 /*
2 * ReactOS Services
3 * Copyright (C) 2005 ReactOS Team
4 *
5 * LICENCE: GPL - See COPYING in the top level directory
6 * PROJECT: ReactOS simple TCP/IP services
7 * FILE: apps/utils/net/tcpsvcs/echo.c
8 * PURPOSE: Provide CharGen, Daytime, Discard, Echo, and Qotd services
9 * PROGRAMMERS: Ged Murphy (gedmurphy@gmail.com)
10 * REVISIONS:
11 * GM 04/10/05 Created
12 *
13 */
14
15 #include "tcpsvcs.h"
16
17 extern BOOL bShutDown;
18
19 DWORD WINAPI EchoHandler(VOID* Sock_)
20 {
21 DWORD RetVal = 0;
22 SOCKET Sock = (SOCKET)Sock_;
23
24 if (!EchoIncomingPackets(Sock)) {
25 LogEvent(_T("Echo: EchoIncomingPackets failed\n"), 0, FALSE);
26 RetVal = -1;
27 }
28
29 LogEvent(_T("Echo: Shutting connection down...\n"), 0, FALSE);
30
31 if (ShutdownConnection(Sock, TRUE))
32 LogEvent(_T("Echo: Connection is down\n"), 0, FALSE);
33 else
34 {
35 LogEvent(_T("Echo: Connection shutdown failed\n"), 0, FALSE);
36 RetVal = -1;
37 }
38
39 LogEvent(_T("Echo: Terminating thread\n"), 0, FALSE);
40 ExitThread(RetVal);
41 }
42
43
44
45 BOOL EchoIncomingPackets(SOCKET Sock)
46 {
47 TCHAR ReadBuffer[BUF];
48 TCHAR buf[256]; // temp for holding LogEvent text
49 INT Temp;
50 INT ReadBytes;
51 INT SentBytes;
52
53 do {
54 ReadBytes = recv(Sock, ReadBuffer, BUF, 0);
55 if (ReadBytes > 0)
56 {
57 _stprintf(buf, _T("Received %d bytes from client\n"), ReadBytes);
58 LogEvent(buf, 0, FALSE);
59
60 SentBytes = 0;
61 while (SentBytes < ReadBytes)
62 {
63 Temp = send(Sock, ReadBuffer + SentBytes,
64 ReadBytes - SentBytes, 0);
65 if (Temp > 0)
66 {
67 _stprintf(buf, _T("Sent %d bytes back to client\n"), Temp);
68 LogEvent(buf, 0, FALSE);
69 SentBytes += Temp;
70 }
71 else if (Temp == SOCKET_ERROR)
72 return FALSE;
73 else
74 {
75 /* Client closed connection before we could reply to
76 all the data it sent, so quit early. */
77 _stprintf(buf, _T("Peer unexpectedly dropped connection!\n"));
78 LogEvent(buf, 0, FALSE);
79 return FALSE;
80 }
81 }
82 }
83 else if (ReadBytes == SOCKET_ERROR)
84 return FALSE;
85
86 } while ((ReadBytes != 0) && (! bShutDown));
87
88 if (! bShutDown)
89 LogEvent(_T("Echo: Connection closed by peer.\n"), 0, FALSE);
90
91 if (bShutDown)
92 LogEvent(_T("Echo: thread recieved shutdown signal\n"), 0, FALSE);
93
94 return TRUE;
95 }