rustweb2 1.1.53

Rust-based web server
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
use crate::share::{Error, SharedState, Trans, U_COUNT, U_CPU, U_READ, U_WRITE, UseInfo};
use rustdb::alloc::{GBTreeMap, GString, GTemp, GVec, Perm};
use rustdb::gentrans::GenQuery;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// Process http request.
pub async fn process(
    mut stream: tokio::net::TcpStream,
    ip: String,
    ss: Arc<SharedState>,
) -> Result<(), Box<dyn std::error::Error>> {
    let (r, mut w) = stream.split();
    let mut r = Buffer::new(r, ss.clone(), ip);

    let h = Headers::get(&mut r).await;

    let h = match h {
        Ok(h) => h,
        Err(e) => {
            if e.code == 0 {
                return Ok(());
            }
            return Err(e)?;
        }
    };

    let (hdrs, outp) = {
        let mut t = Trans::new_with_state(ss.clone(), r.uid.clone());
        let readonly =
            h.method == b"GET" && !h.args.contains_key("save") || h.args.contains_key("readonly");

        t.x.qy.path = h.path;
        t.x.qy.params = h.args;
        t.x.qy.cookies = h.cookies;
        let (ct, clen) = (&h.content_type, h.content_length);

        // Set limits based on login info etc.
        t.readonly = true;
        let save = t.x.qy.sql.clone();
        t.x.qy.sql = Arc::new("EXEC web.SetUser()".to_string());
        t = ss.process(t).await;
        t.x.qy.sql = save;
        r.u.limit = ss.u_budget(t.uid.clone());
        t.readonly = false;

        if ct.is_empty() {
            // No body.
        } else if ct == b"application/x-www-form-urlencoded" {
            let clen: usize = clen.parse()?;
            let bytes = r.read(clen).await?;
            t.x.qy.form = serde_urlencoded::from_bytes(&bytes)?;
            // let pairs = std::str::from_utf8(&bytes)?;
            // decode_pairs(&pairs, &mut t.x.qy.form );
        } else if is_multipart(ct) {
            get_multipart(&mut r, &mut t.x.qy).await?;
        } else {
            t.x.rp.status_code = 501;
        }
        r.read_complete();

        if t.x.rp.status_code == 200 {
            t.readonly = readonly;
            t = ss.process(t).await;
            r.uid = t.uid.clone();
            r.u.used[U_CPU] = t.run_time.as_micros() as u64;
            if ss.tracetime {
                println!(
                    "run time={}µs updates={} readonly={} path={} args={:?}",
                    t.run_time.as_micros(),
                    t.updates,
                    readonly,
                    t.x.qy.path,
                    t.x.qy.params,
                );
            }
            if ss.tracemem {
                let s = ss.spd.stash.lock().unwrap();
                println!(
                    "stash limit={}K used={}K free={}K pages={} cached={} read={} misses={} allocs={}",
                    s.mem_limit / 1024,
                    s.total / 1024,
                    (s.mem_limit as i64 - s.total) / 1024,
                    s.pages.len(),
                    s.cached(),
                    s.read,
                    s.miss,
                    Perm::alloc_count()
                );
                println!("Perm::info = {:?}", Perm::info());
                println!("GTemp::info = {:?}", GTemp::info());
            }
        }
        (header(&t), t.x.rp.output)
    };

    let budget = r.u.limit[U_WRITE];
    write(&mut w, &hdrs, budget, &mut r.u.used[U_WRITE]).await?;
    write(&mut w, &outp, budget, &mut r.u.used[U_WRITE]).await?;
    Ok(())
}

/// Get response header.
fn header(t: &Trans) -> Vec<u8> {
    let mut h = Vec::with_capacity(4096);
    let status_line = format!("HTTP/1.1 {}\r\n", t.x.rp.status_code);
    h.extend_from_slice(status_line.as_bytes());
    for (name, value) in &t.x.rp.headers {
        h.extend_from_slice(name.as_bytes());
        h.push(b':');
        h.extend_from_slice(value.as_bytes());
        h.push(13);
        h.push(10);
    }
    let clen = t.x.rp.output.len();
    let x = format!("Content-Length: {clen}\r\n\r\n");
    h.extend_from_slice(x.as_bytes());
    h
}

