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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#include "gate/gatemain.h"

#include "gate/console.hpp"
#include "gate/applications.hpp"
#include "gate/files.hpp"
#include "gate/net/sockets.hpp"
#include "gate/net/nameresolvers.hpp"
#include "gate/utilities.hpp"
#include "gate/exceptions.hpp"

#if defined(GATE_COMPILER_MSVC) && defined(GATE_LEAK_DETECTION) && defined(GATE_SYS_WIN) && !defined(GATE_SYS_WINCE) && (GATE_ARCH != GATE_ARCH_ARM32) && (GATE_ARCH != GATE_ARCH_ARM64)
#	include <vld.h>
#endif

namespace gate
{
    namespace apps
    {

        using namespace gate::net;

        static Socket::Endpoint parse_host(String const& host, int32_t port, bool ipv6)
        {
            Array<net::Socket::Endpoint> eps = net::NameResolver::resolveHost(
                host, ipv6 ? net::Socket::Family_Inet6 : net::Socket::Family_Inet4);
            if (eps.empty())
            {
                raiseException(results::NotAvailable, "Failed to resolve hostname");
            }

            Socket::Endpoint ep = eps[0];
            if (ipv6)
            {
                ep.ip6.port = (uint16_t)port;
            }
            else
            {
                ep.ip4.port = (uint16_t)port;
            }
            return ep;
        }


        static void run_connect(String const& host, int32_t const& port, bool ipv6 = false)
        {
            Socket::Endpoint ep = parse_host(host, port, ipv6);
            Socket s(ep.getFamily(), Socket::MsgType_Stream, Socket::Protocol_Tcp);
            VoidResult result = s.tryConnect(ep);
            if (result.hasError())
            {
                Console << "Failed to establish connection to: " << host << " on port " << port << strings::NewLine;
            }
            else
            {
                Console << "Connection established to: " << host << " on port " << port << strings::NewLine;
            }
        }

        static size_t refill_socket_group(Socket* sockEntries, TimeCounter* timeoutEntries, uint8_t* flagsEntries, uint16_t* portEntries, size_t count,
            TimeCounter const& nextTimeout, uint8_t nextFlags,
            Socket::Endpoint& endpoint, ArrayList<uint16_t>& portsPool)
        {
            for (size_t n = 0; (n != count) && !portsPool.empty(); ++n)
            {
                Socket& sock = sockEntries[n];
                if (!sock.valid())
                {
                    TimeCounter& timeout = timeoutEntries[n];
                    uint16_t& port = portEntries[n];

                    uint16_t nextPort = portsPool[0];
                    if (endpoint.family == GATE_SOCKET_FAMILY_INET6)
                    {
                        endpoint.ip6.port = nextPort;
                        Socket newsock(Socket::SocketType_Tcp6);
                        newsock.setOption(Socket::Option_Blocking, 0);
                        newsock.connect(endpoint);
                        sock.swap(newsock);
                    }
                    else
                    {
                        endpoint.ip4.port = nextPort;
                        Socket newsock(Socket::SocketType_Tcp4);
                        newsock.setOption(Socket::Option_Blocking, 0);
                        newsock.connect(endpoint);
                        newsock.setOption(Socket::Option_Blocking, 1);
                        sock.swap(newsock);
                    }
                    timeout = nextTimeout;
                    port = nextPort;
                    portsPool.removeAt(0);
                }
            }
            // move empty sockets to back

            size_t ret = 0;
            for (size_t n = 0; n != count; ++n)
            {
                Socket& sock = sockEntries[n];
                TimeCounter& timeout = timeoutEntries[n];
                uint16_t& port = portEntries[n];
                uint8_t& flags = flagsEntries[n];
                flags = nextFlags;
                if (sock.valid())
                {
                    if (n != ret)
                    {
                        sock.swap(sockEntries[ret]);
                        timeout.swap(timeoutEntries[ret]);
                        gate::swapRefsNoExcept(port, portEntries[ret]);
                    }
                    ++ret;
                }
            }
            return ret;
        }

