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
use axon::CommandExt;
use certificate;
use config::{self, Config};
use endpoint;
use error::Error;
use headers;
use identity;
use osaka::Future;
use osaka::{osaka, Poll};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::Command;

#[cfg(feature = "openwrt")]
pub mod openwrt;
pub mod sft;
pub mod shell;
pub mod sysinfo;
pub mod tcp;
#[cfg(target_os = "android",)]
pub mod android;

pub struct RouteHandler {
    f: Box<dyn Fn(Poll, headers::Headers, &identity::Identity, endpoint::Stream) -> Option<osaka::Task<()>>>,
    max_fragmentation: u32,
}

pub struct PublisherBuilder {
    config:     Config,
    routes:     HashMap<String, RouteHandler>,
    with_axons: bool,
    with_disco: Option<(String, String)>,
}

pub fn new(config: Config) -> PublisherBuilder {
    PublisherBuilder {
        config,
        routes: HashMap::new(),
        with_axons: false,
        with_disco: None,
    }
}

fn newstreamhandler(
    poll: Poll,
    headers: headers::Headers,
    mut stream: endpoint::Stream,
    identity: &identity::Identity,
    auth: &certificate::Authenticator,
    routes: &HashMap<String, RouteHandler>,
    with_axons: bool,
    with_disco: Option<(String, String)>,
) -> Option<(osaka::Task<()>, u32)> {
    let resource = headers
        .path()
        .as_ref()
        .map(|v| String::from_utf8_lossy(v).to_string())
        .unwrap_or(String::from(""));

    if let Err(e) = auth.check(identity, &resource, &Vec::new()) {
        stream.send(headers::Headers::with_error(403, format!("{}", e)).encode());
        return None;
    }

    if let Some(ref v) = routes.get(&resource) {
        return (*v.f)(poll, headers, &identity, stream).map(|f| (f, v.max_fragmentation));
    }

    if with_axons {
        if let Some(exe) = resource.split("/v0/").nth(1) {
            if exe.chars().all(|c| c.is_ascii_alphanumeric()) {
                let exe = format!("carrier-axon-v0-{}", exe);
                if let Ok(path) = which::which(exe) {
                    return Some((axon_exe(poll, headers, stream, path), 0));
                }
            }
        }
    }

    if let Some((application, application_version)) = with_disco {
        if resource == "/v2/carrier.discovery.v1/discover" {
            stream.send(headers::Headers::ok().encode());
            stream.message(super::proto::DiscoveryResponse {
                carrier_revision: super::REVISION,
                carrier_build_id: super::BUILD_ID.into(),
                application,
                application_version,
                paths: routes.keys().cloned().collect(),
            });
            return None;
        }
        if let Some(exe) = resource.split("/v0/").nth(1) {
            if exe.chars().all(|c| c.is_ascii_alphanumeric()) {
                let exe = format!("carrier-axon-v0-{}", exe);
                if let Ok(path) = which::which(exe) {
                    return Some((axon_exe(poll, headers, stream, path), 0));
                }
            }
        }
    }

    stream.send(headers::Headers::with_error(404, "not found").encode());
    None
}

impl PublisherBuilder {
    pub fn route<S: Into<String>, F>(mut self, path: S, max_fragmentation: Option<u32>, f: F) -> Self
    where
        S: Into<String>,
        F: 'static + Fn(Poll, headers::Headers, &identity::Identity, endpoint::Stream) -> Option<osaka::Task<()>>,
    {
        self.routes.insert(
            path.into(),
            RouteHandler {
                f:                 Box::new(f),
                max_fragmentation: max_fragmentation.unwrap_or(0),
            },
        );
        self
    }

    pub fn with_disco(mut self, app: String, version: String) -> Self {
        self.with_disco = Some((app, version));
        self
    }

    pub fn with_axons(mut self) -> Self {
        self.with_axons = true;
        self
    }

    #[osaka]
    pub fn publish(self, poll: Poll) -> Result<(), Error> {
        let mut ep = endpoint::EndpointBuilder::new(&self.config)?.connect(poll.clone());
        let mut ep = osaka::sync!(ep)?;

        let with_axons = self.with_axons;
        let with_disco = self.with_disco;
        let routes: &'static HashMap<String, RouteHandler> = Box::leak(Box::new(self.routes));
        let publish_config = self.config.publish.expect("missing publish section in config");
        ep.publish(publish_config.shadow.clone(), || panic!("publish closed"))?;
        let publish_config: &'static config::PublisherConfig = Box::leak(Box::new(publish_config));

        loop {
            match osaka::sync!(ep)? {
                endpoint::Event::BrokerGone => panic!("broker gone"),
                endpoint::Event::Disconnect { .. } => (),
                endpoint::Event::OutgoingConnect(_) => (),
                endpoint::Event::IncommingConnect(q) => {
                    info!("incomming {}", q.identity);
                    let poll = poll.clone();
                    let identity = q.identity.clone();
                    match publish_config.auth.reject_early(&q.identity, &Vec::new()) {
                        Ok(()) => {
                            let with_disco = with_disco.clone();
                            ep.accept_incomming(q, move |h, s| {
                                newstreamhandler(
                                    poll.clone(),
                                    h,
                                    s,
                                    &identity,
                                    &publish_config.auth,
                                    &routes,
                                    with_axons,
                                    with_disco.clone(),
                                )
                            })
                        }
                        Err(e) => {
                            warn!("rejecting incomming {}: {}", q.identity, e);
                            ep.reject(q, format!("{}", e));
                        }
                    }
                }
            };
        }
    }
}

#[osaka]
pub fn axon_exe(poll: osaka::Poll, headers: headers::Headers, mut stream: endpoint::Stream, exe: PathBuf) {
    info!("executing axon executable {:?}", exe);

    let mut child = Command::new(exe)
        .spawn_with_axon()
        .expect("Failed to start axon process");

    child.io.write(&headers.encode()).ok();
    child.io.make_async().expect("axon io");

    let token1 = poll
        .register(&child.io, mio::Ready::readable(), mio::PollOpt::level())
        .unwrap();

    let token2 = poll
        .register(&child.wait, mio::Ready::readable(), mio::PollOpt::level())
        .unwrap();

    let mut buffer = vec![0; 700];

    loop {
        yield poll.any(vec![token1.clone(), token2.clone()], None);

        if let Ok(()) = child.wait.try_recv() {
            info!("axon child exited");
            return;
        }

        match child.io.read(&mut buffer) {
            Ok(l) => {
                stream.send(&buffer[..l]);
                if l == 0 {
                    return;
                }
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => (),
            Err(e) => {
                error!("{}", e);
                return;
            }
        };

        if let osaka::FutureResult::Done(msg) = stream.poll() {
            if msg.len() == 0 {
                child.io.shutdown(std::net::Shutdown::Write).ok();
            } else {
                if let Err(e) = child.io.write(&msg) {
                    error!("{}", e);
                    return;
                }
            }
        }
    }
}