Alejandro Acuña
2024-07-30 65a64a81d30f00f1fffd5da6866850e1308e1135
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
package art.servers.controller;
 
 
import art.library.interop.InteropParameter;
import art.library.interop.InteropParameters;
import art.library.interop.InteropResponse;
import art.library.interop.serialization.Serialization;
import art.library.interop.serialization.SerializationException;
import art.library.utils.licence.Licence;
import art.servers.Shared;
import art.servers.configuration.Configuration;
import art.servers.configuration.ConfigurationListenerHttp;
import art.servers.configuration.ConfigurationSecurity;
import art.servers.types.HttpAuthentication;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
 
 
 
public class ControllerListenerHttpWeb extends Thread
{
    protected String name = null;
    protected ConfigurationListenerHttp configuration = null;
    protected HttpServer server = null;
    protected ListenerImplementation listenerImplementation = null;
    protected ConfigurationSecurity security = null;
    
    public List<HttpAuthentication> autentications = new ArrayList<HttpAuthentication>();
 
    
    public ControllerListenerHttpWeb(ConfigurationListenerHttp configuration, ConfigurationSecurity security)
    {
        this.name = Shared.getMessage("Listener HTTPS");
        this.configuration = configuration;
        this.security = security;
        this.listenerImplementation = new ListenerImplementation();
        this.setName(name);
    }
        
    
    
    public void run()
    {
        Shared.traceInformation(name, "Starting");
        
        while (isInterrupted() == false)
        {
            try
            {
                if (server == null)
                {
                    connect();
                }
                
                sleep(1000);
            }
            catch (Exception e)
            {
            }
        }
        
        Shared.traceInformation(name, "Finishing");
    }
    
    
    
    
    
    
    protected void connect()
    {
        try
        {
            server = HttpServer.create(new InetSocketAddress(configuration.port), 0);
            contexts();
            server.setExecutor(Executors.newCachedThreadPool());
            server.start();    
            return;
            
        }
        catch (Exception e)
        {
        }        
    }
    
    
    protected void contexts()
    {
        server.createContext("/login", new login());
        server.createContext("/art", new art());
    }
    
    
 
    
 
    
 
 
    protected class login implements HttpHandler 
    {
        public void handle(HttpExchange httpExchange) throws IOException 
        {
            String language = null;
            
            try
            {
                InteropParameters parameters = new InteropParameters(httpExchange.getRequestURI().getRawQuery());
                language = (parameters.hasParameter("language") == true) ? (String)parameters.getParameterValue("language") : "";
                String type = (parameters.hasParameter("type") == true) ? (String)parameters.getParameterValue("type") : "text";
                parameters.addParameter(new InteropParameter("body-content", getRequestBody(httpExchange)));
                InteropResponse response = login(parameters, type, httpExchange.getRemoteAddress().getHostName());
                result(httpExchange, response);
            }
            catch (Exception e)
            {
                result(httpExchange, 400, language, e);
            }
        }
        
        
        
        
        private InteropResponse login(InteropParameters parameters, String type, String address) throws SerializationException
        {
            String language = (String)parameters.getParameterValue("language");
 
            try
            {
                String username = (String)parameters.getParameterValue("username");
                String password = (String)parameters.getParameterValue("password");
                HttpAuthentication authentication = login(username, password, address);
 
                if (type.equalsIgnoreCase("json"))
                {
                    InteropResponse response = new InteropResponse(authentication.getHttpToken());
                    Object[] objects = response.getValue();
                    return response;
                }
                else
                {
                    InteropResponse response = new InteropResponse(authentication.getHttpToken().token);
                    response.mime = "text/plain";
                    return response;
                }
            }
            catch (Exception e)
            {
               StringWriter sw = new StringWriter();
               e.printStackTrace(new PrintWriter(sw));
               throw new SerializationException(Shared.getMessage(language, "Authentication error"));
            }
        }
 
 
        
        
        private HttpAuthentication login(String username, String password, String address) throws Exception
        {
            // Check user autentication
            
            Configuration configuration = (Configuration)Shared.configuration;
 
            HttpAuthentication authentication = new HttpAuthentication(username, password, address);
            
            if ((username.equals("read")) && (password.equals(Licence.decrypt(security.readPassword))))
            {
                authentication.profileWebServer = HttpAuthentication.PROFILE_READ;
            }
            else if ((username.equals("write")) && (password.equals(Licence.decrypt(security.writePassword))))
            {
                authentication.profileWebServer = HttpAuthentication.PROFILE_WRITE;
            }
            else if ((username.equals("admin")) && (password.equals(Licence.decrypt(security.adminPassword))))
            {
                authentication.profileWebServer = HttpAuthentication.PROFILE_ADMIN;
            }
            else
            {
                throw new Exception("Autentication error");
            }            
 
            return authentication;
        }        
    }    
        
    
    
    
    
