Where It All Started.

Where It All Started.

Life, Stock Trading, Investments, Business and Startup. Most are programming stuff.

Month: December 2020

Creating A Cloudflare Worker Using Rust For Fetching Resources

To learn something new, you need to try new things and not be afraid to be wrong.

— Roy T. Bennett.

Have you ever worked on Web Assembly? Now is a good time, first because its already supported by your browser from Chromium based (e.g. Edge, Brave, Google Chrome) to Firefox and its enabled by default since 2019. Plus you can use your favorite language (technically not all) to develop web assembly.

In this quick tutorial we will be using Rust, not the game though.

Ferris, the Rust language mascot.

Ferris saying hello 👋.
Come on, let’s jump in! 💪

Prerequisites

First of all, you must have a Cloudflare account. Second, the Rust tool chain installed in your computer and I also assumed you are currently running Windows 10 or a Linux distro with proper environment set.

If you don’t have Rust, go to this link in order to install it. And for the Cloudflare account, basically just use the free tier which gives you 100,000 worker calls per day and a free Key-Value (KV) storage.

So where do we start?

The first thing we need to do, is to install wrangler which is a command-line tool specifically developed by Cloudflare to complement the deployment and development of Workers. Install the wrangler tool using the cargo command utility.

cargo install wrangler

The command above will first fetch the source from crates.io and compile it as binary. The command will also automatically install it on your ~/.cargo/bin directory.

💡: Cloudflare Worker is similar to AWS Lambda and Azure Cloud Function. They’re both under the serverless computing category.

After the installation of wrangler, you need to authenticate using your Cloudflare account API key, on which you can get on the user settings panel.

wrangler login

If all works well, the next thing we need to do is to generate the cargo project using the wrangler command line. Execute the code below to generate a cargo project using the Rust WASM worker template:

wrangler generate worker_fetch_demo https://github.com/cloudflare/rustwasm-worker-template.git --type="rust"

After that, go inside the folder named worker_fetch_demo to edit the file cargo.toml . Add the following crate dependencies.

cfg-if = "0.1.2"
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
console_error_panic_hook = { version = "0.1.1", optional = true }
wee_alloc = { version = "0.4.2", optional = true }
futures = { version = "0.3", default-features = false }
js-sys = "0.3.45"
wasm-bindgen-futures = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde_derive = "^1.0.59"
serde_json = "1.0"
log = "0.4"
console_log = { version = "0.2", optional = true }

The wasm-bindgen package is the most important, as that is what links the package to call to JavaScript scopes and other web and web assembly related functionalities. You also need to add the web-sys package as that will provide basic mapping and calls to JavaScript functions.

You’ll be able to get to know what the other package are for, if you’ve already read the Rust Programming Language Book.

[dependencies.web-sys]
version = "0.3.45"
features = [
  'Headers',
  'Request',
  'RequestInit',
  'Response',
  'ServiceWorkerGlobalScope',
]

After adding those crate dependencies it will automatically be fetched on build or upon call to cargo update .

Next thing we modify is the file worker > worker.js . This file serves as the main entry-point of our program that will call our compiled wasm files. We need to add minor modification to it, specifically capturing request and serving the wasm response as JSON.

async function handleRequest(request) {
  const { test } = wasm_bindgen;
  await wasm_bindgen(wasm);

  const data = await test();
  return new Response(JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    },
    status: 200,
  });
}

We move on now to the rust files. 🦀

On the file src > lib.rs add the following code, this particular instruction will add a basic initialization for our console log (similar to JavaScript console.log ) if the console_log dependency is present.

cfg_if! {
    if #[cfg(feature = "console_log")] {
        fn init_log() {
            console_log::init_with_level(Level::Trace).expect("error initializing log");
        }
    } else {
        fn init_log() {}
    }
}

Next, we add a function that will hook to js_sys to return the ServiceWorkerGlobalScope.

Specifically on Cloudflare, the normal browser fetch call won’t work, as the workers run on headless V8 JavaScript engine. That’s why we need to hook on internal HTTP client for service workers.

