Just An Application

July 26, 2014

Rust Revisted: Ch…ch…ch…changes Or No More Sockets Anymore

Looking at Swift and some of its more Rust-like features, e.g., tuples, reminded me that its been over a year since I last looked at Rust.

In that time its gone from version 0.07 to 0.11 and there have been lots of changes including the disappearance of all the socket functions.

In their place we have the structs

  • TcpListener

  • TcpAcceptor

  • TcpStream

These are all in the std::io::net::tcp module.

Listening For Connections

To listen for incoming connections you call the static method

    TcpListener::bind

passing it an address and a port, like so (this and the other code snippets are all from examples given in the documentation)

    ...

    let listener = TcpListener::bind("127.0.0.1", 80);

    ...

This creates a TcpListener instance and binds it to the given address and port.

You can then listen for incoming connections by calling the listen method

    ...
    
    let mut acceptor = listener.listen();

    ...

This creates a TcpAcceptor instance which can be used to accept incoming connections

Accepting Connections

Once you have a TcpAcceptor you can accept a single connection by calling the method accept.

Alternatively, you can call the method incoming which returns an iterator which can be used to loop over incoming connections as they are made.

    ...
    
    for stream in acceptor.incoming() {
        match stream {
            Err(e) => { /* connection failed */ }
            Ok(stream) => spawn(proc() {
                // connection succeeded
                handle_client(stream)
            })
        }
    }

    ...

The IoResult<T> Type And IO Traits

There is one thing about the example given in the documentation which is at first glance rather puzzling.

The method

    TcpListener::bind

is declared to return

    IOResult<TcpListener>

The type IoResult is declared as

    type IoResult<T> = Result<T, IoError>

and

    Result<T, E>

is a variant enum.

So the method TcpListener::bind actually returns an enum and yet in the example the method listen is called directly on the return value, i.e. the enum.

The same is true for the method listen which is defined to return

    IOResult<TcpAcceptor>

So why does the code even compile ?

The answer is that IoResult implements all the methods defined for the traits

  • Acceptor
  • Listener
  • Reader
  • Seek
  • Writer

For example, this is the definition of the IOResult implementation of the Listener trait

    impl<T, A: Acceptor<T>, L: Listener<T, A>> Listener<T, A> for IoResult<L> {
        fn listen(self) -> IoResult<A> {
            match self {
                Ok(listener) => listener.listen(),
                Err(e) => Err(e),
            }
        }
    }

which can be found in the file

    $(RUST_SRC)/src/libstd/io/result.rs

As you can see if the IOResult contains a Listener the result of calling the method listen on it is returned, otherwise the IOResult must contain an error and that is returned.

Whilest not having to explicitly unwrap the result of each method which returns an IOResult is certainly convenient there can be a potential drawback in some cases.

If you run the following, which is based on the example code from the documentation, under Mac OS X

    fn main()
    {
        // bind the listener to the specified address
        
        let listener = TcpListener::bind("127.0.0.1", 80);
    
        match listener
        {
            Ok(_) =>
            {
                println!("bind: have listener");
            }
            Err(_) =>
            {
                println!("bind: have error");
            }
        }
    
        let mut acceptor = listener.listen();
    
        match acceptor
        {
            Ok(_) =>
            {
                println!("listen: have acceptor");
            }
            Err(e) =>
            {
                println!("listen: have error");
            }
        }
    
    
        // accept connections and process them, spawning a new tasks for each one
    
        for stream in acceptor.incoming()
        {
            match stream
            {
                Err(e) =>
                {
                    /* connection failed */
                    println!("incoming: have error {}", e);
                }
    
                Ok(stream) => spawn(proc()
                                    {
                                       // connection succeeded
                                       handle_client(stream)
                                    })
            }
        }
    
        // close the socket server
        drop(acceptor);
    }

you get

    bind: have error
    listen: have error

because by default the program cannot open port 80, followed by

    incoming: have error permission denied (Permission denied)

repeated ad infinitum, or at least until the point that you hit Ctrl-C, as the program screams around in a tight loop doing absolutely nothing.

In non-example code the failure case within the loop would probably cause the loop to exit or the task to terminate so it wouldn’t loop indefinitely but even so it would probably be better to check whether the initial call to bind actually worked before doing anything else.

Explicit Error Checking

The problem with explicit error checking is that it can get quite messy quite fast.

For example

    fn main()
    {
        match TcpListener::bind("127.0.0.1", 80)
        {
            Ok(listener) =>
            {
                println!("bind: have listener");
                match listener.listen()
                {
                    Ok(mut acceptor) =>
                    {
                        println!("listen: have acceptor");
                        for stream in acceptor.incoming()
                        {
                            match stream
                            {
                                Err(e) =>
                                {
                                    /* connection failed */
                                    println!("incoming: have error");
                                }

                                Ok(stream) => spawn(proc()
                                                    {
                                                        // connection succeeded
                                                        handle_client(stream)
                                                    })
                            }
                        }
                        // close the socket server
                        drop(acceptor);
                    }
                    Err(_) =>
                    {
                        println!("listen: have error");
                    }
                }
            }
            Err(_) =>
            {
                println!("bind: have error");
            }
        }
    }

Whilest not completely impenetrable its not the kind of code you would want to have to maintain if you could possibly avoid it.

The try Macro

There is a utility macro

    try

which is intended to help in this situation.

It is defined like this

    macro_rules! try(
        ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
    )

The definition can be found in the file

    $(RUST_SRC)/rust-0.11.0/src/libcore/macros.rs

As you can see, it works by returning from the function immediately if an error occurs, so you can do something like this

    ...
    
    let listener = try!(TcpListener::bind("127.0.0.1", 80));
    
    ...

and if the call to TcpListener::bind fails the calling function returns immediately

We can then do the same thing for the call to listen

    ...
    
    let mut acceptor = try!(listener.listen());
    
    ...

so we end up with something like this

    fn run(host:&str, port: u16) -> IoResult<????>
    {
        // bind the listener to the specified address
    
        let listener = try!(TcpListener::bind(host, port));
    
        println!("listen: have listener");
    
        let mut acceptor = try!(listener.listen());
    
        println!("listen: have acceptor");
    
        // accept connections and process them, spawning a new tasks for each one
    
        for stream in acceptor.incoming()
        {
            match stream
            {
                Err(e) =>
                {
                     /* connection failed */
                    println!("incoming: have error");
                }
    
                Ok(stream) => spawn(proc()
                                    {
                                        // connection succeeded
                                        handle_client(stream)
                                    })
            }
        }
        // close the socket server
        drop(acceptor);
        return ????;
    }

Note that the function has to have a non-void return type and in this case it has to be

    IoResult<????>

or

    Result<????, IoError>

if you prefer, where ???? is the type of whatever the function returns in the non-error case.

Since there really isn’t anything to return from the function unless something goes wrong the easiest thing to do is reflect that in the return type and declare it to be

    IoResult<()>

i.e., the empty tuple type, so we now have

    fn run(host:&str, port: u16) -> IoResult<()>
    {
        // bind the listener to the specified address
    
        let listener = try!(TcpListener::bind(host, port));
    
        println!("listen: have listener");
    
        let mut acceptor = try!(listener.listen());
    
        println!("listen: have acceptor");
    
        // accept connections and process them, spawning a new tasks for each one
    
        for stream in acceptor.incoming()
        {
            match stream
            {
                Err(e) =>
                {
                    /* connection failed */
                    println!("incoming: have error");
                }
    
                Ok(stream) => spawn(proc()
                                    {
                                        // connection succeeded
                                        handle_client(stream)
                                    })
            }
        }
    
        // close the socket server
        drop(acceptor);
        return ();
    }

which is definitely an improvement upon the deeply nested version above.


Copyright (c) 2014 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

Advertisements

July 8, 2013

