aboutsummaryrefslogtreecommitdiffstats
path: root/src/TcpLog.cpp
blob: 9fc73b77dd97920b7de6fd6f7433ac9f878497d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
   Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Her Majesty the Queen in
   Right of Canada (Communications Research Center Canada)
   */
/*
   This file is part of CRC-DabMux.

   CRC-DabMux is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as
   published by the Free Software Foundation, either version 3 of the
   License, or (at your option) any later version.

   CRC-DabMux is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with CRC-DabMux.  If not, see <http://www.gnu.org/licenses/>.
   */

#include "TcpLog.h"
#include "InetAddress.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>

#ifdef _WIN32
#   include <io.h>
#
#   define vsnprintf _vsnprintf
#   define MSG_NOSIGNAL 0
#   define socklen_t int
#else
#   include <sys/socket.h>
#   include <netinet/in.h>
#   include <arpa/inet.h>
#   include <unistd.h>
#endif

#include <sstream>


const int TcpLog::EMERG   = 0;      // system is unusable
const int TcpLog::ALERT   = 1;      // action must be taken immediately
const int TcpLog::CRIT    = 2;      // critical conditions
const int TcpLog::ERR     = 3;      // error conditions
const int TcpLog::WARNING = 4;      // warning conditions
const int TcpLog::NOTICE  = 5;      // normal but significant condition
const int TcpLog::INFO    = 6;      // informational
const int TcpLog::DBG     = 7;      // debug-level messages


TcpLog::TcpLog() : listenPort(0), client(-1), name(NULL), serverThread(0), running(false)
{
    buffer = (char*)malloc(512);
    bufferSize = 512;
    headers = (char**)malloc(sizeof(char**));
    headers[0] = NULL;
}


TcpLog::~TcpLog()
{
    if (running) {
        running = false;
    }
    if (client != -1) {
        ::close(client);
    }
    if (headers != NULL) {
        for (int count = 0; headers[count] != NULL; ++count) {
            free(headers[count]);
        }
        free(headers);
    }
}


//TcpLog::TcpLog(int port);


void TcpLog::open(const char *ident, const int option, const int port)
{
    listenPort = port;

    if (name != NULL) {
        free(name);
    }
    name = strdup(ident);

    if (running) {
        running = false;
#ifdef WIN32
        DWORD status;
        for (int i = 0; i < 5; ++i) {
            if (GetExitCodeThread(serverThread, &status)) {
                break;
            }
            Sleep(100);
        }
        TerminateThread(serverThread, 1);
#else
        pthread_join(serverThread, NULL);
#endif
    }
    running = true;
#ifdef _WIN32
    serverThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)listen, this, 0, NULL);
    if (serverThread == NULL) {
        fprintf(stderr, "Can't create TCP listen thread\n");
    }
#else
    pthread_create(&serverThread, NULL, (void*(*)(void*))listen, this);
#endif
}


void TcpLog::printHeader(const int priority, const char *format, ...)
{
    static char last = '\n';
    std::string beginning;
    std::string message;
    int ret;


    beginning = "<";
    beginning += '0' + (priority % 10);
    beginning += "> ";

    va_list argp;
    va_start(argp, format);
    for (ret = vsnprintf(buffer, bufferSize, format, argp);
            ret >= bufferSize || ret == -1;
            ret = vsprintf(buffer, format, argp)) {
        if (ret == -1) {
            buffer = (char*)realloc(buffer, bufferSize * 2);
            bufferSize *= 2;
        } else {
            buffer = (char*)realloc(buffer, ret + 1);
            bufferSize = ret + 1;
        }
    }
    va_end(argp);

    if (last == '\n') {
        message += beginning;
    }
    message += buffer;

    last = buffer[ret - 1];

    for (unsigned long pos = message.find('\n');
            pos != std::string::npos && ++pos != message.size();
            pos = message.find('\n', pos)) {
        message.insert(pos, beginning);
    }

    fprintf(stderr, "%s", message.c_str());
    if (client != -1) {
        if (write(client, message.c_str(), message.size())
                != (int)message.size()) {
            fprintf(stderr, "<6> Client closed\n");
            ::close(client);
            client = -1;
        }
    }

    int count = 0;
    while (headers[count++] != NULL) {
    }
    headers = (char**)realloc(headers, sizeof(char**) * (count + 1));
    headers[count - 1] = strdup(message.c_str());
    headers[count] = NULL;
}


