1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::http_server::http_handlers::{create_filename_hash_set, handle_connection};
16
17 use crate::http_server::thread_pool::ThreadPool;
18 use log::{info, warn};
19 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, TcpListener};
20 use std::sync::Arc;
21 use std::thread;
22
23 const DEFAULT_HTTP_PORT: u16 = 7681;
24
25 /// Bind HTTP Server to IPv4 or IPv6 based on availability.
bind_listener(http_port: u16) -> Result<TcpListener, std::io::Error>26 fn bind_listener(http_port: u16) -> Result<TcpListener, std::io::Error> {
27 TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, http_port)))
28 .or_else(|e| {
29 warn!("Failed to bind to 127.0.0.1:{http_port} in netsimd frontend http server. Trying [::1]:{http_port}. {e:?}");
30 TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, http_port)))
31 })
32 }
33
34 /// Start the HTTP Server.
run_http_server(instance_num: u16, dev: bool) -> u1635 pub fn run_http_server(instance_num: u16, dev: bool) -> u16 {
36 let http_port = DEFAULT_HTTP_PORT + instance_num - 1;
37 let _ = thread::Builder::new().name("http_server".to_string()).spawn(move || {
38 let listener = match bind_listener(http_port) {
39 Ok(listener) => listener,
40 Err(e) => {
41 warn!("{e:?}");
42 return;
43 }
44 };
45 let pool = ThreadPool::new(4);
46 info!("Frontend http server is listening on http://localhost:{}", http_port);
47 let valid_files = Arc::new(create_filename_hash_set());
48 for stream in listener.incoming() {
49 let stream = stream.unwrap();
50 let valid_files = valid_files.clone();
51 pool.execute(move || {
52 handle_connection(stream, valid_files, dev);
53 });
54 }
55 info!("Shutting down frontend http server.");
56 });
57 http_port
58 }
59