Programming With Rust — Part Twenty: Where Have The Sockets Gone ? – Changes Between Rust 0.6 And Rust 0.7

One moment the socket functions were in the module std:net::tcp and the next moment they had gone.

A bit of an exaggeration, but between Rust 0.6 and 0.7 there have been a number of changes which affect the httpd code.

1.0 Std Is The New Core

The core crate has renamed to std and some modules that were in the previous version of the std crate in 0.6 have been moved elsewhere.

Like the core crate before it, it is not necessary to explicitly link to the std crate, but the visibility of some items has changed in the transition and in some cases explicit name bindings are now required.

The most obvious example affects the use of the function io::println.

In 0.6 it was possible to use it as is, in 0.7 it is now necessary to bind the io module name like this

    use std::io;

in files which use io::println.

2.0 The Extra Crate

The extra crate is the new home of some of the modules which had previously been in the std crate in 0.6.

In particular it is the new home of the net modules. So that is where the sockets have gone

3.0 Iterators

Rust is moving from iteration via closures to iteration via explicit iterators.

3.1 The Iterator Trait

The trait Iterator is defined in the module std::iterator.

It defines the method

    fn next(&mut self) -> Option<A>

which will look familiar to anybody who has progammed in Java.

3.2 The Changes

A number of functions/methods have either changed or disappeared entirely.

For example, the function

    fn each_word<'a>(s: &'a str, it: &fn(&'a str) -> bool)

defined in the str module has gone.

In its place is the method

    fn word_iter(&self) -> WordIterator<'self>

defined by the Str trait.

So

    fn readRequestLine(buffer: &mut RequestBuffer) -> (Method, RequestURI)
    {
        let     line           = buffer.readLine();
        let mut parts: ~[&str] = ~[];
        
        str::each_word(line, |part| { parts.push(part); true });
    
        if (vec::len(parts) != 3)
        {
            fail!(fmt!("Invalid status line: %s", line));
        }
    
        let method = Method::fromString(parts[0]);
        let uri    = RequestURI::fromString(method, parts[1]);
    
        (method, uri)
    }

in Rust 0.6, becomes

    fn readRequestLine(buffer: &mut RequestBuffer) -> (Method, RequestURI)
    {    
        let     line           = buffer.readLine();
        let mut parts: ~[&str] = ~[];
    
        for line.word_iter().advance |part| 
        {
            parts.push(part);
        }
        if (parts.len() != 3)
        {
            fail!(fmt!("Invalid status line: %s", line));
        }
    
        let method = Method::fromString(parts[0]);
        let uri    = RequestURI::fromString(method, parts[1]);

        (method, uri)
    }

in Rust 0.7

4.0 Lifetimes

The methods in httpd which return a borrowed pointer and consequently need to specify a lifetime for that pointer, for example,

    pub fn getURI(&self) -> &'self RequestURI
    {
        &self.uri
    }

no longer compile in Rust 0.7.

This change is not specifically mentioned in the release notes.

The solution is to parameterize the method in terms of the lifetime, like so

    pub fn getURI<'a>(&'a self) -> &'a RequestURI
    {
        &self.uri
    }

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

Programming With Rust — Part Nineteen: Just One More Thing – Traits

1.0 Traits

A Rust Trait item defines an abstract type in terms of a set of methods.

For example

    trait Alchemist
    {
        fn transmutate(&self, baseMetal: Lead) -> Gold;
    }

defines the trait Alchemist.

The method transmutate can be called on the value of any type that has the trait Alchemist.

In its basic guise a Rust trait is very similar to a Java interface.

Traits also support inheritance like Java Interfaces but unlike them traits support static methods and default implementations of methods.[1]

2.0 Trait Implementation

The implementation of a trait for a given type is defined using a variant of the implementation item.

For example,

    impl Alchemist for NuclearReactor
    {
        fn transmutate(&self, baseMetal: Lead) -> Gold
        {
            bombardWithNeutronsAndOtherStuff(baseMetal)
        }
    }

defines the implementation of the trait Alchemist for the type NuclearReactor.

3.0 Object Types

The abstract type defined by a trait item is an object type.

A pointer to value of a type which implements a trait, e.g., ~NuclearReactor, is not automatically a pointer to a value of the object type defined by that trait, i.e., ~Alchemist.

In other words, you cannot do this

    let alchemist: ~Alchemist = ~NuclearReactor;

To obtain a pointer to a value of the object type defined by the trait from a pointer to value of a type which implements that trait,
you must explicitly cast it, for example

    let alchemist: ~Alchemist = ~NuclearReactor as ~Alchemist;

4.0 Default Methods

The Rust Reference Manual states that

Traits can include default implementations of methods

However, if you attempt to compile something like this

    trait TraitWithDefaultMethod
    {
        fn notVeryUsefulDefaultMethod(&self, x: uint) -> uint
        {
            x
        }
    
        fn notVeryUsefulMethod(&self);
    }

    struct AStruct;

    impl TraitWithDefaultMethod for AStruct
    {
        fn notVeryUsefulMethod(&self)
        {
        }
    }

    fn main()
    {

        let twdm = ~AStruct as ~TraitWithDefaultMethod;
    
        twdm.notVeryUsefulDefaultMethod(1203);

    }

you will get this

    ... error: default methods are experimental

Support for default methods can be enabled using the -A flag, like this

    rustc -A default_methods crate-file

which, when attempting to compile the code above, gets you this

    error: internal compiler error: unexpected failure

which is a bit unfortunate.

Update

In the all new Rust 0.7 which has just been released default methods remain experimental but the above code now compiles and runs, which is nice.

Notes

  1. Work being done as part of JSR 335: Lambda Expressions for the Java Programming Language will result in Java interfaces also supporting default methods and static methods.


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog's author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

July 2, 2013

Programming With Rust — Part Eighteen: Let’s Build A Library

We are now in a position to do something with an incoming HTTP Request, but what ?

HTTP is a versatile protocol, but a protocol is all it is. What a GET Request, for example, should actually get and how is up for grabs.

Rather than hardwire it for one implementation of GET, or POST or what have you, what we can do is turn httpd into a ‘framework’ which just deals with the protocol part and leave the semantics to the user of the framework.

The first step is to turn our executable into a library.

1.0 A Brief Introduction To Rust Attributes

Rust Attributes are a form of metadata which can be associated with crates and items.

An Attribute declaration is defined like this

    attributes_decl : ’#’ ’[’ attributes ’]’ [ ';' ] ? ; 

    attributes      : attribute [ ’,’ attributes ]* 
    
    attribute       : ident [ ’=’ literal | ’(’ attributes ’)’ ] ? ;

An Attribute declaration applies to the item it precedes unless the declaration is terminated with a semi-colon (;). In this case it applies to the entity in which it is contained.

Currently it is only possible to specify pre-defined Attributes.

2.0 Crate Files And Attributes

We can use the crate_type attribute to specify the type of the binary crate that should be built.

For example, if we include this crate_type Attribute declaration in a crate file

    #[crate_type = "lib"];

then the binary crate built from the crate file will be a library.

The default is bin which is why none of the earlier versions of httpd.rc needed to specify a crate_type attribute.

The name of the library and its version can be specified using the link attribute, like so

    #[link(name = "httpd", vers = "0.6")];

3.0 Modified Source Files

The only existing file we need to change is the crate file, httpd.rc

We need to add the appropriate crate_type and link attributes and remove the main function definition.

We also need to make public those modules that a user of the framework may need to access.

3.1 httpd.rc

// httpd.rc

// Crate file httpd v0.6

#[crate_type = "lib"];

#[link(name = "httpd", vers = "0.6")];


extern mod std;

pub mod HTTP;
pub mod headers;
pub mod request;
pub mod response;
pub mod server;

mod buffer;
mod writer;


4.0 A New Crate: httpd_main

For testing purposes we need a new executable that will link against our new library and initially at least, just run the server as before.