        static void run_scan(String const& host, int32_t const& port, int32_t const& portscount,
            int32_t const& timeout_ms, bool ipv6 = false)
        {
            Stream& strm = Console;

            if (!port || !portscount)
            {
                raiseException(results::InvalidArg, "Missing port arguments", "scan");
            }

            ArrayList<uint16_t> portsPool;
            for (int32_t n = 0; n < portscount; ++n)
            {
                int32_t p = port + n;
                if ((p > 0) && (p < 65536))
                {
                    portsPool.add(static_cast<uint16_t>(p));
                }
            }

            Socket::Endpoint ep = parse_host(host, 0, ipv6);

            Socket sockets[60];
            uint16_t ports[60];
            uint8_t flags[60];
            TimeCounter timeouts[60];

            TimeCounter startTime = TimeCounter::now();
            for (size_t n = 0; n != sizeof(timeouts) / sizeof(timeouts[0]); ++n)
            {
                timeouts[n] = startTime;
            }

            while (!portsPool.empty())
            {
                TimeCounter nextTimeout = TimeCounter::now() + time::Milliseconds(timeout_ms);
                uint8_t nextStatusFlags = static_cast<uint8_t>(Socket::SelectStatus_Send | Socket::SelectStatus_Error);
                size_t socketCount = refill_socket_group(sockets, timeouts, flags, ports, 60,
                    nextTimeout, nextStatusFlags, ep, portsPool);

                Socket::select(sockets, socketCount, flags, 250);

                TimeCounter now = TimeCounter::now();

                for (size_t n = 0; n != socketCount; ++n)
                {
                    Socket& sock = sockets[n];
                    uint8_t& statusFlags = flags[n];
                    uint16_t& port = ports[n];
                    TimeCounter& timeout = timeouts[n];

                    if (statusFlags & Socket::SelectStatus_Send)
                    {
                        // connection was established
                        sock.close();
                        strm << "Port " << port << " connected" << strings::NewLine;
                    }
                    else if (statusFlags & Socket::SelectStatus_Error)
                    {
                        // socket error detected, connection rejected
                        sock.close();
                    }
                    else
                    {
                        if (now > timeout)
                        {
                            // connection not established within timeout
                            sock.close();
                        }
                    }
                }
            }
        }

        static void run_terminal(String const& host, int32_t const& port, bool ipv6 = false)
        {
            Socket::Endpoint ep = parse_host(host, port, ipv6);
            Socket client(ep.getFamily(), Socket::MsgType_Stream, Socket::Protocol_Tcp);
            VoidResult result = client.tryConnect(ep);
            if (result.hasError())<--- Shadowed declaration
            {
                Console << "Failed to establish connection to: " << host << " on port " << port << strings::NewLine;
                return;
            }
            Console << "Connection established to: " << host << " on port " << port << strings::NewLine;

            for (;;)
            {
                bool canRead = false;
                bool canWrite = false;
                bool hasError = false;
                uint32_t readTimeout = 10;
                VoidResult result;
                result = client.trySelect(NULL, &canWrite, NULL, 0);<--- Shadow variable
                if (result.hasError())
                {
                    Console << strings::NewLine << "Client socket select error detected" << strings::NewLine;
                    break;
                }
                if (canWrite)
                {
                    char_32_t chr;
                    if (Console.readChar(chr, 0))
                    {
                        char bytes[16];
                        size_t len = Char::writeUtf8(chr, bytes, sizeof(bytes));
                        size_t sent = 0;
                        if (chr == 13)
                        {
                            bytes[len] = 10;
                            ++len;
                        }
                        Result<size_t> sendResult;
                        while (sent < len)
                        {
                            sendResult = client.trySend(&bytes[sent], len - sent);
                            if (sendResult.hasError())
                            {
                                break;
                            }
                            else
                            {
                                sent += sendResult.value();
                            }
                        }
                        if (sendResult.hasError())
                        {
                            Console << strings::NewLine << "Failed to send input to remote server" << strings::NewLine;
                            break;
                        }
                        readTimeout = 0;
                    }
                }

                result = client.trySelect(&canRead, NULL, &hasError, readTimeout);
                if (result.hasError())
                {
                    Console << strings::NewLine << "Client socket select error detected" << strings::NewLine;
                    break;
                }
                if (hasError)
                {
                    Console << strings::NewLine << "Client socket error detected" << strings::NewLine;
                    break;
                }
                if (canRead)
                {
                    char chr;
                    Result<size_t> readResult = client.tryReceive(&chr, 1);
                    if (readResult.hasError())
                    {
                        Console << strings::NewLine << "Failed to read from socket" << strings::NewLine;
                        break;
                    }
                    if (readResult.value() == 0)
                    {
                        Console << strings::NewLine << "Connection closed" << strings::NewLine;
                        break;
                    }

                    Console.tryWrite(&chr, 1);
                }
            }
        }


