<?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 Oguzhan Oztaskin on Medium]]></title>
        <description><![CDATA[Stories by Oguzhan Oztaskin on Medium]]></description>
        <link>https://medium.com/@oguzhanoztaskin?source=rss-fe9afbc7571a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PddkFV3e7Z2QtBGn7V50ig.jpeg</url>
            <title>Stories by Oguzhan Oztaskin on Medium</title>
            <link>https://medium.com/@oguzhanoztaskin?source=rss-fe9afbc7571a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:38:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oguzhanoztaskin/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[Hybrid VPN: Many VPNs Under One]]></title>
            <link>https://medium.com/@oguzhanoztaskin/hybrid-vpn-a-swiss-army-knife-for-android-networking-61e3fc88c09a?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e3fc88c09a</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 00:00:12 GMT</pubDate>
            <atom:updated>2026-11-06T12:28:04.920Z</atom:updated>
            <content:encoded><![CDATA[<p>I made an Android VPN app because I was tired of managing separate apps for different networking needs. I wanted DNS filtering, access to my devices through Tailscale, OpenVPN for my university network, and an HTTP proxy for debugging. Sometimes I wanted more than one of these active at the same time.</p><p>Android gets in the way here: <a href="https://developer.android.com/develop/connectivity/vpn#service">only one VPN service can be active per user or profile</a>. Starting another stops the existing one. A DNS-filtering app can therefore compete for the same slot as Tailscale or OpenVPN, even though I use them for very different purposes.</p><p>There were other annoyances too: ads, apps I did not particularly trust, and the battery cost of keeping networking tools running. LLMs had made trying a project like this easy enough that I decided to give it a go. The result is <a href="https://github.com/oguzhanoztaskin/hybrid-vpn">Hybrid VPN</a>, which brings these functions together behind a single Android VPN service.</p><h3>DNS filtering</h3><p>The first feature is a custom DNS resolver with built-in filtering. This is also the part I currently use the most: ad blocking is already good enough for my needs.</p><p>An AdGuard sign-up form made me uncomfortable and nudged me toward building something I could configure myself.</p><p>I also wanted local DNS filtering without a separate app competing with Tailscale or OpenVPN for the VPN slot. Including it here lets me keep filtering alongside the other connections I need.</p><h3>Tailscale</h3><p>I use Tailscale to connect to my devices, particularly the ones I leave at home. Its Android app needs the VPN slot too, so it was another obvious thing to include.</p><p>One use case I like is KDE Connect. I use it for multimedia controls, and I can reach my devices over Tailscale. This is useful on Wi-Fi networks where devices on the same WLAN cannot communicate directly with each other.</p><p>Hybrid VPN also includes support for connecting to multiple Tailscale networks, or <em>tailnets</em>, at once. I have not tested that feature yet, so for now it is something the app is designed to support rather than something I can personally vouch for.</p><h3>OpenVPN</h3><p>OpenVPN lets me browse through another network. In my case, that network is my university’s: connecting through it allows me to access research papers using the university’s subscriptions, one of the intended purposes of the connection.</p><p>This is another reason I wanted these tools together. Accessing a paper should not mean switching off my DNS filtering or losing access to my devices at home.</p><h3>HTTP proxy</h3><p>The fourth piece is HTTP proxy support. I use mitmproxy from time to time to inspect traffic and debug things, so I added a way to route traffic through it from the same app. Having that option here saves me from going through Android’s proxy settings or reaching for another app whenever I need it. Inspecting HTTPS contents still requires the client to trust mitmproxy’s certificate, and certificate pinning can prevent interception.</p><h3>Battery and development</h3><p>Battery use mattered to me from the beginning. I asked the coding agent to run benchmarks, identify unnecessary work, and fix the issues it found. The repository includes <a href="https://github.com/oguzhanoztaskin/hybrid-vpn/blob/main/docs/benchmarks/results.md">benchmark notes and results</a>, covering things such as idle wake-ups, CPU use, and throughput. Those are useful indicators, but I do not have a measured battery-life improvement to claim.</p><p>The entire app is vibe-coded. I have not read a single line of its code. I directed the development and tried the parts I needed, but that leaves a considerable gap in my understanding of how the implementation works.</p><p>LLMs took away much of the work of getting this built. They also let development move faster than I could learn the details, especially with the limited time I had. Much of the challenge would otherwise have been learning Android, a platform I do not often develop for. Being able to get something useful out of the project anyway has been a good experience.</p><h3>Where it stands</h3><p>There are features I have not tested and bugs I know about that I have not fixed. I plan to develop the app as I need it; for now, the ad-blocking feature is doing its job for me.</p><p>I am sharing it as an experimental personal project, with all of those limitations. Building it myself has given me control over what I ask it to do, but I have not reviewed the code or established that it deserves more trust than the apps I wanted to replace.</p><p>The source is on <a href="https://github.com/oguzhanoztaskin/hybrid-vpn">GitHub: oguzhanoztaskin/hybrid-vpn</a>. The app is provided without warranty, so please use it at your own discretion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Cbx3RcdMIZuo-P099sWKQ.png" /></figure><p><em>Originally published at </em><a href="https://oguzhanstech.com/2026/10/29/hybrid-vpn.html"><em>https://oguzhanstech.com</em></a><em> on October 29, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e3fc88c09a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Zero-Knowledge Sudoku Prover]]></title>
            <link>https://medium.com/@oguzhanoztaskin/a-zero-knowledge-sudoku-prover-dca3098a53e2?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dca3098a53e2</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 06:36:00 GMT</pubDate>
            <atom:updated>2026-07-31T06:36:00.193Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Can you prove you’ve solved a Sudoku puzzle without ever revealing the solution? 🧩</strong></h3><p>In my latest post, I built a <strong>Zero-Knowledge Sudoku Prover</strong> that does exactly that. By dropping the coordinate binding from Plonk’s permutation argument, I explain how we can strip Sudoku’s rules down to a much lighter, highly efficient <em>multiset</em> constraint.</p><p>I built the entire polynomial-IOP argument system in Rust and compiled it to WebAssembly (WASM) so anyone can test it directly in their browser.</p><p>Since Medium lacks proper LaTeX support for complex equations, I published the full mathematical breakdown, detailed proofs, and the interactive demo on my own blog.</p><p>If you are interested in cryptography, ZKPs, and Rust, you can read the full article and <a href="https://oguzhanstech.com/2026/07/21/zk-sudoku-prover.html">play with the live demo here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*6NxKI8F-ALxrPrqni6UF7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dca3098a53e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring KZG Polynomial Commitments]]></title>
            <link>https://medium.com/@oguzhanoztaskin/exploring-kzg-polynomial-commitments-4fcef7b3a29b?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fcef7b3a29b</guid>
            <category><![CDATA[plonk]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[kzg-commitment]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 13:44:04 GMT</pubDate>
            <atom:updated>2025-11-07T13:44:04.222Z</atom:updated>
            <content:encoded><![CDATA[<p>Just published two posts on KZG Polynomial Commitments — a fundamental building block in zero-knowledge proofs!</p><p>As I dive deeper into cryptographic writing, I’m learning valuable lessons about balancing thoroughness with accessibility. My goal was to explain these complex concepts from scratch, but I discovered the challenge of being both precise and readable while providing proper citations for every fact used in the time I allocated for my blog.</p><p>I have had the following insights from this:<br>• Writing from ground-up for completeness of my blog requires more time than I thought<br>• There’s a tension between comprehensiveness and progress — I spent significant time rewriting well-covered topics in my own words<br>• While this approach improves readers experience by leading them to a simple linear reading journey, it slows me down from discussing novel ideas</p><p>Moving forward, I’m shifting focus toward more novel explanations rather than recreating existing resources.</p><p>Check out my latest posts on KZG and its role in Plonk’s batching mechanism 👇</p><p><a href="https://oguzhanstech.com/2025/10/13/kzg-poly-commit-scheme.html">https://oguzhanstech.com/2025/10/13/kzg-poly-commit-scheme.html</a></p><p><a href="https://oguzhanstech.com/2025/11/07/kzg-batching-in-plonk.html">https://oguzhanstech.com/2025/11/07/kzg-batching-in-plonk.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*wBJaKhEn_FYjw-lAlysz-A.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fcef7b3a29b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Pinning Bypass: SSLContext]]></title>
            <link>https://medium.com/@oguzhanoztaskin/ssl-pinning-bypass-sslcontext-b79070ebeea7?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b79070ebeea7</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ssl-pinning-bypass]]></category>
            <category><![CDATA[ssl-pinning]]></category>
            <category><![CDATA[frida]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 07:34:58 GMT</pubDate>
            <atom:updated>2025-10-04T07:34:58.821Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will explain how to bypass SSL Pinning via <a href="https://developer.android.com/reference/javax/net/ssl/SSLContext">SSLContext</a> using <a href="https://frida.re/">Frida</a>.</p><p>As the injection method, I use dylib injection for the reasons I explain below.</p><p><a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-sslcontext.html"><em>Read this post on my blog!</em></a></p><h3>Split APKs</h3><p>Nowadays most apps are split APKs, meaning that they are split into different parts: A main APK that contains .dex files and most resources, one for native libraries (config.arm64_v8a.apk), one for each language the app supports (config.en.apk), one for graphics (config.mdpi.apk) etc. Furthermore, sometimes apktool fails on decompiling/recompiling the main APK and in such cases dylib injection is useful. This is because we do not have to change main APK at all (just resign it with our key), we only have to inject the Frida gadget into a library which lies in config.&lt;arch&gt;.apk.</p><h3>Injecting Frida into a library</h3><p>First, we decompile config.&lt;arch&gt;.apk that contains the libraries. Then we will find a library that is loaded first, like libreact_render_core.so or anything else that might work. Then we will use the following script to inject the Frida gadget libfrida-gadget.so into it.</p><pre>import lief, sys<br><br>target = sys.argv<br>libnative = lief.parse(target)<br>libnative.add_library(&quot;libfrida-gadget.so&quot;)<br>libnative.write(target)</pre><p>This adds libfrida-gadget.so to the ELF’s dynamic section so that our gadget is loaded alongside the target library<a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-sslcontext.html#fn:1">1</a>. You can check this with the readelf command:</p><pre>$ readelf -d libreact_render_core.so <br><br>Dynamic section at offset 0x22000 contains 43 entries:<br>  Tag        Type                         Name/Value<br> 0x00000001 (NEEDED)                     Shared library: [libfrida.so]<br> 0x00000001 (NEEDED)                     Shared library: [libjsi.so]<br> 0x00000001 (NEEDED)                     Shared library: [liblogger.so]<br> 0x00000001 (NEEDED)                     Shared library: [libreact_config.so]<br>...</pre><p>This is explained in a much better detail at <a href="https://lief.re/doc/stable/tutorials/09_frida_lief.html">here</a>.</p><p>Once the Frida gadget works (the app freezes until I connect to it on startup), I ran the following command, <a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-network-security-config.html#a-note-on-adb-port-forwarding">explained more detailed here</a>:</p><pre>adb forward tcp:27042 tcp:27042</pre><p>This forwards the port 27042 on my computer to the same port on my mobile, where Frida gadget listens by default. I can then connect to the Frida gadget via frida -R gadget -l ssl.js and let the script do the bypassing.</p><h3>Frida — SSL Pinning Bypass Script</h3><p>The ssl.js I used above can be found <a href="https://codeshare.frida.re/@pcipolloni/universal-android-ssl-pinning-bypass-with-frida/">here</a>. This script does the following:</p><ul><li>Get javax.net.ssl.TrustManagerFactory and use it to create a TrustManager for the certificate at /data/local/tmp/cert-der.crt<a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-sslcontext.html#fn:2">2</a></li><li>Hook SSLContext.init method so that all calls to it are intercepted.</li><li>When SSLContext.init is called, instead of the provided TrustManager, use our own that carries mitmproxy’s certificate. Once injected, the script logs its actions in real-time, so you can confirm whether the bypass worked.</li></ul><p>And that’s it. At this point I am supposed to be able to see the traffic. However I noticed while I can see some, there is still some traffic which I cannot as evident by mitmproxy’s logs. Then I realized there was another SSL pinning layer I hadn’t addressed: Network Security Config.</p><h3>Conclusion</h3><p>In this post, I demonstrated a less known way of injecting Frida by modifying shared libraries, which avoids the common pitfalls of smali recompilation errors. Then we used a Frida script to hook SSLContext.init method. I have no practical defense solutions for this attack - Android does not seem to provide a way to see whether SSLContext is initialized with the intended trust manager or not. For a more general defense, detecting whether the gadget is present or not can be used, perhaps by listing the libraries.</p><p><strong>Disclaimer:</strong> This post is intended solely for educational and research purposes. The techniques described here should only be applied to applications you own or have explicit permission to analyze. Reverse engineering, modifying, or intercepting traffic of third-party apps without consent may violate their terms of service and applicable laws. I do not encourage or condone using these methods against third-party apps without permission.</p><ol><li>Sometimes this method silently fails and I haven’t figured out why yet. Injecting the Frida gadget into another library often works. <a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-sslcontext.html#fnref:1">↩</a></li><li>This will be the mitmproxy’s certificate and we will push it to the device with adb push mitmproxy.cert /data/local/tmp/cert-der.crt. This is a directory all apps can access and that’s why we are using it. You can find mitmproxy certificates on your computer at ~/.mitmproxy or your mobile that uses mitmproxy as proxy at http://mitm.it. <a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-sslcontext.html#fnref:2">↩</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*wBJaKhEn_FYjw-lAlysz-A.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b79070ebeea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Pinning Bypass: Network Security Config]]></title>
            <link>https://medium.com/@oguzhanoztaskin/ssl-pinning-bypass-network-security-config-268fc250fbdd?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/268fc250fbdd</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ssl-pinning]]></category>
            <category><![CDATA[mitmproxy]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 09:13:34 GMT</pubDate>
            <atom:updated>2025-08-29T09:18:53.763Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will talk about how I bypassed the simplest SSL pinning method: <a href="https://developer.android.com/privacy-and-security/security-config">Network Security Config</a> via APK resource editing. I will also explain my setup.</p><p>I assume you know how to use the tools mitmproxy, an Android proxy client, apktool, adb and do not detail it here.</p><p><a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-network-security-config.html"><strong><em>Read this post on my blog!</em></strong></a></p><h3>Why Do This At All?</h3><p>SSL Pinning protects your apps their network protocols revealed. Though it is a client side protection and you should focus on server side for the most part, it is still relevant: This will slow down anyone that wants to learn your API, bot it or cheat it.</p><p>Studying SSL pinning bypasses is both a fun technical challenge and a way to better understand app defenses. My personal goal here is to observe app traffic directly in mitmproxy, while learning how different protections work.</p><h3>Bypassing Network Security Config</h3><p>Bypassing Network Security Config was simple:</p><ul><li>Decompile the APK with <a href="https://apktool.org/">apktool</a></li><li>Find the name of the config from AndroidManifest.xml in the application tag as the value of android:networkSecurityConfig, usually it is res/xml/network_security_config.xml</li><li>Then set it to be:</li></ul><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;network-security-config&gt;<br>    &lt;base-config cleartextTrafficPermitted=&quot;false&quot;&gt;<br>        &lt;trust-anchors&gt;<br>            &lt;certificates src=&quot;system&quot; /&gt;<br>            &lt;certificates src=&quot;user&quot; /&gt;<br>        &lt;/trust-anchors&gt;<br>    &lt;/base-config&gt;<br>&lt;/network-security-config&gt;</pre><p>This will make it trust installed certificates — including the <a href="https://www.mitmproxy.org/">mitmproxy</a>’s certificate if installed. Also if there was any certificate pinned this way, we effectively erased it<a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-network-security-config.html#fn:1">¹</a>.</p><p>We can see that the default setting is to only trust system certificates and no cleartext traffic, for API level 28 and higher according to <a href="https://developer.android.com/privacy-and-security/security-config">here</a>. Therefore, adding user certificates as a trust anchor is necessary.</p><p>After this, we can build and sign the app and install it on the target device. Next, we need to put the app’s network traffic through mitmproxy to observe it.</p><h3>Setting up the Proxy</h3><p>We need to run mitmproxy on the host and configure the target device to use it. However, the host and the target device possibly lie on different networks and cannot see each other. We cannot make the target device connect to mitmproxy then. I assume a USB connection to the target device is present, so I will use adb to make the devices connect. In the next subsection I explain how.</p><h3>A Note on ADB Port Forwarding</h3><p>ADB has two useful commands for port forwarding, the second one is something I wish I had seen sooner<a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-network-security-config.html#fn:2">²</a>. Here I detail them:</p><pre>adb forward tcp:7777 tcp:8888</pre><p>This forwards the port 7777 on the host (i.e. the device running adb, your computer) to the port 8888 on the target device (i.e. your mobile which is connected using a USB cable maybe). What this means is, any connection to port 7777 on your host will be directed to the port 8888 on your target device. For example, if you have an HTTP server listening on port 8888 on your target device, you can access it on your computer via localhost:7777.</p><p>The other command I wish I had learned sooner is the adb reverse command.</p><pre>adb reverse tcp:3333 tcp:4444</pre><p>This does the opposite of the adb forward command as the name suggests: The port 3333 on the target device is forwarded to the port 4444 on the host device. That is, if you host the HTTP server on your host at 4444, you can access it on your mobile via localhost:3333.</p><p>Mitmproxy listens at 8080 by default, so we are going to do</p><pre>adb reverse tcp:8080 tcp:8080</pre><p>Now we can run a http proxy app on the target device and connect it to 127.0.0.1:8080 so that it connects to the mitmproxy. Then you should be able to see the network traffic.</p><h3>Conclusion</h3><p>We saw how easy it is to bypass the Network Security Config. All we needed to do was decompile, change an XML file, and recompile. To defend against modification of the APK, one can harden their APK using special tools that make apktool fail.</p><p><strong>Disclaimer:</strong> This post is intended solely for educational and research purposes. The techniques described here should only be applied to applications you own or have explicit permission to analyze. Reverse engineering, modifying, or intercepting traffic of third-party apps without consent may violate their terms of service and applicable laws. I do not encourage or condone using these methods against third-party apps without permission.</p><ol><li>Actually I used a script for this and it did not remove the domain-configs and pin-sets, it just added this base-config after them. I thought bypass would fail because pin-set tags would override the base-config, yet it works. <a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-network-security-config.html#fnref:1">↩</a></li><li><a href="https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/master/docs/user/adb.1.md">https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/master/docs/user/adb.1.md</a> <a href="https://oguzhanstech.com/2025/08/25/ssl-pinning-bypass-network-security-config.html#fnref:2">↩</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*wBJaKhEn_FYjw-lAlysz-A.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=268fc250fbdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GStreamer H264 Encryption Plugin]]></title>
            <link>https://medium.com/@oguzhanoztaskin/gstreamer-h264-encryption-plugin-cf2c7b43c383?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf2c7b43c383</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[gstreamer]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 06:12:41 GMT</pubDate>
            <atom:updated>2024-07-04T06:19:36.480Z</atom:updated>
            <content:encoded><![CDATA[<p>I have created a new GStreamer plugin for encrypting and decrypting H264 streams without breaking the stream. This way, the encrypted stream can be saved to the disc in MP4 format, streamed via RTSP, its alignment changed, all while maintaining proper decryption. Note that this plugin is experimental; for robust security, consider DRM solutions.</p><p>So, why did I bother with this then? Because I have worked on GStreamer a fair bit but I did not have anything to show until now. This project summarizes the most critical things I have learned, which are listed below:</p><ul><li>Inserting frame perfect metadata into H264 streams and reading it back.</li><li>Creating GStreamer plugins in C. This requires understanding of GLib type-system, which seems to be a rare skill.</li><li>Understanding of H264 stream structures, its NAL units, modifying streams at low level.</li><li>Understanding of GStreamer, its source code, and my debugging skills on it.</li></ul><p>Also it demonstrates my cryptography understanding:</p><ul><li>Modes of encryption: CTR, CBC, ECB etc.</li><li>Correct use of IV / encryption in a lossy medium. Encrypted H264 packets can get lost but this does not fail the decryption process.</li></ul><p>You can find the repository <a href="https://github.com/ReFormationPro/Gstreamer-H264-Encryption">here.</a></p><p>I will explain how I utilized such knowledge in this project below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDkSl5_UZSV_a1tPPBHcdQ.png" /><figcaption>Lock icon by <a href="https://www.flaticon.com/free-icons/lock">Freepik</a></figcaption></figure><h3><strong>Plugin Overview</strong></h3><p>This plugin contains two new elements: `h264encrypt, h264decrypt`. They are used in the most intuitive way:</p><pre>gst-launch-1.0 videotestsrc pattern=ball ! nvh264enc ! \<br>    h264encrypt iv-seed=31357476677378414 key=01234567012345670123456701234567 encryption-mode=aes-ctr ! \<br>    h264decrypt key=01234567012345670123456701234567 encryption-mode=aes-ctr ! \<br>    nvh264dec ! glimagesink</pre><p>Here, h264encrypt receives h264 encoded frames and encrypts them with the given key. IV seed is used to initialize random IV generator and encryption mode is just the encryption mode.</p><p>Then, h264decrypt receives the encrypted frames from h264encrypt element and decrypts them with the given key. This produces the exact same stream back. After this point, it can be used as h264 again.</p><p>Thus, what did we gain here? Nothing, we just encrypted and quickly decrypted it back. However, assume that you are streaming over an unsafe medium. Your packets could be listened and your video stream could be observed. To avoid that, you can simply do:</p><pre># To stream<br>gst-launch-1.0 videotestsrc pattern=ball ! nvh264enc ! h264parse config-interval=1 ! \<br>    h264encrypt iv-seed=31357476677378414 key=01234567012345670123456701234567 encryption-mode=aes-ctr ! \<br>    h264parse ! rtph264pay ! rtpsink address=127.0.0.1 port=1025<br><br># To receive and view<br>gst-launch-1.0 rtpsrc address=127.0.0.1 port=1025 encoding-name=H264 ! rtph264depay ! h264parse ! \<br>    h264decrypt key=01234567012345670123456701234567 encryption-mode=aes-ctr ! \<br>    nvh264dec ! glimagesink</pre><p>With these simple bash commands, you can stream your H264 encoded video over RTP with AES encryption.</p><h3><strong>How It Works</strong></h3><p>H264 stream consists of NAL units. This plugin accepts AU-aligned H264 streams in byte-stream (Annex-B<em>) </em>format. That means, h264encrypt receives H264 buffers that carry the data between two consecutive AU NAL units. I will call them “frames” from here on, though they need not to carry exactly one frame.</p><p>For each such frame, I iterate all NAL units and detect the first slice NAL unit of any kind (see last paragprah of this section). This kind of NAL units carry the video data and their payload is what I encrypt. However, for some encryption modes supplying only the key is not enough, they also need IV.</p><p>IV is a necessary public data and used both in encryption and decryption. Since it is public, I simply put it in H264 stream as Supplemental Enhancement Information (SEI) so that h264decrypt can later retrieve it and initialize its encryption context.</p><p>Thus, each slice-carrying H264 frame has one extra SEI NAL unit that has IV used for that frame. This IV is used to initialize the encryption context. It is positioned right before the first slice NAL unit and all slice NAL unit payloads of that frame is encrypted with that context. That completes the encryption process.</p><p>Decryption is similar. h264decrypt iterates all NAL units and finds the first SEI that carries the IV and initializes its decryption context. Then, h264decrypt removes that SEI and decrypts the frame using this decryption context.</p><p>Note that a stream can be encrypted and decrypted multiple times. If a frame is encrypted multiple times, multiple IV carrying SEI are inserted into the stream where the SEI of the most recent encryption is the first IV carrying SEI found in the stream from the start of the frame. During multiple decryption, the first SEI observed is used to initialize the decryption process and it is then removed from the stream.</p><h3><strong>Implementation</strong></h3><p>I kind of took the idea from <a href="https://discourse.gstreamer.org/t/is-it-possible-that-gsth264parser-and-gsth265parser-parse-encrypted-nal-data-header-isnt-encrypted/719/14">this discussion</a> and also received help from <strong>ndufrense</strong> to figure out what part of H264 stream to encrypt and decrypt. I used the gstreamer plugin template repository to start coding the plugin.</p><p>I used the following to implement the functionality described in the previous chapter:</p><ul><li><strong>Parsing and iterating NAL units:</strong> I used gst h264 nal parser for this.</li><li><strong>Finding slice NAL unit payload: </strong>Same as above. I used gst_h264_parser_parse_slice_hdr to parse the header and then calculated payload offset and size.</li><li><strong>Storing IV in H264 Stream:</strong> I used gst codecparsers to create SEI of payload type “user data unregistered” and stored the IV in it. This gave me a GstMemory * for SEI, which contains SEI NAL unit.</li><li><strong>Padding: </strong>I applied bit padding to the stream as it is the simplest to implement. I needed this to each slice payload.</li><li><strong>Emulation Prevention Bytes:</strong> Rarely, encrypted slice payloads contain illegal byte sequences. I inserted emulation prevention bytes (see <a href="https://membrane.stream/learn/h264/3">here</a>) in h264encrypt and removed them in h264decrypt.</li><li><strong>Random IV generation: </strong>I generate random IVs using random_r method of stdlib, whose seed is initialized with “iv-seed” property of h264encrypt. I allowed the use of a seed for the sake of easy reproduction of an encrypted stream for debug purposes. It is possible to use other IV generators by responding to “iv” signal of h264encrypt.</li><li><strong>AES cipher:</strong> I used “Tiny AES in C” implementation provided <a href="https://github.com/kokke/tiny-AES-c/tree/master">here</a>.</li><li><strong>Elements: </strong>I used gstreamer plugin template as base repository and used GstBaseTransform as base to implement h264encrypt and h264decrypt elements.</li></ul><h3><strong>Limitations</strong></h3><ul><li>It is very slow as encryption is on CPU and single threaded.</li><li>This is a non-standard encryption scheme for H264. Thus, you have to use this plugin on both streaming and receiving sides to encrypt and decrypt it. Existent tools will not support it.</li><li>This scheme is experimental and comes with no guarantee. You might want to look into DRM and/or other tools for this task.</li><li>Key property is visible when used with gst-launch-1.0 and this might cause accidental leaks of keys. This plugin should be used with gst-launch-1.0 command only for debugging purposes as it leaks the key in several ways (ie. ps command lists gst-launch-1.0 command args). The correct use of the plugin is inside of a GStreamer application. Key is write-only and not visible in bin graphs.</li><li>Absolutely no guarantee of any sort.</li></ul><h3><strong>Afterthoughts</strong></h3><p>The implementation was not hard as GstBaseTransform provided a good point to start writing elements, gst h264 nal parser was easy to understand, and I received help in the GStreamer Discourse forum. There were some confusing offset calculations and for some stuff I only had struct member name to guess what it is and how it is used. However, I did not lose much time on them. At the end, this plugin worked as I intended: Encryption before streaming over RTP, still works after changing stream properties, packet loss does not break it. It is just a bit slower than I expected. Maybe a faster algorithm or AES implementation can be used. Maybe AES-CTR mode can be parallelized to get some speed-up. However, these are out-of-scope of this project.</p><p>I hope you enjoyed the read.</p><p>If you missed, <a href="https://github.com/ReFormationPro/Gstreamer-H264-Encryption">here is the repository.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2c7b43c383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autopilot: Flight Simulator for Embedded Systems Development]]></title>
            <link>https://medium.com/@oguzhanoztaskin/autopilot-flight-simulator-for-embedded-systems-development-7126a7c206c1?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7126a7c206c1</guid>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 08:37:01 GMT</pubDate>
            <atom:updated>2024-06-26T08:37:01.195Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone again! In this article, I will talk about the simulator I created for my students as part of an assignment. It runs and tests the students’ homeworks which simulate a flight of a plane. You can browse the repository by clicking <a href="https://github.com/ReFormationPro/AutopilotFlightSimulator">here.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUaG3jZGs3QBix8DMDOjPg.png" /><figcaption>Altitude Mode of the Simulator</figcaption></figure><p>I used PyGame to implement its UI, and used pyserial to communicate with the board.</p><p>I will shortly talk about its features and then focus on the development process I had.</p><h3><strong>Features</strong></h3><ul><li>Semi-periodic serial communication with the board. Expects periodic messages from the board and sends commands / replies to the board.</li><li>Shows altitude zones in its PyGame UI as in the screenshot, and expects the user to align the plane to the expected altitude via ADC.</li><li>Lits leds and expects the corresponding buttons to be pressed.</li><li>Expects errors and logs them. Logs are used for grading.</li><li>Consists of many modular components called agents, which will be the focus of this article.</li></ul><p>For a demo of the ADC controls, you can watch this YouTube video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJkjKEpW0Qds%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJkjKEpW0Qds&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJkjKEpW0Qds%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3c6032a1d7b29e63b7cc0a8cc312fb/href">https://medium.com/media/7d3c6032a1d7b29e63b7cc0a8cc312fb/href</a></iframe><p><strong>Hustles of Development</strong></p><p>In the following sections, I will share my opinions and comments on PyGame and the design I followed.</p><h3><strong>PyGame</strong></h3><p>PyGame library allows you to create a window, draw shapes, set FPS etc. on a <em>very basic</em> level. PyGame lacks many fundamental higher level things I would expect from a graphics library (like a container system or alike as in PIXI) that has “game” (you work with composed entities) in its name. However, this is just my expectation and I understand that if it does not have to or maybe it is better this way.</p><p>Thus, I had to create those higher level things from scratch. I created a container system because that was how I worked with PIXI JS. The best things I produced are I believe:</p><ul><li>Sliding background image with perfect tile loop.</li><li>Container system for ease of control of UI elements.</li><li>Simple text anchors.</li></ul><p>Containers allowed me to make UI components modular. I could put images, texts, containers in a parent containers and move the parent container around with everything in it also moving the same way. I was developing in agile fashion, and I knew I had to try different things with the UI, so I had to make sure it was flexible enough and it really paid off. Same with the text anchors.</p><p>Also, you do not even have transparency right out of the box. In order to draw a semi-transparent rectangle, you need to draw it onto a surface (call it canvas) with SRCALPHA attribute and then blit that canvas onto the target surface. That’s how I created the semi-transparent altitude zones.</p><p>Making a sliding background image was similar. I had to draw the repeating tiled image on a temporary surface I called canvas, then blit a region of that canvas onto the target surface in order to crop it. This is because you cannot select what region of the source surface will be blitted (aka. cropping) but you can select within which region of the target surface you will blit it to. Thus, everything that falls out of that destination region is lost. That’s how you achieve cropping. Counter-intuitive to me but I guess that is just as much as valid as cropping is. Maybe this way it is easier to implement and port? Maybe the underlying library is this way?</p><p>Overall, despite lacking the tools I am used to and being counter-intuitive to me, PyGame is good and docs and troubleshooting were good too.</p><h3><strong>Agents</strong></h3><p>Designing the agents was the most fun part of the design process. I designed the agents from the most abstract classes to more solid and useful classes. The simulator consisted of various interacting systems that override each other. In order to leave space for changes and avoiding tight coupling, this was necessary. With back and forth interactions, really hard to debug/fix bugs could have occurred but I did not run into them with this design.</p><p>Below, I list the important agents from the most abstract to the solid:</p><ul><li>Agent: Defines and implements Agent interface and basic functionalities.</li><li>ThreadedAgent extends Agent: Base class for agents that require a thread. Provides functions for starting and stopping its worker thread.</li><li>CommandDispatcherAgent extends ThreadedAgent: Commands received are fed into a queue (CommandQueue) elsewhere. This agent blocks on this queue and dispatches the commands to its sub-agents as soon as it gets the commands. Since it is blocking, it needs its own thread.</li><li>AlarmAgent extends ThreadedAgent: Simulator uses timed events for changing its states. Many agents need to act on certain times: Leds needs to be turned off after timing out by LedAgent, AltitudeControllerAgent needs to enter and exit to altitude mode, fake commands will be sent etc. AlarmAgent uses a single thread to wait for the soonest event / alarm in its queue (a priority queue) and provides methods to add new events anytime. Existent alternative solutions I found created a new thread for each alarm requested.</li><li>PeriodicAgent extends Agent: An abstract agent that consumes or rejects the command received during the current period. Details on PeriodicityAgent.</li><li>PeriodicityAgent extends Agent: Subscriber of the CommandDispatcherAgent. Checks if the retrieved message belongs to the current period, and if so, attempts to feed the command into its PeriodicAgents by the order of importance.<br>PeriodicAgents need to know if they missed a message or if they are overriden by a higher priority PeriodicAgent during that period. If they missed a message, that’s a failure and if they were overriden, they did not fail.<br>PeriodicAgents only consume or ignore a message, the state and delivery of the message is handled by the PeriodicityAgent. This simplifies the interactions between the agents.</li><li>DistanceAgent, LedAgent, AltitudeAgent etc. extend PeriodicAgent: They are all agents of periodic messages handled by PeriodicityAgent.</li></ul><p>That’s all for the agents.</p><p>To conclude, in this project I learned or practiced PyGame, blitting images, timing events, simplifying complex interactions between different modules (agents). I wanted this simulator to be the base implementation of evaluators for embedded course’s assignments but it still has way to go. For example, more interactions among the agents can be simplified or more focus for the non-periodic messages can be given.</p><p>Thank you for reading my article. I hope you enjoyed.</p><p>Once again, to browse the repository you can click <a href="https://github.com/ReFormationPro/AutopilotFlightSimulator">here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7126a7c206c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Get Fast VPN On PC with EveryProxy?]]></title>
            <link>https://medium.com/@oguzhanoztaskin/how-to-get-fast-vpn-on-pc-with-everyproxy-a0b6517fecd9?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0b6517fecd9</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[vpn]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 05:46:34 GMT</pubDate>
            <atom:updated>2024-06-25T05:46:34.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVcmvIegoIzjLgp9G9FV2A.jpeg" /><figcaption>VPN Image by <a href="https://www.freepik.com/free-vector/hand-drawn-flat-design-vpn-illustration_22111243.htm">freepik.com</a></figcaption></figure><p>Did you know that free mobile VPNs are faster than those browser extension based free VPNs? You can use mobile VPNs on your personal computer if you want to. It is really easy. Just make sure you are allowed to do so by checking terms of use of the mobile VPN etc.</p><p>In this tutorial I will show you my setup. We are going to use <em>Proxy Switch Omega</em> browser extension and <em>EveryProxy</em> proxy server.</p><p>Note that I am using Chrome browser on my PC and the mobile device I am using is Android.</p><p><strong>Installation Steps:</strong></p><ul><li>Install <em>Proxy Switch Omega</em> for Chrome or Firefox on your personal computer. It may be available for other browsers too.</li><li>Install EveryProxy on your mobile.</li><li>Find and install a free, fast mobile VPN.</li></ul><p><strong>Connection Steps For Mobile:</strong></p><ul><li>Turn on mobile data or your WiFi, whichever you will be sharing with your computer.</li><li>Turn on hotspot. For the most of the recent mobile devices I had, you could connect to a WiFi and share it/extend it via hotspot feature. That’s what I am doing.</li><li>Open EveryProxy and configure:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*cv0zhIK2LIh-UPH1eNpBzA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*JacJJsihdETmgX53oA13KQ.jpeg" /><figcaption>Configured and running EveryProxy</figcaption></figure><p>On settings page on the left, make sure HTTP proxy listens on an IP address such that pc can access the phone through hotspot connection. Clicking on “IP Address” will show you a list of all IP addresses you can listen on. For me, the bottom most one is the correct one but I used 0.0.0.0 to listen on all IP addresses. Also, remember the port you set here, 8080 in my case.</p><p>Next, go back to the initial page and start the proxy. If all is good, you should see something similar.</p><p><strong>Connection Steps for PC:</strong></p><ul><li>Connect to the hotspot.</li><li>Open your browser and go to the <em>Proxy Switch Omega</em><strong><em> </em></strong>settings by clicking on the extension icon and then “Options” item:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*Akku5Dx8iGMeuxoDioEOhA.png" /><figcaption>Quick menu of the proxy</figcaption></figure><ul><li>On the options page, click “New profile” on the left menu and create “mobile-proxy” profile as I do:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufG_EIKFgmiKaMDUBJUmhA.png" /></figure><ul><li>In the proxy servers table, choose the protocol as HTTP and fill in the EveryProxy listening IP address and port as server and port in the table. If you are using 0.0.0.0 as EveryProxy listening IP address, you need to use one of the ip addresses in<strong> &lt;your ip addresses&gt; </strong>I indicated in the screenshots of the EveryProxy. I had three IP addresses, one being the IP address as observed by the outside, and all of them worked.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*XjUMLGqNkADBrUqERyvnrg.png" /><figcaption>Profile proxy settings</figcaption></figure><ul><li>Do not forget to apply the changes:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*BAQ7FRmc54I9iZVfXd_P6g.png" /><figcaption>Apply changes</figcaption></figure><ul><li>Now go to a webpage, such as google.com test the proxy by changing to mobile-proxy config:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*2nPQFmeSAh9ObbGb0_xheQ.png" /></figure><ul><li>To see if your IP address has changed you can use websites like <a href="http://ifconfig.me/">ifconfig.me</a>. You can compare your IP with and without proxy on. To switch the proxy off, you can simply choose <strong>[System Proxy] </strong>option in the quick menu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Tp0SNe1th9j38eyUbjqaGQ.png" /><figcaption>Checking if IP address is changed by browsing this page with and without proxy on</figcaption></figure><p>Thus, you have successfully used your mobile VPN on your PC. However, please ensure that you are not violating the terms of use of the mobile VPN app by doing this setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0b6517fecd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Cross-Platform Plugin Architecture with Libtool for Dynamic Loading in C/C++]]></title>
            <link>https://medium.com/@oguzhanoztaskin/building-cross-platform-plugin-architecture-with-libtool-for-dynamic-loading-in-c-c-b2339e1ac143?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2339e1ac143</guid>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[dynamic-loading]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 07:51:16 GMT</pubDate>
            <atom:updated>2024-01-29T07:51:16.756Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how some applications can extend their behavior by installing some libraries in certain directories? Without needing any recompilation, they dynamically discover these libraries and provide additional functionality. I have always been curious about this concept, and finally, I created my own plugin architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*ehMuCiYE1Bw_fP3iuliZRg.png" /><figcaption>Achieving the same result in this article by more familiar and simpler methods, dlopen and dlsym</figcaption></figure><p>I think I had first seen this when I was playing Minecraft as a kid. Minecraft Bukkit server had plugins in jar format (library/applications for Java) that you could download from the Bukkit’s website, start your server, and immediately see the plugin in effect. Then, in my professional life, I have used GStreamer and ROS2 which also had their own plugins as C/C++ libraries. I was developing a <strong>GStreamer — ROS2 bridge</strong> and then realized a need for plugins for the bridge as different ROS2 messages were necessitating small extensions to the code. Ideally, no one needed to know GStreamer to extend the bridge, so I created a lightweight plugin architecture with no GStreamer dependency (does not link to GStreamer or use its headers).</p><p><strong>What I Used to Achieve This and How It Works</strong></p><p>The architecture was supposed to be cross-platform thus I could not just use <strong>dlopen </strong>as Windows had <strong>LoadLibrary</strong>. I needed a wrapper for these different operating systems and I chose <strong>Libtool </strong>for being a lightweight tool.</p><p>Libtool uses familiar names like <strong>lt_dlopen</strong> and <strong>lt_dlsym</strong>. The first one is used to load a library programmatically, and the second one used to get a pointer a symbol in it. For example, you can lt_dlopen(“libplugina.so”) and get a handle to it, then use lt_dlsym to get a pointer to where “kPluginDesc” struct is. For example:</p><pre>#include &lt;map&gt;<br>#include &lt;cstddef&gt;<br><br>class PluginDesc {<br>  public:  <br>    const char *pluginName;<br>    virtual void customFunction(void *customArg, std::size_t arg_size) = 0;<br>};<br><br>extern PluginDesc *kPluginDesc;</pre><p>This is the most basic plugin interface. Any plugin has to contain a symbol called “kPluginDesc”, which is a global pointer to the “PluginDesc” class of the plugin. Here, customFunction is a virtual method because, with dynamic loading, the type information is not available to us. Hence, we cannot cast the PluginDesc abstract class to a concrete class. Thus, non-virtual functions would be inaccessible — well, maybe with lt_dlsym we could achieve that but there is no need.</p><p>Note that I also declared kPluginDesc to be extern. If I do not do this, the compiler removes that symbol in order to decrease the library size and avoid initializing something that is not used, thus decreasing the loading time of the library.</p><p>Now assume the following code is run:</p><pre>lt_dlhandle handle = lt_dlopenext (&quot;libmyplugina&quot;);<br>PluginDesc *pluginDesc = *(PluginDesc **) lt_dlsym (handle, &quot;kPluginDesc&quot;);<br>std::cout &lt;&lt; &quot;Plugin Name: &quot; &lt;&lt; pluginDesc-&gt;pluginName &lt;&lt; std::endl;<br>pluginDesc-&gt;customFunction(nullptr, 0);</pre><p>Here, I first used lt_dlopenext so that Libtool would try different suffixes like “.so” or “.dll” depending on the platform. Thus, I do not have to worry about differences between file extensions among different platforms.</p><p>Second, I used the handle to retrieve a pointer to the “kPluginDesc” symbol. Be careful here, the symbol itself is a pointer to a PluginDesc object, lt_dlsym returns a pointer to the symbol, hence the return value of lt_dlsym is “PluginDesc **”, not “PluginDesc *”.</p><p>Finally, I have a pointer to the plugin’s PluginDesc object and thus I can use the plugin now. The rest is just like using abstract classes. As a very simple example, you can name your plugin “increment” and have customFunction increment the integer you give as the first argument, or you can name your plugin “song-suggest” and call the customFunction with a char buffer and get a song suggestion in it after the function returns. Notice that you need to know where the plugin can be used and with what, and it all depends on you. In my case, it does some conversions between GStreamer buffers and ROS2 messages.</p><p><strong>Conclusion</strong></p><p>In wrapping up, I successfully crafted a cross-platform plugin architecture using Libtool to tackle dynamic loading intricacies across different systems. Leveraging lt_dlopen and lt_dlsym, I established a core framework. The PluginDesc interface, featuring the crucial kPluginDesc symbol, ensures smooth interaction with plugins while keeping things platform-independent.</p><p>This architecture is all about flexibility. It lets you expand functionalities through plugins without the hassle of recompilation of the entire library. In my professional work, I even removed a core dependency from the plugin architecture, GStreamer, demonstrating how powerful plugins are at abstraction.</p><p>I hope this was an interesting read. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2339e1ac143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Hidden Potential: Exploring the Power of Shared Pointer Aliasing Constructors in C++]]></title>
            <link>https://medium.com/@oguzhanoztaskin/unlocking-hidden-potential-exploring-the-power-of-shared-pointer-aliasing-constructors-in-c-1be2faa7b2a1?source=rss-fe9afbc7571a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be2faa7b2a1</guid>
            <category><![CDATA[type-casting]]></category>
            <category><![CDATA[aliasing]]></category>
            <category><![CDATA[shared-pointer]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Oguzhan Oztaskin]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 07:10:34 GMT</pubDate>
            <atom:updated>2024-01-22T07:10:34.396Z</atom:updated>
            <content:encoded><![CDATA[<p>Shared pointers are very important tools to manage memory. However, I don’t think many of us aware of some very useful features of them. Today, I will write about the aliasing constructor, specifically in what way they are useful and give an example.</p><p>Aliasing constructor has the following signature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*kAG49GnONSnu1jGSDM0cJg.png" /><figcaption>Taken from: <a href="https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr">https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr</a></figcaption></figure><p>Here, when reading this signature do not make the same mistake I made. I read this as a shared pointer that points to type Y; however, Y is just the template parameter of the constructor that allows its first argument to be a pointer of any type, instead of what I thought: Type of the stored pointer. The type information is on the template of the class and it is called T:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*YfJQe5aaFWssRBs7Xi0Gxg.png" /><figcaption>Taken from: <a href="https://en.cppreference.com/w/cpp/memory/shared_ptr">https://en.cppreference.com/w/cpp/memory/shared_ptr</a></figcaption></figure><p>Upon reading the signature, the type of the first argument reminds me of the copy constructor/assignment argument, that is I thought that the first argument is something to be copied. Moreover, this is a constructor and hence we are creating a shared pointer. It seems like there is something related to the ownership of the object pointer by the first argument. That is indeed the case.</p><p><strong>What Is Aliasing Constructor Used For?</strong></p><p>It is used for creating a shared pointer that shares the ownership with the given shared pointer (first argument) but that returns the second argument when de-referenced. The following code illustrates this:</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br>#include &lt;string&gt;<br><br>typedef struct MyStruct {<br>   int a;<br>   char b;<br>   std::string str;<br>} MyStruct;<br><br>int main(int argc, char *argv[]) {<br> std::shared_ptr&lt;MyStruct&gt; a { new MyStruct {1, 2, &quot;secret string&quot;} };<br> std::shared_ptr&lt;std::string&gt; b(a, &amp;a-&gt;str);<br> std::cout &lt;&lt; &quot;Str: &quot; &lt;&lt; *b &lt;&lt; std::endl;<br> return 0;<br>}<br>// Outputs &quot;Str: secret string&quot;</pre><p>Here, I created a shared pointer called “a”, and then created another shared pointer for the pointer “&amp;a-&gt;str” called “b”.</p><p>How is this useful? Assume you do not need pointer “a” as you are not working with “MyStruct” object but you are only working with its child, “str”. In order to keep using “str”, you need to make sure that “MyStruct” object is not destroyed, or else “str” will also be destroyed. In other words, you want to manage “str”s lifetime with a shared pointer but you cannot directly own it. The aliasing constructor allows you to achieve this. “b” shares the ownership of the object owned by “a” but it is a shared pointer to “a-&gt;str” actually. If “a” goes out of scope and destructed but “b” is still alive, “*a” will not be destructed until “b” is destructed too. This ensures “*b” will point to a valid std::string.</p><p>Note that second argument does not have to be related to the first argument at all. The above is just an example I came up with. You can use it in other ways as well.</p><p><strong>Example 1: Shared Pointer Casting</strong></p><p>One place the aliasing constructor is used is something you may already know: <a href="https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast">“std::static_pointer_cast” method and alike.</a> They basically use the aliasing constructor to create a shared pointer that returns the same address when de-referenced but with the cast type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkOy2d2rinrluV_fUDG6DA.png" /><figcaption>Taken from: <a href="https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast">https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast</a></figcaption></figure><p>Above, shared pointer “r” is casted to shared pointer of type T, where T is the type of the cast target.</p><p><strong>Example 2: Working with complicated dependencies</strong></p><p>Here is a case I faced: I was defining a common interface for managing various types and I was working with shared pointers. I needed to extract a certain field from objects maintained by shared pointers, and I could not simply copy that field as it was large. Furthermore, I was going to lend this field to other parts of the application so there was no way to tell how long this data was needed. Hence, I decided to use the aliasing constructor.</p><p>My function signature — which is a factory method btw — was like the following:</p><pre>bool GetImage(const std::shared_ptr&lt;void&gt;&amp; message, std::shared_ptr&lt;uint8_t&gt;&amp; image, size_t &amp;image_size);</pre><p>Here, the first argument is the container of the field I am interested in, and the rest of the arguments are the outputs of this function. A const left reference can be bound to both left and right values, so that’s why I used it for my first argument. I had multiple values to be returned, so I used non-const references for the other arguments.</p><pre>bool GetImage(const std::shared_ptr&lt;void&gt;&amp; message, std::shared_ptr&lt;uint8_t&gt;&amp; image, size_t &amp;image_size) {<br>    std::shared_ptr&lt;CustomMessageA&gt; msg = std::dynamic_pointer_cast&lt;CustomMessageA&gt; (message);<br>    if (!msg) return false;<br>    image = std::shared_ptr&lt;uint8_t&gt;(msg, (uint8_t *)&amp;msg-&gt;image);<br>    image_size = msg-&gt;image_size;<br>    return true;<br>}</pre><p>Here is a potential implementation for the function signature I shared before. Using aliasing constructor, I create a shared pointer to uint8_t that shares the ownership of the given message. Thus, I do not copy the large image and I do not need to worry about input message’s lifetime.</p><p>There are a few shortcomings of this solution:</p><ul><li>Somewhat hard to understand what it does</li><li>Create a very short-lived shared pointer “msg”</li><li>The input message could be huge even when the image field is excluded. We are delaying its deallocation and potentially increasing the memory use.</li></ul><p><strong>Conclusion</strong></p><p>We have seen that the aliasing constructor can be used for type casting, keeping a shared pointer to a member of another shared pointer, and efficiently managing memory. Though in certain cases, it can delay the deallocation of the shared pointer and increase memory use, too.</p><p>I hope you enjoyed my article. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be2faa7b2a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>