001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.terminal.region;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.util.*;
023
024import org.apache.juneau.http.*;
025import org.apache.juneau.http.response.BadRequest;
026import org.apache.juneau.http.response.NotFound;
027import org.apache.juneau.rest.server.*;
028import org.apache.juneau.terminal.report.*;
029import org.apache.juneau.rest.server.util.*;
030
031/**
032 * Static helpers that implement the terminal endpoints and serve the terminal runtime.
033 *
034 * <p>
035 * {@link TerminalMixin} delegates to these; an application that wants its own paths writes {@code @RestGet} methods
036 * that call them and gets the same validation, cap and headers.
037 *
038 * <h2 class='section'>Bytes headers:</h2>
039 * <ul>
040 *    <li>{@code Term-Next}: the offset to ask for next.
041 *    <li>{@code Term-End}: the source's current end.
042 *    <li>{@code Term-Done}: {@code true} once the producer is finished and the reader is at the end.
043 *    <li>{@code Term-Cols}, {@code Term-Rows}: the producer's terminal size.
044 *    <li>{@code Term-Truncated}: {@code true} when the bytes start later than {@code from}.
045 *    <li>{@code Term-Error}: only ever {@code gone}, when the log disappeared.
046 * </ul>
047 */
048public final class TerminalEndpoints {
049
050   /** Classpath location of the terminal runtime. */
051   static final String JS_RESOURCE = "/org/apache/juneau/terminal/juneau-terminal.js";
052
053   /** Classpath location of the terminal stylesheet. */
054   static final String CSS_RESOURCE = "/org/apache/juneau/terminal/juneau-terminal.css";
055
056   /** The most bytes the raw download streams (64 MiB). */
057   public static final long RAW_MAX_BYTES = 64L * 1024 * 1024;
058
059   private static final String JS_CONTENT_TYPE = "text/javascript;charset=utf-8";
060   private static final String CSS_CONTENT_TYPE = "text/css;charset=utf-8";
061   private static final String CACHE_CONTROL = "max-age=86400, public";
062   private static final String OCTETS = "application/octet-stream";
063
064   /** Anchored on this class so the cache-buster carries this module's version. */
065   private static final ClasspathAssetCache ASSET_CACHE = new ClasspathAssetCache(TerminalEndpoints.class);
066
067   private TerminalEndpoints() {}
068
069   /**
070    * Checks a terminal id against {@code ^[A-Za-z0-9_-]{1,128}$}.
071    *
072    * @param id The id from the URL path.
073    * @return The same id.
074    * @throws BadRequest If the id does not match.
075    */
076   public static String checkId(String id) {
077      if (! TerminalViewChecks.isRunId(id))
078         throw new BadRequest("id must match [A-Za-z0-9_-]{1,128}");
079      return id;
080   }
081
082   /**
083    * Serves {@code ?from=<offset>&max=<n>} as raw bytes with the {@code Term-*} headers.
084    *
085    * <p>
086    * Answers {@code 404} for an empty source, {@code 400} for a malformed {@code from} or {@code max}, {@code 416}
087    * with {@code Term-End} when {@code from} is past the end, and otherwise {@code 200}.  A {@code from} equal to
088    * the end is a {@code 200} with no bytes.
089    *
090    * <p>
091    * A gone source answers {@code 200} with no bytes, {@code Term-Done: true} and {@code Term-Error: gone}, whatever
092    * {@code from} is.  Its {@code Term-Next} and {@code Term-End} are {@code from} itself, so a client that keeps
093    * polling never rewinds; the chunk's own offsets are not consulted.
094    *
095    * @param source The resolved source; empty answers {@code 404}.
096    * @param req The request.
097    * @param res The response.
098    * @throws IOException If the source could not be read or the response written.
099    */
100   public static void bytes(Optional<TerminalSource> source, RestRequest req, RestResponse res) throws IOException {
101      var src = source.orElseThrow(NotFound::new);
102      var from = number(req, "from", 0, TerminalEvent.MAX_SAFE_INT);
103      var max = (int)number(req, "max", TerminalSource.MAX_READ_BYTES, Integer.MAX_VALUE);
104      var c = src.read(from, Math.min(max, TerminalSource.MAX_READ_BYTES));
105      res.setHeader("Cache-Control", "no-store");
106      res.setHeader("X-Content-Type-Options", "nosniff");
107      res.setHeader("Term-Cols", String.valueOf(c.cols()));
108      res.setHeader("Term-Rows", String.valueOf(c.rows()));
109      if (c.gone()) {
110         res.setHeader("Term-Next", String.valueOf(from));
111         res.setHeader("Term-End", String.valueOf(from));
112         res.setHeader("Term-Done", "true");
113         res.setHeader("Term-Error", "gone");
114         write(res, new byte[0]);
115         return;
116      }
117      res.setHeader("Term-End", String.valueOf(c.end()));
118      if (from > c.end()) {
119         res.setStatus(416);
120         return;
121      }
122      res.setHeader("Term-Next", String.valueOf(c.next()));
123      res.setHeader("Term-Done", String.valueOf(c.done()));
124      res.setHeader("Term-Truncated", String.valueOf(c.truncated()));
125      write(res, c.bytes());
126   }
127
128   /**
129    * Adapts a request to the transport-neutral caller handed to {@link TerminalAccess}.
130    *
131    * @param req The request.
132    * @return The caller.
133    */
134   public static TerminalCaller caller(RestRequest req) {
135      return new TerminalCaller() {
136         @Override public String principalName() {
137            var p = req.getUserPrincipal();
138            return p == null ? null : p.getName();
139         }
140         @Override public Object attribute(String name) {
141            return req.getAttribute(name).orElse(null);
142         }
143      };
144   }
145
146   /**
147    * Serves every byte still held as an attachment named {@code <id>.log}.
148    *
149    * <p>
150    * A gone source still answers {@code 200} with an empty body, and carries {@code Term-Error: gone} as {@code bytes}
151    * does.
152    *
153    * <p>
154    * The download takes no range and is capped at {@link #RAW_MAX_BYTES}: it streams the log, {@link TerminalSource#MAX_READ_BYTES}
155    * at a time, up to the end at the time of the request.  The id is checked here as well as by
156    * {@link TerminalMixin}, because it becomes the file name.
157    *
158    * @param source The resolved source; empty answers {@code 404}.
159    * @param id The terminal id (also the download file name).
160    * @param res The response.
161    * @throws IOException If the source could not be read or the response written.
162    */
163   public static void raw(Optional<TerminalSource> source, String id, RestResponse res) throws IOException {
164      checkId(id);
165      var src = source.orElseThrow(NotFound::new);
166      res.setHeader("Cache-Control", "no-store");
167      res.setHeader("X-Content-Type-Options", "nosniff");
168      if (src.read(0, 0).gone())
169         res.setHeader("Term-Error", "gone");
170      res.setHeader("Content-Disposition", "attachment; filename=\"" + id + ".log\"");
171      res.setContentType(OCTETS);
172      var out = res.getOutputStream();
173      src.copyTo(out, RAW_MAX_BYTES);
174      out.flush();
175   }
176
177   /**
178    * The terminal runtime.
179    *
180    * @return {@code juneau-terminal.js} as a JavaScript {@link HttpResource}.
181    */
182   public static HttpResource script() {
183      return ASSET_CACHE.serve(JS_RESOURCE, JS_CONTENT_TYPE, CACHE_CONTROL);
184   }
185
186   /**
187    * The terminal stylesheet.
188    *
189    * @return {@code juneau-terminal.css} as a CSS {@link HttpResource}.
190    */
191   public static HttpResource stylesheet() {
192      return ASSET_CACHE.serve(CSS_RESOURCE, CSS_CONTENT_TYPE, CACHE_CONTROL);
193   }
194
195   /**
196    * Returns the absolute URL of a terminal asset, resolved against the request, with a
197    * {@code ?v=<buildVersion>-<hash8>} cache-buster.
198    *
199    * @param req The current request.
200    * @param path {@link TerminalMixin#JS_PATH} or {@link TerminalMixin#CSS_PATH}.
201    * @return The asset URL.
202    * @throws IllegalArgumentException If this module does not ship the given path.
203    */
204   public static String terminalAssetUrl(RestRequest req, String path) {
205      var resource = resourceFor(path);
206      return req.getUriResolver().resolve("servlet:" + path) + ASSET_CACHE.cacheBuster(resource);
207   }
208
209   private static String resourceFor(String path) {
210      if (TerminalMixin.JS_PATH.equals(path))
211         return JS_RESOURCE;
212      if (TerminalMixin.CSS_PATH.equals(path))
213         return CSS_RESOURCE;
214      throw iaex("TerminalEndpoints does not serve '%s'.", path);
215   }
216
217   private static long number(RestRequest req, String name, long dflt, long limit) {
218      var s = req.getQueryParam(name).asString().orElse(null);
219      if (s == null)
220         return dflt;
221      if (! s.matches("0|[1-9]\\d{0,15}"))
222         throw new BadRequest(name + " must be a non-negative integer");
223      var n = Long.parseLong(s);
224      if (n > limit)
225         throw new BadRequest(name + " must be at most " + limit);
226      return n;
227   }
228
229   private static void write(RestResponse res, byte[] bytes) throws IOException {
230      res.setContentType(OCTETS);
231      res.setContentLength(bytes.length);
232      var out = res.getOutputStream();
233      out.write(bytes);
234      out.flush();
235   }
236}