/// Header parsing.
#[derive(Default)]
struct Headers {
    method: GVec<u8>,
    path: GString,
    args: GBTreeMap<GString, GString>,
    host: GString,
    cookies: GBTreeMap<GString, GString>,

    content_type: GVec<u8>,
    content_length: GString,
}

impl Headers {
    async fn get<'a>(br: &mut Buffer<'a>) -> Result<Headers, Error> {
        let mut r = Self::default();
        br.read_until(b' ', &mut r.method).await?;
        r.method.pop(); // Remove trailing space.

        let mut pq = GVec::new(); // Path and Query string.
        br.read_until(b' ', &mut pq).await?;
        pq.pop(); // Remove trailing space.
        r.split_pq(&pq)?;

        let mut protocol = GVec::new();
        br.read_until(b'\n', &mut protocol).await?;

        let mut line0 = GVec::new();
        loop {
            let n = br.read_until(b'\n', &mut line0).await?;
            if n <= 2 {
                break;
            }
            let line = &line0[0..n - 2];
            if line.len() >= 2 {
                let b0 = lower(line[0]);
                let b2 = lower(line[2]);
                match (b0, b2) {
                    (b'c', b'o') => {
                        if let Some(line) = line_is(line, b"cookie") {
                            r.cookies = cookie_map(line)?;
                        }
                    }
                    (b'c', b'n') => {
                        if let Some(line) = line_is(line, b"content-type") {
                            r.content_type = GVec::from(line);
                        } else if let Some(line) = line_is(line, b"content-length") {
                            r.content_length = togs(line)?;
                        }
                    }
                    (b'h', b's') => {
                        if let Some(line) = line_is(line, b"host") {
                            r.host = togs(line)?;
                        }
                    }
                    (b'x', b'r') => {
                        if let Some(line) = line_is(line, b"x-real-ip") {
                            let ip = tos(line)?;
                            br.u.limit = br.ss.u_budget(ip.clone());
                            br.uid = ip;
                            if br.u.limit[U_COUNT] == 0 {
                                return Err(tmr());
                            }
                        }
                    }
                    _ => {}
                }
            }
            line0.clear();
        }
        Ok(r)
    }

    /// Split the path and args by finding '?'.
    fn split_pq(&mut self, pq: &[u8]) -> Result<(), Error> {
        let n = pq.len();
        let mut i = 0;
        let mut q = n;
        while i < n {
            if pq[i] == b'?' {
                q = i;
                break;
            }
            i += 1;
        }
        self.path = togs(&pq[0..q])?;
        if q != n {
            q += 1;
        }
        let qs = &pq[q..n];

        self.args = serde_urlencoded::from_bytes(qs)?;

        // let qs = std::str::from_utf8(qs)?;
        // decode_pairs( qs, &mut self.args );

        Ok(())
    }
}

/* Manual method rather than using serde_urlencoded ( not working..! )
fn decode_pairs( s: &str, map: &mut GBTreeMap<GString,GString> ) {
    for kp in s.split('&') {
        if let Some(p) = kp.find('=') {
            let k = &kp[0..p];
            let v = &kp[p+1..];
            if let Ok(v) = urlencoding::decode(v) {
                let k = GString::from_str(k);
                let v = GString::from_str(&v);
                map.insert(k,v);
            }
        }
    }
}
*/

/// Check whether current line is named header.
fn line_is<'a>(line: &'a [u8], name: &[u8]) -> Option<&'a [u8]> {
    let n = name.len();
    if line.len() < n + 1 {
        return None;
    }
    if line[n] != b':' {
        return None;
    }
    for i in 0..n {
        if lower(line[i]) != name[i] {
            return None;
        }
    }
    let mut skip = n + 1;
    let n = line.len();
    while skip < n && line[skip] == b' ' {
        skip += 1;
    }
    Some(&line[skip..n])
}

/// Map upper case char to lower case.
fn lower(mut b: u8) -> u8 {
    if b.is_ascii_uppercase() {
        b += 32;
    }
    b
}

fn togs(s: &[u8]) -> Result<GString, Error> {
    Ok(GString::from_str(std::str::from_utf8(s)?))
}

