summaryrefslogtreecommitdiff
path: root/runtime/ops/http.rs
blob: 7a58da3612342e7e1fdad02d702ec0d7c00e9fcd (plain)
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
use std::cell::RefCell;
use std::rc::Rc;

use deno_core::error::bad_resource_id;
use deno_core::error::custom_error;
use deno_core::error::AnyError;
use deno_core::op;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::RcRef;
use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
use deno_http::http_create_conn_resource;
use deno_http::HttpRequestReader;
use deno_http::HttpStreamResource;
use deno_net::io::TcpStreamResource;
use deno_net::ops_tls::TlsStream;
use deno_net::ops_tls::TlsStreamResource;
use hyper::upgrade::Parts;
use serde::Serialize;
use tokio::net::TcpStream;

#[cfg(unix)]
use deno_net::io::UnixStreamResource;
#[cfg(unix)]
use tokio::net::UnixStream;

pub fn init() -> Extension {
  Extension::builder()
    .ops(vec![
      op_http_start::decl(),
      op_http_upgrade::decl(),
      op_flash_upgrade_http::decl(),
    ])
    .build()
}

#[op]
fn op_http_start(
  state: &mut OpState,
  tcp_stream_rid: ResourceId,
) -> Result<ResourceId, AnyError> {
  if let Ok(resource_rc) = state
    .resource_table
    .take::<TcpStreamResource>(tcp_stream_rid)
  {
    let resource = Rc::try_unwrap(resource_rc)
      .expect("Only a single use of this resource should happen");
    let (read_half, write_half) = resource.into_inner();
    let tcp_stream = read_half.reunite(write_half)?;
    let addr = tcp_stream.local_addr()?;
    return http_create_conn_resource(state, tcp_stream, addr, "http");
  }

  if let Ok(resource_rc) = state
    .resource_table
    .take::<TlsStreamResource>(tcp_stream_rid)
  {
    let resource = Rc::try_unwrap(resource_rc)
      .expect("Only a single use of this resource should happen");
    let (read_half, write_half) = resource.into_inner();
    let tls_stream = read_half.reunite(write_half);
    let addr = tls_stream.get_ref().0.local_addr()?;
    return http_create_conn_resource(state, tls_stream, addr, "https");
  }

  #[cfg(unix)]
  if let Ok(resource_rc) = state
    .resource_table
    .take::<deno_net::io::UnixStreamResource>(tcp_stream_rid)
  {
    super::check_unstable(state, "Deno.serveHttp");

    let resource = Rc::try_unwrap(resource_rc)
      .expect("Only a single use of this resource should happen");
    let (read_half, write_half) = resource.into_inner();
    let unix_stream = read_half.reunite(write_half)?;
    let addr = unix_stream.local_addr()?;
    return http_create_conn_resource(state, unix_stream, addr, "http+unix");
  }

  Err(bad_resource_id())
}

#[op]
fn op_flash_upgrade_http(
  state: &mut OpState,
  token: u32,
  server_id: u32,
) -> Result<deno_core::ResourceId, AnyError> {
  let flash_ctx = state.borrow_mut::<deno_flash::FlashContext>();
  let ctx = flash_ctx.servers.get_mut(&server_id).unwrap();

  let tcp_stream = deno_flash::detach_socket(ctx, token)?;
  Ok(
    state
      .resource_table
      .add(TcpStreamResource::new(tcp_stream.into_split())),
  )
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HttpUpgradeResult {
  conn_rid: ResourceId,
  conn_type: &'static str,
  read_buf: ZeroCopyBuf,
}

#[op]
async fn op_http_upgrade(
  state: Rc<RefCell<OpState>>,
  rid: ResourceId,
  _: (),
) -> Result<HttpUpgradeResult, AnyError> {
  let stream = state
    .borrow_mut()
    .resource_table
    .get::<HttpStreamResource>(rid)?;
  let mut rd = RcRef::map(&stream, |r| &r.rd).borrow_mut().await;

  let request = match &mut *rd {
    HttpRequestReader::Headers(request) => request,
    _ => {
      return Err(custom_error(
        "Http",
        "cannot upgrade because request body was used",
      ))
    }
  };

  let transport = hyper::upgrade::on(request).await?;
  let transport = match transport.downcast::<TcpStream>() {
    Ok(Parts {
      io: tcp_stream,
      read_buf,
      ..
    }) => {
      return Ok(HttpUpgradeResult {
        conn_type: "tcp",
        conn_rid: state
          .borrow_mut()
          .resource_table
          .add(TcpStreamResource::new(tcp_stream.into_split())),
        read_buf: read_buf.to_vec().into(),
      });
    }
    Err(transport) => transport,
  };
  #[cfg(unix)]
  let transport = match transport.downcast::<UnixStream>() {
    Ok(Parts {
      io: unix_stream,
      read_buf,
      ..
    }) => {
      return Ok(HttpUpgradeResult {
        conn_type: "unix",
        conn_rid: state
          .borrow_mut()
          .resource_table
          .add(UnixStreamResource::new(unix_stream.into_split())),
        read_buf: read_buf.to_vec().into(),
      });
    }
    Err(transport) => transport,
  };
  match transport.downcast::<TlsStream>() {
    Ok(Parts {
      io: tls_stream,
      read_buf,
      ..
    }) => Ok(HttpUpgradeResult {
      conn_type: "tls",
      conn_rid: state
        .borrow_mut()
        .resource_table
        .add(TlsStreamResource::new(tls_stream.into_split())),
      read_buf: read_buf.to_vec().into(),
    }),
    Err(_) => Err(custom_error(
      "Http",
      "encountered unsupported transport while upgrading",
    )),
  }
}