void TcpLog::print(const int priority, const char *format, ...)
{
    static char last = '\n';
    std::string beginning;
    std::string message;
    int ret;


    beginning = "<";
    beginning += '0' + (priority % 10);
    beginning += "> ";

    va_list argp;
    va_start(argp, format);
    for (ret = vsnprintf(buffer, bufferSize, format, argp);
            ret >= bufferSize || ret == -1;
            ret = vsprintf(buffer, format, argp)) {
        if (ret == -1) {
            buffer = (char*)realloc(buffer, bufferSize * 2);
            bufferSize *= 2;
        } else {
            buffer = (char*)realloc(buffer, ret + 1);
            bufferSize = ret + 1;
        }
    }
    va_end(argp);

    if (last == '\n') {
        message += beginning;
    }
    message += buffer;

    last = buffer[ret - 1];

    for (unsigned long pos = message.find('\n');
            pos != std::string::npos && ++pos != message.size();
            pos = message.find('\n', pos)) {
        message.insert(pos, beginning);
    }

    fprintf(stderr, "%s", message.c_str());
    if (client != -1) {
        if (send(client, message.c_str(), message.size(), MSG_NOSIGNAL)
                != (int)message.size()) {
            fprintf(stderr, "<6> Client closed\n");
            ::close(client);
            client = -1;
        }
    }
}


void TcpLog::close(void)
{
}


void* TcpLog::listen(TcpLog* obj)
{
    int server;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    socklen_t addrlen = sizeof(client_addr);

#ifdef _WIN32
    WSADATA wsaData;
    WORD wVersionRequested = wVersionRequested = MAKEWORD( 2, 2 );

    int res = WSAStartup( wVersionRequested, &wsaData );
    if (res) {
        fprintf(stderr, "Can't initialize winsock\n");
        ExitThread(1);
    }
#endif
    server = socket(PF_INET, SOCK_STREAM, 0);
    if (server == INVALID_SOCKET) {
#ifdef _WIN32
        fprintf(stderr, "Can't create socket\n");
        ExitThread(1);
#else
        perror("Can't create socket");
        pthread_exit(NULL);
#endif
    }

    int reuse = 1;
    if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse))
            == -1) {
        perror("Can't set socket reusable");
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(obj->listenPort);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(server, (struct sockaddr*)&server_addr, sizeof(server_addr))
            == -1) {
        perror("Can't bind socket");
        fprintf(stderr, " port: %i\n", obj->listenPort);
#ifdef _WIN32
        ExitThread(1);
#else
        pthread_exit(NULL);
#endif
    }

    if (::listen(server, 1) == -1) {
        perror("Can't listen on socket");
#ifdef _WIN32
        ExitThread(1);
#else
        pthread_exit(NULL);
#endif
    }

    while (obj->running) {
        int client = accept(server, (struct sockaddr*)&client_addr, &addrlen);
        if (client == INVALID_SOCKET) {
#ifdef _WIN32
            if (WSAGetLastError() != WSAEINTR) {
                setInetError("Can't accept client");
                fprintf(stderr, "%s: %s\n", inetErrDesc, inetErrMsg);
                ExitThread(1);
            }
#else
            perror("Can't accept client");
            pthread_exit(NULL);
#endif
        }
        obj->print(INFO, "%s:%d connected\n",
                inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
        if (obj->client != -1) {
            ::close(obj->client);
        }
        obj->client = client;
        for (int i = 0; obj->headers[i] != NULL; ++i) {
            send(client, obj->headers[i], strlen(obj->headers[i]), MSG_NOSIGNAL);
        }
    }
    if (obj->client != -1) {
        ::close(obj->client);
        obj->client = -1;
    }
    ::close(server);

#ifdef _WIN32
    ExitThread(1);
#else
    pthread_exit(NULL);
#endif
    return NULL;
}