4.1 httpd_main.rc

// httpd_main.rc


extern mod httpd;

use httpd::server;

static PORT: uint = 3534;

static IPV4_LOOPBACK: &'static str = "127.0.0.1";

fn main()
{	
    server::run(IPV4_LOOPBACK, PORT);
}

5.0 Building The Library

We build the library by compiling the crate file as usual

    rustc httpd.rc

This produces a Mac OS X dynamic library

    libhttpd-94839cbfe144198-0.6.dylib

6.0 Building The Executable

We build the executable by compiling its crate file but in this case we need to tell the compiler where the library is using the -L flag like so

    rustc -L . httpd_main.rc

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

June 27, 2013

Programming With Rust — Part Seventeen: The Rest Of httpd v0.5

1.0 Handling A Connection

The handleConnection function now looks like this

    fn handleConnection(socket: TcpSocket)
    {	    
        let     socketBuf = tcp::socket_buf(socket);
        let mut buffer    = RequestBuffer::new(socketBuf);
        let mut writer    = ResponseWriter::new(socketBuf);

        let     request   = Request::read(&mut buffer);
        let     response  = handleRequest(&request);
        
        response.write(&mut writer);
    }

This is both sub-optimal and incorrect and results in the connection being closed after a single Request but it will do for now.

2.0 Handling A Request

The handleRequest function currently does nothing more than print out the Request and return a ‘not found’ Response.

    fn handleRequest(request: &Request) -> Response
    {
        io::println(fmt!("request == %?", request));
    
        ResponseBuilder::notFound()
    }

3.0 Testing

Connecting with a web browser is OK as a basic ‘smoke test’ but we are now at the stage where we need some actual tests.

While it is tempting to write the tests in Rust as well by extending the server side code to support HTTP clients, when writing
anything involving protocols it is always a good idea to test against a completely independent implementation if possible.

3.1 The Test Code

Below is some very simple test code written in Ruby.

    require 'net/http'

    class MethodTests

        def initialize(host, port)
    
            @host = host
            @port = port
        
        end
        
        def run()
    
            method_tests.each { |method| self.method(method).call() }

        end
    
        def connect()

            begin
         
                Net::HTTP.start(
                              @host, @port + 2, 
                              @host, @port, 
                              'sjL', 'sjL', { :use_ssl => true } ) do |http|
            
                    http.get('/connect_test')

                end
         
            rescue Net::HTTPServerException => hse
         
                puts 'connect: ' + hse.to_s

            end

        end

        def delete

            http_method('delete')

        end
    
        def get

            http_method('get')

        end
    
        def get_proxy
    
            begin
         
                Net::HTTP.start(@host, @port + 2, @host, @port) do |http|
            
                    res = http.get('/absolute_uri_test')

                    puts 'get_proxy: ' + res.code

                end
         
            rescue Net::HTTPServerException => hse
         
                puts 'get_proxy: ' + hse.to_s

            end
    
        end
    
        def head

            http_method('head')
        end
    
        def options

            http_method('options', '*')

        end

        def post
        
            http_method('post', '/post_test', '')

        end

        def put

            http_method('put', '/put_test', '')

        end


        def trace
    
            http_method('trace')
        
        end
    
        private

            def method_tests
        
                ['connect', 'delete', 'get', 'get_proxy', 'head', 'options', 'post', 'put', 'trace']

            end
        
            def http_method(name, *args)
        
                res = Net::HTTP.start(@host, @port) do |http|
    
                    case args.length
                
                        when 1
                    
                            http.method(name).call(args[0])
                       
                        when 2
                    
                            http.method(name).call(args[0], args[1])
                       
                        else
                      
                            http.method(name).call('/' + name + '_test')
                        
                    end

                end
                puts name + ': ' + res.code

            end
        
    end


    MethodTests.new('127.0.0.1', 3534).run()


3.2 The Tests

Between them the tests test all the supported methods and request URI formats.

The only test methods that are possibly not self-explanatory are connect and get_proxy

3.2.1 connect

The connect test method creates an HTTP client that will attampt to use the actual HTTP server at @host:@port as a proxy to access another non-existent HTTP server at @host:(@port + 2) using a secure connection.

The call to the HTTP client’s get method causes it to attempt to create an SSL connection which tunnels through the proxy using the HTTP CONNECT method, which is what we want.

3.2.2 get_proxy

Like the connect test method, the get_proxy test method creates an HTTP client that will attampt to use the actual HTTP server at @host:@port as a proxy to access another non-existent HTTP server at @host:(@port + 2) but in this case using an ordinary non-secure connection.

The call to the HTTP client’s get method causes it to send an HTTP Request with an Absolute URI as the Request URI.

4.0 Running The Tests

4.1 Test Output

When run the test code outputs the following

connect: 404 "Not Found"
delete: 404
get: 404
get_proxy: 404
head: 404
options: 404
post: 404
put: 404
trace: 404

4.2 Server Output

When the test code is run httpd outputs the following (heavily edited for readability)

