Debian Codegraph @

current/server/ServerTools.java

raw symbols SCIP
1 package server;
2
3 import java.io.BufferedReader;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.OutputStream;
9 import java.net.HttpURLConnection;
10 import java.net.InetSocketAddress;
11 import java.net.MalformedURLException;
12 import java.net.URI;
13 import java.net.URL;
14 import java.net.URLConnection;
15 import java.net.http.HttpClient;
16 import java.net.http.HttpRequest;
17 import java.net.http.HttpResponse;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.ExecutorService;
25 import java.util.concurrent.Executors;
26 import java.util.concurrent.ThreadFactory;
27 import java.util.zip.GZIPOutputStream;
28
29 import com.sun.net.httpserver.Headers;
30 import com.sun.net.httpserver.HttpExchange;
31
32 import fileIO.ReadWrite;
33 import shared.Shared;
34 import shared.Timer;
35 import shared.Tools;
36 import structures.ByteBuilder;
37 import structures.StringNum;
38
39 public class ServerTools {
40
41 public static void main(String[] args){
42 String address=args[0];
43 int rounds=1;
44 String message="";
45 if(args.length>1){rounds=Integer.parseInt(args[1]);}
46 if(args.length>2){message=args[2];}
47 byte[] messageBytes=message.getBytes();
48
49 long[] times=new long[rounds];
50 StringNum response=null;
51 long prevTime=System.nanoTime();
52 for(int i=0; i<rounds; i++){
53 response=sendAndReceive(messageBytes, address);
54 long currentTime=System.nanoTime();
55 times[i]=currentTime-prevTime;
56 prevTime=currentTime;
57 System.out.println(times[i]);
58 }
59
60 System.out.println(response.s);
61
62 Arrays.sort(times);
63 long sum=shared.Vector.sum(times);
64 System.out.println("Avg: \t"+sum/1000000.0+" ms");
65 System.out.println("QPS: \t"+(rounds*1000000000/sum)+" ms");
66 System.out.println("Median: \t"+(times[rounds/2]/1000000.0)+" ms");
67
68 }
69
70 public static ByteBuilder readPage(String address, boolean convert){
71 if(convert){address=PercentEncoding.commonSymbolToCode(address);}
72 // assert(false) : address;
73 ByteBuilder bb=new ByteBuilder(256);
74 boolean success=false;
75 for(int i=0; i<10 && !success; i++){
76 try {
77 URL url=new URL(address);
78 InputStream is=url.openStream();
79
80 byte[] buffer=new byte[4096];
81 for(int len=is.read(buffer); len>0; len=is.read(buffer)){
82 bb.append(buffer, 0, len);
83 }
84 is.close();
85 success=true;
86 } catch (MalformedURLException e) {
87 e.printStackTrace();
88 bb.clear();
89 Tools.pause(1000);
90 System.err.println("Retrying; attempt "+(i+1)+", URL "+address);
91 } catch (IOException e) {
92 e.printStackTrace();
93 bb.clear();
94 Tools.pause(1000);
95 System.err.println("Retrying; attempt "+(i+1)+", URL "+address);
96 }
97 }
98 return bb;
99 }
100
101 /** Send a message to a remote URL, and return the response.
102 * Set message to null if there is no message. */
103 public static StringNum sendAndReceive(byte[] message, String address){
104 //This may or may not work since the client is statically initialized.
105 if(Shared.javaVersion>=11) {
106 return sendAndReceive_httpClient(message, address);
107 }
108 return sendAndReceive_httpUrlConnection(message, address);
109 }
110
111
112 /** Send a message to a remote URL, and return the response.
113 * Set message to null if there is no message. */
114 public static StringNum sendAndReceive_httpUrlConnection(byte[] message, String address){
115 address=PercentEncoding.commonSymbolToCode(address);
116 URL url=null;
117 InputStream is=null;
118 HttpURLConnection connection=null;
119 OutputStream os=null;
120 try {
121 url=new URL(address);
122 connection=(HttpURLConnection) url.openConnection();
123 connection.setDoOutput(true);
124 connection.setConnectTimeout(40000); //For testing
125 os=connection.getOutputStream();
126 } catch (IOException e1) {
127 // System.err.println("A:\t"+address+" -> "+url+" -> "+connection+" -> "+os);
128 // TODO Auto-generated catch block
129 if(!suppressErrors){e1.printStackTrace();}
130 }
131
132 if(os!=null){
133 try {
134 //TODO: It may be useful to set a timeout here.
135 if(message!=null){os.write(message);}
136 } catch (IOException e) {
137 // System.err.println("B:\t"+connection+" -> "+os);
138 // TODO Auto-generated catch block
139 if(!suppressErrors){e.printStackTrace();}
140 }
141 try {
142 os.close();
143 } catch (IOException e) {
144 // TODO Auto-generated catch block
145 e.printStackTrace();
146 }
147 }
148
149 String result=null;
150 int responseCode=1;
151 if(connection!=null){
152 IOException noInputStream=null;
153 try {
154 is=connection.getInputStream();
155 } catch (IOException e) {
156 noInputStream=e;
157 }
158 if(is==null){is=connection.getErrorStream();}
159
160 try {
161 responseCode=connection.getResponseCode();
162 if(!suppressErrors && (responseCode<200 || responseCode>299)){
163 System.err.println("Error: Server returned response code "+responseCode);
164 // System.err.println(connection.getRequestProperties());//Can't do this - throws exception while connected
165 // System.err.println(connection.getResponseMessage());
166 new Exception().printStackTrace();
167 }
168 } catch (IOException e) {
169 if(!suppressErrors) {
170 e.printStackTrace();
171 }
172 }
173
174 if(is!=null){
175 result=readStream(is);
176 try {
177 // System.err.println("C:\t"+connection+" -> "+os+" -> "+is+" -> "+(result!=null));
178 is.close();
179 } catch (IOException e) {
180 e.printStackTrace();
181 }
182 }else if(noInputStream!=null && !suppressErrors){
183 noInputStream.printStackTrace();
184 }
185 }
186 if(result!=null && result.length()<1) {result=null;}
187 return new StringNum(result, responseCode);
188 }
189
190 /** Send a message to a remote URL, and return the response.
191 * Set message to null if there is no message. */
192 public static StringNum sendAndReceive_httpClient(byte[] message, String address){
193 address=PercentEncoding.commonSymbolToCode(address);
194
195 HttpRequest request = HttpRequest.newBuilder()
196 .uri(URI.create(address))
197 // .header("Accept-Encoding", "gzip")
198 .POST(HttpRequest.BodyPublishers.ofByteArray(message))
199 .build();
200 HttpResponse<String> response=null;
201
202 int responseCode=-1;
203 String result=null;
204
205 for(int i=0; i<12 && (result==null || responseCode<200 || responseCode>299); i++) {
206 try {
207 if(i>0) {Tools.sleep(20*i*i);}
208 response = client.send(request, HttpResponse.BodyHandlers.ofString());
209 result=response.body();
210 responseCode=response.statusCode();
211 } catch (IOException | InterruptedException e2) {
212 e2.printStackTrace();
213 // return null;
214 }
215 if(!suppressErrors && (responseCode<200 || responseCode>299) && i>0){
216 System.err.println("Warning: Server returned response code "+responseCode);
217 new Exception().printStackTrace();
218 }
219 }
220 if(result!=null && result.length()<1) {result=null;}
221 return new StringNum(result, responseCode);
222 }
223
224 public static byte[] gzipCompress(byte[] data) {
225 ByteArrayOutputStream bos = new ByteArrayOutputStream();
226 try {
227 GZIPOutputStream gzip = new GZIPOutputStream(bos);
228 gzip.write(data);
229 } catch (IOException e) {
230 // TODO Auto-generated catch block
231 e.printStackTrace();
232 }
233 return bos.toByteArray();
234 }
235
236 public static String determineContentEncoding(
237 HttpResponse<?> httpResponse) {
238 return httpResponse.headers().firstValue("Content-Encoding").orElse("");
239 }
240
241
242 /** Send a message to a remote URL, and return the response.
243 * Set message to null if there is no message. */
244 public static StringNum sendAndReceive(ArrayList<byte[]> messages, String address,
245 boolean verbose){
246 address=PercentEncoding.commonSymbolToCode(address);
247 URL url=null;
248 InputStream is=null;
249 HttpURLConnection connection=null;
250 OutputStream os=null;
251 try {
252 url=new URL(address);
253 connection=(HttpURLConnection) url.openConnection();
254 connection.setDoOutput(true);
255 connection.setConnectTimeout(1600000); //For testing
256 os=connection.getOutputStream();
257 } catch (IOException e1) {
258 // System.err.println("A:\t"+address+" -> "+url+" -> "+connection+" -> "+os);
259 // TODO Auto-generated catch block
260 if(!suppressErrors){e1.printStackTrace();}
261 }
262
263 long sent=0, received=0;
264 Timer t=new Timer();
265 if(os!=null){
266 try {
267 //TODO: It may be useful to set a timeout here.
268 for(byte[] message : messages) {
269 if(message!=null){
270 os.write(message);
271 sent+=message.length;
272 }
273 }
274 } catch (IOException e) {
275 // System.err.println("B:\t"+connection+" -> "+os);
276 // TODO Auto-generated catch block
277 if(!suppressErrors){e.printStackTrace();}
278 }
279 try {
280 os.close();
281 } catch (IOException e) {
282 // TODO Auto-generated catch block
283 e.printStackTrace();
284 }
285 }
286 if(verbose) {t.stopAndStart("Sent "+sent+" bytes in ");}
287
288 String result=null;
289 int responseCode=1;
290 if(connection!=null){
291 IOException noInputStream=null;
292 try {
293 is=connection.getInputStream();
294 } catch (IOException e) {
295 noInputStream=e;
296 }
297 if(is==null){is=connection.getErrorStream();}
298
299 try {
300 responseCode=connection.getResponseCode();
301 if(!suppressErrors && (responseCode<200 || responseCode>299)){
302 System.err.println("Error: Server returned response code "+responseCode);
303 // System.err.println(connection.getRequestProperties());//Can't do this - throws exception while connected
304 // System.err.println(connection.getResponseMessage());
305 new Exception().printStackTrace();
306 }
307 } catch (IOException e) {
308 if(!suppressErrors) {
309 e.printStackTrace();
310 }
311 }
312
313 if(is!=null){
314 result=readStream(is);
315 received+=(result==null ? 0 : result.length());
316 try {
317 // System.err.println("C:\t"+connection+" -> "+os+" -> "+is+" -> "+(result!=null));
318 is.close();
319 } catch (IOException e) {
320 e.printStackTrace();
321 }
322 }else if(noInputStream!=null && !suppressErrors){
323 noInputStream.printStackTrace();
324 }
325 }
326 if(verbose) {t.stop("Recieved "+received+" bytes in ");}
327
328 return new StringNum(result, responseCode);
329 }
330
331
332 /** Send a message to a remote URL, and return the response.
333 * Set message to null if there is no message. */
334 public static StringNum sendAndReceiveFTP(byte[] message, String address){
335 address=PercentEncoding.commonSymbolToCode(address);
336 URL url=null;
337 InputStream is=null;
338 URLConnection connection=null;
339 OutputStream os=null;
340 try {
341 url=new URL(address);
342 connection=url.openConnection();
343 connection.setDoOutput(true);
344 connection.setConnectTimeout(40000); //For testing
345 os=connection.getOutputStream();
346 } catch (IOException e1) {
347 // System.err.println("A:\t"+address+" -> "+url+" -> "+connection+" -> "+os);
348 // TODO Auto-generated catch block
349 if(!suppressErrors){e1.printStackTrace();}
350 }
351
352 if(os!=null){
353 try {
354 //TODO: It may be useful to set a timeout here.
355 if(message!=null){os.write(message);}
356 } catch (IOException e) {
357 // System.err.println("B:\t"+connection+" -> "+os);
358 // TODO Auto-generated catch block
359 if(!suppressErrors){e.printStackTrace();}
360 }
361 try {
362 os.close();
363 } catch (IOException e) {
364 // TODO Auto-generated catch block
365 e.printStackTrace();
366 }
367 }
368
369 String result=null;
370 // int responseCode=1;
371 if(connection!=null){
372 IOException noInputStream=null;
373 try {
374 is=connection.getInputStream();
375 } catch (IOException e) {
376 noInputStream=e;
377 }
378
379 // try {
380 //responseCode=connection.getResponseCode();
381 // if(!suppressErrors && (responseCode<200 || responseCode>299)){
382 // System.err.println("Error: Server returned response code "+responseCode);
383 // }
384 // }
385 // catch (IOException e) {
386 // if(!suppressErrors) {
387 // e.printStackTrace();
388 // }
389 // }
390
391 if(is!=null){
392 result=readStream(is);
393 try {
394 // System.err.println("C:\t"+connection+" -> "+os+" -> "+is+" -> "+(result!=null));
395 is.close();
396 } catch (IOException e) {
397 e.printStackTrace();
398 }
399 }else if(noInputStream!=null && !suppressErrors){
400 noInputStream.printStackTrace();
401 }
402 }
403
404 return new StringNum(result, 400);
405 }
406
407 /** Read the body of an incoming HTTP session */
408 public static String receive(HttpExchange t){
409 InputStream is=t.getRequestBody();
410 String s=readStream(is);
411 return s;
412 }
413
414 /** Completely read an InputStream into a String */
415 public static String readStream(InputStream is){
416 if(is==null){return null;}
417 try {
418 byte[] buffer=new byte[256];
419 int count=is.read(buffer);
420 int next=0;
421 while(count>-1){
422 next+=count;
423 if(next>=buffer.length){
424 buffer=Arrays.copyOf(buffer, buffer.length*2);
425 }
426 count=is.read(buffer, next, buffer.length-next);
427 }
428 is.close();
429 return new String(buffer, 0, next);
430 } catch (IOException e) {
431 // TODO Auto-generated catch block
432 e.printStackTrace();
433 }
434 return null;
435 }
436
437 /** Completely read an InputStream into a String */
438 public static ArrayList<byte[]> readStreamToList(InputStream is){
439 if(is==null){return null;}
440 ArrayList<byte[]> list=new ArrayList<byte[]>();
441 ByteBuilder bb=new ByteBuilder();
442 long next=0;
443 final byte[] buffer=new byte[4096];
444 try {
445 int count=is.read(buffer);
446 while(count>-1){
447 next+=count;
448 bb.append(buffer, count);
449 if(bb.length()>8000000) {
450 list.add(bb.toBytes());
451 bb.clear();
452 }
453 count=is.read(buffer);
454 }
455 if(bb.length()>0) {
456 list.add(bb.toBytes());
457 bb.clear();
458 }
459 System.err.println("Read "+next+" bytes into "+list.size()+" chunks.");
460 is.close();
461 return list;
462 } catch (IOException e) {
463 // TODO Auto-generated catch block
464 e.printStackTrace();
465 }
466 return null;
467 }
468
469 /** Write to the body of an incoming HTTP session */
470 public static boolean reply(String response, String type, HttpExchange t, boolean verbose, int code, boolean close){
471 if(verbose){System.err.println("Sending: "+response);}
472
473 return reply(response.getBytes(), type, t, false, code, close);
474 }
475
476 /** Write to the body of an incoming HTTP session */
477 public static boolean replyWithFile(String path, String type, HttpExchange t, boolean verbose, int code, boolean close){
478 if(verbose){System.err.println("Sending: "+path);}
479
480 byte[] response=null;
481 try {
482 response=ReadWrite.readRaw(path);
483 } catch (IOException e1) {
484 // TODO Auto-generated catch block
485 e1.printStackTrace();
486 response=new byte[0];
487 code=400; //Node sure about this
488 }
489
490 return reply(response, type, t, false, code, close);
491 }
492
493 /** Write to the body of an incoming HTTP session */
494 public static boolean reply(byte[] response, String type, HttpExchange t, boolean verbose, int code, boolean close){
495 if(verbose){System.err.println("Sending: "+response);}
496
497 {
498 Headers h = t.getResponseHeaders();
499 // String type="text/plain";
500 h.add("Content-Type", type);
501 }
502 try {
503 t.sendResponseHeaders(code, response.length);
504 OutputStream os = t.getResponseBody();
505 os.write(response);
506 os.close();
507 } catch (IOException e) {
508 // TODO Auto-generated catch block
509 e.printStackTrace();
510 if(close){t.close();}
511 return false;
512 }
513 if(close){t.close();}
514 return true;
515 }
516
517
518 /**
519 * Wait for a set amount of time
520 * @param millis Time to wait
521 */
522 public static void pause(long millis){
523 String lock=new String("1");
524 synchronized(lock){
525 final long time=System.currentTimeMillis()+millis;
526 while(System.currentTimeMillis()<time){
527 try {
528 lock.wait(Tools.max(100, time-System.currentTimeMillis()));
529 } catch (InterruptedException e) {
530 // TODO Auto-generated catch block
531 e.printStackTrace();
532 }
533 }
534 }
535 }
536
537 public static String getClientAddress(HttpExchange t) {
538
539 InetSocketAddress client=t.getRemoteAddress();
540 // InetSocketAddress server=t.getLocalAddress();
541
542 //This is for IPv4, class A. Probably extends outside of Berkeley.
543 String clientAddress=client.toString();
544 // String ls=server.toString();
545
546 if(clientAddress.contains("127.0.0.1")){
547 Headers clientRequestHeaders=t.getRequestHeaders();
548 // Headers resh=t.getResponseHeaders();
549
550 String xff=clientRequestHeaders.getFirst("X-forwarded-for");
551 if(xff!=null){clientAddress=xff;}
552
553 // System.err.println("\nRequest: ");
554 // for(Entry<String, List<String>> entry : reqh.entrySet()){
555 // System.err.println(entry.getKey()+" -> "+entry.getValue());
556 // }
557 }
558 return clientAddress;
559 }
560
561 public static boolean isInternalQuery(HttpExchange t,
562 String prefix, boolean allowLocalHost, boolean printIP, boolean printHeaders){
563
564 InetSocketAddress client=t.getRemoteAddress();
565 InetSocketAddress server=t.getLocalAddress();
566
567 if(printIP){System.err.println(client+"\t"+server);}
568
569 //This is for IPv4, class A. Probably extends outside of Berkeley.
570 String clientAddress=client.toString();
571 String serverAddress=server.toString();
572
573 if(clientAddress.contains("127.0.0.1")){//TODO: contains versus startsWith?
574 Headers requestHeaders=t.getRequestHeaders();
575
576 if(printHeaders){
577 Headers responseHeaders=t.getResponseHeaders();
578 System.err.println("\nRequest: ");
579 for(Entry<String, List<String>> entry : requestHeaders.entrySet()){
580 System.err.println(entry.getKey()+" -> "+entry.getValue());
581 }
582 System.err.println("\nResponse: ");
583 for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
584 System.err.println(entry.getKey()+" -> "+entry.getValue());
585 }
586 }
587
588 final String xff=requestHeaders.getFirst("X-forwarded-for");
589 if(xff!=null){
590 if(xff.startsWith(prefix)){return true;}
591 clientAddress=xff;
592 }else{
593 return allowLocalHost;
594 }
595 }else{
596 if(clientAddress.startsWith(prefix)){return true;}
597 }
598
599 //Makes sure they match up to the first delimiter
600 //TODO: This needs to be reviewed
601 for(int i=0, max=Tools.max(clientAddress.length(), serverAddress.length()); i<max; i++){
602 char cc=clientAddress.charAt(i), sc=serverAddress.charAt(i);
603 if(cc!=sc){break;}
604 if(cc=='.'){//IPv4
605 return true;
606 }else if(cc==':'){//IPv6; probably depends on how long the mask is
607 return true;
608 }
609 }
610
611 return false;
612 }
613
614 public static ArrayList<String> listDirectory(String baseAddress, final int retries){
615 // System.err.println("listDirectory '"+baseAddress+"'");
616 while(baseAddress.endsWith("/")){baseAddress=baseAddress.substring(0, baseAddress.length()-1);}
617 String baseAddress2=baseAddress.substring(0, baseAddress.lastIndexOf('/')+1);
618 String address=baseAddress+";type=d";
619 ArrayList<String> list=new ArrayList<String>();
620 boolean success=false;
621 for(int i=Tools.min(0, retries); !success && i<=retries; i++) {
622 try {
623 // System.err.println("URL '"+address+"'");
624 URL url=new URL(address);
625 URLConnection connection=url.openConnection();
626 InputStream is=connection.getInputStream();
627 BufferedReader br=new BufferedReader(new InputStreamReader(is));
628
629 String line=null;
630 while((line=br.readLine())!=null) {
631 list.add(baseAddress2+line);
632 }
633
634 is.close();
635 success=true;
636 } catch (IOException e) {
637 e.printStackTrace();
638 if(i<retries){
639 try {
640 int x=Tools.mid(30000, i*1000, 1000);
641 System.err.println("Sleeping for "+x+"ms...");
642 Thread.sleep(x);
643 } catch (InterruptedException e1) {
644 // TODO Auto-generated catch block
645 e1.printStackTrace();
646 }
647 System.err.println("** Retrying ** "+address);
648 list.clear();
649 }else{
650 System.err.println("*** Gave up ***");
651 }
652 }
653 }
654 return list;
655 }
656
657 public static ArrayList<String> readFTPFile(String address) throws Exception{
658 address=PercentEncoding.commonSymbolToCode(address);
659 URL url = new URL(address);
660 URLConnection conn = url.openConnection();
661
662 BufferedReader reader = new BufferedReader(new InputStreamReader(
663 conn.getInputStream()));
664 ArrayList<String> list=new ArrayList<String>();
665 for(String s=reader.readLine(); s!=null; s=reader.readLine()){
666 list.add(s);
667 }
668 return list;
669 }
670
671 /** Don't print caught exceptions */
672 public static boolean suppressErrors=false;
673
674 private static HttpClient client;
675 static{
676 try {
677
678 //Without make the threads Daemons the process won't terminate
679 ThreadFactory daemonThreadFactory = new ThreadFactory() {
680 public Thread newThread(Runnable r) {
681 Thread t = new Thread(r);
682 t.setDaemon(true);
683 return t;
684 }
685 };
686
687 ExecutorService executor = Executors.newFixedThreadPool(4, daemonThreadFactory);
688 // ExecutorService executor = Executors.newFixedThreadPool(8);
689 client = HttpClient.newBuilder()
690 .version(HttpClient.Version.HTTP_2)
691 .executor(executor)
692 .build();
693
694 // client=HttpClient.newHttpClient();
695 } catch (Throwable e) {
696 System.err.println("You may need a more recent version of Java, specifically, 11 or higher. Your version: "+Shared.javaVersion);
697 e.printStackTrace();
698 }
699 }
700
701 }