Application Layer Protocols
local graph
Chapter 5 — Application Layer Protocols
Section titled “Chapter 5 — Application Layer Protocols”As we saw in the previous few chapters, two hosts in a network exchange bytes, either in a stream or in discrete packets. It is often up to a higher-level application to process those bytes to something that makes sense to the application. These applications define a new layer of protocol over the transport layer, often called application layer protocols. In this chapter, we will look into some of those protocols.
There are a number of important considerations for designing application layer protocols. An implementation needs to know at least the following details:
- Is the communication broadcast or point-to-point? In the first case, the underlying transport protocol must be UDP. In the second case, it can be either TCP or UDP.
- Does the protocol need a reliable transport? If yes, TCP is the only option. Otherwise, UDP might be suitable, too.
- Does the application need a byte stream (TCP), or can it work on packet-by-packet basis (UDP)?
- What signals the end of input between the parties?
- What is the data format and encoding used?
Some very commonly used application layer protocols are DNS (which we studied in the previous chapters) and HTTP (which we will study in a subsequent chapter). Other than these, a very important application layer toolset commonly used for microservice-based architectures is gRPC. Another application layer protocol everyone has used at least a few times is SMTP, the protocol that powers email.
In this chapter, we will study the following topics:
- How RPC works. Specifically, we will look at gRPC and write a small server and client using the toolkit.
- We will take a look at a crate caller lettre that can be used to send emails programmatically.
- The last topic will be on writing a simple FTP client and a TFTP server in Rust.
In regular programming, it is often useful to encapsulate frequently used logic in a function so that it can be reused in multiple places. With the rise of networked and distributed systems, it became necessary to let a common set of operations be accessible over a network, so that validated clients can call them. This is often called a Remote Procedure Call (RPC). In Chapter 4*,* Data Serialization, De-Serialization, and Parsing, we saw a simple example of this when a server returned the distance of a given point from the origin. Real world RPC has a number of application layer protocols defined, which are far more complex. One of the most popular RPC implementations is gRPC, which was initially introduced by Google and later moved to an open source model. gRPC offers high performance RPC over internet scale networks and is widely used in a number of projects, including Kubernetes.
Before digging deeper into gRPC, let’s look at protocol buffers, a related tool. It is a set of mechanisms to build language and platform neutral exchanging structured data between applications. It defines its own Interface Definition Language (IDL) to describe the data format, and a compiler that can take that format and generate code to convert to and from it. The IDL also allows for defining abstract services: input and output message formats that the compiler can use to generate stubs in a given language. We will see an example of a definition of a data format in a subsequent example. The compiler has plugins to generate output code in a large number of languages, including Rust. In our example, we will use such a plugin in a build script to autogenerate Rust modules. Now, gRPC uses protocol buffers to define the underlying data and messages. Messages are exchanged over HTTP/2 on top of TCP/IP. This mode of communication is often faster in practice, since it can make better use of existing connections, and also since HTTP/2 supports bidirectional asynchronous connections. gRPC, being an opinionated system, makes a lot of assumptions about the considerations we discussed in the previous section, on our behalf. Most of these defaults (like HTTP/2 over TCP) were chosen because they support the advanced features gRPC offers (like bidirectional streaming). Some other defaults, like using protobuf, can be swapped for another message format implementation.
For our gRPC example, we will build a service that is a lot like Uber. It has a central server where clients (cabs) can record their names and locations. And then, when a user requests a cab with their location, the server sends back a list of cabs near that user. Ideally, this server should have two classes of clients, one for cabs and one for users. But for simplicity’s sake, we will assume that we have only one type of client.
Let us start with setting up the project. Like always, we will use Cargo CLI to initialize the project:
$ cargo new --bin grpc_exampleAll of our dependencies are listed in the dependencies section of Cargo.toml, as shown in the following code snippet. In this example, we will use the build script feature to generate Rust source code from our protocol definition, using the protoc-rust-grpc crate. Hence, we will need to add that as a build dependency:
$ cat Cargo.toml[package]name = "grpc_example"version = "0.1.0"authors = ["Foo<[email protected]>"]
[dependencies]protobuf = "1.4.1"grpc = "0.2.1"tls-api = "0.1.8"
[build-dependencies]protoc-rust-grpc = "0.2.1"The following script is our build script. It is simply a Rust executable (which has a main function) that Cargo builds and runs right before calling the compiler on the given project. Note that the default name for this script is build.rs, and it must be located in the project root. However, these parameters can be configured in the Cargo config file:
extern crate protoc_rust_grpc;
fn main() { protoc_rust_grpc::run(protoc_rust_grpc::Args { out_dir: "src", includes: &[], input: &["foobar.proto"], rust_protobuf: true, }).expect("Failed to generate Rust src");}One of the most common use cases for build scripts is code generation (like our current project). They can also be used to find and configure native libraries on the host, and so on.
In the script, we use the protoc_rust_grpc crate to generate Rust modules from our proto file (called foobar.proto). We also set the rust_protobuf flag to make it generate protobuf messages. Note that the protoc binary must be available in $PATH for this to work. This is a part of the protobuf package. Follow these steps to install it from the source:
- Download the pre-built binaries from GitHub:
$ curl -Lo https://github.com/google/protobuf/releases/download/v3.5.1/protoc-3.5.1-linux-x86_64.zip- Unzip the archive:
$ unzip protoc-3.5.1-linux-x86_64.zip -d protoc3- Copy the binary to somewhere in $PATH:
$ sudo mv protoc3/bin/* /usr/local/bin/This current example has been tested on Ubuntu 16.04 with protoc version 3.5.1.
Next, we will need the protocol definition, as shown in the following code snippet:
syntax = "proto3";
package foobar;
// Top level gRPC service with two RPC callsservice FooBarService { rpc record_cab_location(CabLocationRequest) returns (CabLocationResponse); rpc get_cabs(GetCabRequest) returns (GetCabResponse);}
// A request to record location of a cab// Name: unique name for a cab// Location: current location of the given cabmessage CabLocationRequest { string name = 1; Location location = 2;}
// A response for a CabLocationRequest// Accepted: a boolean indicating if this// request was accepted for processingmessage CabLocationResponse { bool accepted = 1;}
// A request to return cabs at a given location// Location: a given locationmessage GetCabRequest { Location location = 1;}
// A response for GetCabLocation// Cabs: list of cabs around the given locationmessage GetCabResponse { repeated Cab cabs = 1;}
// Message that the CabLocationRequest passes// to the servermessage Cab { string name = 1; Location location = 2;}
// Message with the location of a cabmessage Location { float latitude = 1; float longitude = 2;}The proto file starts with a declaration of the version of protobuf IDP spec; we will be using version 3. The package declaration indicates that all the generated code will be placed in a Rust module called foobar, and all other generated code will be placed in a module called foobar_grpc. We define a service called FooBarService that has two RPC functions; record_cab_location records the location of a cab, given its name and location, and get_cabs returns a set of cabs, given a location. We will also need to define all associated protobuf messages for each of the requests and responses. The spec also defines a number of built-in data types that closely correspond to those in a programming language (string, float, and so on).
Having set up everything related to the protobuf message formats and functions, we can use Cargo to generate actual Rust code. The generated code will be located in the src directory and will be called foobar.rs and foobar_grpc.rs. These names are automatically assigned by the compiler. The lib.rs file should re-export those using the pub mod syntax. Note that Cargo build will not modify the lib.rs file for us; that needs to be done by hand. Let us move on to our server and client. Here is what the server will look:
extern crate grpc_example;extern crate grpc;extern crate protobuf;
use std::thread;
use grpc_example::foobar_grpc::*;use grpc_example::foobar::*;
struct FooBarServer;
// Implementation of RPC functions impl FooBarService for FooBarServer { fn record_cab_location(&self, _m: grpc::RequestOptions, req: CabLocationRequest) -> grpc::SingleResponse<CabLocationResponse> { let mut r = CabLocationResponse::new();
println!("Recorded cab {} at {}, {}", req.get_name(), req.get_location().latitude, req.get_location().longitude);
r.set_accepted(true); grpc::SingleResponse::completed(r) }
fn get_cabs(&self, _m: grpc::RequestOptions, _req: GetCabRequest) -> grpc::SingleResponse<GetCabResponse> { let mut r = GetCabResponse::new();
let mut location = Location::new(); location.latitude = 40.7128; location.longitude = -74.0060;
let mut one = Cab::new(); one.set_name("Limo".to_owned()); one.set_location(location.clone());
let mut two = Cab::new(); two.set_name("Merc".to_owned()); two.set_location(location.clone());
let vec = vec![one, two]; let cabs = ::protobuf::RepeatedField::from_vec(vec);
r.set_cabs(cabs);
grpc::SingleResponse::completed(r) }}
fn main() { let mut server = grpc::ServerBuilder::new_plain(); server.http.set_port(9001); server.add_service(FooBarServiceServer::new_service_def(FooBarServer)); server.http.set_cpu_pool_threads(4); let _server = server.build().expect("Could not start server"); loop { thread::park(); }}Note that this server is very different from the servers we wrote in previous chapters. This is because grpc::ServerBuilder encapsulates a lot of the complexity in writing servers. FooBarService is the service protobuf compiler generated for us, defined as a trait in the file foobar_grpc.rs. As expected, this trait has two methods: record_cab_location and get_cabs. Thus, for our server, we will need to implement this trait on a struct and pass that struct to ServerBuilder to run on a given port.
In our toy example, we will not actually record cab locations. A real world app would want to put these in a database to be looked up later. Instead, we will just print a message saying that we received a new location. We also need to work with some boilerplate code here, to make sure all gRPC semantics are fulfilled. In the get_cabs function, we always return a static list of cabs for all requests. Note that since all protobuf messages are generated for us, we get a bunch of utility functions, like get_name and get_location, for free. Finally, in the main function, we pass our server struct to gRPC to create a new server on a given port and run it on an infinite loop.
Our client is actually defined as a struct in the source generated by the protobuf compiler. We just need to make sure the client has the same port number we are running our server on. We use the new_plain method on the client struct and pass an address and port to it, along with some default options. We can then call the record_cab_location and get_cabs methods over RPC and process the responses:
extern crate grpc_example;extern crate grpc;
use grpc_example::foobar::*;use grpc_example::foobar_grpc::*;
fn main() { // Create a client to talk to a given server let client = FooBarServiceClient::new_plain("127.0.0.1", 9001, Default::default()).unwrap();
let mut req = CabLocationRequest::new(); req.set_name("foo".to_string());
let mut location = Location::new(); location.latitude = 40.730610; location.longitude = -73.935242; req.set_location(location);
// First RPC call let resp = client.record_cab_location(grpc::RequestOptions::new(), req); match resp.wait() { Err(e) => panic!("{:?}", e), Ok((_, r, _)) => println!("{:?}", r), }
let mut nearby_req = GetCabRequest::new(); let mut location = Location::new(); location.latitude = 40.730610; location.longitude = -73.935242; nearby_req.set_location(location);
// Another RPC call let nearby_resp = client.get_cabs(grpc::RequestOptions::new(), nearby_req); match nearby_resp.wait() { Err(e) => panic!("{:?}", e), Ok((_, cabs, _)) => println!("{:?}", cabs), }}Here is how a run of the client will look like. As noted before, this is not as dynamic as it should be, since it returns only hardcoded values:
$ cargo run --bin client Blocking waiting for file lock on build directory Compiling grpc_example v0.1.0 (file:///rust-book/src/ch5/grpc) Finished dev [unoptimized + debuginfo] target(s) in 3.94 secs Running \`/rust-book/src/ch5/grpc/target/debug/client\`accepted: truecabs {name: "Limo" location {latitude: 40.7128 longitude: -74.006}} cabs {name: "Merc" location {latitude: 40.7128 longitude: -74.006}}Notice how it exits right after talking to the server. The server, on the other hand, runs in an infinite loop, and does not exit till it gets a signal:
$ cargo run --bin server Compiling grpc_example v0.1.0 (file:///rust-book/src/ch5/grpc) Finished dev [unoptimized + debuginfo] target(s) in 5.93 secs Running \`/rust-book/src/ch5/grpc/target/debug/server\`Recorded cab foo at 40.73061, -73.93524Internet email uses a protocol called Simple Mail Transfer Protocol (SMTP), which is an IETF standard. Much like HTTP, it is a simple text protocol over TCP, using port 25 by default. In this section, we will look at a small example of using lettre for sending emails. For this to work, let us set up our project first:
$ cargo new --bin lettre-exampleNow, our Cargo.toml file should look like this:
$ cat Cargo.toml[package]name = "lettre-example"version = "0.1.0"authors = ["Foo<[email protected]>"]
[dependencies]lettre = "0.7"uuid = "0.5.1"native-tls = "0.1.4"Let’s say we want to send crash reports for a server automatically. For this to work, we need to have an SMTP server running somewhere accessible. We also need to have a user who can authenticate using a password set up on that server. Having set those up, our code will look like this:
extern crate uuid;extern crate lettre;extern crate native_tls;
use std::env;use lettre::{SendableEmail, EmailAddress, EmailTransport};use lettre::smtp::{SmtpTransportBuilder, SUBMISSION_PORT};use lettre::smtp::authentication::Credentials;use lettre::smtp::client::net::ClientTlsParameters;
use native_tls::TlsConnector;
// This struct represents our email with all the data// we want to send.struct CrashReport { to: Vec<EmailAddress>, from: EmailAddress, message_id: String, message: Vec<u8>,}
// A simple constructor for our email.impl CrashReport { pub fn new(from_address: EmailAddress, to_addresses: Vec<EmailAddress>, message_id: String, message: String) -> CrashReport { CrashReport { from: from_address, to: to_addresses, message_id: message_id, message: message.into_bytes() } }}
impl<'a> SendableEmail<'a, &'a [u8]> for CrashReport { fn to(&self) -> Vec<EmailAddress> { self.to.clone() }
fn from(&self) -> EmailAddress { self.from.clone() }
fn message_id(&self) -> String { self.message_id.clone() }
fn message(&'a self) -> Box<&[u8]> { Box::new(self.message.as_slice()) }}
fn main() { let server = "smtp.foo.bar"; let connector = TlsConnector::builder().unwrap().build().unwrap(); let mut transport = SmtpTransportBuilder::new((server, SUBMISSION_PORT), lettre::ClientSecurity::Opportunistic(<ClientTlsParameters>::new(server.to_string(), connector))).expect("Failed to create transport") .credentials(Credentials::new(env::var("USERNAME").unwrap_or_else(|_| "user".to_string()),env::var("PASSWORD").unwrap_or_else(|_| "password".to_string()))) .build(); let report = CrashReport::new(EmailAddress:: new("[email protected]".to_string()), vec! [EmailAddress::new("[email protected]".to_string())] , "foo".to_string(), "OOPS!".to_string()); transport.send(&report).expect("Failed to send the report");}Our email is represented by the CrashReport struct; as expected, it has a from email address. The to field is a vector of email addresses, enabling us to send an email to multiple addresses. We implement a constructor for the struct. The crate lettre defines a trait called SendableEmail that has a bunch of properties an SMTP server needs to send an email. For a user-defined email to be sendable, it needs to implement that trait. In our case, CrashReport needs to implement it. We go on to implement all required methods in the trait. At this point, a new instance of CrashReport should be sendable as an email.
In our main function, we will need to auth against the SMTP server to send our emails. We create a transport object which has all of the required info to talk to the SMTP server. The username and password can be passed as environment variables (or defaults). We then create an instance of our CrashReport and use the send method of the transport to send it. Running this does not output any information (if it ran successfully).
One might have noticed that the API exposed by lettre is not very easy to use. This is primarily because the library is largely immature, being at version 0.7 at the time of writing. Thus, one should expect breaking changes in the API till it reaches a 1.0 release.
Another common application layer protocol is the File Transfer Protocol (FTP). This is a text-based protocol, where the server and clients exchange text commands to upload and download files. The Rust ecosystem has a crate called rust-ftp to interact with FTP servers programmatically. Let us look at an example of its use. We set up our project using Cargo:
$ cargo new --bin ftp-exampleOur Cargo.toml should look like this:
[package]name = "ftp-example"version = "0.1.0"authors = ["Foo<[email protected]>"]
[dependencies.ftp]version = "2.2.1"For this example to work, we will need a running FTP server somewhere. Once we have set that up and made sure a regular FTP client can connect to it, we can move on to our main code:
extern crate ftp;
use std::str;use std::io::Cursor;use ftp::{FtpStream, FtpError};
fn run_ftp(addr: &str, user: &str, pass: &str) -> Result<(), FtpError> { let mut ftp_stream = FtpStream::connect((addr, 21))?; ftp_stream.login(user, pass)?; println!("current dir: {}", ftp_stream.pwd()?);
let data = "A random string to write to a file"; let mut reader = Cursor::new(data); ftp_stream.put("my_file.txt", &mut reader)?;
ftp_stream.quit()}
fn main() { run_ftp("ftp.dlptest.com", "[email protected]", "eiTqR7EMZD5zy7M").unwrap();}For our example, we will connect to a free public FTP server, located at ftp.dlptest.com. The credentials for using the server are in this website: https://dlptest.com/ftp-test/. Our helper function, called run_ftp, takes in the address of an FTP server, with its username and password as strings. It then connects to the server on port 21 (the default port for FTP). It goes on to log in using the given credentials, and then prints the current directory (which should be /). We then write a file there using the put function, and, at the end, close our connection to the server. In our main function, we simply call the helper with the required parameters.
A thing to note here is the usage of cursor; it represents an inmemory buffer and provides implementations of Read, Write, and Seek over that buffer. The put function expects an input that implements Read; wrapping our data in a Cursor automatically does that for us.
Here is what we see on running this example:
$ cargo run Compiling ftp-example v0.1.0 (file:///Users/Abhishek/Desktop/rust-book/src/ch5/ftp-example) Finished dev [unoptimized + debuginfo] target(s) in 1.5 secs Running \`target/debug/ftp-example\`current dir: /We have used an open FTP server in this example. Since this server is not under our control, it might be taken offline without notice. If that happens, the example will need to be modified to use another server.
A protocol closely related to FTP is called Trivial File Transfer Protocol (TFTP). TFTP is text-based, like FTP, but unlike FTP, it is way simpler to implement and maintain. It uses UDP for transport and does not provide any authentication primitives. Since it is faster and lighter, it is frequently implemented in embedded systems and boot protocols, like PXE and BOOTP. Let us look at a simple TFTP server using the crate called tftp_server. For this example, we will start with Cargo, like this:
$ cargo new --bin tftp-exampleOur manifest is very simple and looks like this:
[package]name = "tftp-example"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]tftp_server = "0.0.2"Our main file will look like this:
extern crate tftp_server;
use tftp_server::server::TftpServer;
use std::net::SocketAddr;use std::str::FromStr;
fn main() { let addr = format!("0.0.0.0:{}", 69); let socket_addr = SocketAddr::from_str(addr.as_str()).expect("Error parsing address"); let mut server = TftpServer::new_from_addr(&socket_addr).expect("Error creating server"); match server.run() { Ok(_) => println!("Server completed successfully!"), Err(e) => println!("Error: {:?}", e), }}This can be easily tested on any Unix machine that has a TFTP client installed. If we run this on one terminal and run the client on another, we will need to connect the client to a localhost on port 69. We should then be able to download a file from the server.
Running this might require root privileges. If that is the case, use sudo.
$ sudo./target/debug/tftp-example
An example session is as follows:
$ tftptftp> connect 127.0.0.1 69tftp> statusConnected to 127.0.0.1.Mode: netascii Verbose: off Tracing: offRexmt-interval: 5 seconds, Max-timeout: 25 secondstftp> get Cargo.tomlReceived 144 bytes in 0.0 secondstftp> ^DIn this chapter, we built upon what we studied previously. In essence, we moved the network stack up to the application layer. We studied some major considerations for building application layer protocols. We then looked at RPC, and in particular, gRPC, studying how it enables developers to build large-scale networked services. We then looked at a Rust crate that can be used to send emails via an SMTP server. The last few examples were on writing an FTP client and a TFTP server. Along with other application layer protocols covered elsewhere in this book, we should have a good standing in understanding these protocols.
HTTP is one text-based application layer protocol that deserves a chapter of its own. In the next chapter, we will take a closer look at it and write some code to make it work.