- Don't call winsock initialiser for each seperate server thread
[reactos.git] / reactos / apps / utils / net / tcpsvcs / chargen.c
1 #include <stdio.h>
2 #include <winsock2.h>
3 #include <tchar.h>
4 #include "tcpsvcs.h"
5
6 DWORD WINAPI ChargenHandler(VOID* Sock_)
7 {
8 DWORD Retval = 0;
9 SOCKET Sock = (SOCKET)Sock_;
10
11 if (!GenerateChars(Sock))
12 {
13 _tprintf(_T("Char generation failed\n"));
14 Retval = 3;
15 }
16
17 _tprintf(_T("Shutting connection down...\n"));
18 if (ShutdownConnection(Sock, FALSE))
19 _tprintf(_T("Connection is down.\n"));
20 else
21 {
22 _tprintf(_T("Connection shutdown failed\n"));
23 Retval = 3;
24 }
25 _tprintf(_T("Terminating chargen thread\n"));
26 ExitThread(0);
27
28 return Retval;
29 }
30
31
32 BOOL GenerateChars(SOCKET Sock)
33 {
34 int i;
35 int charIndex; /* internal loop */
36 int loopIndex; /* line loop */
37 char ring[END-START];
38 char *endring;
39 char Line[LINESIZ];
40
41 /* fill ring with printable characters */
42 for (charIndex=0, i=START; i<=END; charIndex++, i++)
43 ring[charIndex] = i;
44 /* establish the end character in the ring */
45 endring = &ring[charIndex];
46
47 /* where we will start output from */
48 loopIndex = 0;
49 while (1)
50 {
51 /* if the loop index is equal to the last char,
52 * start the loop again from the beginning */
53 if (loopIndex == END-START)
54 loopIndex = 0;
55
56 /* start printing from char controled by loopIndex */
57 charIndex = loopIndex;
58 for (i=0; i < LINESIZ - 2; i++)
59 {
60 Line[i] = ring[charIndex];
61
62 if (ring[charIndex] == *endring)
63 charIndex = 0;
64 else
65 charIndex++;
66 }
67
68 Line[LINESIZ - 2] = L'\r';
69 Line[LINESIZ - 1] = L'\n';
70
71 if (!SendLine(Sock, Line))
72 break;
73
74 /* increment loop index to start printing from next char in ring */
75 loopIndex++;
76 }
77
78 return TRUE;
79 }
80
81 BOOL SendLine(SOCKET Sock, TCHAR* Line)
82 {
83 INT RetVal;
84 INT SentBytes;
85 INT LineSize;
86
87 LineSize = sizeof(TCHAR) * LINESIZ;
88
89 SentBytes = 0;
90 RetVal = send(Sock, Line, LineSize, 0);
91 /*FIXME: need to establish if peer closes connection,
92 not just report a socket error */
93 if (RetVal > 0)
94 {
95 if (RetVal != LineSize)
96 {
97 _tprintf(("Not sent enough\n"));
98 return FALSE;
99 }
100 SentBytes += RetVal;
101 return TRUE;
102 }
103 else if (RetVal == SOCKET_ERROR)
104 {
105 _tprintf(("Socket error\n"));
106 return FALSE;
107 }
108 else
109 _tprintf(("unknown error\n"));
110 //WSAGetLastError()
111
112 _tprintf(("Connection closed by peer.\n"));
113 return TRUE;
114 }