001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.http.events;
020
021import java.net.URI;
022import java.net.URISyntaxException;
023import java.net.URL;
024import java.util.Iterator;
025import java.util.List;
026import java.util.Optional;
027import java.util.Stack;
028import java.util.function.BiConsumer;
029import java.util.stream.Collectors;
030import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpProtocol;
031import org.jdrupes.httpcodec.protocols.http.HttpRequest;
032import org.jgrapes.core.Channel;
033import org.jgrapes.core.CompletionEvent;
034import org.jgrapes.core.Components;
035import org.jgrapes.core.Event;
036import org.jgrapes.http.ResourcePattern;
037import org.jgrapes.http.ResourcePattern.PathSpliterator;
038import org.jgrapes.io.events.Output;
039import org.jgrapes.net.SocketIOChannel;
040
041/**
042 * The base class for all HTTP requests such as {@link Request.In.Get},
043 * {@link Request.In.Post} etc.
044 *
045 * @param <R> the generic type
046 */
047public class Request<R> extends MessageReceived<R> {
048
049    /**
050     * @param channels
051     */
052    protected Request(Channel... channels) {
053        super(channels);
054    }
055
056    /**
057     * The base class for all incoming HTTP requests. Incoming
058     * request flow downstream and are served by the framework. 
059     * 
060     * A result of `true` indicates that the request has been processed, 
061     * i.e. a response has been sent or will be sent. Handlers MUST
062     * check that a request has not been {@link fulfilled} before
063     * firing a {@link Response} event to avoid duplicate response
064     * events. Handlers that have fired a response event and all
065     * related {@link Output} events SHOULD {@link Event#stop stop}
066     * the request event to avoid unnecessary subsequent invocations of
067     * handlers. Handlers that want to do "postprocessing" MUST
068     * therefore listen for the corresponding {@link Completed}
069     * event instead of defining a handler for the request event
070     * with low priority.
071     */
072    @SuppressWarnings("PMD.ShortClassName")
073    public static class In extends Request<Boolean> {
074
075        private final HttpRequest request;
076        private final int matchLevels;
077        private final MatchValue matchValue;
078        private final URI resourceUri;
079        private URI uri;
080
081        /**
082         * Creates a new request event with the associated {@link Completed}
083         * event.
084         * 
085         * @param protocol the protocol as reported by {@link #requestUri()}
086         * @param request the request data
087         * @param matchLevels the number of elements from the request path
088         * to use in the match value (see {@link #matchValue})
089         * @param channels the channels associated with this event
090         * @throws URISyntaxException 
091         */
092        @SuppressWarnings({ "PMD.ConstructorCallsOverridableMethod" })
093        public In(String protocol, HttpRequest request,
094                int matchLevels, Channel... channels)
095                throws URISyntaxException {
096            super(channels);
097            new Completed(this);
098            this.request = request;
099            this.matchLevels = matchLevels;
100
101            // Do any required request specific processing of the original
102            // request URI
103            URI requestUri = effectiveRequestUri(protocol, request);
104
105            // Clean the request URI's path, keeping the segments for matchValue
106            List<String> segs = pathToSegs(requestUri);
107            requestUri = new URI(requestUri.getScheme(),
108                requestUri.getUserInfo(), requestUri.getHost(),
109                requestUri.getPort(),
110                "/" + segs.stream().collect(Collectors.joining("/")),
111                requestUri.getQuery(), null);
112            setRequestUri(requestUri);
113
114            // The URI for handler selection ignores user info and query
115            resourceUri = new URI(requestUri.getScheme(), null,
116                requestUri.getHost(), requestUri.getPort(),
117                requestUri.getPath(), null, null);
118            @SuppressWarnings("PMD.InefficientStringBuffering")
119            StringBuilder matchPath = new StringBuilder("/" + segs.stream()
120                .limit(matchLevels).collect(Collectors.joining("/")));
121            if (segs.size() > matchLevels) {
122                if (!matchPath.toString().endsWith("/")) {
123                    matchPath.append('/');
124                }
125                matchPath.append('…');
126            }
127            matchValue = new MatchValue(getClass(),
128                (requestUri.getScheme() == null ? ""
129                    : (requestUri.getScheme() + "://"))
130                    + (requestUri.getHost() == null ? ""
131                        : (requestUri.getHost()
132                            + (requestUri.getPort() == -1 ? ""
133                                : (":" + requestUri.getPort()))))
134                    + matchPath);
135        }
136
137        @SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
138        private List<String> pathToSegs(URI requestUri)
139                throws URISyntaxException {
140            Iterator<String> origSegs = PathSpliterator.stream(
141                requestUri.getPath()).iterator();
142            // Path must not be empty and must be absolute
143            if (!origSegs.hasNext() || !origSegs.next().isEmpty()) {
144                throw new URISyntaxException(
145                    requestUri().getPath(), "Must be absolute");
146            }
147            // Remove dot segments and check for "...//..."
148            @SuppressWarnings({ "PMD.LooseCoupling" })
149            Stack<String> segs = new Stack<>();
150            while (origSegs.hasNext()) {
151                if (!segs.isEmpty() && segs.peek().isEmpty()) {
152                    // Empty segment followed by more means "//"
153                    segs.clear();
154                }
155                String seg = origSegs.next();
156                if (".".equals(seg)) {
157                    continue;
158                }
159                if ("..".equals(seg)) {
160                    if (!segs.isEmpty()) {
161                        segs.pop();
162                    }
163                    continue;
164                }
165                segs.push(seg);
166            }
167            return segs;
168        }
169
170        /**
171         * Builds the URI that represents this request. The default
172         * implementation checks that request URI in the HTTP request
173         * is directed at this server as specified in the "Host"-header
174         * and adds the protocol, host and port if not specified 
175         * in the request URI. 
176         *
177         * @param protocol the protocol
178         * @param request the request
179         * @return the URI
180         * @throws URISyntaxException if the request is not acceptable
181         */
182        protected URI effectiveRequestUri(String protocol, HttpRequest request)
183                throws URISyntaxException {
184            URI serverUri = new URI(protocol, null,
185                request.host(), request.port(), "/", null, null);
186            URI origRequest = request.requestUri();
187            URI result = serverUri.resolve(new URI(null, null, null, -1,
188                origRequest.getPath(), origRequest.getQuery(), null));
189            if (!result.getScheme().equals(protocol)
190                || !result.getHost().equals(request.host())
191                || result.getPort() != request.port()) {
192                throw new URISyntaxException(origRequest.toString(),
193                    "Scheme, host or port not allowed");
194            }
195            return result;
196        }
197
198        /**
199         * Creates the appropriate derived request event type from
200         * a given {@link HttpRequest}.
201         * 
202         * @param request the HTTP request
203         * @param secure whether the request was received over a secure channel
204         * @param matchLevels the match levels
205         * @return the request event
206         * @throws URISyntaxException 
207         */
208        @SuppressWarnings("PMD.AvoidDuplicateLiterals")
209        public static In fromHttpRequest(
210                HttpRequest request, boolean secure, int matchLevels)
211                throws URISyntaxException {
212            switch (request.method()) {
213            case "OPTIONS":
214                return new Options(request, secure, matchLevels);
215            case "GET":
216                return new Get(request, secure, matchLevels);
217            case "HEAD":
218                return new Head(request, secure, matchLevels);
219            case "POST":
220                return new Post(request, secure, matchLevels);
221            case "PUT":
222                return new Put(request, secure, matchLevels);
223            case "DELETE":
224                return new Delete(request, secure, matchLevels);
225            case "TRACE":
226                return new Trace(request, secure, matchLevels);
227            case "CONNECT":
228                return new Connect(request, secure, matchLevels);
229            default:
230                return new In(secure ? "https" : "http", request, matchLevels);
231            }
232        }
233
234        /**
235         * Sets the request URI.
236         *
237         * @param uri the new request URI
238         */
239        protected final void setRequestUri(URI uri) {
240            this.uri = uri;
241        }
242
243        /**
244         * Returns an absolute URI of the request. For incoming requests, the 
245         * URI is built from the information provided by the decoder.
246         * 
247         * @return the URI
248         */
249        public final URI requestUri() {
250            return uri;
251        }
252
253        /**
254         * Returns the "raw" request as provided by the HTTP decoder.
255         * 
256         * @return the request
257         */
258        public HttpRequest httpRequest() {
259            return request;
260        }
261
262        /**
263         * The match value consists of the event class and a URI.
264         * The URI is similar to the request URI but its path elements
265         * are shortened as specified in the constructor.
266         * 
267         * The match value is used as key in a map that speeds up
268         * the lookup of handlers. Having the complete URI in the match
269         * value would inflate this map.
270         *
271         * @return the object
272         * @see org.jgrapes.core.Event#defaultCriterion()
273         */
274        @Override
275        public Object defaultCriterion() {
276            return matchValue;
277        }
278
279        /*
280         * (non-Javadoc)
281         * 
282         * @see org.jgrapes.core.Event#isMatchedBy(java.lang.Object)
283         */
284        @Override
285        public boolean isEligibleFor(Object value) {
286            if (!(value instanceof MatchValue)) {
287                return super.isEligibleFor(value);
288            }
289            MatchValue mval = (MatchValue) value;
290            if (!mval.type.isAssignableFrom(matchValue.type)) {
291                return false;
292            }
293            if (mval.resource instanceof ResourcePattern) {
294                return ((ResourcePattern) mval.resource).matches(resourceUri,
295                    matchLevels) >= 0;
296            }
297            return mval.resource.equals(matchValue.resource);
298        }
299
300        /**
301         * Checks if the request has been processed, i.e. a response has 
302         * been sent.
303         *
304         * @return true, if fulfilled
305         */
306        public boolean fulfilled() {
307            return !currentResults().isEmpty() && currentResults().get(0);
308        }
309
310        /*
311         * (non-Javadoc)
312         * 
313         * @see java.lang.Object#toString()
314         */
315        @Override
316        @SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
317        public String toString() {
318            StringBuilder builder = new StringBuilder(50);
319            builder.append(Components.objectName(this))
320                .append(" [\"");
321            String path = Optional.ofNullable(request.requestUri().getPath())
322                .orElse("");
323            if (path.length() > 15) {
324                builder.append("...")
325                    .append(path.substring(path.length() - 12));
326            } else {
327                builder.append(path);
328            }
329            builder.append('\"');
330            if (channels().length > 0) {
331                builder.append(", channels=")
332                    .append(Channel.toString(channels()));
333            }
334            builder.append(']');
335            return builder.toString();
336        }
337
338        /**
339         * Creates the match value.
340         *
341         * @param type the type
342         * @param resource the resource
343         * @return the object
344         */
345        public static Object createMatchValue(
346                Class<?> type, ResourcePattern resource) {
347            return new MatchValue(type, resource);
348        }
349
350        /**
351         * Represents a match value.
352         */
353        @SuppressWarnings("PMD.PublicMemberInNonPublicType")
354        private static class MatchValue {
355            private final Class<?> type;
356            private final Object resource;
357
358            /**
359             * @param type
360             * @param resource
361             */
362            public MatchValue(Class<?> type, Object resource) {
363                super();
364                this.type = type;
365                this.resource = resource;
366            }
367
368            /*
369             * (non-Javadoc)
370             * 
371             * @see java.lang.Object#hashCode()
372             */
373            @Override
374            public int hashCode() {
375                final int prime = 31;
376                int result = 1;
377                result = prime * result
378                    + ((resource == null) ? 0 : resource.hashCode());
379                result
380                    = prime * result + ((type == null) ? 0 : type.hashCode());
381                return result;
382            }
383
384            /*
385             * (non-Javadoc)
386             * 
387             * @see java.lang.Object#equals(java.lang.Object)
388             */
389            @Override
390            public boolean equals(Object obj) {
391                if (this == obj) {
392                    return true;
393                }
394                if (obj == null) {
395                    return false;
396                }
397                if (getClass() != obj.getClass()) {
398                    return false;
399                }
400                MatchValue other = (MatchValue) obj;
401                if (resource == null) {
402                    if (other.resource != null) {
403                        return false;
404                    }
405                } else if (!resource.equals(other.resource)) {
406                    return false;
407                }
408                if (type == null) {
409                    if (other.type != null) {
410                        return false;
411                    }
412                } else if (!type.equals(other.type)) {
413                    return false;
414                }
415                return true;
416            }
417
418        }
419
420        /**
421         * The associated completion event.
422         */
423        public static class Completed extends CompletionEvent<In> {
424
425            /**
426             * Instantiates a new event.
427             *
428             * @param monitoredEvent the monitored event
429             * @param channels the channels
430             */
431            public Completed(In monitoredEvent, Channel... channels) {
432                super(monitoredEvent, channels);
433            }
434        }
435
436        /**
437         * Represents a HTTP CONNECT request.
438         */
439        public static class Connect extends In {
440
441            /**
442             * Create a new event.
443             * 
444             * @param request the request data
445             * @param secure indicates whether the request was received on a
446             * secure channel
447             * @param matchLevels the number of elements from the request path
448             * to use in the match value
449             * @param channels the channels on which the event is to be 
450             * fired (optional)
451             * @throws URISyntaxException 
452             */
453            public Connect(HttpRequest request, boolean secure, int matchLevels,
454                    Channel... channels) throws URISyntaxException {
455                super(secure ? "https" : "http", request, matchLevels,
456                    channels);
457            }
458
459            /**
460             * Builds the URI that represents this request. This
461             * implementation returns the request URI without
462             * path and query component. 
463             *
464             * @param protocol the protocol
465             * @param request the request
466             * @return the uri
467             * @throws URISyntaxException the URI syntax exception
468             * @see "[RFC 7230, Section 5.5](https://datatracker.ietf.org/doc/html/rfc7230#section-5.5)"
469             */
470            @Override
471            protected URI effectiveRequestUri(String protocol,
472                    HttpRequest request) throws URISyntaxException {
473                URI req = request.requestUri();
474                return new URI(req.getScheme(), req.getUserInfo(),
475                    req.getHost(), req.getPort(), null, null, null);
476            }
477        }
478
479        /**
480         * The Class Delete.
481         */
482        public static class Delete extends In {
483
484            /**
485            * Create a new event.
486            * 
487            * @param request the request data
488            * @param secure indicates whether the request was received on a
489            * secure channel
490            * @param matchLevels the number of elements from the request path
491            * to use in the match value
492            * @param channels the channels on which the event is to be 
493            * fired (optional)
494             * @throws URISyntaxException 
495            */
496            public Delete(HttpRequest request, boolean secure, int matchLevels,
497                    Channel... channels) throws URISyntaxException {
498                super(secure ? "https" : "http", request, matchLevels,
499                    channels);
500            }
501
502        }
503
504        /**
505         * Represents a HTTP GET request.
506         */
507        public static class Get extends In {
508
509            /**
510             * Create a new event.
511             * 
512             * @param request the request data
513             * @param secure indicates whether the request was received on a
514             * secure channel
515             * @param matchLevels the number of elements from the request path
516             * to use in the match value
517             * @param channels the channels on which the event is to be 
518             * fired (optional)
519             * @throws URISyntaxException 
520             */
521            public Get(HttpRequest request, boolean secure, int matchLevels,
522                    Channel... channels) throws URISyntaxException {
523                super(secure ? "https" : "http", request, matchLevels,
524                    channels);
525            }
526        }
527
528        /**
529         * Represents a HTTP HEAD request.
530         */
531        public static class Head extends In {
532
533            /**
534             * Create a new event.
535             * 
536             * @param request the request data
537             * @param secure indicates whether the request was received on a
538             * secure channel
539             * @param matchLevels the number of elements from the request path
540             * to use in the match value
541             * @param channels the channels on which the event is to be 
542             * fired (optional)
543             * @throws URISyntaxException 
544             */
545            public Head(HttpRequest request, boolean secure, int matchLevels,
546                    Channel... channels) throws URISyntaxException {
547                super(secure ? "https" : "http", request, matchLevels,
548                    channels);
549            }
550        }
551
552        /**
553         * Represents a HTTP OPTIONS request.
554         */
555        public static class Options extends In {
556
557            /**
558             * Create a new event.
559             * 
560             * @param request the request data
561             * @param secure indicates whether the request was received on a
562             * secure channel
563             * @param matchLevels the number of elements from the request path
564             * to use in the match value
565             * @param channels the channels on which the event is to be 
566             * fired (optional)
567             * @throws URISyntaxException 
568             */
569            public Options(HttpRequest request, boolean secure, int matchLevels,
570                    Channel... channels) throws URISyntaxException {
571                super(secure ? "https" : "http", request, matchLevels,
572                    channels);
573            }
574        }
575
576        /**
577         * Represents a HTTP POST request.
578         */
579        public static class Post extends In {
580
581            /**
582             * Create a new event.
583             * 
584             * @param request the request data
585             * @param secure indicates whether the request was received on a
586             * secure channel
587             * @param matchLevels the number of elements from the request path
588             * to use in the match value
589             * @param channels the channels on which the event is to be 
590             * fired (optional)
591             * @throws URISyntaxException 
592             */
593            public Post(HttpRequest request, boolean secure, int matchLevels,
594                    Channel... channels) throws URISyntaxException {
595                super(secure ? "https" : "http", request, matchLevels,
596                    channels);
597            }
598
599        }
600
601        /**
602         * Represents a HTTP PUT request.
603         */
604        public static class Put extends In {
605
606            /**
607             * Create a new event.
608             * 
609             * @param request the request data
610             * @param secure indicates whether the request was received on a
611             * secure channel
612             * @param matchLevels the number of elements from the request path
613             * to use in the match value
614             * @param channels the channels on which the event is to be 
615             * fired (optional)
616             * @throws URISyntaxException 
617             */
618            public Put(HttpRequest request, boolean secure, int matchLevels,
619                    Channel... channels) throws URISyntaxException {
620                super(secure ? "https" : "http", request, matchLevels,
621                    channels);
622            }
623        }
624
625        /**
626         * Represents a HTTP TRACE request.
627         */
628        public static class Trace extends In {
629
630            /**
631             * Create a new event.
632             * 
633             * @param request the request data
634             * @param secure indicates whether the request was received on a
635             * secure channel
636             * @param matchLevels the number of elements from the request path
637             * to use in the match value
638             * @param channels the channels on which the event is to be 
639             * fired (optional)
640             * @throws URISyntaxException 
641             */
642            public Trace(HttpRequest request, boolean secure, int matchLevels,
643                    Channel... channels) throws URISyntaxException {
644                super(secure ? "https" : "http", request, matchLevels,
645                    channels);
646            }
647        }
648    }
649
650    /**
651     * The base class for all outgoing HTTP requests. Outgoing
652     * request flow upstream and are served externally.
653     */
654    @SuppressWarnings("PMD.ShortClassName")
655    public static class Out extends Request<Void> {
656
657        private final HttpRequest request;
658        private BiConsumer<Request.Out, SocketIOChannel> connectedCallback;
659
660        /**
661         * Instantiates a new request.
662         *
663         * @param method the method
664         * @param url the url
665         */
666        public Out(String method, URL url) {
667            try {
668                request = new HttpRequest(method, url.toURI(),
669                    HttpProtocol.HTTP_1_1, false);
670            } catch (URISyntaxException e) {
671                // This should not happen because every valid URL can be
672                // converted to a URI.
673                throw new IllegalArgumentException(e);
674            }
675        }
676
677        /**
678         * Sets a "connected callback". When the {@link Out} event is
679         * created, the network connection is not yet known. Some
680         * header fields' values, however, need e.g. the port information
681         * from the connection. Therefore a callback may be set which is
682         * invoked when the connection has been obtained that will be used
683         * to send the request.
684         *
685         * @param connectedCallback the connected callback
686         * @return the out
687         */
688        public Out setConnectedCallback(
689                BiConsumer<Request.Out, SocketIOChannel> connectedCallback) {
690            this.connectedCallback = connectedCallback;
691            return this;
692        }
693
694        /**
695         * Returns the connected callback.
696         *
697         * @return the connected callback, if set
698         */
699        public Optional<BiConsumer<Request.Out, SocketIOChannel>>
700                connectedCallback() {
701            return Optional.ofNullable(connectedCallback);
702        }
703
704        /**
705         * The HTTP request that will be sent by the event.
706         *
707         * @return the http request
708         */
709        public HttpRequest httpRequest() {
710            return request;
711        }
712
713        /**
714         * Returns an absolute URI of the request.
715         * 
716         * @return the URI
717         */
718        public URI requestUri() {
719            return request.requestUri();
720        }
721
722        /*
723         * (non-Javadoc)
724         * 
725         * @see java.lang.Object#toString()
726         */
727        @Override
728        public String toString() {
729            StringBuilder builder = new StringBuilder();
730            builder.append(Components.objectName(this))
731                .append(" [").append(request.toString());
732            if (channels().length > 0) {
733                builder.append(", channels=")
734                    .append(Channel.toString(channels()));
735            }
736            builder.append(']');
737            return builder.toString();
738        }
739
740        /**
741         * Represents a HTTP CONNECT request.
742         */
743        public static class Connect extends Out {
744
745            /**
746             * Instantiates a new request.
747             *
748             * @param uri the uri
749             */
750            public Connect(URL uri) {
751                super("CONNECT", uri);
752            }
753        }
754
755        /**
756         * Represents a HTTP DELETE request.
757         */
758        public static class Delete extends Out {
759
760            /**
761             * Instantiates a new request.
762             *
763             * @param uri the uri
764             */
765            public Delete(URL uri) {
766                super("DELETE", uri);
767            }
768        }
769
770        /**
771         * Represents a HTTP GET request.
772         */
773        public static class Get extends Out {
774
775            /**
776             * Instantiates a new request.
777             *
778             * @param uri the uri
779             */
780            public Get(URL uri) {
781                super("GET", uri);
782            }
783        }
784
785        /**
786         * Represents a HTTP HEAD request.
787         */
788        public static class Head extends Out {
789
790            /**
791             * Instantiates a new request.
792             *
793             * @param uri the uri
794             */
795            public Head(URL uri) {
796                super("HEAD", uri);
797            }
798        }
799
800        /**
801         * Represents a HTTP OPTIONS request.
802         */
803        public static class Options extends Out {
804
805            /**
806             * Instantiates a new request.
807             *
808             * @param uri the uri
809             */
810            public Options(URL uri) {
811                super("OPTIONS", uri);
812            }
813        }
814
815        /**
816         * Represents a HTTP POST request.
817         */
818        public static class Post extends Out {
819
820            /**
821             * Instantiates a new request.
822             *
823             * @param uri the uri
824             */
825            public Post(URL uri) {
826                super("POST", uri);
827            }
828        }
829
830        /**
831         * Represents a HTTP PUT request.
832         */
833        public static class Put extends Out {
834
835            /**
836             * Instantiates a new request.
837             *
838             * @param uri the uri
839             */
840            public Put(URL uri) {
841                super("PUT", uri);
842            }
843        }
844
845        /**
846         * Represents a HTTP TRACE request.
847         */
848        public static class Trace extends Out {
849
850            /**
851             * Instantiates a new request.
852             *
853             * @param uri the uri
854             */
855            public Trace(URL uri) {
856                super("TRACE", uri);
857            }
858        }
859    }
860}