http.ts 21.5 KB
Newer Older
A
Asher 已提交
1
import { field, logger } from "@coder/logger"
A
Asher 已提交
2 3 4 5 6 7 8 9 10 11 12 13
import * as fs from "fs-extra"
import * as http from "http"
import * as httpolyglot from "httpolyglot"
import * as https from "https"
import * as net from "net"
import * as path from "path"
import * as querystring from "querystring"
import safeCompare from "safe-compare"
import { Readable } from "stream"
import * as tls from "tls"
import * as url from "url"
import { HttpCode, HttpError } from "../common/http"
A
Asher 已提交
14
import { normalize, Options, plural, split } from "../common/util"
A
Asher 已提交
15
import { SocketProxyProvider } from "./socket"
A
Asher 已提交
16
import { getMediaMime, xdgLocalDir } from "./util"
A
Asher 已提交
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

export type Cookies = { [key: string]: string[] | undefined }
export type PostData = { [key: string]: string | string[] | undefined }

interface AuthPayload extends Cookies {
  key?: string[]
}

export enum AuthType {
  Password = "password",
  None = "none",
}

export type Query = { [key: string]: string | string[] | undefined }

export interface HttpResponse<T = string | Buffer | object> {
  /*
   * Whether to set cache-control headers for this response.
   */
  cache?: boolean
  /**
   * If the code cannot be determined automatically set it here. The
   * defaults are 302 for redirects and 200 for successful requests. For errors
   * you should throw an HttpError and include the code there. If you
   * use Error it will default to 404 for ENOENT and EISDIR and 500 otherwise.
   */
  code?: number
  /**
   * Content to write in the response. Mutually exclusive with stream.
   */
  content?: T
  /**
   * Cookie to write with the response.
A
Asher 已提交
50
   * NOTE: Cookie paths must be absolute. The default is /.
A
Asher 已提交
51
   */
A
Asher 已提交
52
  cookie?: { key: string; value: string; path?: string }
A
Asher 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  /**
   * Used to automatically determine the appropriate mime type.
   */
  filePath?: string
  /**
   * Additional headers to include.
   */
  headers?: http.OutgoingHttpHeaders
  /**
   * If the mime type cannot be determined automatically set it here.
   */
  mime?: string
  /**
   * Redirect to this path. Will rewrite against the base path but NOT the
   * provider endpoint so you must include it. This allows redirecting outside
A
Asher 已提交
68
   * of your endpoint.
A
Asher 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
   */
  redirect?: string
  /**
   * Stream this to the response. Mutually exclusive with content.
   */
  stream?: Readable
  /**
   * Query variables to add in addition to current ones when redirecting. Use
   * `undefined` to remove a query variable.
   */
  query?: Query
}

/**
 * Use when you need to run search and replace on a file's content before
 * sending it.
 */
export interface HttpStringFileResponse extends HttpResponse {
  content: string
  filePath: string
}

A
Asher 已提交
91 92 93 94
export interface RedirectResponse extends HttpResponse {
  redirect: string
}

A
Asher 已提交
95
export interface HttpServerOptions {
A
Asher 已提交
96
  readonly auth?: AuthType
A
Asher 已提交
97 98
  readonly cert?: string
  readonly certKey?: string
A
Asher 已提交
99
  readonly commit?: string
A
Asher 已提交
100
  readonly host?: string
A
Asher 已提交
101
  readonly password?: string
A
Asher 已提交
102
  readonly port?: number
A
Asher 已提交
103 104 105
  readonly socket?: string
}

A
Asher 已提交
106
export interface Route {
A
Asher 已提交
107 108 109 110 111 112 113
  base: string
  requestPath: string
  query: querystring.ParsedUrlQuery
  fullPath: string
  originalPath: string
}

A
Asher 已提交
114 115 116 117
interface ProviderRoute extends Route {
  provider: HttpProvider
}

A
Asher 已提交
118 119
export interface HttpProviderOptions {
  readonly auth: AuthType
A
Asher 已提交
120
  readonly base: string
A
Asher 已提交
121
  readonly commit: string
A
Asher 已提交
122
  readonly password?: string
A
Asher 已提交
123 124 125 126 127 128 129 130 131
}

/**
 * Provides HTTP responses. This abstract class provides some helpers for
 * interpreting, creating, and authenticating responses.
 */
export abstract class HttpProvider {
  protected readonly rootPath = path.resolve(__dirname, "../..")

A
Asher 已提交
132
  public constructor(protected readonly options: HttpProviderOptions) {}
A
Asher 已提交
133 134 135 136 137 138 139 140

  public dispose(): void {
    // No default behavior.
  }

  /**
   * Handle web sockets on the registered endpoint.
   */
141 142 143 144 145 146 147
  public handleWebSocket(
    /* eslint-disable @typescript-eslint/no-unused-vars */
    _route: Route,
    _request: http.IncomingMessage,
    _socket: net.Socket,
    _head: Buffer,
    /* eslint-enable @typescript-eslint/no-unused-vars */
A
Asher 已提交
148
  ): Promise<void> {
149 150
    throw new HttpError("Not found", HttpCode.NotFound)
  }
A
Asher 已提交
151 152 153 154

  /**
   * Handle requests to the registered endpoint.
   */
A
Asher 已提交
155
  public abstract handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse>
A
Asher 已提交
156

A
Asher 已提交
157
  /**
A
Asher 已提交
158 159 160 161 162 163 164
   * Get the base relative to the provided route. For each slash we need to go
   * up a directory. For example:
   * / => ./
   * /foo => ./
   * /foo/ => ./../
   * /foo/bar => ./../
   * /foo/bar/ => ./../../
A
Asher 已提交
165
   */
A
Asher 已提交
166
  public base(route: Route): string {
A
Asher 已提交
167
    const depth = (route.originalPath.match(/\//g) || []).length
A
Asher 已提交
168 169 170
    return normalize("./" + (depth > 1 ? "../".repeat(depth - 1) : ""))
  }

A
Asher 已提交
171 172 173
  /**
   * Get error response.
   */
A
Asher 已提交
174 175 176 177 178 179
  public async getErrorRoot(route: Route, title: string, header: string, body: string): Promise<HttpResponse> {
    const response = await this.getUtf8Resource(this.rootPath, "src/browser/pages/error.html")
    response.content = response.content
      .replace(/{{ERROR_TITLE}}/g, title)
      .replace(/{{ERROR_HEADER}}/g, header)
      .replace(/{{ERROR_BODY}}/g, body)
A
Asher 已提交
180 181 182 183 184 185
    return this.replaceTemplates(route, response)
  }

  /**
   * Replace common templates strings.
   */
186 187 188 189 190 191
  protected replaceTemplates(route: Route, response: HttpStringFileResponse, sessionId?: string): HttpStringFileResponse
  protected replaceTemplates<T extends object>(
    route: Route,
    response: HttpStringFileResponse,
    options: T,
  ): HttpStringFileResponse
A
Asher 已提交
192 193 194
  protected replaceTemplates(
    route: Route,
    response: HttpStringFileResponse,
195
    sessionIdOrOptions?: string | object,
A
Asher 已提交
196
  ): HttpStringFileResponse {
197 198 199 200 201 202 203
    if (typeof sessionIdOrOptions === "undefined" || typeof sessionIdOrOptions === "string") {
      sessionIdOrOptions = {
        base: this.base(route),
        commit: this.options.commit,
        logLevel: logger.level,
        sessionID: sessionIdOrOptions,
      } as Options
A
Asher 已提交
204 205 206
    }
    response.content = response.content
      .replace(/{{COMMIT}}/g, this.options.commit)
207
      .replace(/{{TO}}/g, Array.isArray(route.query.to) ? route.query.to[0] : route.query.to || "/dashboard")
A
Asher 已提交
208
      .replace(/{{BASE}}/g, this.base(route))
209
      .replace(/"{{OPTIONS}}"/, `'${JSON.stringify(sessionIdOrOptions)}'`)
A
Asher 已提交
210 211 212
    return response
  }

A
Asher 已提交
213 214
  protected get isDev(): boolean {
    return this.options.commit === "development"
A
Asher 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  }

  /**
   * Get a file resource.
   * TODO: Would a stream be faster, at least for large files?
   */
  protected async getResource(...parts: string[]): Promise<HttpResponse> {
    const filePath = path.join(...parts)
    return { content: await fs.readFile(filePath), filePath }
  }

  /**
   * Get a file resource as a string.
   */
  protected async getUtf8Resource(...parts: string[]): Promise<HttpStringFileResponse> {
    const filePath = path.join(...parts)
    return { content: await fs.readFile(filePath, "utf8"), filePath }
  }

  /**
A
Asher 已提交
235
   * Helper to error on invalid methods (default GET).
A
Asher 已提交
236
   */
A
Asher 已提交
237 238 239
  protected ensureMethod(request: http.IncomingMessage, method?: string | string[]): void {
    const check = Array.isArray(method) ? method : [method || "GET"]
    if (!request.method || !check.includes(request.method)) {
A
Asher 已提交
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
      throw new HttpError(`Unsupported method ${request.method}`, HttpCode.BadRequest)
    }
  }

  /**
   * Helper to error if not authorized.
   */
  protected ensureAuthenticated(request: http.IncomingMessage): void {
    if (!this.authenticated(request)) {
      throw new HttpError("Unauthorized", HttpCode.Unauthorized)
    }
  }

  /**
   * Use the first query value or the default if there isn't one.
   */
  protected queryOrDefault(value: string | string[] | undefined, def: string): string {
    if (Array.isArray(value)) {
      value = value[0]
    }
    return typeof value !== "undefined" ? value : def
  }

  /**
   * Return the provided password value if the payload contains the right
   * password otherwise return false. If no payload is specified use cookies.
   */
  protected authenticated(request: http.IncomingMessage, payload?: AuthPayload): string | boolean {
    switch (this.options.auth) {
      case AuthType.None:
        return true
      case AuthType.Password:
        if (typeof payload === "undefined") {
          payload = this.parseCookies<AuthPayload>(request)
        }
        if (this.options.password && payload.key) {
          for (let i = 0; i < payload.key.length; ++i) {
            if (safeCompare(payload.key[i], this.options.password)) {
              return payload.key[i]
            }
          }
        }
        return false
      default:
        throw new Error(`Unsupported auth type ${this.options.auth}`)
    }
  }

  /**
   * Parse POST data.
   */
  protected getData(request: http.IncomingMessage): Promise<string | undefined> {
    return request.method === "POST" || request.method === "DELETE"
      ? new Promise<string>((resolve, reject) => {
          let body = ""
          const onEnd = (): void => {
            off() // eslint-disable-line @typescript-eslint/no-use-before-define
            resolve(body || undefined)
          }
          const onError = (error: Error): void => {
            off() // eslint-disable-line @typescript-eslint/no-use-before-define
            reject(error)
          }
          const onData = (d: Buffer): void => {
            body += d
            if (body.length > 1e6) {
              onError(new HttpError("Payload is too large", HttpCode.LargePayload))
              request.connection.destroy()
            }
          }
          const off = (): void => {
            request.off("error", onError)
            request.off("data", onError)
            request.off("end", onEnd)
          }
          request.on("error", onError)
          request.on("data", onData)
          request.on("end", onEnd)
        })
      : Promise.resolve(undefined)
  }

  /**
   * Parse cookies.
   */
  protected parseCookies<T extends Cookies>(request: http.IncomingMessage): T {
    const cookies: { [key: string]: string[] } = {}
    if (request.headers.cookie) {
      request.headers.cookie.split(";").forEach((keyValue) => {
        const [key, value] = split(keyValue, "=")
        if (!cookies[key]) {
          cookies[key] = []
        }
        cookies[key].push(decodeURI(value))
      })
    }
    return cookies as T
  }
}

/**
 * Provides a heartbeat using a local file to indicate activity.
 */
export class Heart {
  private heartbeatTimer?: NodeJS.Timeout
  private heartbeatInterval = 60000
  private lastHeartbeat = 0

  public constructor(private readonly heartbeatPath: string, private readonly isActive: () => Promise<boolean>) {}

  /**
   * Write to the heartbeat file if we haven't already done so within the
   * timeout and start or reset a timer that keeps running as long as there is
   * activity. Failures are logged as warnings.
   */
  public beat(): void {
    const now = Date.now()
    if (now - this.lastHeartbeat >= this.heartbeatInterval) {
      logger.trace("heartbeat")
      fs.outputFile(this.heartbeatPath, "").catch((error) => {
        logger.warn(error.message)
      })
      this.lastHeartbeat = now
      if (typeof this.heartbeatTimer !== "undefined") {
        clearTimeout(this.heartbeatTimer)
      }
      this.heartbeatTimer = setTimeout(() => {
A
Asher 已提交
367 368 369 370 371 372 373 374 375
        this.isActive()
          .then((active) => {
            if (active) {
              this.beat()
            }
          })
          .catch((error) => {
            logger.warn(error.message)
          })
A
Asher 已提交
376 377 378 379 380
      }, this.heartbeatInterval)
    }
  }
}

A
Asher 已提交
381 382 383 384 385 386 387 388
export interface HttpProvider0<T> {
  new (options: HttpProviderOptions): T
}

export interface HttpProvider1<A1, T> {
  new (options: HttpProviderOptions, a1: A1): T
}

A
Asher 已提交
389 390 391 392
export interface HttpProvider2<A1, A2, T> {
  new (options: HttpProviderOptions, a1: A1, a2: A2): T
}

393 394 395 396
export interface HttpProvider3<A1, A2, A3, T> {
  new (options: HttpProviderOptions, a1: A1, a2: A2, a3: A3): T
}

A
Asher 已提交
397 398 399 400 401 402 403 404 405 406 407
/**
 * An HTTP server. Its main role is to route incoming HTTP requests to the
 * appropriate provider for that endpoint then write out the response. It also
 * covers some common use cases like redirects and caching.
 */
export class HttpServer {
  protected readonly server: http.Server | https.Server
  private listenPromise: Promise<string | null> | undefined
  public readonly protocol: "http" | "https"
  private readonly providers = new Map<string, HttpProvider>()
  private readonly heart: Heart
A
Asher 已提交
408
  private readonly socketProvider = new SocketProxyProvider()
A
Asher 已提交
409

A
Asher 已提交
410
  public constructor(private readonly options: HttpServerOptions) {
A
Asher 已提交
411 412 413 414 415 416 417 418 419 420 421 422
    this.heart = new Heart(path.join(xdgLocalDir, "heartbeat"), async () => {
      const connections = await this.getConnections()
      logger.trace(`${connections} active connection${plural(connections)}`)
      return connections !== 0
    })
    this.protocol = this.options.cert ? "https" : "http"
    if (this.protocol === "https") {
      this.server = httpolyglot.createServer(
        {
          cert: this.options.cert && fs.readFileSync(this.options.cert),
          key: this.options.certKey && fs.readFileSync(this.options.certKey),
        },
A
Anmol Sethi 已提交
423
        this.onRequest,
A
Asher 已提交
424 425 426 427 428 429 430
      )
    } else {
      this.server = http.createServer(this.onRequest)
    }
  }

  public dispose(): void {
A
Asher 已提交
431
    this.socketProvider.stop()
A
Asher 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445
    this.providers.forEach((p) => p.dispose())
  }

  public async getConnections(): Promise<number> {
    return new Promise((resolve, reject) => {
      this.server.getConnections((error, count) => {
        return error ? reject(error) : resolve(count)
      })
    })
  }

  /**
   * Register a provider for a top-level endpoint.
   */
A
Asher 已提交
446 447
  public registerHttpProvider<T extends HttpProvider>(endpoint: string, provider: HttpProvider0<T>): T
  public registerHttpProvider<A1, T extends HttpProvider>(endpoint: string, provider: HttpProvider1<A1, T>, a1: A1): T
A
Asher 已提交
448 449 450 451
  public registerHttpProvider<A1, A2, T extends HttpProvider>(
    endpoint: string,
    provider: HttpProvider2<A1, A2, T>,
    a1: A1,
452
    a2: A2,
A
Asher 已提交
453
  ): T
454 455 456 457 458 459 460
  public registerHttpProvider<A1, A2, A3, T extends HttpProvider>(
    endpoint: string,
    provider: HttpProvider3<A1, A2, A3, T>,
    a1: A1,
    a2: A2,
    a3: A3,
  ): T
A
Asher 已提交
461
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
A
Asher 已提交
462
  public registerHttpProvider(endpoint: string, provider: any, ...args: any[]): any {
A
Asher 已提交
463 464 465 466 467 468 469
    endpoint = endpoint.replace(/^\/+|\/+$/g, "")
    if (this.providers.has(`/${endpoint}`)) {
      throw new Error(`${endpoint} is already registered`)
    }
    if (/\//.test(endpoint)) {
      throw new Error(`Only top-level endpoints are supported (got ${endpoint})`)
    }
A
Asher 已提交
470 471 472 473 474 475 476
    const p = new provider(
      {
        auth: this.options.auth || AuthType.None,
        base: `/${endpoint}`,
        commit: this.options.commit,
        password: this.options.password,
      },
477
      ...args,
A
Asher 已提交
478
    )
A
Asher 已提交
479 480
    this.providers.set(`/${endpoint}`, p)
    return p
A
Asher 已提交
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
  }

  /**
   * Start listening on the specified port.
   */
  public listen(): Promise<string | null> {
    if (!this.listenPromise) {
      this.listenPromise = new Promise((resolve, reject) => {
        this.server.on("error", reject)
        this.server.on("upgrade", this.onUpgrade)
        const onListen = (): void => resolve(this.address())
        if (this.options.socket) {
          this.server.listen(this.options.socket, onListen)
        } else {
          this.server.listen(this.options.port, this.options.host, onListen)
        }
      })
    }
    return this.listenPromise
  }

  /**
   * The *local* address of the server.
   */
  public address(): string | null {
    const address = this.server.address()
    const endpoint =
      typeof address !== "string" && address !== null
        ? (address.address === "::" ? "localhost" : address.address) + ":" + address.port
        : address
    return endpoint && `${this.protocol}://${endpoint}`
  }

  private onRequest = async (request: http.IncomingMessage, response: http.ServerResponse): Promise<void> => {
A
Asher 已提交
515 516
    this.heart.beat()
    const route = this.parseUrl(request)
A
Asher 已提交
517
    try {
A
Asher 已提交
518
      const payload = this.maybeRedirect(request, route) || (await route.provider.handleRequest(route, request))
A
Asher 已提交
519 520
      response.writeHead(payload.redirect ? HttpCode.Redirect : payload.code || HttpCode.Ok, {
        "Content-Type": payload.mime || getMediaMime(payload.filePath),
A
Asher 已提交
521
        ...(payload.redirect ? { Location: this.constructRedirect(request, route, payload as RedirectResponse) } : {}),
A
Asher 已提交
522
        ...(request.headers["service-worker"] ? { "Service-Worker-Allowed": route.provider.base(route) } : {}),
A
Asher 已提交
523 524 525
        ...(payload.cache ? { "Cache-Control": "public, max-age=31536000" } : {}),
        ...(payload.cookie
          ? {
A
Asher 已提交
526 527 528 529 530 531
              "Set-Cookie": [
                `${payload.cookie.key}=${payload.cookie.value}`,
                `Path=${normalize(payload.cookie.path || "/", true)}`,
                "HttpOnly",
                "SameSite=strict",
              ].join(";"),
A
Asher 已提交
532 533 534 535 536 537 538 539 540
            }
          : {}),
        ...payload.headers,
      })
      if (payload.stream) {
        payload.stream.on("error", (error: NodeJS.ErrnoException) => {
          response.writeHead(error.code === "ENOENT" ? HttpCode.NotFound : HttpCode.ServerError)
          response.end(error.message)
        })
541
        payload.stream.on("close", () => response.end())
A
Asher 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554
        payload.stream.pipe(response)
      } else if (typeof payload.content === "string" || payload.content instanceof Buffer) {
        response.end(payload.content)
      } else if (payload.content && typeof payload.content === "object") {
        response.end(JSON.stringify(payload.content))
      } else {
        response.end()
      }
    } catch (error) {
      let e = error
      if (error.code === "ENOENT" || error.code === "EISDIR") {
        e = new HttpError("Not found", HttpCode.NotFound)
      }
A
Asher 已提交
555
      logger.debug("Request error", field("url", request.url))
A
Asher 已提交
556
      logger.debug(error.stack)
A
Asher 已提交
557 558 559 560
      const code = typeof e.code === "number" ? e.code : HttpCode.ServerError
      const content = (await route.provider.getErrorRoot(route, code, code, e.message)).content
      response.writeHead(code)
      response.end(content)
A
Asher 已提交
561 562 563 564 565 566
    }
  }

  /**
   * Return any necessary redirection before delegating to a provider.
   */
A
Asher 已提交
567 568
  private maybeRedirect(request: http.IncomingMessage, route: ProviderRoute): RedirectResponse | undefined {
    // If we're handling TLS ensure all requests are redirected to HTTPS.
A
Asher 已提交
569
    if (this.options.cert && !(request.connection as tls.TLSSocket).encrypted) {
A
Asher 已提交
570
      return { redirect: route.fullPath }
A
Asher 已提交
571
    }
A
Asher 已提交
572

A
Asher 已提交
573 574 575
    return undefined
  }

A
Asher 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
  /**
   * Given a path that goes from the base, construct a relative redirect URL
   * that will get you there considering that the app may be served from an
   * unknown base path. If handling TLS, also ensure HTTPS.
   */
  private constructRedirect(request: http.IncomingMessage, route: ProviderRoute, payload: RedirectResponse): string {
    const query = {
      ...route.query,
      ...(payload.query || {}),
    }

    Object.keys(query).forEach((key) => {
      if (typeof query[key] === "undefined") {
        delete query[key]
      }
    })

A
Asher 已提交
593 594 595
    const secure = (request.connection as tls.TLSSocket).encrypted
    const redirect =
      (this.options.cert && !secure ? `${this.protocol}://${request.headers.host}/` : "") +
A
Asher 已提交
596 597
      normalize(`${route.provider.base(route)}/${payload.redirect}`, true) +
      (Object.keys(query).length > 0 ? `?${querystring.stringify(query)}` : "")
A
Asher 已提交
598 599
    logger.debug("Redirecting", field("secure", !!secure), field("from", request.url), field("to", redirect))
    return redirect
A
Asher 已提交
600 601
  }

A
Asher 已提交
602 603 604 605 606 607 608 609 610 611 612 613 614
  private onUpgrade = async (request: http.IncomingMessage, socket: net.Socket, head: Buffer): Promise<void> => {
    try {
      this.heart.beat()
      socket.on("error", () => socket.destroy())

      if (this.options.cert && !(socket as tls.TLSSocket).encrypted) {
        throw new HttpError("HTTP websocket", HttpCode.BadRequest)
      }

      if (!request.headers.upgrade || request.headers.upgrade.toLowerCase() !== "websocket") {
        throw new HttpError("HTTP/1.1 400 Bad Request", HttpCode.BadRequest)
      }

A
Asher 已提交
615 616
      const route = this.parseUrl(request)
      if (!route.provider) {
A
Asher 已提交
617 618 619
        throw new HttpError("Not found", HttpCode.NotFound)
      }

A
Asher 已提交
620
      await route.provider.handleWebSocket(route, request, await this.socketProvider.createProxy(socket), head)
A
Asher 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    } catch (error) {
      socket.destroy(error)
      logger.warn(`discarding socket connection: ${error.message}`)
    }
  }

  /**
   * Parse a request URL so we can route it.
   */
  private parseUrl(request: http.IncomingMessage): ProviderRoute {
    const parse = (fullPath: string): { base: string; requestPath: string } => {
      const match = fullPath.match(/^(\/?[^/]*)(.*)$/)
      let [, /* ignore */ base, requestPath] = match ? match.map((p) => p.replace(/\/+$/, "")) : ["", "", ""]
      if (base.indexOf(".") !== -1) {
        // Assume it's a file at the root.
        requestPath = base
        base = "/"
      } else if (base === "") {
        // Happens if it's a plain `domain.com`.
        base = "/"
      }
      requestPath = requestPath || "/index.html"
      return { base, requestPath }
    }

    const parsedUrl = request.url ? url.parse(request.url, true) : { query: {}, pathname: "" }
A
Asher 已提交
647
    const originalPath = parsedUrl.pathname || "/"
A
Asher 已提交
648
    const fullPath = normalize(originalPath, true)
A
Asher 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    const { base, requestPath } = parse(fullPath)

    // Providers match on the path after their base so we need to account for
    // that by shifting the next base out of the request path.
    let provider = this.providers.get(base)
    if (base !== "/" && provider) {
      return { ...parse(requestPath), fullPath, query: parsedUrl.query, provider, originalPath }
    }

    // Fall back to the top-level provider.
    provider = this.providers.get("/")
    if (!provider) {
      throw new Error(`No provider for ${base}`)
    }
    return { base, fullPath, requestPath, query: parsedUrl.query, provider, originalPath }
  }
}