pub fn worker_global_scope() -> Option<web_sys::ServiceWorkerGlobalScope> {
    js_sys::global().dyn_into::<web_sys::ServiceWorkerGlobalScope>().ok()
}

After adding our worker_global_scope , we proceed with editing the greet function. First, rename it to run then add our first instruction to hook rust panic to console_error . Then call init_log to initialize basic logging functionality.

std::panic::set_hook(Box::new(console_error_panic_hook::hook));
init_log();

Then we initialize our request with the method GET, you could also use other HTTP methods (e.g. POST, PUT, DELETE, …). The method depends on your application needs and endpoints you want to call.

let mut opts = RequestInit::new();
opts.method("GET");

Next, will be creating the request payload that we will submit to our custom fetch. The instruction will contain the endpoint and request options.

let request = Request::new_with_str_and_init(
    "https://httpbin.org/get",
    &opts
)?;

After finishing that, we will now scope and call the function we created earlier. Then we wrap it in a future (asynchronous method calls similar to JavaScript promise if your much more familiar in that term) .

let global = worker_global_scope().unwrap();
let resp_value = JsFuture::from(global.fetch_with_request(&request)).await?;

assert!(resp_value.is_instance_of::<Response>());
let resp: Response = resp_value.dyn_into().unwrap();
let json = JsFuture::from(resp.json()?).await?;

On the returned response, unwrap it and return its JSON value.

Here is our full wasm function that will be called on our worker.js that we defined earlier above.

#[wasm_bindgen]
pub async fn test() -> Result<JsValue, JsValue> {
    std::panic::set_hook(Box::new(console_error_panic_hook::hook));
    init_log();

    let mut opts = RequestInit::new();
    opts.method("GET");

    let request = Request::new_with_str_and_init(
        "https://httpbin.org/get",
        &opts
    )?;

    let global = worker_global_scope().unwrap();
    let resp_value = JsFuture::from(global.fetch_with_request(&request)).await?;

    assert!(resp_value.is_instance_of::<Response>());
    let resp: Response = resp_value.dyn_into().unwrap();
    let json = JsFuture::from(resp.json()?).await?;

    Ok(json)
}

Now, we need to test it, to see if everything’s okay. Spin up a local server using the following command below.

wrangler dev

Test everything and try to call the URL returned by wrangler dev using Postman or Insomnia HTTP client. If everything is working fine, its now time to deploy the worker to live server.

wrangler publish

After running the command above, it will return a live worker URL which you can now access everywhere.

That’s all guys!

Conclusion

You can found the complete repository here.

This is not the only way to call fetch on Cloudflare worker rust, the other method involves in hooking directly to JavaScript exposed fetch (kindly look at Cloudflare example files). If you have any questions kindly leave a comment or DM me 😉.

Follow me for similar article, tips, and tricks ❤.

Top 10 NMAP Flags That I Use Daily

It is not the monsters we should be afraid of; it is the people that don’t recognize the same monsters inside of themselves.

— Shannon L. Alder.

If you’re a network IT (Information Technology) engineer or cybersecurity professional for sure you’d know about the tool nmap.

The tool nmap which stands for network mapper 1 is an open source tool for network discovery and is mostly use for security auditing. Been using this tool for many years and this are my favorite command line flags:

Skip reverse DNS call

This is a helpful flag specially if you don’t want that additional millisecond of fetching records from a DNS server. Or you have a specific case scenario that involves using only internal cached host file.

nmap -n scanme.nmap.org

Stop ping checks

The -PN flag specifically tells nmap that the host is online, skipping check if its alive through ping2. This is particularly useful in situation where you know the target is blocking all ICMP (Internet Control Message Protocol)3 in firewall.

nmap -PN scanme.nmap.org

Fingerprint scan

This -sV flag is useful specially in network auditing and determining if there are any ports available. The command will probe the target machine ports availability and guess the service (including the service version) that is running.

nmap -sV scanme.nmap.org

