File size: 7,319 Bytes
9552aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use hyper::body::{Buf, Bytes};
use tokio_util::bytes::BytesMut;
use tokio_util::codec::Decoder;

#[derive(Debug)]
pub enum FcgiDecodedData {
  Stdout(Bytes),
  Stderr(Bytes),
}

enum FcgiDecodeState {
  ReadingHead,
  ReadingContent,
  Finished,
}

pub struct FcgiDecoder {
  header: Vec<u8>,
  content_length: u16,
  padding_length: u8,
  state: FcgiDecodeState,
}

impl FcgiDecoder {
  pub fn new() -> Self {
    Self {
      header: Vec::new(),
      content_length: 0,
      padding_length: 0,
      state: FcgiDecodeState::ReadingHead,
    }
  }
}

impl Decoder for FcgiDecoder {
  type Error = std::io::Error;
  type Item = FcgiDecodedData;

  fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
    loop {
      match self.state {
        FcgiDecodeState::ReadingHead => {
          if src.len() >= 8 {
            let header = &src[..8];
            self.header = header.to_vec();
            src.advance(8);
            self.content_length = u16::from_be_bytes(
              self.header[4..6]
                .try_into()
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?,
            );
            self.padding_length = self.header[6];
            self.state = FcgiDecodeState::ReadingContent;
          } else {
            return Ok(None);
          }
        }
        FcgiDecodeState::ReadingContent => {
          if src.len() >= self.content_length as usize + self.padding_length as usize {
            let request_id = u16::from_be_bytes(
              self.header[2..4]
                .try_into()
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?,
            );
            let record_type = self.header[1];
            if request_id != 1 || (record_type != 3 && record_type != 6 && record_type != 7) {
              // Ignore the record for wrong request ID or if the record isn't END_REQUEST, STDOUT or STDERR
              src.advance(self.content_length as usize + self.padding_length as usize);
              return Ok(None);
            }
            let content_borrowed = &src[..(self.content_length as usize)];
            let content = content_borrowed.to_vec();
            src.advance(self.content_length as usize + self.padding_length as usize);

            match record_type {
              3 => {
                // END_REQUEST record
                if content.len() > 5 {
                  let app_status = u32::from_be_bytes(
                    content[0..4]
                      .try_into()
                      .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?,
                  );
                  let protocol_status = content[4];
                  match protocol_status {
                    0 => (),
                    1 => return Err(std::io::Error::other("FastCGI server overloaded")),
                    2 => {
                      return Err(std::io::Error::other(
                        "Role not supported by the FastCGI application",
                      ))
                    }
                    3 => {
                      return Err(std::io::Error::other(
                        "Multiplexed connections not supported by the FastCGI application",
                      ))
                    }
                    _ => return Err(std::io::Error::other("Unknown error")),
                  }

                  self.state = FcgiDecodeState::Finished;
                  if app_status != 0 {
                    // Inject data into standard error stream
                    return Ok(Some(FcgiDecodedData::Stderr(Bytes::from_owner(format!(
                      "FastCGI application exited with code {}",
                      app_status
                    )))));
                  }
                } else {
                  // Record malformed, ignoring the record
                  return Ok(None);
                }
              }
              6 => {
                // STDOUT record
                self.state = FcgiDecodeState::ReadingHead;
                if content.is_empty() {
                  return Ok(None);
                }
                return Ok(Some(FcgiDecodedData::Stdout(Bytes::from_owner(content))));
              }
              7 => {
                // STDERR record
                self.state = FcgiDecodeState::ReadingHead;
                if content.is_empty() {
                  return Ok(None);
                }
                return Ok(Some(FcgiDecodedData::Stderr(Bytes::from_owner(content))));
              }
              _ => {
                // This should be unreachable
                unreachable!()
              }
            };
          } else {
            return Ok(None);
          }
        }
        FcgiDecodeState::Finished => {
          src.clear();
          return Ok(None);
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::ferron_util::fcgi_record::construct_fastcgi_record;
  use tokio_util::bytes::BytesMut;
  use tokio_util::codec::Decoder;

  #[test]
  fn test_fcgi_decoder_stdout() {
    let mut decoder = FcgiDecoder::new();
    let mut buf = BytesMut::new();

    // Construct a STDOUT record
    let record_type = 6;
    let request_id = 1;
    let content = b"Hello, FastCGI!";
    let record = construct_fastcgi_record(record_type, request_id, content);

    buf.extend_from_slice(&record);

    let result = decoder.decode(&mut buf).unwrap();
    assert!(result.is_some());
    if let Some(FcgiDecodedData::Stdout(data)) = result {
      assert_eq!(&data[..], content);
    } else {
      panic!("Expected STDOUT data");
    }
  }

  #[test]
  fn test_fcgi_decoder_stderr() {
    let mut decoder = FcgiDecoder::new();
    let mut buf = BytesMut::new();

    // Construct a STDERR record
    let record_type = 7;
    let request_id = 1;
    let content = b"Error message";
    let record = construct_fastcgi_record(record_type, request_id, content);

    buf.extend_from_slice(&record);

    let result = decoder.decode(&mut buf).unwrap();
    assert!(result.is_some());
    if let Some(FcgiDecodedData::Stderr(data)) = result {
      assert_eq!(&data[..], content);
    } else {
      panic!("Expected STDERR data");
    }
  }

  #[test]
  fn test_fcgi_decoder_end_request() {
    let mut decoder = FcgiDecoder::new();
    let mut buf = BytesMut::new();

    // Construct an END_REQUEST record
    let record_type = 3;
    let request_id = 1;
    let mut content = [0u8; 4].to_vec(); // App status
    content.push(0); // Protocol status
    let record = construct_fastcgi_record(record_type, request_id, &content);

    buf.extend_from_slice(&record);

    let result = decoder.decode(&mut buf).unwrap();
    assert!(result.is_none()); // No data for END_REQUEST
  }

  #[test]
  fn test_fcgi_decoder_invalid_record() {
    let mut decoder = FcgiDecoder::new();
    let mut buf = BytesMut::new();

    // Construct an invalid record with wrong request ID
    let record_type = 6;
    let request_id = 2; // Invalid request ID
    let content = b"Invalid record";
    let record = construct_fastcgi_record(record_type, request_id, content);

    buf.extend_from_slice(&record);

    let result = decoder.decode(&mut buf).unwrap();
    assert!(result.is_none()); // Invalid record should be ignored
  }
}