    protected class art implements HttpHandler 
    {
        public void handle(HttpExchange httpExchange) throws IOException 
        {
            String language = null;
            
            try
            {
                InteropParameters parameters = new InteropParameters(httpExchange.getRequestURI().getRawQuery());
                language = (parameters.hasParameter("language") == true) ? (String)parameters.getParameterValue("language") : "";
                
                int tokenStatus = checkToken(httpExchange, parameters);
                
                
                if (tokenStatus != 200)
                {
                    result(httpExchange, tokenStatus, Shared.getMessage(language, "Invalid token"));
                }
                else
                {
                    parameters.addParameter(new InteropParameter("body-content", getRequestBody(httpExchange)));
                    String operation = (String)parameters.getParameterValue("operation");
                    Method method = listenerImplementation.getClass().getMethod(operation, parameters.getClass());
                    InteropResponse response = (InteropResponse)method.invoke(listenerImplementation, parameters);
                    result(httpExchange, response);
                }
            }
            catch (Exception exception)
            {
                result(httpExchange, 400, language, exception);
            }
        }
    }
 
 
    
    
     
    
    protected int checkToken(HttpExchange httpExchange, InteropParameters parameters)
    {
        Configuration configuration = (Configuration)Shared.configuration;        
        
        try
        {
            HttpAuthentication authentication = Serialization.deserialize(HttpAuthentication.class, Licence.decrypt((String)parameters.getParameterValue("token")));
            authentication.updateExpirationTimestamp();
            
            if (authentication.isTokenValid(httpExchange.getRemoteAddress().getHostName()) == false)
            {
                return 401; // Page expired
            }
            
            authentication.lastRequestTimestamp = System.currentTimeMillis();
            return 200;
        }
        catch (Exception e)
        {
        }   
        
        try
        {
            String[] login = ((String)parameters.getParameterValue("token")).split(",");
            String username = login[0];
            String password = login[1];
 
            if ((username.equals("read")) && (password.equals(Licence.decrypt(security.readPassword))))
            {
                HttpAuthentication authentication = new HttpAuthentication(username, password, httpExchange.getRemoteAddress().getHostName(), HttpAuthentication.PROFILE_READ);
                authentication.updateExpirationTimestamp();
                String token = URLDecoder.decode(authentication.getHttpToken().token, StandardCharsets.UTF_8.toString());
                parameters.setParameter("token", token);
                authentication.lastRequestTimestamp = System.currentTimeMillis();
                return 200;
            }
 
            if ((username.equals("write")) && (password.equals(Licence.decrypt(security.writePassword))))
            {
                HttpAuthentication authentication = new HttpAuthentication(username, password, httpExchange.getRemoteAddress().getHostName(), HttpAuthentication.PROFILE_WRITE);
                authentication.updateExpirationTimestamp();
                String token = URLDecoder.decode(authentication.getHttpToken().token, StandardCharsets.UTF_8.toString());
                parameters.setParameter("token", token);
                authentication.lastRequestTimestamp = System.currentTimeMillis();
                return 200;
            }
 
            if ((username.equals("admin")) && (password.equals(Licence.decrypt(security.adminPassword))))
            {
                HttpAuthentication authentication = new HttpAuthentication(username, password, httpExchange.getRemoteAddress().getHostName(), HttpAuthentication.PROFILE_ADMIN);
                authentication.updateExpirationTimestamp();
                String token = URLDecoder.decode(authentication.getHttpToken().token, StandardCharsets.UTF_8.toString());
                parameters.setParameter("token", token);
                authentication.lastRequestTimestamp = System.currentTimeMillis();
                return 200;
            }
 
        }
        catch (Exception e)
        {
        }      
        
        try
        {
            HttpAuthentication authentication = getAuthentication(httpExchange);
            authentication.updateExpirationTimestamp();
            String token = URLDecoder.decode(authentication.getHttpToken().token, StandardCharsets.UTF_8.toString());
            parameters.addParameter("token", token);
            authentication.lastRequestTimestamp = System.currentTimeMillis();
            return 200;
        }
        catch (Exception e)
        {
        }
       
        
        return 401; // Invalid token, unauthorized 
    }
 
   
    
 
    public HttpAuthentication getAuthentication(HttpExchange httpExchange)
    {
        String address = httpExchange.getRemoteAddress().getHostName();
        String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");
        
 
        for (HttpAuthentication current : autentications)
        {
            if ((current.userAgent.equals(userAgent)) && (current.address.equals(address)))
            {
                return current;
            }
        }
        
        return null;
    }
        
 
    
    
    // <editor-fold defaultstate="collapsed" desc="Request body">
    
 
 
    protected byte[] getRequestBody(HttpExchange httpExchange) throws Exception
    {
        ByteArrayOutputStream bos = null;
 
        try
        {
            InputStream input = httpExchange.getRequestBody();
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8196]; 
            int length;
 
            while ((length = input.read(buffer)) != -1) 
            {
                bos.write(buffer, 0, length);
            }
            return bos.toByteArray();
        }
        catch (Exception exception)
        {
            throw exception;
        }
        finally
        {
            try { bos.close(); } catch (Exception ex) {};
            httpExchange.getRequestBody().close();
        }
    }
 
        
    
    
     // </editor-fold>  
    
 
    // <editor-fold defaultstate="collapsed" desc="Response">
    
    
    protected void result(HttpExchange httpExchange, int httpErrorCode,  byte[] data) throws Exception
    {
        try
        {
            httpExchange.sendResponseHeaders(httpErrorCode, data.length);
            httpExchange.getResponseBody().write(data);
        }
        finally
        {
            try { httpExchange.getResponseBody().close(); } catch (Exception e) {}
            try { httpExchange.close(); } catch (Exception e) {}
        }
    }
     
    
     
       
    protected void result(HttpExchange httpExchange, InteropResponse response)
    {
        // https://www.sitepoint.com/mime-types-complete-list/
        // httpExchange.getResponseHeaders().set("Content-Type", "text/html; charset=" + StandardCharsets.UTF_8);
        // httpExchange.getResponseHeaders().set("Content-Type", "application/pdf"; charset=" + StandardCharsets.UTF_8);
        // httpExchange.getResponseHeaders().set("Content-Type", "application/vnd.ms-excel"; charset=" + StandardCharsets.UTF_8);
 
        httpExchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
        
        if (httpExchange.getRequestMethod().equalsIgnoreCase("OPTIONS")) 
        {
            httpExchange.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            httpExchange.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
 
            try
            {
                httpExchange.sendResponseHeaders(204, -1);
            }
            catch (Exception e)
            {
            }
 
            httpExchange.close();
            return;
        }
        
        if (response.mime == null)
        {
            httpExchange.getResponseHeaders().set("Content-Type", "application/json; charset=" + StandardCharsets.UTF_8);
        }
        else
        {
            httpExchange.getResponseHeaders().set("Content-Type", response.mime + "; charset=" + StandardCharsets.UTF_8);
        }
        
        
        // Check if response is a file
        
        if (response.name != null)
        {
            try
            {
                // For filenames with polish characters
                
                byte[] filenameBytes = response.name.getBytes("UTF-8");
                String filename = "";
                for (byte character : filenameBytes) filename += (char)(character & 0xFF);
                httpExchange.getResponseHeaders().set("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            }
            catch (Exception e)
            {
                httpExchange.getResponseHeaders().set("Content-Disposition", "attachment; filename=\"" + response.name + "\"");
            }
        }
        
        
        // Check mime text/plain
        
        if (response.mime != null)
        {
            if (response.mime.equalsIgnoreCase("text/plain"))
            {
                try
                {
                    byte[] data = ((String)response.getValue()[0]).getBytes(); 
                    result(httpExchange, 200, data);
                    httpExchange.close();
                    return;
                }
                catch (Exception exception)
                {
                    manageException(httpExchange, exception);
                }
                
                return;
            }
            else if (response.mime.equalsIgnoreCase("application/json"))
            {
                 try
                {
                    if (response.array == true)
                    {
                        String message = Serialization.toString(response.getValue());
                        result(httpExchange, 200, message.getBytes());
                    }
                    else
                    {
                        String message = Serialization.toString(response.getValue()[0]);
                        result(httpExchange, 200, message.getBytes());
                    }
                }
                catch (Exception e)
                {
                    manageException(httpExchange, e);
                }
                
                return;
            }
        }
        
        
        // Try send raw bytes
        
        try
        {
            byte[] data = (byte[])response.getValue()[0];
            result(httpExchange, 200, data);
            httpExchange.close();
            return;
        }
        catch (Exception exception)
        {
            manageException(httpExchange, exception);
        }
        
        
        
      
        
        // Default JSON
        
        try
        {
            if (response.array == false)
            {
                String message = Serialization.toString(response.getValue()[0]);
                result(httpExchange, 200, message.getBytes());
                httpExchange.close();
                return;
            }
            else
            {
                if (response.getValue().length == 0)
                {
                    String message = Serialization.toString(response.getValue());
                    result(httpExchange, 200, message.getBytes());
                    httpExchange.close();
                    return;
                }
                else
                {
                    String message = Serialization.toString(response.getValue());
                    result(httpExchange, 200, message.getBytes());
                    httpExchange.close();
                    return;
                }
            }
        }
        catch (Exception exception)
        {
            manageException(httpExchange, exception);
        }
        
    }
    
 
    
    
 
    protected void result (HttpExchange httpExchange, int httpErrorCode, String language, Exception exception)
    {
        Throwable throwable = exception.getCause();
        
        if (throwable != null)
        {
            if ((throwable instanceof SerializationException) || (throwable instanceof ServerException))
            {
                result(httpExchange, httpErrorCode, Shared.getMessage(language, throwable.getMessage()));
            }
        }
        
        if ((exception instanceof SerializationException) || (exception instanceof ServerException))
        {
            result(httpExchange, httpErrorCode, Shared.getMessage(language, exception.getMessage()));
        }
        
        StringWriter sw = new StringWriter();
        exception.printStackTrace(new PrintWriter(sw));
        String message = sw.toString();
        result(httpExchange, httpErrorCode, message);
    }
 
    
 
    
    protected void result (HttpExchange httpExchange, int httpErrorCode, String message)
    {
        try
        {
            result(httpExchange, httpErrorCode, message.getBytes());
        }
        catch (Exception e)
        {
            manageException(httpExchange, e);
        }
    }
 
    
     // </editor-fold>  
 
   
    // <editor-fold defaultstate="collapsed" desc="Exception">    
    
    
    protected void manageException (HttpExchange httpExchange, Exception exception)
    {
        try
        {
            httpExchange.close();
        }
        catch (Exception e)
        {
        }
        
        if (exception instanceof IOException)
        {
            String message = exception.toString().toLowerCase();
            
            if (message.contains("an established connection was aborted by the software in your host machine") == true)
            {
                if (server != null)
                {
                    try{server.stop(10);} catch (Exception ex){};
                    server = null;
                    connect();
                }
            }
        }
    }
    
    
     // </editor-fold>  
        
}