        class GATE_API_LOCAL TcpCliApp : public App
        {
        public:
            virtual void run() override
            {

                static AppOptionDef help = AppOptionDef::createSwitch("help", "?", "show_help", "Shows help");
                static AppOptionDef connect = AppOptionDef::createString("connect", "C", "", "server_host_or_ip", "Connects to a TCP server IP");
                static AppOptionDef port = AppOptionDef::createInt32("port", "P", 22, "server_port", "Port number to start the connection attempt");
                static AppOptionDef scan = AppOptionDef::createString("scan", "S", "", "server_host_or_ip", "Tries to connect to the given TCP server");
                static AppOptionDef portscount = AppOptionDef::createInt32("ports-count", "N", 1, "port_count", "Number of ports to access");
                static AppOptionDef timeout = AppOptionDef::createInt32("timeout", "T", 5000, "milliseconds", "Connection timeout in milliseconds");
                static AppOptionDef iaterm = AppOptionDef::createString("interactive", "I", "", "server_host_or_ip", "Connects to a TCP server IP with terminal");

                static AppOptionDef* options[] =
                {
                    &help,
                    &connect,
                    &port,
                    &scan,
                    &portscount,
                    &iaterm,
                    &timeout
                };

                size_t const optionsCount = sizeof(options) / sizeof(options[0]);

                App::parseAppOptions(this->getArgs(), options, optionsCount);

                if (help.getBool())
                {
                    App::printAppOptions(options, optionsCount, Console);
                    return;
                }

                try
                {
                    String optConnect = connect.getString();
                    if (optConnect)
                    {
                        run_connect(optConnect, port.getInt32(), false);
                        return;
                    }

                    String optScan = scan.getString();
                    if (optScan)
                    {
                        run_scan(optScan, port.getInt32(), portscount.getInt32(), timeout.getInt32(), false);
                        return;
                    }

                    String optInteractive = iaterm.getString();
                    if (optInteractive)
                    {
                        run_terminal(optInteractive, port.getInt32());
                        return;
                    }
                }
                catch (Throwable const& xcpt)
                {
                    ConError << util::printException(xcpt);
                    throw;
                }
                catch (...)
                {
                    Console.writeErr("Unknown exception");
                    GATEXX_RAISE_EXCEPTION(results::UnknownException, NULL, 0);
                }

                ConError
                    << "Missing arguments." << strings::NewLine
                    << "Use '--help' to see all available options." << strings::NewLine;
                GATEXX_RAISE_ERROR(results::InvalidArg);
            }
        };

    }   // end of namespace apps
}	// end of namespace gate

int gate_main(char const* program, char const* const* arguments, gate_size_t argcount, gate_uintptr_t apphandle)
{
    gate::apps::TcpCliApp app;
    return gate::App::runApp(app, program, arguments, argcount, apphandle);
}