/// Convert byte slice into string.
fn tos(s: &[u8]) -> Result<String, Error> {
    Ok(std::str::from_utf8(s)?.to_string())
}

/// Not enough input.
fn eof() -> Error {
    Error { code: 0 }
}

/// Too many requests.
fn tmr() -> Error {
    Error { code: 429 }
}

/// Some other error.
fn bad() -> Error {
    Error { code: 400 }
}

/// Parse cookie header to a map of cookies.
fn cookie_map(s: &[u8]) -> Result<GBTreeMap<GString, GString>, Error> {
    let mut map = GBTreeMap::new();
    let n = s.len();
    let mut i = 0;

    while i < n {
        while i < n && s[i] == b' ' {
            i += 1;
        }
        let start = i;
        while i < n && s[i] != b'=' {
            i += 1;
        }
        let name = togs(&s[start..i])?;
        if i < n {
            i += 1;
        }
        let start = i;
        while i < n && s[i] != b';' {
            i += 1;
        }
        let value = togs(&s[start..i])?;
        i += 1;
        map.insert(name, value);
    }
    Ok(map)
}

/// Check content-type is multipart.
fn is_multipart(s: &[u8]) -> bool {
    let temp = b"multipart/form-data";
    let n = temp.len();
    s.len() >= n && temp == &s[0..n]
}

/// Extract name and file_name from content-disposition header.
fn split_cd(s: &[u8]) -> Option<(GString, GString)> {
    /* Expected input:
       form-data; name="file"; filename="logo.png"
    */
    if let Ok(s) = std::str::from_utf8(s) {
        let s = "multipart/".to_string() + s;
        let (mut name, mut filename) = ("", "");
        let m: mime::Mime = s.parse().ok()?;
        if m.subtype() != mime::FORM_DATA {
            return None;
        }
        if let Some(n) = m.get_param("name") {
            name = n.as_str()
        }
        if let Some(n) = m.get_param("filename") {
            filename = n.as_str()
        }
        Some((GString::from_str(name), GString::from_str(filename)))
    } else {
        None
    }
}

/*
Parts are delimited by boundary lines.
Each boundary line starts with --
The final boundary line has an extra --
Each part has headers, typically Content-Disposition and Content-Type.
Example:
------WebKitFormBoundaryAhgB6VordnzCD84Z
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream


------WebKitFormBoundaryAhgB6VordnzCD84Z
Content-Disposition: form-data; name="submit"

Upload
------WebKitFormBoundaryAhgB6VordnzCD84Z--
*/

use rustdb::Part;

/// Parse multipart body.
async fn get_multipart<'a>(br: &mut Buffer<'a>, q: &mut GenQuery) -> Result<(), Error> {
    let mut boundary = GVec::new();
    let n = br.read_until(10, &mut boundary).await?;
    if n < 4 {
        return Err(eof())?;
    }

    let bn = boundary.len() - 2;
    boundary.truncate(bn);

    let mut got_last = false;
    while !got_last {
        let mut part = Part::default();
        // Read headers
        let mut line0 = GVec::new();
        loop {
            let n = br.read_until(10, &mut line0).await?;
            if n <= 2 {
                break;
            }
            let line = &line0[0..n - 2];
            if let Some(line) = line_is(line, b"content-type") {
                part.content_type = togs(line)?;
                // Note: if part content-type is multipart, maybe it should be parsed.
            } else if let Some(line) = line_is(line, b"content-disposition")
                && let Some((name, file_name)) = split_cd(line)
            {
                part.name = name;
                part.file_name = file_name;
            }
            line0.clear();
        }
        // Read lines into data looking for boundary.
        let mut data = GVec::new();
        loop {
            let n = br.read_until(10, &mut data).await?;
            if n == bn + 2 || n == bn + 4 {
                let start = data.len() - n;
                if data[start..start + bn] == *boundary {
                    got_last = n == bn + 4;
                    data.truncate(start - 2);
                    break;
                }
            }
        }
        if part.content_type.is_empty() {
            let value = togs(&data)?;
            q.form.insert(part.name, value);
        } else {
            part.data = Arc::new(data);
            q.parts.push(part);
        }
    }
    Ok(())
}