Finding live host

This command is specifically useful for network engineers to know if there are any alive host on the network. The notation below tells to scan the specific subnet4 using ICMP protocol and return the list of host that responded.

nmap -sP 192.168.1.1/24

Scan using specified network interface

If you have multiple NIC’s (Network Interface Controller)5 and you want to route the scan to a specific NIC, then this is the solution. Normally nmap or any other tool that utilize the computer network would use the OS designated network route (normally determined by network table and preferred gateway). The -e flag tells nmap to use that specific network controller to perform/resolve the scan.

nmap -e eth0 scanme.nmap.org

SYN ping scans

The SYN scan specifically tries to send request packets to target machine and check if it accepts the request packets. Mostly this is one of the default alternative ways of checking if the host is alive.

nmap -sP -PS scanme.nmap.org

ACK ping scans

The ACK scan is the opposite of SYN. In which this particular scan sends and ACK or (acknowledge) packet to the target machine if it will respond. Most modern firewalls block this if its not associated in a three way handshake.

nmap -sP -PA scanme.nmap.org

UDP port scans

This UDP6 port/ping scan is helpful when you know the target machine only blocks TCP packets. This specific flag sends a UDP packet to ports available on the machine and check’s if the target machine responds.

nmap -sP -PU scanme.nmap.org

IP (Internet Protocol) ping scans

Actually, this particular scan is special as its send IP packets to the specified IP protocol number in their IP header. It’s kinda special in a sense that if you didn’t supply a protocol type it will send multi-packets ICMP, IGMP, and IP-in-IP packet.

nmap -sP -PO scanme.nmap.org

ARP ping scans

This particular scan is mostly useful in LAN scenario. As you send an ARP packet it will return specific address or addresses that consumed the broadcast request.

nmap -sP -PR scanme.nmap.org

Mostly, that’s all. I’ve used other flags but this are my most used command flags for nmap.


  1. Nmap (Network Mapper) is a free and open-source network scanner created by Gordon Lyon (also known by his pseudonym Fyodor Vaskovich). ↩︎
  2. Ping measures the round-trip time for messages sent from the originating host to a destination computer that are echoed back to the source. The name comes from active sonar terminology that sends a pulse of sound and listens for the echo to detect objects under water. ↩︎
  3. The Internet Control Message Protocol (ICMP) is a supporting protocol in the Internet protocol suite. It is used by network devices, including routers, to send error messages and operational information indicating success or failure when communicating with another IP address, for example, an error is indicated when a requested service is not available or that a host or router could not be reached. ↩︎
  4. A subnetwork or subnet is a logical subdivision of an IP network. ↩︎
  5. A network interface controller (NIC, also known as a network interface card, network adapter, LAN adapter or physical network interface, and by similar terms) is a computer hardware component that connects a computer to a computer network. ↩︎
  6. The User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network. Prior communications are not required in order to set up communication channels or data paths. ↩︎

Change Default Template In Inkscape For Windows 10

Recently, I’ve been doing some vector and animations, It’s for my new android app for the stock market. Every time I open Inkscape1, it always greeted me with the default template the next thing I do is change the document properties to the way I want, and it became a chore.


Every child is an artist. The problem is how to remain an artist once we grow up.

— Pablo Picasso.

So I searched the internet on how to basically set the default template to my liking.

Steps to change the default template

  1. Create a new document and set its document properties which can be found on File > Document Properties.
  2. It will show a simple dialog which is this.
  1. In the dialog do what to your liking. Modify it base on what you want to see everytime you open Inkscape.
  2. After that, do a File > Save As... and save it to your local user inkscape directory which will be in C:\Users\<your-user>\AppData\Roaming\Inkscape\template
  1. Save it as default.svg. Then restart Inkscape for changes to take effect.

Enjoy that’s all. 🍂


  1. Inkscape is a free and open-source vector graphics editor used to create vector images, primarily in Scalable Vector Graphics (SVG) format. Other formats can be imported and exported. ↩︎