./httpd
on_establish_callback({x: {data: (0x100709600 as *())}})
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: CONNECT, \
             uri: Authority(~"127.0.0.1:3536"), \
             headers: {headers: ~[{key: ~"Host", value: ~"127.0.0.1:3536"}, \
                                  {key: ~"Proxy-Authorization", value: ~"Basic c2pMOnNqTA=="}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: DELETE, \
             uri: AbsolutePath(~"/delete_test"), \
             headers: {headers: ~[{key: ~"Depth", value: ~"Infinity"}, {key: ~"Accept", value: ~"*/*"}, \
                                  {key: ~"User-Agent", value: ~"Ruby"}, {key: ~"Host", value: ~"127.0.0.1:3534"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: GET, \
             uri: AbsolutePath(~"/get_test"), \
             headers: {headers: ~[{key: ~"Accept-Encoding", value: ~"gzip;q=1.0,deflate;q=0.6,identity;q=0.3"}, \
                                  {key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"}, \
                                  {key: ~"Host", value: ~"127.0.0.1:3534"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: GET, \
             uri: AbsoluteURI({scheme: ~"http", user: None, host: ~"127.0.0.1", port: Some(~"3536"), \
             path: ~"/absolute_uri_test", query: ~[], fragment: None}), \
             headers: {headers: ~[{key: ~"Accept-Encoding", value: ~"gzip;q=1.0,deflate;q=0.6,identity;q=0.3"}, \
                                  {key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"},\
                                  {key: ~"Host", value: ~"127.0.0.1:3536"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: HEAD, \
             uri: AbsolutePath(~"/head_test"), \
             headers: {headers: ~[{key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"}, \
                                  {key: ~"Host", value: ~"127.0.0.1:3534"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: OPTIONS, \
             uri: Wildcard, \
             headers: {headers: ~[{key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"}, \
                                  {key: ~"Host", value: ~"127.0.0.1:3534"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: POST, \
             uri: AbsolutePath(~"/post_test"), \
             headers: {headers: ~[{key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"}, \
                                  {key: ~"Host", value: ~"127.0.0.1:3534"}, {key: ~"Content-Length", value: ~"0"}, \
                                  {key: ~"Content-Type", value: ~"application/x-www-form-urlencoded"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: PUT, 
             uri: AbsolutePath(~"/put_test"), \
             headers: {headers: ~[{key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"}, \
                                  {key: ~"Host", value: ~"127.0.0.1:3534"}, {key: ~"Content-Length", value: ~"0"}, \
                                  {key: ~"Content-Type", value: ~"application/x-www-form-urlencoded"}]}}
new_connection_callback(NewTcpConn((0x101810400 as *())), {x: {data: (0x100709600 as *())}})
accept succeeded
request == &{method: TRACE, \
             uri: AbsolutePath(~"/trace_test"), \
             headers: {headers: ~[{key: ~"Accept", value: ~"*/*"}, {key: ~"User-Agent", value: ~"Ruby"},\
                                  {key: ~"Host", value: ~"127.0.0.1:3534"}]}}

5.0 Source Files

5.1 httpd.rc

// httpd.rc

// v0.5

extern mod std;

mod HTTP;
mod buffer;
mod headers;
mod request;
mod response;
mod server;
mod writer;

static PORT: uint = 3534;

static IPV4_LOOPBACK: &'static str = "127.0.0.1";

fn main()
{	
    server::run(IPV4_LOOPBACK, PORT);
}

5.2 server.rs

// server.rs

// part of httpd v0.5

use core::comm::SharedChan;

use core::option::Option;

use core::task;

use std::net::ip;
use std::net::tcp;
use std::net::tcp::TcpErrData;
use std::net::tcp::TcpNewConnection;
use std::net::tcp::TcpSocket;

use std::sync::Mutex;

use std::uv_iotask;


use buffer::RequestBuffer;

use request::Request;

use response::Response;
use response::ResponseBuilder;

use writer::ResponseWriter;

//

static BACKLOG: uint = 5;


fn on_establish_callback(chan: SharedChan<Option>)
{
    io::println(fmt!("on_establish_callback(%?)", chan));
}

fn new_connection_callback(newConn :TcpNewConnection, chan: SharedChan<Option>)
{
    io::println(fmt!("new_connection_callback(%?, %?)", newConn, chan));
	
    let mx = Mutex();
	
    do mx.lock_cond
        |cv|
        {
            let mxc = ~mx.clone();

            do task::spawn 
            {
                match tcp::accept(newConn)
                {
                    Ok(socket) => 
                    {
                        io::println("accept succeeded");
                        do mxc.lock_cond
                            |cv|
                            {
                                cv.signal();
                            }
                        handleConnection(socket);
				                
                    },
                    Err(error) => 
                    {
                        io::println(fmt!("accept failed: %?", error));
                        do mxc.lock_cond
                            |cv|
                            {
                                cv.signal();
                            }
                    }
                }
            }
            cv.wait();
        }
}

fn handleConnection(socket: TcpSocket)
{	    
    let     socketBuf = tcp::socket_buf(socket);
    let mut buffer    = RequestBuffer::new(socketBuf);
    let mut writer    = ResponseWriter::new(socketBuf);
    
    let     request   = Request::read(&mut buffer);
    let     response  = handleRequest(&request);
    
    response.write(&mut writer);
}

//


fn handleRequest(request: &Request) -> Response
{
    io::println(fmt!("request == %?", request));
    
    ResponseBuilder::notFound()
}


//

pub fn run(address: &str, port: uint)
{	
    tcp::listen(
        ip::v4::parse_addr(address),
        port,
        BACKLOG,
        &uv_iotask::spawn_iotask(task::task()),
        on_establish_callback,
        new_connection_callback);
}

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

Programming With Rust — Part Sixteen: Representing An HTTP Response

For the moment we will concentrate on getting the client-to-server/server-to-client round-trip working so the initial representation of an HTTP Response will be distinctly minimal.

1.0 HTTP Response: The RFC 2616 Definition

1.1 Response

An HTTP Response is defined like this

    Response      = Status-Line               ; Section 6.1
                    *(( general-header        ; Section 4.5
                     | response-header        ; Section 6.2
                     | entity-header ) CRLF)  ; Section 7.1
                    CRLF
                    [ message-body ]          ; Section 7.2

1.2 Status-Line

Status-Line is defined like this

    Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

The Status-Code is a three digit integer, 404 probably being the most familiar example, and the Reason-Phrase is any text excluding CR and/or LF, the counterpart to 404 being Not Found

2.0 Representing A Response

2.1 The Components

2.1.1 Status

The Status struct represents both the Status-Code and the Reason-Phrase since they are always paired.

    pub struct Status
    {
        code:   uint,
        reason: &'static str
    }

The Status-Code/Reason-Phrase pairs can then be represented as static items, like so

    pub static NOT_FOUND: Status = Status { code: 404, reason: "Not Found" };

2.2 The Response

For the moment the Response struct only holds a Status value.

    pub struct Response
    {
        priv status: Status
    }

3.0 Building A Response

A Response is constructed using a ResponseBuilder.

For the moment it implements a single static method notFound

    impl ResponseBuilder
    {
        pub fn notFound() -> Response
        {
            Response { status: NOT_FOUND }
        }
    }

4.0 Writing A Response

4.1 ResponseWriter

A ResponseWriter is the counterpart of a RequestBuffer.

It knows how to write the lines that make up the HTTP Response to the connection but it does not know how an HTTP Response is represented.

4.2 The Response write Method

The write method implemented by the Response struct writes the most minimal HTTP Response possible

    pub fn write(&self, writer: &mut ResponseWriter)
    {
        writer.beginResponse();
        writer.writeStatus(self.status.code, self.status.reason);
        writer.endResponse();
    }

4.0 Source Files

4.1 HTTP.rs

// HTTP.rs

// part of httpd v0.5

use std::net::url;

pub static CR: u8 = 13;

pub static LF: u8 = 10;

pub static SP: u8 = 32;

//

pub static VERSION: &'static str = "HTTP/1.1";

//

pub enum Method
{
    CONNECT,
    DELETE,
    GET,
    HEAD,
    OPTIONS,
    POST,
    PUT,
    TRACE
}

impl Method
{
    pub fn fromString(s: &str) -> Method
    {
        match s
        {
            "CONNECT" => CONNECT,
            "DELETE"  => DELETE,
            "GET"     => GET,
            "HEAD"    => HEAD,
            "OPTIONS" => OPTIONS,
            "POST"    => POST,
            "PUT"     => PUT,
            "TRACE"   => TRACE,
       
            _ => 
            {   
                fail!(fmt!("Unrecognized method %s", s));
            }
        }
    }
}

//

pub enum RequestURI
{
    AbsolutePath(~str),
    AbsoluteURI(url::Url),
    Authority(~str),
    Wildcard
}

impl RequestURI
{    
    pub fn fromString(method: Method, s: &str) -> RequestURI
    {
        match method
        {
            CONNECT =>
            {
                Authority(s.to_str())
            },
            
            _ =>
            {
                let length = s.len();
        
                if (length == 1)
                {
                    match s.char_at(0)
                    {
                        '*' =>
                        {
                            Wildcard
                        },
                
                        '/' =>
                        {
                            AbsolutePath(~"/")
                        },
                
                        _ =>
                        {
                            fail!(fmt!("Invalid URI: %s", s));
                        }
                    }
                }
                else
                {
                    match s.char_at(0)
                    {
                        '/' =>
                        {
                            AbsolutePath(s.to_str())
                        }
                        
                        _ =>
                        {                            
                            match url::from_str(s)
                            {
                                Ok(url)  => AbsoluteURI(url),
                                
                                Err(err) => fail!(err)
                            }
                        }
                    }
                }
            }
        }
    }
}

//

pub struct Status
{
    code:   uint,
	reason: &'static str
}

pub static OK:        Status = Status { code: 200, reason: "OK" };

pub static NOT_FOUND: Status = Status { code: 404, reason: "Not Found" };
 

4.2 response.rs

// response.rs

// part of httpd v0.5

use HTTP::Status;

use HTTP::NOT_FOUND;

use writer::ResponseWriter;

pub struct Response
{
    priv status: Status
}

impl Response
{
    pub fn write(&self, writer: &mut ResponseWriter)
    {
        writer.beginResponse();
        writer.writeStatus(self.status.code, self.status.reason);
        writer.endResponse();
    }
}

pub struct ResponseBuilder
{
    priv status: Status
}

impl ResponseBuilder
{
    pub fn notFound() -> Response
    {
        Response { status: NOT_FOUND }
    }
}

4.3 writer.rs

// writer.rs

// part of httpd v0.5

use std::net::tcp::TcpSocketBuf;

use HTTP::CR;
use HTTP::LF;
use HTTP::SP;
use HTTP::VERSION;

enum State
{
    INIT,
    STATUS,
    HEADERS
}

pub struct ResponseWriter
{
    priv socketBuf: TcpSocketBuf,
    priv state:     State,
    priv buffer:    ~[u8]
}

static SIZE: uint = 1024;

//

static COLON: u8 = 58;

impl ResponseWriter
{
    pub fn new(socketBuf: TcpSocketBuf) -> ResponseWriter
    {
        ResponseWriter { socketBuf: socketBuf, state: INIT, buffer: ~[0u8, ..SIZE] }
    }
    
    //
    
    pub fn beginResponse(&mut self)
    {
        self.state = INIT;
        self.buffer.clear();
    }
    
    pub fn writeStatus(&mut self, code: uint, reason: &str)
    {
        match self.state
        {
            INIT =>
            {
                // build status line
        
                self.appendString(VERSION);
                self.append(SP);
                self.appendString(code.to_str());
                self.append(SP);
                self.appendString(reason);
                //
                self.writeLine();
                //
                self.state = STATUS;
            }
            
            _ =>
            {
                fail!(~"Internal Error");
            }
        }
    }
    
    pub fn writeHeader(&mut self, key: &str, value: &str)
    {
        match self.state
        {
            STATUS|HEADERS =>
            {
                // build message-header
        
                self.appendString(key);
                self.append(COLON);
                self.append(SP);
                self.appendString(value);
                //
                self.writeLine();
                //
                self.state = HEADERS;
            }
            
            _ =>
            {
                fail!(~"Internal Error");
            }
        }
    }
    
    pub fn endResponse(&mut self)
    {
        match self.state
        {
            STATUS|HEADERS =>
            {
                self.writeLine();
            }
            
            _ =>
            {
                fail!(~"Internal Error");
            }
        }
    }
    
    //
    
    fn writeLine(&mut self)
    {
        io::println(str::from_bytes(self.buffer));
        
        
        self.append(CR);
        self.append(LF);
        self.socketBuf.write(self.buffer);
        self.buffer.clear();
    }
    
    fn append(&mut self, byte: u8)
    {
        self.buffer.push(byte);
    }
    
    fn appendBytes(&mut self, bytes: &[u8])
    {
        self.buffer.push_all(bytes);
    }
    
    fn appendString(&mut self, s: &str)
    {
        self.appendBytes(s.to_bytes());
    }
}

Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

June 24, 2013

Programming With Rust — Part Fifteen: Representing An HTTP Request

Now we can read a raw HTTP response we need to turn it into something useful.

1.0 HTTP Request: The RFC 2616 Definition

1.1 Request

An HTTP Request is defined like this

    Request    = Request-Line              ; Section 5.1
                 *(( general-header        ; Section 4.5
                  | request-header         ; Section 5.3
                  | entity-header ) CRLF)  ; Section 7.1
                 CRLF
                 [ message-body ]          ; Section 4.3

1.2 Request-Line

Request-Line is defined like this

    Request-Line    = Method SP Request-URI SP HTTP-Version CRLF

1.2.1 Method

Method is defined like this

    Method    = "OPTIONS"                ; Section 9.2
              | "GET"                    ; Section 9.3
              | "HEAD"                   ; Section 9.4
              | "POST"                   ; Section 9.5
              | "PUT"                    ; Section 9.6
              | "DELETE"                 ; Section 9.7
              | "TRACE"                  ; Section 9.8
              | "CONNECT"                ; Section 9.9
              | extension-method

1.2.2 Request-URI

Request-URI is defined like this

    Request-URI    = "*" | absoluteURI | abs_path | authority

where absoluteURI, abs_path and authority are as defined in RFC 2396.

1.3 Headers

general-header, request-header and entity-header
are all forms of message-header which is defined like this

    message-header = field-name ":" [ field-value ]

1.4 The Message Body

message-body is defined like this.

    message-body = entity-body
                   | <entity-body encoded as per Transfer-Encoding>
    entity-body    = *OCTET

2.0 Representing A Request

2.1 The Components

2.1.1 The Request Method

We can represent the Method using an enum like so

    enum Method
    {
        CONNECT,
        DELETE,
        GET,
        HEAD,
        OPTIONS,
        POST,
        PUT,
        TRACE
    }

For the moment we are not going to support extension methods

2.1.2 The Request URI

We can represent the Request URI in terms of its four possible variants by using an enum like so

    enum RequestURI
    {
        AbsolutePath(~str),
        AbsoluteURI(url::Url),
        Authority(~str),
        Wildcard
    }

The AbsoluteURI variant uses the type Url from the std library.

2.1.3 Headers

We are going to represent the set of headers using a new type Headers which is defined like this

    pub struct Headers
    {
        priv headers: ~[Header]
    }

and Header is defined like this

    struct Header
    {
        priv key:   ~str,
        priv value: ~str
    }

2.2 The Request

A Request simply holds the method, the URI and the headers.

    pub struct Request
    {
        priv method:  Method,
        priv uri:     RequestURI,
        priv headers: Headers
    }

For the moment we are going to ignore the message-body.

3.0 The Request Methods

3.1 Reading A Request

We define a static method read on the Request type which takes a RequestBuffer and returns a Request

    pub fn read(buffer: &mut RequestBuffer) -> Request
    {
        let (method, uri) = readRequestLine(buffer);
        let headers       = Headers::read(buffer);
        
        Request { method: method, uri: uri, headers: headers}
    }

The function readRequestLine reads the request line and splits it into its constituent parts and returns them as a tuple.

    fn readRequestLine(buffer: &mut RequestBuffer) -> (Method, RequestURI)
    {
        let     line           = buffer.readLine();
        let mut parts: ~[&str] = ~[];
        
        str::each_word(line, |part| { parts.push(part); true });
    
        if (vec::len(parts) != 3)
        {
            fail!(fmt!("Invalid status line: %s", line));
        }
    
        let method = Method::fromString(parts[0]);
        let uri    = RequestURI::fromString(method, parts[1]);
    
        (method, uri)
    }

3.2 Accessors

3.2.1 getMethod

This method is very simple. It just returns the Method held by the Request.

    pub fn getMethod(&self) -> Method
    {
         self.method
    }

3.2.2 getURI

This method is a little less straightforward than getMethod.

3.2.1.1 Take One

We cannot simply return a shallow copy of the RequestURI like this

    pub fn getURI(&self) -> RequestURI
    {
        self.uri
    }

because to quote the compiler

    request.rs:41:8: 41:16 error: moving out of immutable field
    request.rs:41         self.uri
                          ^~~~~~~~
    error: aborting due to previous error

As we know in this case the RequestURI value is returned via a shallow copy.

A RequestURI value may contain an owned pointer so this would be moved to the copy being returned which would make the original in the Request invalid.

3.2.1.2 Take Two

We could return a deep copy with a pointer to a copy of the original string in the owned heap as well, but this seems a tad extravagant.

An alternative would be to return a borrowed pointer like so

    pub fn getURI(&self) -> &RequestURI
    {
        &self.uri
    }

but the compiler is now very unhappy indeed

    request.rs:41:8: 41:17 error: cannot infer an appropriate lifetime due to conflicting requirements
    request.rs:41         &self.uri
                      ^~~~~~~~~
    request.rs:40:4: 42:5 note: first, the lifetime cannot outlive the lifetime &'self  as defined on the block at 40:4...
    request.rs:40     {
    request.rs:41         &self.uri
    request.rs:42     }
    request.rs:41:8: 41:17 note: ...due to the following expression
    request.rs:41         &self.uri
                      ^~~~~~~~~
    request.rs:40:4: 42:5 note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the block at 40:4...
    request.rs:40     {
    request.rs:41         &self.uri
    request.rs:42     }
    request.rs:41:8: 41:17 note: ...due to the following expression
    request.rs:41         &self.uri
                      ^~~~~~~~~
    error: aborting due to previous error

but it does have a point.

We have not so much attempted to borrow a pointer, as tried to walk off with it without any indication of when we might be planning to give it back, if ever.

3.2.1.3 Take Three

To placate the compiler and assure it of our good intentions we need to explicitly specify the intended lifetime of the borrowed pointer like this

    pub fn getURI(&self) -> &'self RequestURI
    {
        &self.uri
    }

The named lifetime

    'self

specifies that the lifetime of the borrowed pointer is the same as the thing from which it was borrowed which in this case is the Request.

This makes sense because as long as the Request exists the RequestURI exists, so as long as the Request exists the borrowed pointer to the RequestURI is valid.

3.2.3 getHeader

This method delegates to the Headers get method and returns its result.

    pub fn getHeader(&self, key: &str) -> Option<&'self str>
    {
        self.headers.get(key)
    }

4.0 The Headers Methods

4.1 Reading The Headers

The static method read reads the successive header lines until an empty line is read.

Each header lined is convered to a Header value.

The method returns a Headers value constructed using the collected Header values.

    pub fn read(buffer: &mut RequestBuffer) -> Headers
    {
        let mut headers: ~[Header] = ~[];
        
        loop
        {
            let line = buffer.readLine();
        
            if (line.len() == 0)
            {
                break;
            }
            headers.push(toHeader(line));
        }
        Headers { headers: headers }
    }

The function toHeader splits the header line into a key and a value and returns the result as a Header value.

    fn toHeader(line: &str) -> Header
    {
        let mut parts: ~[&str] = ~[];
    
        str::each_splitn_char(line, ':', 1, |s| { parts.push(s); true });
        if (vec::len(parts) != 2)
        {
            fail!(fmt!("Bad header: %s", line));
        }
    
        Header { key: parts[0].to_str(), value: parts[1].trim().to_str() }
    }

4.2 Getting A Header Value

The get method returns an Option as it is possible that the specified header was not present in the original HTTP Request.

If the header is present a borrowed pointer to the value is returned via the Option Ok variant.

The lifetime of the borrowed pointer is explicitly specified to be self. (See the Request getURI method.)

    pub fn get(&self, key: &str) -> Option<&'self str>
    {
        let lcKey = str::to_lower(key);
        
        match self.headers.position(|h| h.key.to_lower() == lcKey)
        {
            Some(index) => 
            {
                let value: &str = self.headers[index].value;
                
                Some(value)
            },
            
            None        => None
        }
    }

5.0 Method and RequestURI Methods

5.1 Method.fromString

The Method fromString static method is very simple. If the argument matches one of the defined methods return the corresponding enum variant, otherwise fail.

    impl Method
    {
        pub fn fromString(s: &str) -> Method
        {
            match s
            {
                "CONNECT" => CONNECT,
                "DELETE"  => DELETE,
                "GET"     => GET,
                "HEAD"    => HEAD,
                "OPTIONS" => OPTIONS,
                "POST"    => POST,
                "PUT"     => PUT,
                "TRACE"   => TRACE,
       
                _ => 
                {   
                    fail!(fmt!("Unrecognized method %s", s));
                }
            }
        }
    }

5.2 RequestURI.fromString

The RequestURI fromString static method converts the string specifying the URI contained in the HTTP Request into one of the variants of the enum type RequestURI.

It takes the Method of the Request as an argument so that it can identify the CONNECT case where the specified Request-URI is actually is an authority which may otherwise be indistinguishable from an absoluteURI in certain circumstances.

    impl RequestURI
    {    
        pub fn fromString(method: Method, s: &str) -> RequestURI
        {
            match method
            {
                CONNECT =>
                {
                    Authority(s.to_str())
                },
            
                _ =>
                {
                    let length = s.len();
        
                    if (length == 1)
                    {
                        match s.char_at(0)
                        {
                            '*' =>
                            {
                                Wildcard
                            },
                
                            '/' =>
                            {
                                AbsolutePath(~"/")
                            },
                
                            _ =>
                            {
                                fail!(fmt!("Invalid URI: %s", s));
                            }
                        }
                    }
                    else
                    {
                        match s.char_at(0)
                        {
                            '/' =>
                            {
                                AbsolutePath(s.to_str())
                            }
                        
                            _ =>
                            {                            
                                match url::from_str(s)
                                {
                                    Ok(url)  => AbsoluteURI(url),
                                
                                    Err(err) => fail!(err)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

6.0 Source Files

6.1 headers.rs

// headers.rs

// part of httpd v0.5

use buffer::RequestBuffer;

pub struct Headers
{
    priv headers: ~[Header]
}

struct Header
{
    priv key:   ~str,
    priv value: ~str
}

impl Headers
{
    pub fn read(buffer: &mut RequestBuffer) -> Headers
    {
        let mut headers: ~[Header] = ~[];
        
        loop
        {
            let line = buffer.readLine();
        
            if (line.len() == 0)
            {
                break;
            }
            headers.push(toHeader(line));
        }
        Headers { headers: headers }
    }
    
    pub fn get(&self, key: &str) -> Option<&'self str>
    {
        let lcKey = str::to_lower(key);
        
        match self.headers.position(|h| h.key.to_lower() == lcKey)
        {
            Some(index) => 
            {
                let value: &str = self.headers[index].value;
                
                Some(value)
            },
            
            None        => None
        }
    }
}


fn toHeader(line: &str) -> Header
{
    let mut parts: ~[&str] = ~[];
    
    str::each_splitn_char(line, ':', 1, |s| { parts.push(s); true });
    if (vec::len(parts) != 2)
    {
        fail!(fmt!("Bad header: %s", line));
    }
    
    Header { key: parts[0].to_str(), value: parts[1].trim().to_str() }
}

6.2 request.rs

// request.rs

// part of httpd v0.5

use HTTP::Method;
use HTTP::RequestURI;

use buffer::RequestBuffer;

use headers::Headers;

//

pub struct Request
{
     priv method:  Method,
     priv uri:     RequestURI,
     priv headers: Headers
}

impl Request
{
    pub fn read(buffer: &mut RequestBuffer) -> Request
    {
        let (method, uri) = readRequestLine(buffer);
        let headers       = Headers::read(buffer);
        
        Request { method: method, uri: uri, headers: headers}
    }
    
    //
    
    pub fn getMethod(&self) -> Method
    {
         self.method
    }
    
    pub fn getURI(&self) -> &'self RequestURI
    {
        &self.uri
    }
    
    pub fn getHeader(&self, key: &str) -> Option<&'self str>
    {
        self.headers.get(key)
    }
}

fn readRequestLine(buffer: &mut RequestBuffer) -> (Method, RequestURI)
{
    let     line           = buffer.readLine();
    let mut parts: ~[&str] = ~[];
        
    str::each_word(line, |part| { parts.push(part); true });
    
    if (vec::len(parts) != 3)
    {
        fail!(fmt!("Invalid status line: %s", line));
    }
    
    let method = Method::fromString(parts[0]);
    let uri    = RequestURI::fromString(method, parts[1]);
    
    (method, uri)
}


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

June 21, 2013

Programming With Rust — Part Fourteen: Crates, Modules And Files

Whilest adding the RequestBuffer definitions directly to the existing httpd.rc file was OK for the purposes of experimentation it is not a good habit to get into.

If we keep lobbing everything into httpd.rc before very long it will have turned into an impenetrable “wall of code”.

We need to place sets of related definitions in separate files and then specify that they are part of the crate.

1.0 Crate Files And Modules

A crate comprises an anonymous module and the items it contains.

These items are defined in the crate file.

The items in the crate file can include module items.

A module item defines a module nested within the anonymous top-level module of the crate.

A module item can define a module and the items it contains explicitly or it can reference a module contained in another file.

A module item which references a module in another file is of the form

    "mod" module_name ';'

By default this identifies the module contained in a file of the same name with the suffix “.rs”.

For example, the module item

    mod buffer;

identifies the module buffer in the file buffer.rs

2.0 Source Files And Modules

A Rust source file implicitly defines a module which contains all the items within that file.

When specified as part of a crate the name of the implicitly defined module is determined by the module item in the crate file which references it.

3.0 Moving Items Into Separate Files

We effectively have two sets of items which we can move into separate files.

  • the items which define the RequestBuffer and implement it, and

  • the function definitions and static items for listening on a socket and accepting a connection

We will move these into the files

    buffer.rs

and

    server.rs

respectively.

3.1 buffer.rs

We need to make the RequestBuffer struct and the static method new and the method readLine public so they can be accessed from outside the module. [1].

3.2 server.rs

In server.rs we need to add

    use buffer::RequestBuffer;

and we are going to rename the main function to run and add parameters for address and port so they can be passed in rather than being hard-wired

httpd.rc

In httpd.rc nearly everything has gone.

We need to add

    ...
    mod buffer;
    mod server;
    ...

We are going to hang on the IPV4_LOOPBACK and PORT static items so we can pass them to the function server::run which we are going to invoke from our new main function.

4.0 The New httpd Crate Module Structure

crate_file

5.0 The Source Code For httpd v0.4

5.1 buffer.rs

// buffer.rs

// part of httpd v0.4


use std::net::tcp::TcpSocketBuf;

// RequestBuffer

pub struct RequestBuffer
{
    priv socketBuf: TcpSocketBuf,
    priv bytes:     ~[u8],
}

//

static SIZE: uint = 4096;

// 

static CR: u8 = 13;

static LF: u8 = 10;

impl RequestBuffer
{    
    pub fn new(socketBuf: TcpSocketBuf) -> RequestBuffer
    {
        RequestBuffer { socketBuf: socketBuf, bytes: ~[0u8, ..SIZE] }
    }

    pub fn readLine(&mut self) -> ~str
    {
        self.bytes.clear();
        
        let mut state = 0;
		
        loop
        {
            let i = self.socketBuf.read_byte();
			
            if (i < 0)
            {
                fail!(~"EOF");
            }
            
            let b = i as u8;
            
            match state
            {
                0 => 
                {
                    if (b == CR)
                    {
                        state = 1;
                    }
                },
						
                1 => 
                {
                    if (b == LF)
                    {
                        return str::from_bytes(vec::const_slice(self.bytes, 0, self.bytes.len() - 1));
                    }
                    else
                    {
                        state = 0;
                    }
                },
						
                _ => 
                {
                    fail!(fmt!("state == %u !", state));
                }
            }
            self.bytes.push(b);
        }
    }
}

5.2 server.rs


// server.rs

// part of httpd v0.4

extern mod std;

use core::comm::SharedChan;

use core::option::Option;


use core::task;

use std::net::ip;
use std::net::tcp;
use std::net::tcp::TcpErrData;
use std::net::tcp::TcpNewConnection;
use std::net::tcp::TcpSocket;

use std::net::tcp::socket_buf;

use std::sync::Mutex;

use std::uv_iotask;

use buffer::RequestBuffer;



fn on_establish_callback(chan: SharedChan<Option>)
{
    io::println(fmt!("on_establish_callback(%?)", chan));
}

fn new_connection_callback(newConn :TcpNewConnection, chan: SharedChan<Option>)
{
    io::println(fmt!("new_connection_callback(%?, %?)", newConn, chan));
	
    let mx = Mutex();
	
    do mx.lock_cond
        |cv|
        {
            let mxc = ~mx.clone();

            do task::spawn 
                {
                    match tcp::accept(newConn)
                    {
                        Ok(socket) => 
                        {
                            io::println("accept succeeded");
                            do mxc.lock_cond
                                |cv|
                                {
                                    cv.signal();
                                }
                            handleConnection(socket);
				                
                        },
                        Err(error) => 
                        {
                            io::println(fmt!("accept failed: %?", error));
                            do mxc.lock_cond
                                |cv|
                                {
                                    cv.signal();
                                }
                        }
                    }
                }
            cv.wait();
        }
}

fn handleConnection(socket: TcpSocket)
{	
    let mut buffer      = RequestBuffer::new(socket_buf(socket));
    let     requestLine = buffer.readLine();
	
    io::println(requestLine);
    loop
    {
        let line = buffer.readLine();
		
        io::println(line);
        if (str::len(line) == 0)
        {
            break;
        }
    }
    io::stdout().flush();
    fail!(~"Now what ?");
}

static BACKLOG: uint = 5;


pub fn run(address: &str, port: uint)
{	
    tcp::listen(
        ip::v4::parse_addr(address),
        port,
        BACKLOG,
        &uv_iotask::spawn_iotask(task::task()),
        on_establish_callback,
        new_connection_callback);
}

5.3 httpd.rc

// httpd.rc

// v0.4

extern mod std;

mod buffer;
mod server;

static PORT: uint = 3534;

static IPV4_LOOPBACK: &'static str = "127.0.0.1";

fn main()
{	
    server::run(IPV4_LOOPBACK, PORT);
}

Notes

  • I discovered quite inadvertently that it is not actually necessary to make the RequestBuffer type public explicitly.
    The implementation seems to do this implicitly. This behaviour does not seem to be documented.


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

June 20, 2013

Programming With Rust — Part Thirteen: Reading An HTTP Request

Now we have a connection we can read the incoming HTTP request.

1.0 An HTTP Request

An HTTP request arrives over a connection as

  • a request line

followed by

  • zero or more header lines

followed by

  • an empty line

followed by

  • a message body

which is optional.

A line is terminated by a carriage-return (CR == ASCII 13) immediately followed by a line-feed (LF == ASCII 10).

Ideally we would like to read the entire request from the connection “in one go” but that is not possible because there is no way of knowing how big a given HTTP request is before we read it.

To abstract out the unfortunately indeterminate nature of an incoming HTTP request, we will start by defining a RequestBuffer type which will deal with the vagaries of reading the necessary bytes from the connection and converting them into lines.

2.0 RequestBuffer: Take One

The original idea was that RequestBuffer would look something like this

    struct RequestBuffer
    {
        priv socketBuf:     TcpSocketBuf,
        priv bytes:         ~[u8],
        priv size:          uint,
        priv available:     uint,
        priv position:      uint,
        priv lastLineEnd:   uint
    }

and there would be a readLine method which would look something like this

    impl RequestBuffer
    {
        ...
        
        fn readLine(&mut self) -> ~str
        {
            let mut state = 0;
		
            loop
            {
                if (self.position == self.available)
                {
                    // read all the bytes currently available from the connection
            
                    ...
                }
            
                let b = self.bytes[self.position];
			
                self.position += 1;
            
                match state
                {
                    0 => 
                    {
                        if (b == 13) // CR
                        {
                            state = 1;
                        }
                    },
						
                    1 => 
                    {
                        if (b == 10) // LF
                        {
                            // make string representing line from buffered bytes
                    
                            let line = ...
                        
                            self.lastLineEnd = self.position;
                            return line;
                        }
                        else
                        {
                            state = 0;
                        }
                    },
						
                    _ => 
                    {
                        fail!(fmt!("state == %u !", state));
                    }
                }
            }
        }
        
        ...
        
    }

but at the moment there does not seem to be any way of simply reading all the bytes currently available on the connection in one go that actually works.

2.1 RequestBuffer: Take Two

This is a version that works but there really isn’t a whole lot of buffering going on.

2.1.1 RequestBuffer

    struct RequestBuffer
    {
        priv socketBuf: TcpSocketBuf,
        priv bytes:     ~[u8],
    }

2.1.2 The readLine Method

    ...

    static CR: u8 = 13;

    static LF: u8 = 10;

    ...

    impl RequestBuffer
    {
    
        ...
        
        fn readLine(&mut self) -> ~str
        {
            self.bytes.clear();
        
            let mut state = 0;
		
            loop
            {
                let i = self.socketBuf.read_byte();
			
                if (i < 0)
                {
                    fail!(~"EOF");
                }
            
                let b = i as u8;
            
                match state
                {
                    0 => 
                    {
                        if (b == CR)
                        {
                            state = 1;
                        }
                    },
						
                    1 => 
                    {
                        if (b == LF)
                        {
                            return str::from_bytes(vec::const_slice(self.bytes, 0, self.bytes.len() - 1));
                        }
                        else
                        {
                            state = 0;
                        }
                    },
						
                    _ => 
                    {
                        fail!(fmt!("state == %u !", state));
                    }
                }
                self.bytes.push(b);
            }
        }

        ...
        
    }

2.1.3 The new Method

The new method is a static method which can be used to create a RequestBuffer.

    fn new(socketBuf: TcpSocketBuf) -> RequestBuffer
    {
        RequestBuffer { socketBuf: socketBuf, bytes: ~[0u8, ..SIZE] }
    }

3.0 The handleConnection Function

If the accept function is successful we now call the handleConnection function which is defined like this

    fn handleConnection(socket: TcpSocket)
    {	
        let mut buffer      = RequestBuffer::new(socket_buf(socket));
        let     requestLine = buffer.readLine();
	
        io::println(requestLine);
        loop
        {
            let line = buffer.readLine();
		
            io::println(line);
            if (str::len(line) == 0)
            {
                break;
            }
        }
        io::stdout().flush();
        fail!(~"Now what ?");
    }

4.0 Running The Code

Running the code and pointing a web browser at 127.0.0.1:3534 produces this

 
    ./httpd
    on_establish_callback({x: {data: (0x1007094f0 as *())}})
    new_connection_callback(NewTcpConn((0x10200b000 as *())), {x: {data: (0x1007094f0 as *())}})
    accept succeeded
    GET / HTTP/1.1
    Host: 127.0.0.1:3534
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:21.0) Gecko/20100101 Firefox/21.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate
    DNT: 1
    Connection: keep-alive

    rust: task failed at 'Now what ?', httpd.rc:172
    rust: domain main @0x10201ee10 root task failed
    rust: task failed at 'killed', /Users/simon/Src/lang/rust-0.6/src/libcore/pipes.rs:314

5.0 The Source Code For httpd v0.3


// httpd.rc

// v0.3

extern mod std;

use core::comm::SharedChan;

use core::option::Option;


use core::task;

use std::net::ip;
use std::net::tcp;
use std::net::tcp::TcpErrData;
use std::net::tcp::TcpNewConnection;
use std::net::tcp::TcpSocket;
use std::net::tcp::TcpSocketBuf;

use std::net::tcp::socket_buf;

use std::sync::Mutex;

use std::uv_iotask;

// RequestBuffer

struct RequestBuffer
{
    priv socketBuf: TcpSocketBuf,
    priv bytes:     ~[u8],
}

//

static SIZE: uint = 4096;

// 

static CR: u8 = 13;

static LF: u8 = 10;

impl RequestBuffer
{    
    fn new(socketBuf: TcpSocketBuf) -> RequestBuffer
    {
        RequestBuffer { socketBuf: socketBuf, bytes: ~[0u8, ..SIZE] }
    }

    fn readLine(&mut self) -> ~str
    {
        self.bytes.clear();
        
        let mut state = 0;
		
        loop
        {
            let i = self.socketBuf.read_byte();
			
            if (i < 0)
            {
                fail!(~"EOF");
            }
            
            let b = i as u8;
            
            match state
            {
                0 => 
                {
                    if (b == CR)
                    {
                        state = 1;
                    }
                },
						
                1 => 
                {
                    if (b == LF)
                    {
                        return str::from_bytes(vec::const_slice(self.bytes, 0, self.bytes.len() - 1));
                    }
                    else
                    {
                        state = 0;
                    }
                },
						
                _ => 
                {
                    fail!(fmt!("state == %u !", state));
                }
            }
            self.bytes.push(b);
        }
    }
}


static BACKLOG: uint = 5;
static PORT:    uint = 3534;

static IPV4_LOOPBACK: &'static str = "127.0.0.1";


fn on_establish_callback(chan: SharedChan<Option<TcpErrData>>)
{
    io::println(fmt!("on_establish_callback(%?)", chan));
}

fn new_connection_callback(newConn :TcpNewConnection, chan: SharedChan<Option<TcpErrData>>)
{
    io::println(fmt!("new_connection_callback(%?, %?)", newConn, chan));
	
    let mx = Mutex();
	
    do mx.lock_cond
        |cv|
        {
            let mxc = ~mx.clone();

            do task::spawn 
            {
                match tcp::accept(newConn)
                {
                    Ok(socket) => 
                    {
                        io::println("accept succeeded");
                        do mxc.lock_cond
                            |cv|
                            {
                                cv.signal();
                            }
                        handleConnection(socket);
				                
                    },
                    Err(error) => 
                    {
                        io::println(fmt!("accept failed: %?", error));
                        do mxc.lock_cond
                            |cv|
                            {
                                cv.signal();
                            }
                    }
                }
            }
            cv.wait();
        }
}

fn handleConnection(socket: TcpSocket)
{	
    let mut buffer      = RequestBuffer::new(socket_buf(socket));
    let     requestLine = buffer.readLine();
	
    io::println(requestLine);
    loop
    {
        let line = buffer.readLine();
		
        io::println(line);
        if (str::len(line) == 0)
        {
            break;
        }
    }
    io::stdout().flush();
    fail!(~"Now what ?");
}

fn main()
{	
    tcp::listen(
        ip::v4::parse_addr(IPV4_LOOPBACK),
        PORT,
        BACKLOG,
        &uv_iotask::spawn_iotask(task::task()),
        on_establish_callback,
        new_connection_callback);
}


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and specific direction to the original content.

June 18, 2013

Programming With Rust — Part Twelve: Even More Things We Need To Know – Methods

1.0 Implementations

Methods are defined for a specific type using an implementation.

For example, given this struct definition

    struct QName
    {
        prefix:    ~str,
        nsURI:     ~str,
        localPart: ~str
    }

we would do this to define methods on the type QName

    impl QName
    {
        ... method definitions go here ...
    }

2.0 Method Definitions

A method is defined in the same way as a function but with self or some kind of pointer to self as a special first parameter.

At runtime self is bound to the value on which the method has been invoked.

For example,

    impl QName
    {
        ...
        
        fn getPrefix(&self) -> ~str
        {
            self.prefix.clone()
        }

        ...
    }

Using a borrowed pointer to self means that the method is applicable to a value of type QName regardless of where it is stored.

If a method can modify the value on which it is called the self parameter must be declared mutable.

    impl QName
    {
        ...
        
        fn setPrefix(&mut self, prefix: ~str)
        {
            self.prefix = prefix;
        }
        
        ...
    }

3.0 Static Method Definitions

A static method definition is an ordinary function definition, or, if you prefer, a method definition without a self parameter.

We can define a static method new to create a QName value like this

    impl QName
    {
        ...
        
        
        fn new(prefix: ~str, nsURI: ~str, localPart: ~str) -> QName
        {
            QName { prefix: prefix, nsURI: nsURI, localPart: localPart }
        }
        
        ...
    }

4.0 Invoking Static Methods

Static methods are invoked as functions but with the name prefixed by the type name like so

    let rights = QName::new(~"dc", ~"http://purl.org/dc/elements/1.1/", ~"rights");


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and
specific direction to the original content.

Older Posts »

Create a free website or blog at WordPress.com.

%d bloggers like this: