~jpgleeson/spawsh

ref: 09365a78459e390323acba2eea450233fa9c55d8 spawsh/Program.cs -rw-r--r-- 11.7 KiB
09365a78 — jpgleeson Redirect Handling 1 year, 5 months ago
                                                                                
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
368
369
370
371
372
373
374
375
using System;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace spawsh
{
    class Program
    {

        static string server = "gemini.circumlunar.space";
        static string page = "/";
        static string[] LineBuffer;
        static string[] linksInPage;
        static bool inInteractive = false;
        static int selectedLinkIndex = -1;
        static string currentPage;

        static void Main(string[] args)
        {

            string server = "gemini.circumlunar.space";
            string page = "/";
            bool validProtocol = true;

            int windowLineCount = Console.WindowHeight;            

            if (args.Length > 0)
            {
                string hostArgument = args[0];

                if (hostArgument == "-i")
                {
                    inInteractive = true;
                    LineBuffer = new string[windowLineCount];

                    buildRequest(server + page);
                    LineBuffer = fetchPage();
                    linksInPage = buildLinkSet(LineBuffer);

                    while (inInteractive)
                    {
                        interactiveLoop();
                    }
                }
                else
                {
                    if (hostArgument.Contains("gemini://"))
                    {
                        hostArgument = hostArgument.Trim();
                        hostArgument = hostArgument.Substring(9);
                    }
                    else if (hostArgument.Contains("https://") || hostArgument.Contains("http://") || hostArgument.Contains("gopher://"))
                    {
                        Console.WriteLine("Protocol not supported.");
                        validProtocol = false;
                    }

                    if (hostArgument.Contains("/"))
                    {
                        int firstSlashIndex = hostArgument.IndexOf('/');

                        server = hostArgument.Remove(firstSlashIndex);
                        page = hostArgument.Substring(firstSlashIndex, hostArgument.Length - firstSlashIndex);
                    }
                    else
                    {
                        server = hostArgument;
                    }

                    if (validProtocol)
                    {
                        TcpClient client = new TcpClient(server, 1965);


                        using (SslStream sslStream = new SslStream(client.GetStream(), false,
                            new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                        {
                            sslStream.AuthenticateAsClient(server);

                            byte[] messageToSend = Encoding.UTF8.GetBytes("gemini://" + server + page + '\r' + '\n');
                            sslStream.Write(messageToSend);

                            string responseData = ReadMessage(sslStream);

                            handleResponse(responseData);

                        }
                        client.Close();
                    }
                }
            }
            else
            {
                buildRequest(server);
                fetchPage();
            }

        }

        public static bool ValidateServerCertificate(object sender, X509Certificate certificate,
        X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static void interactiveLoop()
        {
            Console.Clear();

            for (int i = 0; i < Console.WindowWidth - LineBuffer[0].Length; i++)
            {
                Console.Write(" ");    
            }
            Console.WriteLine(LineBuffer[0]);

            for (int i = 0; i < Console.WindowWidth; i++)
            {
                Console.Write("-");
            }
            Console.Write('\n');

            for (int i = 1; i < LineBuffer.Length; i++)
            {
                Console.WriteLine(LineBuffer[i]);
            }

            if (selectedLinkIndex != -1)
            {
                Console.WriteLine(linksInPage[selectedLinkIndex]);
            }

            ConsoleKeyInfo keyRead = Console.ReadKey();

            if (keyRead.Key == ConsoleKey.Escape)
            {
                inInteractive = false;
            }
            else if (keyRead.Key == ConsoleKey.Enter)
            {
                string newInput;

                if (selectedLinkIndex == -1)
                {
                    Console.Write("url: ");
                    page = "";
                    newInput = Console.ReadLine();
                }
                else
                {
                    newInput = linksInPage[selectedLinkIndex];
                }

                Console.WriteLine(newInput);
                if (buildRequest(newInput))
                {
                    Console.WriteLine("Fetching {0}", newInput);

                    LineBuffer = fetchPage();

                    linksInPage = buildLinkSet(LineBuffer);
                }

                selectedLinkIndex = -1;
            }
            else if (keyRead.Key == ConsoleKey.RightArrow)
            {
                if (selectedLinkIndex < linksInPage.Length - 1)
                {
                    selectedLinkIndex++;
                }
            }
            else if (keyRead.Key == ConsoleKey.LeftArrow)
            {
                if (selectedLinkIndex > -1)
                {
                    selectedLinkIndex--;
                }
            }

            if (selectedLinkIndex < 0)
            {
                selectedLinkIndex = -1;
            }
        }

        static string[] fetchPage()
        {
            TcpClient client = new TcpClient(server, 1965);
            string responseData;

            using (SslStream sslStream = new SslStream(client.GetStream(), false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
            {
                sslStream.AuthenticateAsClient(server);

                byte[] messageToSend = Encoding.UTF8.GetBytes("gemini://" + server + page + '\r' + '\n');
                sslStream.Write(messageToSend);

                responseData = ReadMessage(sslStream);

                handleResponse(responseData);

            }
            client.Close();

            return responseData.Split('\n');
        }

        static bool buildRequest(string inputString)
        {
            if (inputString.Contains("gemini://"))
            {
                inputString = inputString.Trim();
                inputString = inputString.Substring(9);
            }
            else if (inputString.Contains("https://") || inputString.Contains("http://") || inputString.Contains("gopher://"))
            {
                Console.WriteLine("Protocol not supported.");
                return false;
            }

            if (inputString.Contains("/"))
            {
                int firstSlashIndex = inputString.IndexOf('/');

                if (firstSlashIndex == 0 || firstSlashIndex == 1)
                {
                    //Should be same server
                }
                else
                {
                    server = inputString.Remove(firstSlashIndex);
                }
                
                page = inputString.Substring(firstSlashIndex, inputString.Length - firstSlashIndex);
            }
            else if (inputString.Split('.').Length == 2 && inputString.Split('.')[1] == "gmi")
            {
                inputString = "/" + inputString;
                page = inputString;
            }
            else
            {
                server = inputString;
            }

            return true;
        }

        static string[] buildLinkSet(string[] lines)
        {
            string[] linkSet = Array.Empty<string>();
            int counter = 0;

            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].Length > 2)
                {
                    if (lines[i].Substring(0, 2) == "=>")
                    {
                        string[] biggerArray = new string[counter + 1];
                        for (int e = 0; e < linkSet.Length; e++)
                        {
                            biggerArray[e] = linkSet[e];
                        }
                        biggerArray[counter] = lines[i].Split(' ')[1];

                        if (biggerArray[counter].Contains('\t'))
                        {
                            biggerArray[counter] = biggerArray[counter].Split('\t')[0];
                        }

                        if (!biggerArray[counter].Contains('.'))
                        {
                            //These should be local links
                            biggerArray[counter] = server + "/" + biggerArray[counter];
                        }

                        linkSet = biggerArray;
                        counter++;
                    }
                }
            }

            return linkSet;
        }

        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the client.
            // The client signals the end of the message using the
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                // Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                // Check for EOF or an empty message.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }

        static void handleResponse(string responseData)
        {
            string[] responseLines = responseData.Split('\n');
            string responseBody = "";

            string responseHeader = responseLines[0];


            if (responseLines.Length > 1)
            {
                string[] responseBodyLines = new string[responseLines.Length-1];
                for (int i = 1; i < responseLines.Length; i++)
                {
                    responseBodyLines[i - 1] = responseLines[i];
                }
                responseBody = string.Join('\n', responseBodyLines);

            }

            string responseCode = responseHeader.Split(' ')[0];

            if (responseCode == "20")
            {
                Console.WriteLine(responseBody);
            }
            else if (responseCode == "31")
            {
                string redirectAddress = responseHeader.Split(' ')[1];

                if (buildRequest(redirectAddress))
                {
                    Console.WriteLine("Redirect to {0}. Fetching.", redirectAddress);

                    LineBuffer = fetchPage();

                    linksInPage = buildLinkSet(LineBuffer);
                }

                selectedLinkIndex = -1;
            }
            else if (responseCode[0] == '3')
            {
                Console.WriteLine("Redirect to {0}", responseHeader.Split(' ')[1]);
                Console.WriteLine("Try again at new url above.");
            }
            else if (responseCode == "50")
            {
                Console.WriteLine("Permanent Failure");
            }
            else if (responseCode == "51")
            {
                Console.WriteLine("File not found.");
            }
        }

    }
}