<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by hc on Medium]]></title>
        <description><![CDATA[Stories by hc on Medium]]></description>
        <link>https://medium.com/@hongchai?source=rss-eb1c32821b69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nKK8O-CfqaUHuN5hyWh6Fw.jpeg</url>
            <title>Stories by hc on Medium</title>
            <link>https://medium.com/@hongchai?source=rss-eb1c32821b69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 13:10:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hongchai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting up Cloudflared on a Raspberry PI 3B]]></title>
            <link>https://hongchai.medium.com/setting-up-cloudflared-on-a-raspberry-pi-3b-c40a667ac022?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/c40a667ac022</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[tunnel]]></category>
            <category><![CDATA[cloudflared]]></category>
            <category><![CDATA[zero-trust]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 07:14:19 GMT</pubDate>
            <atom:updated>2023-03-21T07:14:19.457Z</atom:updated>
            <content:encoded><![CDATA[<p>The official instructions doesn’t include a connector for the Raspberry PI armv7l processor when setting up a tunnel. Even the Docker file doesn’t have the correct architecture for the RPI.</p><p>To get cloudflared running on the RPI, we can use the offical binary released in Github by cloudflare.</p><p><a href="https://github.com/cloudflare/cloudflared/releases">Releases · cloudflare/cloudflared</a></p><pre># Fetch the file<br>wget https://github.com/cloudflare/cloudflared/releases/download/2023.3.1/cloudflared-linux-armhf<br><br># Move it to our bin directory so we can just call it<br>sudo mv cloudflared-linux-armhf /usr/local/bin/cloudflared<br><br># Make it executable<br>sudo chmod +x cloudflared</pre><p>At the time of writing this post, the latest version is 2023.3.1 .</p><p>Now head to Cloudflare Zero Trust Dashboard -&gt; Access -&gt; Tunnels and create a tunnel. You will get a token to configure the connector. Then run the command with the flags below.</p><pre># Start the tunnel<br>cloudflared tunnel --no-autoupdate run --token eyJh...</pre><p>This will establish the connection and you should see some response like this.</p><pre>2023-03-21T02:30:51Z INF Starting tunnel tunnelID=xxxx<br>2023-03-21T02:30:51Z INF Version 2023.3.1<br>2023-03-21T02:30:51Z INF GOOS: linux, GOVersion: go1.19.3, GoArch: arm<br>2023-03-21T02:30:51Z INF Settings: map[token:*****]<br>2023-03-21T02:30:51Z INF cloudflared will not automatically update when run from the shell. To enable auto-updates, run cloudflared as a service: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/run-tunnel/as-a-service/<br>2023-03-21T02:30:51Z INF Generated Connector ID: xxxx<br>2023-03-21T02:30:51Z WRN No ingress rules were defined in provided config (if any) nor from the cli, cloudflared will return 503 for all incoming HTTP requests<br>2023-03-21T02:30:51Z INF Initial protocol quic<br>2023-03-21T02:30:51Z INF ICMP proxy will use xxxx as source for IPv4<br>2023-03-21T02:30:51Z INF ICMP proxy will use xxxx in zone eth0 as source for IPv6<br>2023-03-21T02:30:51Z INF Starting metrics server on 127.0.0.1:43095/metrics<br>2023/03/21 10:30:51 failed to sufficiently increase receive buffer size (was: 176 kiB, wanted: 2048 kiB, got: 352 kiB). See https://github.com/lucas-clemente/quic-go/wiki/UDP-Receive-Buffer-Size for details.<br>2023-03-21T02:30:52Z INF Connection xxxx registered with protocol: quic connIndex=0 ip=xxxx location=xx<br>2023-03-21T02:30:53Z INF Connection xxxx registered with protocol: quic connIndex=1 ip=xxxx location=xx<br>2023-03-21T02:30:54Z INF Connection xxxx registered with protocol: quic connIndex=2 ip=xxxx location=xx<br>2023-03-21T02:30:55Z INF Connection xxxx registered with protocol: quic connIndex=3 ip=xxxx location=xx</pre><p>With that, the tunnel is setup successfully. Now we have a HTTPS cert, and we can set authentication using One-time pin or Google Authentication in front of any web application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c40a667ac022" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access a whitelisted service using ssh & socks5]]></title>
            <link>https://hongchai.medium.com/access-a-whitelisted-service-using-ssh-socks5-b8f4daf06478?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8f4daf06478</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tunnel]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 08:08:29 GMT</pubDate>
            <atom:updated>2023-03-11T08:08:29.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why?</h3><p>I wanted to access a production mongodb cluster to look at some data but the database has a list of whitelisted IP addresses which I cannot edit.</p><p>I do have access to the production server but I didn’t want to install any tools on it. I wanted to use the GUI interface Mongo Compass to view the data.</p><h3>How?</h3><p>Since the mongodb cluster is hosted on Atlas and not on the production server itself, I couldn’t do a local port forwarding.</p><p>The only way is if the production server can perform the requests my local computer requested. This sounds like a VPN or a Proxy.</p><p>Instead of setting up a VPN server, I used the ssh -D flag to open a SOCKS proxy server on a specific port locally and forward all traffic through the SSH tunnel to the remote server.</p><p>In my head, I imagine the setup will look something like this for the command ssh -D 8080 user@remote-server</p><pre>+-------------------+             +---------------------+        +----------------------+<br>|  Local Machine    |             |   Remote Server     |        |   Destination Server |<br>+-------------------+             +---------------------+        +----------------------+<br>        |                                   |                                   |<br>        |                                   |                                   |<br>        |      SSH Connection with -D flag  |                                   |<br>        |----------------------------------&gt;|                                   |<br>        |                                   |                                   |<br>        |        Local SOCKS Proxy          |                                   |<br>        |&lt;----------------------------------|                                   |<br>        |                                   |                                   |<br>        |       Traffic forwarded           |                                   |<br>        |----------------------------------&gt;|                                   |<br>        |                                   |            Traffic sent to        |<br>        |                                   |----------------------------------&gt;|<br>        |                                   |         Destination Service       |<br>        |                                   |&lt;----------------------------------|<br>        |                                   |                                   |<br>        |       Traffic forwarded           |                                   |<br>        |&lt;----------------------------------|                                   |<br>        |                                   |                                   |<br>+-------------------+             +---------------------+        +----------------------+<br>|  Local Machine    |             |   Remote Server     |        |   Destination Server |<br>+-------------------+             +---------------------+        +----------------------+</pre><p>With that setup, I can connect to the mongodb server by adding some additional connection options. Which looks like this.</p><pre>mongodb+srv://admin:*****@abcd.mongodb.net/db?proxyHost=localhost&amp;proxyPort=8080</pre><p>With that, I am able to view my whitelisted database on my local pc using the production server as a tunnel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8f4daf06478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross compiling armv7-linux-androideabi using Rust]]></title>
            <link>https://hongchai.medium.com/cross-compiling-armv7-linux-androideabi-using-rust-5b59c857353c?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b59c857353c</guid>
            <category><![CDATA[linker]]></category>
            <category><![CDATA[cross-compile]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gcc]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 16:43:14 GMT</pubDate>
            <atom:updated>2021-12-09T16:43:14.212Z</atom:updated>
            <content:encoded><![CDATA[<p>I spent the whole day trying to cross compile on a x86 Ubuntu to a armv7-linux-androideabi but failed.</p><p>Then I remembered about cross which boasted it could cross compile magically. I was skeptical. But I thought maybe it’ll work… and I tried it.</p><p><a href="https://github.com/rust-embedded/cross">GitHub - rust-embedded/cross: &quot;Zero setup&quot; cross compilation and &quot;cross testing&quot; of Rust crates</a></p><p>The setup was easy. Install cross using the following command and have docker on your system — which I already had.</p><pre>cargo install cross</pre><p>Next, they provided some examples to cross compile like building on a aarch64.</p><pre>cross build --target aarch64-unknown-linux-gnu</pre><p>So I tried the following command to build for an armv7 android device.</p><pre>cross build --target armv7-linux-androideabi</pre><p>There was some errors building Openssl… but after so many searching on google the whole day I tried adding the vendored flag in the feature in the Cargo.toml.</p><pre>[dependencies]<br>tokio-tungstenite = &quot;*&quot;<br>tokio = { version = &quot;1.14.0&quot;, features = [&quot;full&quot;] }<br>reqwest = { version = &quot;0.11.6&quot;, features = [&quot;json&quot;] }<br>serde = { version = &quot;1.0.130&quot;, features = [&quot;derive&quot;] }<br>url = &quot;2.2.2&quot;<br>futures-util = &quot;0.3.18&quot;<br>futures-channel = &quot;0.3.18&quot;<br>openssl = { version = &quot;0.10&quot;, features = [&quot;vendored&quot;] }</pre><p>It WORKED. The build succeeded. Checking the file we can see that it is dynamically linked. I copied the file to the android device and ran it using termux.</p><pre>ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /system/bin/linker, with debug_info, not stripped</pre><p>Viola! It worked! It’s magic. No more downloading of custom gcc linkers manually. Everything handled using a docker container.</p><p>To find the targets available for cross compilation, see the link below. Under <strong>Tier 2</strong>, there is a table which shows all the available targets.</p><p><a href="https://doc.rust-lang.org/nightly/rustc/platform-support.html">https://doc.rust-lang.org/nightly/rustc/platform-support.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b59c857353c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building your own Termux with a custom package name]]></title>
            <link>https://hongchai.medium.com/building-your-own-termux-with-a-custom-package-name-4b2de0c09fac?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2de0c09fac</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[termux]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[application]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 17:27:43 GMT</pubDate>
            <atom:updated>2021-12-08T17:27:43.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Termux is an awesome Android app which emulates a linux environment. It allows you to run command line applications which is very useful for deployment.</p><p>In my latest project, I needed to use Termux but with a new package name. A simple refactoring of com.termux wasn’t enough to get the application to work properly.</p><p>Here I document the steps that I took to get my own package name to work.</p><h3>1. Downloading the Termux Source</h3><p>First we clone the termux-app. Open the project with Android Studio.</p><pre>git clone <a href="https://github.com/termux/termux-app">https://github.com/termux/termux-app</a></pre><p>Next, refactor com.termux and rename it to a new package name for example com.mytermux</p><p>Then we will edit all occurrence of com.termux to com.mytermux and com_termux to com_mytermux.</p><p>That is all for the renaming part.</p><p>Next, in the app’s build.gradlefile, add a return statement under task downloadBootstra().</p><pre>task downloadBootstraps() <strong>{<br>    </strong>return;<br>    doLast <strong>{<br>        </strong>def version = &quot;2021.06.30-r1&quot;<br>        downloadBootstrap(&quot;aarch64&quot;, &quot;ce56ce9a4e8845bd1d35cc2695bbdd636c72625ee10ce21c9b98ab38ebbee5ab&quot;, version)<br>        downloadBootstrap(&quot;arm&quot;,     &quot;537e81951c7d3d3f3def9ce6778e1032457488e21edb2c037a1e0e680c39e747&quot;, version)<br>        downloadBootstrap(&quot;i686&quot;,    &quot;3c2ca858c0225671c00c44ac182e31819ffa93ec624e95e02824e7d6d30ca1b4&quot;, version)<br>        downloadBootstrap(&quot;x86_64&quot;,  &quot;93c50d36b45bca42bb014395e8e184e5b540adcad5d4e215f7e64ebf0d655d2b&quot;, version)<br>    <strong>}<br>}</strong></pre><p>This will prevent the bootstraping process to download from the official termux servers. Instead it will use the local files we are going to build.</p><h3>2. Building our bootstrap-{arch}.zip</h3><p>The next step is to prepare our bootstrap packages which is used to setup when we install termux.</p><p>This process is very important as termux packages when built, have hardcoded path names.</p><p>Lets clone the package repository at termux-packages.</p><pre>git clone <a href="https://github.com/termux/termux-packages.git">https://github.com/termux/termux-packages.git</a></pre><p>Next download build-bootstrap.shand put it in the folder termux-packages/scripts. This script is used to build termux packages locally instead of using the apt repository method. Doing so it means that you will not be able to do apt install package_name on your termux build.</p><pre>wget <a href="https://gist.github.com/seeya/a9ce074cf560aa7113043859360b7bfc/raw/206b5f4755b65569cf4af8d92b2481258c134b74/build-bootstrap.sh">https://gist.github.com/seeya/a9ce074cf560aa7113043859360b7bfc/raw/206b5f4755b65569cf4af8d92b2481258c134b74/build-bootstrap.sh</a></pre><p>Next we need to edit /termux-packages/scripts/properties.sh.</p><p>Look for the variable TERMUX_APP_PACKAGE and set it to your package name.</p><pre>TERMUX_APP_PACKAGE=&quot;com.mytermux&quot;</pre><p>Next, lets use docker as our environment to build our packages.</p><pre>./scripts/run-docker.sh</pre><p>Once ran, you should see your terminal showing something like this.</p><pre>builder@533f0f18e289:~/termux-packages</pre><p>This means that you are in the docker container. Now we can build our packages. For this example, I’m building the package vim for the architecture arm. Change it according to your needs.</p><pre>./build-package.sh -a arm vim</pre><p>Once built, you should find a vim_8.2.3700.deb inside outputs folder. You can build for packages and once done we will prepare our bootstrap-arm.zip. Doing so will ensure that all packages we built previously be available once the application is installed on the device.</p><pre>./scripts/build-bootstrap.sh --architectures arm</pre><p>This will start the building process and may take awhile. Depending on your computer’s speed, it could take up to 30 minutes.</p><p>Once completed you should see something like this.</p><pre>  ...  <br>  adding: var/lib/dpkg/info/findutils.md5sums (deflated 62%)<br>  adding: var/lib/dpkg/info/docbook-xml.list (deflated 95%)<br>  adding: var/lib/dpkg/info/findutils.list (deflated 85%)<br>  adding: var/lib/dpkg/info/tmux.md5sums (deflated 53%)<br>  adding: var/lib/dpkg/info/xsltproc.list (deflated 79%)<br>  adding: var/lib/dpkg/info/ca-certificates-java.md5sums (stored 0%)<br>  adding: var/lib/dpkg/alternatives/ (stored 0%)<br>  adding: var/log/ (stored 0%)<br>  adding: var/log/apt/ (stored 0%)<br>  adding: var/service/ (stored 0%)<br>  adding: var/service/sshd/ (stored 0%)<br>  adding: var/service/sshd/down (stored 0%)<br>  adding: var/service/sshd/run (deflated 5%)<br>  adding: var/service/sshd/log/ (stored 0%)<br>  adding: var/service/tor/ (stored 0%)<br>  adding: var/service/tor/down (stored 0%)<br>  adding: var/service/tor/run (deflated 5%)<br>  adding: var/service/tor/log/ (stored 0%)<br>[*] Finished successfully (arm).</pre><p>Now if you check your directory, there will be a file bootstrap-arm.zip generated.</p><pre>builder@533f0f18e289:~/termux-packages$ ll<br>total 77664<br>drwxrwxr-x   11 builder builder     4096 Dec  8 17:18 ./<br>drwxr-xr-x    1 builder builder     4096 Dec  8 09:54 ../<br>-rw-rw-r--    1 builder builder      245 Dec  8 08:03 BACKERS.md<br>-rw-r--r--    1 builder builder 79365148 Dec  8 17:18 bootstrap-arm.zip<br>-rwxrwxr-x    1 builder builder     2632 Dec  8 08:03 build-all.sh*<br>-rwxrwxr-x    1 builder builder    19809 Dec  8 08:03 build-package.sh*<br>-rwxrwxr-x    1 builder builder     1254 Dec  8 08:03 clean.sh*<br>-rw-rw-r--    1 builder builder     5391 Dec  8 08:03 CODEOWNERS<br>-rw-rw-r--    1 builder builder    12134 Dec  8 08:03 CONTRIBUTING.md<br>drwxr-xr-x    2 builder builder     4096 Dec  8 09:12 debs/<br>drwxrwxr-x   38 builder builder     4096 Dec  8 08:03 disabled-packages/<br>drwxrwxr-x    8 builder builder     4096 Dec  8 08:03 .git/<br>-rw-rw-r--    1 builder builder      404 Dec  8 08:03 .gitattributes<br>drwxrwxr-x    5 builder builder     4096 Dec  8 08:03 .github/<br>-rw-rw-r--    1 builder builder      249 Dec  8 08:03 .gitignore<br>-rw-rw-r--    1 builder builder      503 Dec  8 08:03 LICENSE.md<br>drwxrwxr-x    2 builder builder     4096 Dec  8 08:03 ndk-patches/<br>drwxr-xr-x    2 builder builder    12288 Dec  8 14:11 output/<br>drwxrwxr-x 1109 builder builder    32768 Dec  8 08:03 packages/<br>-rw-rw-r--    1 builder builder     1932 Dec  8 08:03 README.md<br>drwxrwxr-x    2 builder builder     4096 Dec  8 08:03 sample/<br>drwxrwxr-x    4 builder builder     4096 Dec  8 17:13 scripts/</pre><h3>3. Building the Termux App</h3><p>Now, we can extract the file and put it into our Termux:App in the folder /app/src/main/cpp/bootstrap-arm.zip.</p><p>To prevent any issues, do clean the project first and put the bootstrap-arm.zip in the folder.</p><p>Now build the project and you will see termux being built and intialized successfully!</p><h3>Notes</h3><p>Below are some notes which could prove useful if you’re on this topic.</p><ol><li>./scripts/generate-bootstraps.sh — used when you want to go the apt route to install packages.</li><li>/scripts/build-bootstraps.sh — is not found in the official repository. It’s gotten from <a href="https://github.com/termux/termux-app/issues/1983#issuecomment-812965326">https://github.com/termux/termux-app/issues/1983#issuecomment-812965326</a>. With a slight modification to fix the output path of the debs being built.</li><li>In order to use Termux:Boot, use the same signingConfigs on both application.</li><li><a href="https://gitter.im/termux/dev#">https://gitter.im/termux/dev</a> — very helpful community. Special thanks to agnostic-apollo who helped me along the way.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2de0c09fac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Websocket using Toit.io]]></title>
            <link>https://hongchai.medium.com/websocket-using-toit-io-970d18e40466?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/970d18e40466</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[toit]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Sat, 20 Nov 2021 08:45:16 GMT</pubDate>
            <atom:updated>2021-11-20T08:45:16.074Z</atom:updated>
            <content:encoded><![CDATA[<p>Using toit.io, we can manage ESP32 microcontrollers through the cloud using their services. The interesting thing about toit.io is there’s actually a VM running in the ESP32.</p><p>I came across toit.io probably in 2020 and it was still very early in development. There were a lot of features not available but recently I had a project which required an ESP32 to be controlled over the internet.</p><p>Hence I thought why not give toit.io a shot. The benefits out of the box is once you flash the ESP32 with Toit firmware, WiFi connection is automatic. Handling of reconnection is also done. What’s even more convenient is the online logs. If I remember correctly, in the past they used to charge a fee based on the amount of logs uploaded. But now, it seems like the pricing has updated to per device.</p><p>That’s a very good pricing model and they even allow linking of 10 devices for free.</p><p>There seems to be some issues with using TLS (I’m thinking it’s a limitation on the memory which causes the encryption and decryption of data to fail). So in my use-case I’m just using ws instead of wss for this project.</p><p>The documentation is a not that straight forward to follow. Not everything includes examples and hence I’m documenting this down to help anyone who are doing the same thing.</p><p>You can read up more regarding their WebSocket implementation here <a href="https://libs.toit.io/web_socket/library-summary">https://libs.toit.io/web_socket/library-summary</a>.</p><p>Basically below contains the source code. I’ve a server running a websocket server at the endpoint ws://your-endpoint/ws. The server will just broadcast a simple string “ON” or “OFF” and the ESP32 will toggle the GPIO pin 16 to which controls a relay on my board.</p><p>The codes also includes auto reconnecting to the websocket server incase it disconnect or the server is inaccessible.</p><pre>import net<br>import http<br>import web_socket<br>import bytes<br>import gpio</pre><pre>IS_CONNECTED := false<br>SWITCH ::= gpio.Pin 16 --output <br>HOST ::= &quot;your-endpoint&quot;<br>PORT ::= 80</pre><pre>main:<br>  print &quot;Device Online&quot;<br>  s := connect_server<br>  <br>  while true:<br>    if IS_CONNECTED == false:<br>      s = connect_server<br>      if s != null:<br>        IS_CONNECTED = true<br>      else:<br>        IS_CONNECTED = false<br>        sleep --ms=5000<br>    else if IS_CONNECTED == true:<br>      try:<br>        print &quot;Waiting data&quot;<br>        dc := catch:<br>          payload := s.read <br>          if payload == &quot;ON&quot;:<br>            SWITCH.set 1<br>          else if payload == &quot;OFF&quot;:<br>            SWITCH.set 0 <br>        <br>          print &quot;$payload&quot;        <br>        if dc:<br>            IS_CONNECTED = false            <br>            SWITCH.set 0<br>      finally:<br>     <br>connect_server:<br>  network_interface := net.open<br>  socket := network_interface.tcp_connect HOST PORT<br>  http_connection := http.Connection socket HOST<br>  <br>  err := catch:<br>    request := http_connection.new_request &quot;GET&quot; &quot;/ws&quot;<br>    client := web_socket.WebSocketClient http_connection request<br>    return client<br>  <br>  if err:<br>    print &quot;Server down, retry in 5s&quot;<br>    <br>  return null</pre><p><a href="https://gist.github.com/seeya/ac7e9dcd6945a4b881e1a41290a559ca#file-ws_service-toit">https://gist.github.com/seeya/ac7e9dcd6945a4b881e1a41290a559ca#file-ws_service-toit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970d18e40466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bash Web Scraping]]></title>
            <link>https://hongchai.medium.com/bash-web-scraping-8025276a83db?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/8025276a83db</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 15:15:46 GMT</pubDate>
            <atom:updated>2021-09-21T15:15:46.694Z</atom:updated>
            <content:encoded><![CDATA[<p>With the built in tools and easily available libraries like curl, xargs, convert,pup it makes it easy to perform web scraping. Let’s go through and example with the tools and libraries mentioned and see how we can use them to scrape a manga website.</p><h3>Manga Scraper</h3><p>We are going to scrape from the website <a href="https://manganato.com/">https://manganato.com/</a>. First we choose a manga we want to download. For our case lets just choose Naruto. Looking at the page <a href="https://readmanganato.com/manga-ng952689">https://readmanganato.com/manga-ng952689</a> , we can see there&#39;s a chapter list which contains all the chapters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*869glZEbJUMsl0-r.png" /></figure><p>Clicking on any chapter brings us to a page with all pages loaded within a single HTML file. With all pages located in a single HTML file, it makes our job easier. If it’s not, we can try finding another site.</p><p>First, lets get all the links to every chapter by inspecting the HTML source. Using Chrome’s built in developer tools, it’s very easy to view the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M4zQR6OyuXDnvR6x.png" /></figure><p>We see that the chapters is within a ul with a class name of row-content-chapter. Each chapter is then in a li element with a a which has the link. Now, we have to extract this link. In this scraping project, lets use pup (<a href="https://github.com/ericchiang/pup">https://github.com/ericchiang/pup</a>) instead of BeautifulSoup. If you know jq you will know how to use pup. It&#39;s a command line tool which allows you to pipe stdin and perform some pipeline to get an output. In our case, we are piping the html source and filtering out the elements we want.</p><p>Hence our first stage of getting all chapters link is just the following.</p><pre>curl -s <a href="https://readmanganato.com/manga-ng952689">https://readmanganato.com/manga-ng952689</a> | pup .row-content-chapter a attr{href}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*i7wnFFoUPxpiMA0e.png" /></figure><p>With that, we can proceed to our second stage, which is extracting all images from the chapter. Lets take <a href="https://readmanganato.com/manga-ng952689/chapter-700.1">https://readmanganato.com/manga-ng952689/chapter-700.1</a> as our experiment chapter.</p><p>Looking at the HTML source, we see all the images are inside a div with the class container-chapter-reader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_lWWQLqEl5j3sWAW.png" /></figure><p>Very simply we can just extract the images with the command</p><pre>curl -s <a href="https://readmanganato.com/manga-ng952689/chapter-700.1">https://readmanganato.com/manga-ng952689/chapter-700.1</a> | pup .container-chapter-reader img attr{src}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QBhNauyQ5BkMPH-N.png" /></figure><p>The next step will be to start downloading from the first chapter until the last. We also need to store the files nicely in their correct folder. To do so, we will use the manga chapter link which we obtained from stage one. For example https://readmanganato.com/manga-ng952689/chapter-0 we can see the chapter number in the link.</p><p>Lets use the grep command to extract the chapter.</p><pre>echo &quot;https://readmanganato.com/manga-ng952689/chapter-0&quot; | grep -Eo &#39;chapter-[0-9]+&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*HtDkVEVYCu2nq5un.png" /></figure><p>With that, we can write a downloader.sh script which takes in the chapter link and perform the following</p><ol><li>Create chapter folder</li><li>Get chapter images</li><li>Download chapter images</li></ol><pre>#!/bin/sh<br>​<br># Obtain our chapter number<br>CHAPTER=$(echo $1 | grep -Eo &#39;chapter-[0-9]+&#39;)<br>echo Downloading $CHAPTER<br>​<br># Creating our chapter folder<br>mkdir &quot;$CHAPTER&quot;<br>​<br># Entering our chapter folder<br>cd $CHAPTER<br>​<br># Extracting all images from the chapter and downloading individual images with the remote name<br>curl -s $1 | pup .container-chapter-reader img attr{src} | xargs -n 1 -P 5 -I {} bash -c &#39;curl -sO {}  -H &quot;referer: https://readmanganato.com/&quot;&#39;</pre><p>In the script we used xargs which allowed us to pass in the previous command output (the individual images) to curl . It also allow us to run a number of processes using the -P tag. This speeds up our download by 5 times as we are doing 5 tasks at once instead of 1.</p><p>With that we are done! Here’s our final command to run.</p><pre>curl -s <a href="https://readmanganato.com/manga-ng952689">https://readmanganato.com/manga-ng952689</a> | pup .row-content-chapter a attr{href} | xargs -n 1 -I {} -P 10 bash -c &#39;./downloader.sh {}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/0*w3zEWJcMcBJLMgMF.png" /></figure><p>With all our images downloaded within the chapter’s folder, let’s merge the images into a pdf! To do so, we can use the convert command. To use this command we will need to install imagemagick.</p><p>The usage of this command is quite simple convert img1.jpg img2.jpg output.pdf. Let’s try to generate our command in that format.</p><p>First we list our folder using ls. One thing to take note is ls doesn&#39;t display in natural order. This will mess up the position of the pdf images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJlrbkqmpjvJsbsA.png" /></figure><p>Instead, we have to add the tag -v.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KEGC9FA8ge_5l_E8.png" /></figure><p>With our image file names, we can pass it into the convert command.</p><pre>convert $(ls -v) chapter.pdf<br>​<br># We can see our images get saved in the chapter.pdf<br>4091982 Aug  8 09:42 chapter.pdf</pre><p>With that said, we can now iterate through every folder and do the conversion from image to pdf!</p><pre>ls | xargs -n 1 -I {} -P 5 bash -c &#39;cd {} &amp;&amp; convert $(ls -v) {}.pdf&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8025276a83db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping Discord channels]]></title>
            <link>https://hongchai.medium.com/scraping-discord-channels-d5de7ee87abe?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5de7ee87abe</guid>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[discord]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Thu, 08 Jul 2021 01:37:41 GMT</pubDate>
            <atom:updated>2021-07-08T01:37:41.190Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The standard way of consuming an API is to use an API key with the provided SDK of a particular service. However there are times whereby we want access to private API endpoints which are not available. This is the motivation to reverse an official client which could be an app or website to find out the API endpoints and to replay the requests as if we were the client.</p><h3>Discord</h3><p>Recently I subscribed to a discord channel and would like to get notified in Telegram whenever a new message is posted. The reason to proxy from Discord to Telegram is I check Telegram more often. Also, the discord channel is a subscriber only for which I wanted to share with my friends the messages I received in a Telegram Group automatically.</p><p>I started off with reading the documentation on the website <a href="https://discord.com/developers/docs/resources/channel">https://discord.com/developers/docs/resources/channel</a>. The documentation was solely for Discord Bots. The issue I had was I couldn’t add my bot to the Discord Channel which I wanted to scrape. That left me with no choice but to use my own account even though there’s a risk of getting the account terminated (<a href="https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-">https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-</a>).</p><h3>Where to start Web or Desktop App?</h3><p>I remembered that discord has a web app, and using the Google Chrome, it is always easier to monitor the network tab using the developer tools built right into it. After logging in, I went to the channel I wanted to scrape. The network tab shows the following requests made. messages?limit=50 does seem a little interesting. Clicking it shows us the json response sent by the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*0oVAHPfQ3dZcdRHN.png" /><figcaption>Response from discord API</figcaption></figure><p>That seems to be what we are looking for! With that, if we are able to replay the endpoint and get back a response we should be confident enough to say that the scraping will work.</p><p>To do so, we have to take a look at what is sent to the Discord’s server when we send the request. We can see that the athe endpoint /api/v8/channels/&lt;channelID&gt;/messages?limit=50 is queried with some extra headers. Authorization: mfa._Xf1ZjwM31.... look like what web servers usually use to authenticate the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*nzhTm93XxH5pFASS.png" /><figcaption>Request headers sent to API</figcaption></figure><p>Creating a simple curl, we can try to test it. And indeed, we get a response containing a json object which has the latest messages!</p><pre>curl https://discord.com/api/v8/channels/&lt;channelID&gt;/messages?limit=50 -H &quot;Authorization: mfa._Xf1ZjwM3l...&quot;</pre><p>The next thing would be to setup a scheduler which runs every minute or so to poll the endpoint. The logic to get the latest message is straightforward. We store a local variable of the latest id as latestId. By comparing the first element in the json response response[0].id, if there&#39;s a mismatch we know that the message is new. Then we update our latestId with response[0].id and continue the polling.</p><h3>Caveats</h3><p>Even though I haven’t face any issue with this method after a week, the token used may expire after a certain amount of time. But I guess Discord will extend the token lifetime if they detect it’s active. This is to prevent a normal user from logging out if he&#39;s constantly on the web.</p><p>The API endpoint may also change in the future but for now, I’m very satisfied with this simple approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5de7ee87abe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a service to poll latest messages from Discord Channels without using Bot API]]></title>
            <link>https://hongchai.medium.com/building-a-service-to-poll-latest-messages-from-discord-channels-without-using-bot-api-da7446ac19da?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7446ac19da</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[discord]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Sat, 06 Mar 2021 05:19:17 GMT</pubDate>
            <atom:updated>2021-03-12T01:03:23.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discord Bot</h3><h3>Introduction</h3><p>The standard way of consuming an API is to use an API key with the provided SDK of a particular service. However there are times whereby we want access to private API endpoints which are not available. This is the motivation to reverse an official client which could be an app or website to find out the API endpoints and to replay the requests as if we were the client.</p><h3>Discord</h3><p>Recently I subscribed to a discord channel and would like to get notified in Telegram whenever a new message is posted. The reason to proxy from Discord to Telegram is I check Telegram more often. Also, the discord channel is a subscriber only for which I wanted to share with my friends the messages I received in a Telegram Group automatically.</p><p>I started off with reading the documentation on the website <a href="https://discord.com/developers/docs/resources/channel">https://discord.com/developers/docs/resources/channel</a>. The documentation was solely for Discord Bots. The issue I had was I couldn’t add my bot to the Discord Channel which I wanted to scrape. That left me with no choice but to use my own account even though there’s a risk of getting the account terminated (<a href="https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-">https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-</a>).</p><h3>Where to start Web or Desktop App?</h3><p>I remembered that discord has a web app, and using the Google Chrome, it is always easier to monitor the network tab using the developer tools built right into it. After logging in, I went to the channel I wanted to scrape. The network tab shows the following requests made. messages?limit=50 does seem a little interesting. Clicking it shows us the json response sent by the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*5JgYmluivzoQ9pb1.png" /></figure><p>That seems to be what we are looking for! With that, if we are able to replay the endpoint and get back a response we should be confident enough to say that the scraping will work.</p><p>To do so, we have to take a look at what is sent to the Discord’s server when we send the request. We can see that the athe endpoint /api/v8/channels/&lt;channelID&gt;/messages?limit=50 is queried with some extra headers. Authorization: mfa._Xf1ZjwM31.... look like what web servers usually use to authenticate the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*xMds1kYyAiALvoY-.png" /></figure><p>Creating a simple curl, we can try to test it. And indeed, we get a response containing a json object which has the latest messages!</p><pre>curl https://discord.com/api/v8/channels/&lt;channelID&gt;/messages?limit=50 -H &quot;Authorization: mfa._Xf1ZjwM3l...&quot;</pre><p>The next thing would be to setup a scheduler which runs every minute or so to poll the endpoint. The logic to get the latest message is straightforward. We store a local variable of the latest id as latestId. By comparing the first element in the json response response[0].id, if there&#39;s a mismatch we know that the message is new. Then we update our latestId with response[0].id and continue the polling.</p><h3>Caveats</h3><p>Even though I haven’t face any issue with this method after a week, the token used may expire after a certain amount of time. But I guess Discord will extend the token lifetime if they detect it’s active. So as not to logout a normal user if he&#39;s constantly on the web.</p><p>The api endpoint may also change in the future but for now, I’m very satisfied with this simple approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7446ac19da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to expose your local website to the web]]></title>
            <link>https://hongchai.medium.com/how-to-expose-your-local-website-to-the-web-9c4dd93117fb?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c4dd93117fb</guid>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[caddy]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 07:43:05 GMT</pubDate>
            <atom:updated>2021-03-12T01:05:06.585Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I used Caddy instead of Traefik or NGINX</h3><p>Recently I came across <a href="https://caddyserver.com/">Caddy</a>. “Caddy 2 is a powerful, enterprise-ready, open source web server with automatic HTTPS written in Go” as stated on their website. It boasts many features like reverse-proxy, load balancing and what caught my eye was automatic HTTPS cert renewal.</p><p>How I usually renew my HTTPS cert now is by using certbot with traefik/nginx . I prefer traefik’s configuration compared to nginx but sometime feel it a little troublesome.</p><p>Caddy does seems very promising and I am considering to swap out traefik with Caddy in production deployment just because it’s much straightforward to setup.</p><p>Previously I wrote an article on on exposing local ports using NGINX and FRP. The configuration for NGINX was a little long as it didn’t have automatic HTTPS certs.</p><p>In this article, I will show you how to use Caddy as an alternative to setup even faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h54a9OdNt4a8hfdGAhK-eA.png" /><figcaption>Overview of configuration</figcaption></figure><p>With reference to the image above, lets download the required files on the server first.</p><h3><strong>Required Server Files</strong></h3><p><a href="https://caddyserver.com/download?package=github.com%2Fcaddy-dns%2Fcloudflare">Caddy </a>— I’m using Cloudflare as my dns. There are modules for other providers like digitalocean to automatically create the acme challenge token. For cloudflare, follow this <a href="https://support.cloudflare.com/hc/en-us/articles/200167836-Managing-API-Tokens-and-Keys">link </a>and put the token into the Caddyfile under TOKEN</p><pre>*.<strong>remote.me</strong> {<br>  reverse_proxy localhost:<strong>8081<br>  </strong>tls {<br>    dns cloudflare <strong>TOKEN</strong><br>  }<br>}</pre><p><a href="https://github.com/fatedier/frp/releases/tag/v0.35.1">Fast Reverse Proxy (FRP)</a> — Create a config.ini with the following settings.</p><pre>[common]<br>bind_port = 7000<br>vhost_http_port = <strong>8081</strong><br>subdomain_host = <strong>remote.me</strong></pre><p>You can start caddy with the following command. You should see caddy getting the certs for your domain.</p><pre>caddy run --watch</pre><p>And run frp server with the following command.</p><pre>frps -c config.ini</pre><h3>Required Client Files</h3><p><a href="https://github.com/fatedier/frp/releases/tag/v0.35.1">Fast Reverse Proxy (FRP)</a> — Create a config.ini with the following settings.</p><pre>[common]<br>server_addr = remote.me<br>server_port = 7000</pre><pre>[web]<br>type = http<br>local_port = 80<br>subdomain = <strong>test</strong></pre><p>Lets establish the connection with our server.</p><pre>frpc -c config.ini</pre><p>Of course, lets not forget our local webserver which should run on port 80 as stated in config.ini under local_port = 80</p><pre>python -m http.server 80</pre><p>Now if we point our browser to <a href="https://test.remote.me,/">https://test.remote.me,</a> we will be able to access our web server!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c4dd93117fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I went from NodeJS to Golang]]></title>
            <link>https://hongchai.medium.com/why-i-went-from-nodejs-to-golang-8ea1249e3566?source=rss-eb1c32821b69------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ea1249e3566</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[hc]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 14:57:55 GMT</pubDate>
            <atom:updated>2021-02-09T14:57:55.935Z</atom:updated>
            <content:encoded><![CDATA[<p>I had been using NodeJS ever since the first version was released. The benefits of NodeJS is no doubt a lot but recently some projects have changed my mind.</p><p>When I started programming about 6 years ago, Java, Python, Ruby were the leaders in backend development. I studied Java in school. The concept of Object Oriented Programming and Polymorphism were useful. They could be applied and you’ll have a structured architecture which makes development easy. But I felt the Java too bloated and I don’t understand why do I need to use a WSGI server to host a web service for python in production. It felt too much of a hassle.</p><p>Then came NodeJS. It’s Javascript for Server Side! And I already knew a little Javascript with all the frontend development so why not give it a try?</p><p>Creating a web service was super easy. Using the built in package manager npm I could just install expressjs and with a little boilerplate codes I’m up with a http server running. The heart of NodeJS is the event-loop. It makes it simple but also fast with asynchronous programming. The standard library is also very comprehensive. I really love streams in NodeJS. Being able to stream raw data saves a lot time saving the data while also keeping the memory consumption to a watermark threshold. It’s very convenient to perform sequenced tasks with streams. I feel that Javascript is a very loose functional programming language which provides a lot of flexibility but at a cost. It takes quite a lot of experience to ensure variables are casted to the correct data type correctly. Honestly, I still prefer using just NodeJS than with Typescript up till now. My thinking is if you want a typed-language, why not just use Java. In recent years, Java has been also improving a lot.</p><p>After using NodeJS for so long, I felt I hit a plateau. I wanted to improve and with all the buzz going about with Golang, why not take the chance to try it. And so I did. In one of my projects, I had to develop an application which can run on a Windows machine and communicate over Serial. I had the idea to create a virtual Serial port and use Golang to handle the communication.</p><p>With a little of research, it seemed feasible. I used com0com to create 2 virtual COM ports and a simple go-serial to establish a channel to communicate over. I struggled a little with the syntax and Go’s handling of errors. But as soon as I get a hold on it, everything worked.</p><p>The best part is Golang’s ability to compile the source code into a binary. With the binary, all I needed was to deploy the binary on the client’s deployment machine and it’s done. No npm install of packages, no worries that the source code is exposed.</p><p>My next step is to try concurrency using goroutines in Golang. From what I understand, goroutines are like thread which can be run in parallel with the main application. The good thing is goroutines are very easy to use. Adding a go in front of a function will execute it as a goroutine — it’s that simple.</p><p>Anyway, these are just my views on NodeJS and Golang. Different problems requires different solutions and so there’s no BEST tool to solve a problem. There is always a better tool, but is it worth the risk, effort and time to get hold of the new tool? Or is it better to use the tool you are good with? It boils down to your personal choice and for this time, I chose to pick a new tool to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ea1249e3566" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>