/// Buffer size.
const BUFFER_SIZE: usize = 2048;

/// Buffer for reading tcp input stream, with budget check.
struct Buffer<'a> {
    stream: tokio::net::tcp::ReadHalf<'a>,
    buf: [u8; BUFFER_SIZE],
    i: usize,
    n: usize,
    total: u64,
    u: UseInfo,
    timer: std::time::SystemTime,
    ss: Arc<SharedState>,
    uid: String,
}

impl<'a> Drop for Buffer<'a> {
    fn drop(&mut self) {
        self.read_complete();
        self.ss.u_inc(&self.uid, self.u.used);
    }
}

impl<'a> Buffer<'a> {
    /// Create a new Buffer.
    fn new(stream: tokio::net::tcp::ReadHalf<'a>, ss: Arc<SharedState>, uid: String) -> Self {
        let limit = ss.u_budget(uid.clone());
        let mut result = Self {
            stream,
            buf: [0; 2048],
            i: 0,
            n: 0,
            total: 0,
            timer: std::time::SystemTime::now(),
            ss,
            u: UseInfo::default(),
            uid,
        };
        result.u.used[U_COUNT] = 1;
        result.u.limit = limit;
        result
    }

    /// Update used read counter based on total bytes read (KB) and elapsed time (milli-seconds).
    fn read_complete(&mut self) {
        if self.total != 0 {
            let elapsed = 1 + self.timer.elapsed().unwrap().as_millis() as u64;
            self.u.used[U_READ] = elapsed * (self.total >> 10);
            self.total = 0;
        }
    }

    /// Fill the buffer. A timeout is set based on the total already read and the buffer size (KB).
    async fn fill(&mut self) -> Result<(), Error> {
        self.i = 0;
        let lim = self.u.limit[U_READ] / ((self.total + BUFFER_SIZE as u64) >> 10);
        let bm = core::time::Duration::from_millis(lim);
        let used = self.timer.elapsed().unwrap();
        if used >= bm {
            return Err(tmr());
        }
        let timeout = bm - used;

        tokio::select! {
            _ = tokio::time::sleep(timeout) =>
            {
               Err(tmr())?
            }
            rd = self.stream.read(&mut self.buf) =>
            {
                match rd
                {
                   Ok(n) =>
                   {
                     if n == 0 {
                        Err(eof())?
                     }
                     self.n = n;
                     self.total += n as u64;
                   }
                   Err(e) => { Err(e)? }
                }
            }

        }
        Ok(())
    }

    /// Read until delim is found. Returns eof error if input is closed.
    async fn read_until(&mut self, delim: u8, to: &mut GVec<u8>) -> Result<usize, Error> {
        let start = to.len();
        loop {
            if self.i == self.n {
                self.fill().await?;
            }
            let b = self.buf[self.i];
            self.i += 1;
            to.push(b);
            if b == delim {
                return Ok(to.len() - start);
            }
        }
    }

    /// Read specified number of bytes.
    async fn read(&mut self, n: usize) -> Result<GVec<u8>, Error> {
        let mut to = GVec::new();
        loop {
            if self.i == self.n {
                self.fill().await?;
            }
            let b = self.buf[self.i];
            self.i += 1;
            to.push(b);
            if to.len() == n {
                return Ok(to);
            }
        }
    }
}

/// Function to write response, with budget-based timeout.
async fn write<'a>(
    w: &mut tokio::net::tcp::WriteHalf<'a>,
    data: &[u8],
    budget: u64,
    used: &mut u64,
) -> Result<(), Error> {
    let mut result = Ok(());
    if !data.is_empty() {
        let timer = std::time::SystemTime::now();
        let lim = (budget - *used) / ((data.len() >> 10) + 1) as u64;
        let timeout = core::time::Duration::from_millis(lim);
        tokio::select! {
            _ = tokio::time::sleep(timeout) =>
                {
                    result = Err(tmr());
                }
            x = w.write_all(data) =>
                {
                    if let Err(_e) = x { result = Err(bad()); }
                }
        }
        let elapsed = timer.elapsed().unwrap();
        *used += elapsed.as_millis() as u64 * (data.len() as u64 >> 10);
    }
    result
}