Improve stopping control of the service
[reactos.git] / reactos / services / tcpsvcs / qotd.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/qotd.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 <stdio.h>
16 #include <winsock2.h>
17 #include <tchar.h>
18 #include <time.h>
19 #include "tcpsvcs.h"
20
21 #define QBUFSIZ 160
22
23 LPCTSTR FilePath = _T("\\drivers\\etc\\quotes");
24
25 DWORD WINAPI QotdHandler(VOID* Sock_)
26 {
27 FILE *fp;
28 SOCKET Sock;
29 TCHAR Sys[MAX_PATH];
30 TCHAR Quote[60][BUFSIZ]; // need to set this dynamically
31 INT QuoteToPrint;
32 INT NumQuotes;
33
34 Sock = (SOCKET)Sock_;
35
36 if(! GetSystemDirectory(Sys, MAX_PATH))
37 {
38 LogEvent(_T("QOTD: Getting system path failed.\n"), 0, TRUE);
39 ExitThread(-1);
40 }
41
42 _tcscat(Sys, FilePath);
43
44 LogEvent(_T("QOTD: Opening quotes file\n"), 0, FALSE);
45 if ((fp = _tfopen(Sys, "r")) == NULL)
46 {
47 TCHAR buf[256];
48
49 _stprintf(buf, _T("QOTD: Error opening quote file : %s\n"), Sys);
50 LogEvent(buf, 0, TRUE);
51 LogEvent(_T("QOTD: Terminating thread\n"), 0, FALSE);
52 ExitThread(-1);
53 }
54
55 /* read all quotes in the file into an array */
56 NumQuotes = 0;
57 while (_fgetts(Quote[NumQuotes], QBUFSIZ, fp) != NULL)
58 NumQuotes++;
59
60 LogEvent(_T("QOTD: Closing quotes file\n"), 0, FALSE);
61 fclose(fp);
62
63 /* randomise the quote */
64 srand((unsigned int) time(0));
65 QuoteToPrint = rand() % NumQuotes;
66
67 if (!SendQuote(Sock, Quote[QuoteToPrint]))
68 LogEvent(_T("QOTD: Error sending data\n"), 0, TRUE);
69
70
71 LogEvent(_T("QOTD: Shutting connection down...\n"), 0, FALSE);
72 if (ShutdownConnection(Sock, FALSE))
73 LogEvent(_T("QOTD: Connection is down\n"), 0, FALSE);
74 else
75 {
76 LogEvent(_T("QOTD: Connection shutdown failed\n"), 0, FALSE);
77 LogEvent(_T("QOTD: Terminating thread\n"), 0, FALSE);
78 ExitThread(-1);
79 }
80
81 LogEvent(_T("QOTD: Terminating thread\n"), 0, FALSE);
82 ExitThread(0);
83
84 //return Retval;
85 }
86
87
88 BOOL SendQuote(SOCKET Sock, TCHAR* Quote)
89 {
90 INT StringSize;
91 INT RetVal;
92
93 StringSize = strlen(Quote);
94 RetVal = send(Sock, Quote, sizeof(TCHAR) * StringSize, 0);
95
96 if (RetVal == SOCKET_ERROR)
97 return FALSE;
98
99 LogEvent(_T("QOTD: Connection closed by peer\n"), 0, FALSE);
100 return TRUE;
101 }