Compare commits

...

156 Commits

Author SHA1 Message Date
Carter Li 4dfba31cae Merge pull request #1911 from fastfetch-cli/dev
Release: v2.50.2
2025-08-16 21:50:39 +08:00
Carter Li 3004f29c08 Release: v2.50.2 2025-08-16 21:18:07 +08:00
李通洲 b994ce5b55 LocalIP: refines default route detection and JSON output for local IPs
Add verbose log for Windows
2025-08-16 18:27:30 +08:00
李通洲 6356f9d0e5 Netif (Linux): improves default route detection and error handling
Ref: #1902
2025-08-16 17:15:44 +08:00
李通洲 597c6f3dbc Netif (Linux): add verbose logs 2025-08-16 15:13:07 +08:00
李通洲 41cffac80c CI: adds default build type to CI environment 2025-08-16 13:10:35 +08:00
李通洲 c4cb6c65a9 LocalIP (Linux): add verbose debug log 2025-08-16 04:43:28 +00:00
李通洲 46081a3e52 LocalIP (Linux): fixes incorrect return and ensures struct initialization 2025-08-16 04:24:26 +00:00
李通洲 a5fd671b92 LocalIP: fix showMac does not honor defaultRouteOnly 2025-08-15 20:20:43 +08:00
李通洲 8319512c83 Merge remote-tracking branch 'origin' into dev 2025-08-15 08:58:15 +08:00
Ashish SHUKLA c1db692982 FFstrbuf: wrap yyjson.h include in conditional 2025-08-15 08:49:53 +08:00
Guiling Qiyu aec2bfd2a4 Packages (Linux): fixes Linglong detection by counting linglong layers (#1903)
* Packages (Linux): fixes Linglong detection on Deepin

* Packages (Linux): fixes Linglong detection to count layers

* Update src/detection/packages/packages_linux.c

---------

Co-authored-by: Carter Li <CarterLi@users.noreply.github.com>
2025-08-14 19:47:20 -05:00
Carter Li 7bacf20f72 Merge pull request #1901 from fastfetch-cli/dev
Release: v2.50.1
2025-08-14 22:35:06 +08:00
Carter Li 1479de19ef Release: v2.50.1 2025-08-14 18:34:30 +08:00
Guiling Qiyu bb9ca73db1 Packages (Linux): fixes Linglong detection on Debian (#1899)
Fixes #1898
2025-08-14 18:06:42 +08:00
李通洲 81bac8bca4 Percent: refactors bar color logic for clarity and consistency; update examples 2025-08-14 16:47:30 +08:00
李通洲 56d22292b0 Revert "Percent: fix a copy-paste error"
This reverts commit 3345c1e9dd.
2025-08-14 16:04:55 +08:00
李通洲 9a11ff8ddb Packages (Android): fix building 2025-08-14 14:42:09 +08:00
Carter Li a99b6d602d Merge pull request #1897 from fastfetch-cli/dev
Release: v2.50.0
2025-08-14 14:24:33 +08:00
李通洲 40921156b8 Doc: update changelog [ci skip] 2025-08-14 14:23:37 +08:00
李通洲 bc3703140b Doc: update changelog 2025-08-14 13:58:21 +08:00
李通洲 bd5b385909 Flashfetch: disable decimal digits in Disk module 2025-08-14 13:32:21 +08:00
李通洲 0fe3db419e Separator: honors FQDN settings in Title module 2025-08-14 13:30:02 +08:00
李通洲 e80bb480c4 Doc: update changelog 2025-08-14 11:03:26 +08:00
李通洲 d4773212b7 Fastfetch: adds support for reading JSON config from stdin 2025-08-14 11:00:35 +08:00
李通洲 9ebff9fd22 Chore: removes undocumented flag --load-config 2025-08-14 10:43:22 +08:00
李通洲 5d8edc0c8b Doc: update changelog [ci skip] 2025-08-14 10:27:02 +08:00
李通洲 78530b4e34 Release: v2.50.0 2025-08-14 10:20:05 +08:00
李通洲 61f2823903 Global: fixes -ffast-math compatibility
Unifies unset double handling using `-DBL_MAX` sentinel

Fixes #1894
2025-08-14 10:01:34 +08:00
李通洲 7446828866 GPU (macOS): don't set platformApi to Metal when Metal API is not used 2025-08-14 08:34:56 +08:00
李通洲 0b37acec5b GPU (Windows): ignore software adapters; add verbose logs 2025-08-14 01:07:39 +08:00
李通洲 53ecf57f19 Doc: update changelog [ci skip] 2025-08-13 10:08:25 +08:00
李通洲 e1c4365c10 Cursor (macOS): improves color detection and rounding for cursor info 2025-08-13 09:28:25 +08:00
NEOAPPS ebc60ac66c Logo (Builtin): add ObsidianOS (#1890) 2025-08-12 21:32:38 +08:00
李通洲 4004501d0f Packages: unifies Nix package detection code
Fixes: #1893
2025-08-12 19:37:52 +08:00
李通洲 a0265c3204 CI: upgrade to actions/checkout@v5 2025-08-12 09:20:04 +08:00
Osama Albahrani 3ef84834fc README: HomeBrew -> Homebrew (#1891) [ci skip]
See https://brew.sh
2025-08-11 20:08:11 -05:00
李通洲 3276949663 Doc: update README & Changelog 2025-08-11 16:42:53 +08:00
李通洲 1ec69d6838 OS (Linux): tidy 2025-08-11 16:38:39 +08:00
李通洲 7f1063d09b Revert "CPU (macOS): use CPUID for freq detection on Intel"
This reverts commit 7ee0e8726e.
2025-08-11 16:35:35 +08:00
李通洲 883923de4a CI (Haiku): reduce errors when installing deps (hopefully) 2025-08-11 15:27:20 +08:00
李通洲 146981009b CommandLine: add --gen-config-full 2025-08-11 14:49:22 +08:00
李通洲 060b69293c Presets: add an example
Fix #1887
2025-08-11 14:19:09 +08:00
李通洲 3345c1e9dd Percent: fix a copy-paste error 2025-08-11 14:18:41 +08:00
李通洲 1c8e2e34ba JsonSchema: remove unused properties [ci skip] 2025-08-11 14:16:13 +08:00
李通洲 5ab51c07d1 Doc: don't recommand Ubuntu PPA [ci skip] 2025-08-11 09:58:44 +08:00
Juanma eee98e54d0 OS (Linux): fix lliurex detection (#1882)
* Proper detection of lliurex distribution

* fix newline

* Trim version and not versionID as assigned to lliurex-version  output

* Update os_linux.c

---------

Co-authored-by: Carter Li <CarterLi@users.noreply.github.com>
2025-08-10 20:45:53 -05:00
Carter Li b0340d5581 DisplayServer: merge serverVender into wmProtocolName
Fix #1888
2025-08-11 09:16:05 +08:00
aequabit 1124342eda Display (Linux): show brand of Xserver in WM section (#1888)
* Display: add server vendor string

* Display (X11): fetch server vendor string using XCB/Xlib

* WM: show server vendor string when not empty

* Display (XCB): use proper string helper function

* Display (X11): shorten "The X.Org Foundation" to "Xorg"
2025-08-11 09:03:23 +08:00
李通洲 329cb229f8 Chore: remove unused functions 2025-08-10 23:15:13 +08:00
李通洲 bedb5eb6c5 Netif (SunOS): work around a bug that fails to detect default route for IPv4 2025-08-10 21:42:01 +08:00
李通洲 f184f8dab5 GPU (FreeBSD): fix gpu driver detection when DRM is used 2025-08-10 08:48:00 +08:00
Carter Li 7ee0e8726e CPU (macOS): use CPUID for freq detection on Intel 2025-08-10 00:14:16 +08:00
Carter Li a7347130de LocalIP (Linux): fix building 2025-08-09 22:20:04 +08:00
Carter Li f3c82ad837 LocalIP (SunOS): add speed detection support 2025-08-09 19:53:31 +08:00
Carter Li 1bde2b31f9 LocalIP (SunOS): support isIPv6AddressPreferred 2025-08-09 19:27:07 +08:00
Carter Li 1edc617b55 LocalIP (SunOS): add more if flags 2025-08-09 19:19:50 +08:00
李通洲 2bb451d9e4 LocalIP (Linux): fix compiler warnings 2025-08-09 18:44:37 +08:00
李通洲 4588644d39 Networking (SunOS): fix compiler warnings 2025-08-09 18:35:53 +08:00
李通洲 ed94b4c46c Netif (SunOS): fix compiler warnings 2025-08-09 18:34:25 +08:00
Carter Li f96ddb4c10 LocalIP (BSD): fix compiling 2025-08-08 15:32:12 +08:00
李通洲 1b0a65ecf2 Wifi: updates default WiFi percentage thresholds 2025-08-08 14:59:39 +08:00
李通洲 33983c5402 LocalIP: improve preferred IPv6 address detection 2025-08-08 14:40:04 +08:00
李通洲 8cfee9d693 Netif: unifies BSD netif handling 2025-08-08 11:03:04 +08:00
Carter Li 64568b31d1 Netif (Haiku): add preferred source addr 2025-08-08 10:03:43 +08:00
李通洲 02c999725c NetIO (SunOS): fix build 2025-08-07 23:30:53 +08:00
李通洲 be11013ae2 LocalIP (BSD): fix building 2025-08-07 23:28:54 +08:00
Carter Li a84c4dc1f4 Netif: refactor API for dual-stack route detection
Unifies IPv4 and IPv6 default route queries under a shared result structure and per-family functions. Improves clarity and extensibility by centralizing route logic, streamlining detection of preferred interfaces, and updating all consumers to use the new API.

Prepares for more robust multi-protocol network information handling.
2025-08-07 16:35:42 +08:00
李通洲 d9455adc7f Display: fix invalid size.maxPrefix default value in generated config file 2025-08-06 21:57:21 +08:00
李通洲 b20aea7ab8 Netif (BSD): split different implementations 2025-08-06 13:58:41 +08:00
Jannis Pohl 5e770dc8b0 LocalIP: consider preferred source address when retrieving default route (#1883)
* LocalIP: consider preferred source address when retrieving default route

* LocalIP: fix logic error when there is no preferred source address

* LocalIP: use macros rather than manual free/close

* LocalIP(BSD): fix build error

* LocalIP: address Copilot suggestions
2025-08-05 23:30:06 +08:00
李通洲 137d5dfe90 LocalIP (Windows): show only preferred IP when showAllIPs is not set
Ref: #1883
2025-08-05 19:35:54 +08:00
李通洲 655d11c1cc Chore: fix building on Windows 2025-08-05 19:15:52 +08:00
李通洲 e32987c408 JsonConfig: make all non-module keys case-sensitive 2025-08-05 16:47:48 +08:00
李通洲 fa4e11c73b JsonConfig: write all flags when generating config file 2025-08-05 16:47:48 +08:00
李通洲 e753d4d3a4 Doc: remove command line flags of modules 2025-08-04 15:08:30 +08:00
李通洲 75d2c668d0 Modules: refactor module option handling for static allocation
Moves module option structs out of global config and removes dynamic allocation, using static buffers and size assertions for safer, simpler management.

Refactors module initialization and destruction to work with isolated option structs, eliminating the need for the previous modules container and related code.

Unifies module option header usage and updates detection logic to leverage statically-sized option buffers, improving encapsulation and maintainability.

Simplifies module function signatures and reduces coupling between modules and config.

Enhances future extensibility and reliability by enforcing max size constraints and removing unnecessary indirections.
2025-08-04 14:46:01 +08:00
李通洲 559082806b Modules: export module info 2025-08-04 00:06:28 +08:00
李通洲 6f8d276545 Modules: add init and destroy option callbacks to module info 2025-08-03 18:40:53 +08:00
李通洲 582268f44f Disk (Linux): ignore Bedrock Linux subvolumes
Ref: https://github.com/fastfetch-cli/fastfetch/issues/1881#issuecomment-3148302531
2025-08-03 18:19:45 +08:00
李通洲 9b68674c4f OS (Linux): don't detect Bedrock linux when ran restricted
Fix #1881
2025-08-03 18:18:12 +08:00
李通洲 badae2ba9d JsonSchema: Improves JSON schema enums with oneOf objects containing descriptive explanations for allowed values 2025-08-03 10:22:32 +08:00
李通洲 dd4f006b5f GPU: support "hideType": null 2025-08-03 10:22:32 +08:00
李通洲 c491c9e8fc Display: add compactMode: null; improve json schema 2025-08-03 10:22:32 +08:00
李通洲 094d736d38 Modules: remove all parseCommandOptions and related stuff 2025-08-03 10:22:32 +08:00
李通洲 22bfaf3c69 JsonSchema: small improvements 2025-08-03 10:22:32 +08:00
李通洲 980e552eba Display: allow "compactType": null; improve json schema 2025-08-03 10:22:32 +08:00
李通洲 4a141c3f57 Disk: add missing JSON config options 2025-08-03 10:22:32 +08:00
Carter Li 59289bef6c Percent: silense compiler warnings 2025-08-02 19:03:42 +08:00
李通洲 0b02543ef2 JsonConfig: refactor JSON key handling to improve safety and consistency
Also make keys case-sensitive
2025-08-02 18:51:03 +08:00
李通洲 3cef51ec4a JsonConfig: refactor string buffer JSON handling for robustness 2025-08-02 17:41:19 +08:00
李通洲 6d86813647 Doc: update changelog; fix typo 2025-08-01 16:36:32 +08:00
李通洲 fb267acac3 Presets: add new config; fix old config 2025-08-01 16:06:03 +08:00
李通洲 ba3e26f2b4 Option: fix a possible null reference segfault 2025-08-01 16:05:18 +08:00
李通洲 4f8d8de749 Doc: update changelog [ci skip] 2025-08-01 15:39:19 +08:00
李通洲 54c5bc5110 Bar: refactor config to use nested objects and deprecates old fields 2025-08-01 15:12:30 +08:00
李通洲 c6675f82f0 Bar: add customizable bar color options for percentage bars 2025-08-01 15:03:24 +08:00
李通洲 afe2c85047 Bar: add configurable elapsed bar borders for percent bars
Fix #1875
2025-08-01 15:03:24 +08:00
李通洲 671b11157e Wifi (macOS): disable using of ipconfig on 15.6 too
Ref: #1874
2025-08-01 08:54:31 +08:00
李通洲 78fb55c35c Chore: remove sensitive data [ci skip] 2025-07-31 18:58:57 +08:00
李通洲 559905da60 Changelog: fix typo [ci skip] 2025-07-31 14:54:53 +08:00
Carter Li e093c8aa72 Packaging: update debian stuff [ci skip] 2025-07-31 14:34:18 +08:00
Carter Li ba8a21142f Merge pull request #1873 from fastfetch-cli/dev
Release: v2.49.0
2025-07-31 13:54:49 +08:00
李通洲 eca3625165 Battery / Uptime: update document of custom format 2025-07-31 13:32:18 +08:00
李通洲 677e920dc8 Battery: address copilot feedback 2025-07-31 10:51:53 +08:00
李通洲 38c0b24daa WM (Linux): fix a copy-paste error. 2025-07-31 10:50:45 +08:00
李通洲 4e05502d7a Release: v2.49.0 2025-07-31 10:42:09 +08:00
李通洲 d0928a63bf Doc: update readme 2025-07-30 16:18:04 +08:00
李通洲 aa0bbd5aee Percent: add option --percent-width 2025-07-30 15:06:16 +08:00
李通洲 ce554dbdd0 Uptime / Battery: add formatted duration string in custom format 2025-07-30 15:03:23 +08:00
李通洲 a0174e8666 Global: add new unit related options
1. `--<module>-space-before-unit`
2. `--duration-abbreviation`
3. various code refactoring and cleanups
2025-07-30 15:03:23 +08:00
李通洲 8be419cfd6 DiskIO: fix wrong /s assignment in custom format
Fix #1871
2025-07-30 09:05:33 +08:00
李通洲 ca79bae36e Packages (Windows): find scoop installation path by parsing scoop config file 2025-07-29 19:29:40 +08:00
Carter Li b1f0248fb3 Font (Linux): parse unicode escaped string stored by qt5ct
Fix #1864
2025-07-29 18:25:34 +08:00
Carter Li 77dd18466b FFstrbuf: add function ffStrbufAppendUtf32CodePoint 2025-07-29 16:36:21 +08:00
李通洲 5bb6e22679 GPU (Intel): read render engine temperature only 2025-07-29 14:23:56 +08:00
Carter Li 9ea9291ab8 WM (Linux): add labwc version detection support 2025-07-29 10:20:05 +08:00
Carter Li 6ec73863ab CPU (Android): make SOC detection more loose
It's less accurate, but higher chance to match.
2025-07-29 09:28:41 +08:00
Carter Li 8c2f93151d CPU (Android): add more QSD SOCs 2025-07-29 09:28:36 +08:00
李通洲 71ddc4ffc6 Disk: update default value of hideFolders
Fix #1869
2025-07-28 23:49:27 +08:00
李通洲 4909d693e3 Packages (Windows): don't rely on the existance of $SCOOP when detecting scoop packages
Fix #1868
2025-07-28 23:41:48 +08:00
李通洲 fe76bbe68a Logo (Builtin): remove Evolinx 2025-07-28 23:06:15 +08:00
李通洲 d1f20822f1 GPU (macOS): silence compiler warnings 2025-07-28 15:39:35 +08:00
李通洲 1ed804db52 Wifi (macOS): use sudo wdutil info on Tahoe
sudo, you know it.
2025-07-28 15:35:02 +08:00
李通洲 0e8b9bec2d FFstrbuf: add function ffStrbufSubstr 2025-07-28 15:35:02 +08:00
李通洲 a3182c31cb Chore: add FF_C_NONNULL 2025-07-28 15:35:02 +08:00
Darloli d2f2c76dfc Version: correct the variable name 'name' to 'project-name' 2025-07-26 08:33:34 +08:00
Darloli 2d1ae1b4c5 Users: correct the variable name 'session' to 'session-name' 2025-07-26 08:33:34 +08:00
李通洲 316409ecc3 LocalIP: cleanup printing code 2025-07-24 20:12:48 +08:00
李通洲 f0fc38bcb5 LocalIP (Windows): fix link speed calcuation 2025-07-24 20:11:04 +08:00
李通洲 e7a6b84107 LocalIP (Windows): ignore stopped interfaces 2025-07-24 19:31:41 +08:00
李通洲 02c3254961 Netif (Windows): correct default route detection (v2) 2025-07-24 19:31:41 +08:00
李通洲 a90e1d7ccf JsonSchema: improve definitions of colors and conditions [ci skip]
Fix #1862
2025-07-23 09:31:25 +08:00
Carter Li 6cdd64ac55 CI (Haiku): remove work around 2025-07-22 22:10:00 +08:00
Carter Li aa1201ffb8 Editor: correct the variable name full-path to path
Fix #1861
2025-07-22 22:06:26 +08:00
Carter Li 9b491c2f49 Wifi (Linux): fix interface status when the interface is up but not connected 2025-07-22 22:03:53 +08:00
李通洲 be3e2ba521 Presets: improve 25.jsonc; add verbose comments [ci skip] 2025-07-22 15:46:36 +08:00
李通洲 ccbb9e90ea Netif (Windows): fix default route detection when the default adapter is disabled
This commit addresses an issue where the default route detection on Windows incorrectly identified a disabled adapter as the default route. Previously, when a user disabled the adapter configured as the default route, the system still reported it as active due to stale routing table entries.
2025-07-21 20:24:43 +08:00
李通洲 d07fe997a9 CI (NetBSD): remove opencl support to fix building 2025-07-21 14:41:02 +08:00
李通洲 b60996bcd1 Packages (Linux): remove qi support
Close #1858
2025-07-21 14:19:12 +08:00
李通洲 272c0aad9c Packages (Linux): improve accuracy of flatpak count detection
Fix #1856
2025-07-21 14:06:19 +08:00
Carter Li 7566f10bb6 Logo (Builtin): add Aeon
Fix  #1855
2025-07-20 16:47:35 +08:00
Carter Li 847b76b863 GPU (Linux): add GPU temp detection for nouveau driver 2025-07-19 18:17:28 +08:00
Carter Li 5c0ad030cc GPU (Linux): support advanced detection for nouveau driver 2025-07-19 16:47:42 +08:00
Carter Li 02aafbd7f4 Merge pull request #1852 from fastfetch-cli/dev
Release: v2.48.1
2025-07-18 19:28:54 +08:00
Carter Li 72da8150bd Release: v2.48.1 2025-07-18 18:50:30 +08:00
Carter Li aca2b5336d WM (Linux): fix a copy-paste error 2025-07-18 18:04:00 +08:00
李通洲 c79b67efc1 Modules: don't report errors when condition key is set 2025-07-18 16:16:38 +08:00
李通洲 30af91ce8e Packages: add new option --packages-combined 2025-07-18 15:55:33 +08:00
李通洲 6c56348e54 JsonConfig: add modules[n].condition to run modules conditionally on different platforms 2025-07-18 15:45:25 +08:00
李通洲 531b25dc2f Version: replace WIN32 with Windows and Darwin with macOS 2025-07-18 15:08:40 +08:00
李通洲 8c6dc34654 Processing (*nix): fix compiling on Android 7 2025-07-18 13:27:17 +08:00
李通洲 cf2034b93e Processing (Windows): redirect unused std handles to NUL to avoid potential errors 2025-07-18 10:39:11 +08:00
李通洲 f7db03b8c4 Processing (*nix): use traditional fork-exec on Android and OpenBSD
Fix https://github.com/termux/termux-packages/issues/25369
2025-07-18 10:37:52 +08:00
Carter Li 8647e366f9 Packaging: update debian stuff [ci skip] 2025-07-17 16:27:07 +08:00
李通洲 1bf41d68f9 WM (Linux): add Openbox version detection 2025-07-17 14:15:35 +08:00
390 changed files with 8447 additions and 7354 deletions
+25 -51
View File
@@ -4,13 +4,16 @@ on:
- push
- pull_request
env:
CMAKE_BUILD_TYPE: ${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }}
jobs:
spellcheck:
runs-on: ubuntu-latest
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Install codespell
shell: bash
@@ -29,7 +32,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: uname -a
run: uname -a
@@ -68,7 +71,7 @@ jobs:
ffversion: ${{ steps.ffversion.outputs.ffversion }}
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: uname -a
run: uname -a
@@ -137,7 +140,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: uname -a
run: uname -a
@@ -198,7 +201,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: uraimo/run-on-arch-action@v3
@@ -237,7 +240,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: uraimo/run-on-arch-action@v3
@@ -273,7 +276,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: uraimo/run-on-arch-action@v3
@@ -308,7 +311,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: uraimo/run-on-arch-action@v3
@@ -343,7 +346,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: uraimo/run-on-arch-action@v3
@@ -374,7 +377,7 @@ jobs:
name: Musl-amd64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: setup alpine linux
uses: jirutka/setup-alpine@master
@@ -416,7 +419,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: uname -a
run: uname -a
@@ -463,7 +466,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: uname -a
run: uname -a
@@ -507,7 +510,7 @@ jobs:
name: SunOS-amd64
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: vmactions/omnios-vm@v1
@@ -543,7 +546,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: cross-platform-actions/action@master
@@ -580,7 +583,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: cross-platform-actions/action@master
@@ -616,7 +619,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: cross-platform-actions/action@master
@@ -628,7 +631,7 @@ jobs:
version: '10.1'
run: |
uname -a
sudo pkgin -y install cmake git pkgconf wayland vulkan-headers dconf dbus sqlite3 ImageMagick opencl-headers ocl-icd
sudo pkgin -y install cmake git pkgconf wayland vulkan-headers dconf dbus sqlite3 ImageMagick
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -653,7 +656,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: run VM
uses: vmactions/dragonflybsd-vm@v1
@@ -688,35 +691,7 @@ jobs:
contents: read
steps:
- name: checkout repository
uses: actions/checkout@v4
- name: Fixup VM
uses: cross-platform-actions/action@master
with:
operating_system: haiku
version: 'r1beta5'
architecture: x86-64
cpu_count: 4
shell: bash
sync_files: false
shutdown_vm: false
run: |
mv '/home/runner/work' '/boot/home/work'
ln -sf '/boot/home/work' '/home/runner/work'
- name: Sync files to VM
uses: cross-platform-actions/action@master
with:
operating_system: haiku
version: 'r1beta5'
architecture: x86-64
cpu_count: 4
shell: bash
sync_files: runner-to-vm
shutdown_vm: false
run: |
chown -R $(id -u):$(id -g) $(pwd)
ls -l
uses: actions/checkout@v5
- name: run VM
uses: cross-platform-actions/action@master
@@ -726,10 +701,9 @@ jobs:
architecture: x86-64
cpu_count: 4
shell: bash
sync_files: vm-to-runner
run: |
uname -a
pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_devel zlib_devel chafa_devel cmake gcc make pkgconfig python3.10
pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_devel zlib_devel chafa_devel cmake gcc make pkgconfig python3.10 || pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_devel zlib_devel chafa_devel cmake gcc make pkgconfig python3.10
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -755,7 +729,7 @@ jobs:
shell: msys2 {0}
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: setup-msys2
uses: msys2/setup-msys2@v2
@@ -817,7 +791,7 @@ jobs:
shell: msys2 {0}
steps:
- name: checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: setup-msys2
uses: msys2/setup-msys2@v2
+132
View File
@@ -1,3 +1,135 @@
# 2.50.2
Bugfixes:
* Fixes linglong package detection V2 (#1903, Packages, Linux)
* Fixes building with `-DENABLE_SYSTEM_YYJSON=ON` (#1904)
* Fixes `showMac` does not honor `defaultRouteOnly` (#1902, LocalIP, Linux)
* Fixes failing to acquire default route on Linux in certain cases (#1902, LocalIP, Linux)
# 2.50.1
Bugfixes:
* Fixes percentage bar not displaying correctly in certain cases
* Fixes linglong package detection on Debian 13 (#1899, Packages, Linux)
# 2.50.0
Changes:
* Keys in JSON configuration files are now case-sensitive, as stated in v2.49.0.
* This is a breaking change, but it should not affect most users as long as your config file passes JSON schema validation.
* All module config flags have been removed, as stated in v2.49.0.
* To configure modules via the command line, use: `echo '{"modules": [{"type":"custom","format":"Hello Fastfetch!"}]}' | fastfetch -c -`.
* The percent bar config `display.bar.*` options have been replaced with a more organized, nested object structure.
* `display.bar.charElapsed` has been renamed to `display.bar.char.elapsed`.
* `display.bar.charTotal` has been renamed to `display.bar.char.total`.
* `display.bar.borderLeft` has been renamed to `display.bar.border.left`.
* `display.bar.borderRight` has been renamed to `display.bar.border.right`.
* The undocumented flag `--load-config` has been removed.
* Use `--config` or `-c` instead.
* Flashfetch, a simplified fastfetch variant that used a hardcoded module list with direct function calls to reduce startup overhead, has been changed to a version that aims to match neofetch's behavior as closely as possible, for demonstration purposes.
* Flashfetch is intended to be built from source (like [st](https://st.suckless.org/)). We do not provide prebuilt binaries in distributions.
Features:
* Added support for reading JSON config from stdin using `--config -` or `-c -`.
* Added `display.bar.border.{leftElapsed,rightElapsed}` for using the border as part of the bar content. (#1875)
* `display.bar.border: null` has been added as a shorthand to disable bar borders.
* Added `display.bar.color.{elapsed,total,border}` to customize the color of the elapsed, total, and border sections of the percent bar.
* `display.bar.color: null` has been added as a shorthand to disable bar colors.
* Improved Bedrock Linux detection (#1881, OS / Disk, Linux)
* Added the command flag `--gen-config-full`, which generates a JSON config file containing all optional module options.
* Improved the default IP address display when `localip.showAllIPs` is not set (LocalIP)
* For IPv4, the preferred source address (if detected) is shown.
* For IPv6, the first GUA or ULA that is not deprecated or temporary is shown.
* Added support for interface speed detection on SunOS (LocalIP, SunOS)
* Added detection support for Xlibre (#1888, WM, Linux)
* Improved the accuracy of color detection (Cursor, macOS)
* Improved the proformance of `Nix` package manager detection on macOS by porting optimizations form Linux port (#1893, Packages, macOS)
Bugfixes:
* Fixed custom object inheriting a key from the previous custom object if the key is blank (#1477)
* Fixed a possible segfault when parsing color strings in the JSON config (#1878)
* Fixed GPU driver detection when DRM is used (GPU, FreeBSD)
* Fixed default route detection on DragonFly BSD (LocalIP, DFBSD)
* Fixed lliurex detection (#1882, OS, Linux)
* Fixed compatibility with `-ffast-math` (#1894)
* Fixed physical GPU sometimes being ignored (#1896, GPU, Windows)
Logos:
* Added ObsidianOS (#1890)
# 2.49.0
Deprecation Notice:
* In fastfetch v2, the JSONC configuration format has been introduced, while command line configuration flags are kept for compatibility. Although they have the same effects, they use two different code paths, and as the number of flags grows, the codebase is becoming increasingly difficult to maintain.
* Removal of module config flags is planned for **v2.50.0**, which will also fix a long-standing issue #1477.
* Removal of most other config flags is also planned for later versions.
* Keys of JSON configuration files will be all case-sensitive. Currently they are inconsistent. Planned for **v2.50.0**.
Changes:
* Due to more restrictive permissions in macOS Tahoe, SSID detection on macOS 26+ requires root privileges. `<redacted>` will be displayed otherwise.
Features:
* Improve `nouveau` driver support for `--gpu-driver-specific` (GPU, Linux)
* VRAM size detection
* GPU temperature detection
* Core count detection (when available)
* Improve Scoop package manager detection (Packages, Windows)
* Support [`scoop-global`](https://github.com/ScoopInstaller/Install?tab=readme-ov-file#advanced-installation)
* Read Scoop's config file to find the installation path of Scoop
* Improve ARM SoC detection (CPU, Android)
* Make SoC detection more lenient. Higher chance to match at the cost of accuracy.
* Add more Snapdragon SoC names
* Support labwc WM version detection, used for XFCE4 on Wayland (WM, Linux)
* Improve accuracy of GPU temperature detection for Intel dedicated GPUs on Windows (GPU, Windows)
* Parse unicode escaped strings generated by qt5ct (#1864, Font, Linux)
* Add `--{duration,percent,size,freq,temp}-space-before-unit [always|never]` options to add a space before the unit when printing duration, percent, size, frequency and temperature values
* Add `--duration-abbreviation` to abbreviate duration values in custom format
* For example: `1 day, 2 hours, 3 mins` will be displayed as `1d 2h 3m`
* Add `--percent-width` to pad the percent value with spaces to a fixed width
* For example: `--percent-width 3` will display ` 50%` instead of `50%`; useful for aligning percent values in custom format
Bugfixes:
* Improve accuracy of Flatpak count detection (#1856, Packages, Linux)
* Remove qi package manager support (#1858, Packages, Linux)
* Fix LocalIP module on Windows (LocalIP, Windows)
* Fix default route detection when multiple network interfaces are connected
* Fix link speed calculation
* Fix interface status when the interface is up but not connected (Wifi, Linux)
* Fix variable names in custom format (#1861)
* `full-path` to `path` (Editor)
* `session` to `session-name` (Users)
* `name` to `project-name` (Version)
* Fix wrong /s assignment in custom format (#1871, DiskIO)
Logos:
* Add `Aeon`
* Remove `Evolinx`
# 2.48.1
Features:
* Add support for detecting Openbox WM version (WM, Linux)
* Improve reliability of child process spawning on Windows (Windows)
* Add a new option `--packages-combined`, which combines related package managers into single counts (#1851, Packages)
* For example: if you have both `flatpak-system` and `flatpak-user` packages installed, they will be combined into a single `flatpak` count with `--packages-combined` enabled.
* Add `modules[n].condition` to conditionally enable modules on different platforms
* Useful when sharing configuration files across platforms
* For example:
```jsonc
{
"type": "custom",
"format": "This string will be printed on Intel macOS only",
"condition": {
"system": "macOS", // Can be an array, optional
"arch": "x86_64" // Can be an array, optional too
}
}
```
Bugfixes:
* Revert the change of `posix_spawn` in v2.48.0 for Android and OpenBSD (Android / OpenBSD)
* Fix completion for Android 7 (Required by Termux)
# 2.48.0
Features:
+10 -5
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.12.0) # target_link_libraries with OBJECT libs & project homepage url
project(fastfetch
VERSION 2.48.0
VERSION 2.50.2
LANGUAGES C
DESCRIPTION "Fast neofetch-like system information tool"
HOMEPAGE_URL "https://github.com/fastfetch-cli/fastfetch"
@@ -351,10 +351,11 @@ file(GENERATE OUTPUT logo_builtin.h CONTENT "${LOGO_BUILTIN_H}")
#######################
set(LIBFASTFETCH_SRC
src/common/percent.c
src/common/commandoption.c
src/common/duration.c
src/common/font.c
src/common/format.c
src/common/frequency.c
src/common/init.c
src/common/jsonconfig.c
src/common/library.c
@@ -363,9 +364,11 @@ set(LIBFASTFETCH_SRC
src/common/networking/networking_common.c
src/common/option.c
src/common/parsing.c
src/common/percent.c
src/common/printing.c
src/common/properties.c
src/common/settings.c
src/common/size.c
src/common/temps.c
src/detection/bluetoothradio/bluetoothradio.c
src/detection/bootmgr/bootmgr.c
@@ -471,7 +474,6 @@ set(LIBFASTFETCH_SRC
src/modules/wmtheme/wmtheme.c
src/modules/zpool/zpool.c
src/options/display.c
src/options/modules.c
src/options/logo.c
src/options/general.c
src/util/edidHelper.c
@@ -545,6 +547,7 @@ if(LINUX)
src/detection/opengl/opengl_linux.c
src/detection/os/os_linux.c
src/detection/packages/packages_linux.c
src/detection/packages/packages_nix.c
src/detection/poweradapter/poweradapter_linux.c
src/detection/processes/processes_linux.c
src/detection/gtk_qt/qt.c
@@ -611,6 +614,7 @@ elseif(ANDROID)
src/detection/opengl/opengl_linux.c
src/detection/os/os_android.c
src/detection/packages/packages_linux.c
src/detection/packages/packages_nix.c
src/detection/poweradapter/poweradapter_nosupport.c
src/detection/processes/processes_linux.c
src/detection/sound/sound_nosupport.c
@@ -893,7 +897,7 @@ elseif(OpenBSD)
elseif(APPLE)
list(APPEND LIBFASTFETCH_SRC
src/common/io/io_unix.c
src/common/netif/netif_bsd.c
src/common/netif/netif_apple.c
src/common/networking/networking_linux.c
src/common/processing_linux.c
src/common/sysctl.c
@@ -937,6 +941,7 @@ elseif(APPLE)
src/detection/opengl/opengl_apple.c
src/detection/os/os_apple.m
src/detection/packages/packages_apple.c
src/detection/packages/packages_nix.c
src/detection/poweradapter/poweradapter_apple.c
src/detection/processes/processes_bsd.c
src/detection/sound/sound_apple.c
@@ -1039,7 +1044,7 @@ elseif(SunOS)
list(APPEND LIBFASTFETCH_SRC
src/common/dbus.c
src/common/io/io_unix.c
src/common/netif/netif_bsd.c
src/common/netif/netif_apple.c
src/common/networking/networking_linux.c
src/common/processing_linux.c
src/detection/battery/battery_nosupport.c
+3 -3
View File
@@ -36,7 +36,6 @@ Some distributions package outdated versions of fastfetch. Older versions receiv
<img src="https://repology.org/badge/vertical-allrepos/fastfetch.svg?columns=2" alt="Packaging status" align="right">
</a>
* Ubuntu: [`ppa:zhangsongcui3371/fastfetch`](https://launchpad.net/~zhangsongcui3371/+archive/ubuntu/fastfetch) (for Ubuntu 22.04 or newer)
* Debian: `apt install fastfetch` (for Debian 13 or newer)
* Debian / Ubuntu: Download `fastfetch-linux-<proper architecture>.deb` from [Github release page](https://github.com/fastfetch-cli/fastfetch/releases/latest) and double-click it (for Ubuntu 20.04 or newer and Debian 11 or newer).
* Arch Linux: `pacman -S fastfetch`
@@ -58,7 +57,7 @@ If fastfetch is not packaged for your distribution or an outdated version is pac
### macOS
* [HomeBrew](https://formulae.brew.sh/formula/fastfetch#default): `brew install fastfetch`
* [Homebrew](https://formulae.brew.sh/formula/fastfetch#default): `brew install fastfetch`
* [MacPorts](https://ports.macports.org/port/fastfetch/): `sudo port install fastfetch`
### Windows
@@ -95,7 +94,8 @@ See the Wiki: https://github.com/fastfetch-cli/fastfetch/wiki/Building
* Run with [all supported modules](https://github.com/fastfetch-cli/fastfetch/wiki/Support+Status#available-modules) to find what interests you: `fastfetch -c all.jsonc`
* View all data that fastfetch detects: `fastfetch -s <module1>[:<module2>][:<module3>] --format json`
* Display help messages: `fastfetch --help`
* Generate a config file based on command line arguments: `fastfetch --arg1 --arg2 --gen-config`
* Generate a minimal config file: `fastfetch [-s <module1>[:<module2>]] --gen-config [</path/to/config.jsonc>]`
* Use: `--gen-config-full` to generate a full config file with all optional options
## Customization
+12
View File
@@ -1,3 +1,15 @@
fastfetch (2.49.0) jammy; urgency=medium
* Update to 2.49.0
-- Carter Li <zhangsongcui@live.cn> Thu, 31 Jul 2025 14:32:59 +0800
fastfetch (2.48.0) jammy; urgency=medium
* Update to 2.48.0
-- Carter Li <zhangsongcui@live.cn> Thu, 17 Jul 2025 16:16:52 +0800
fastfetch (2.47.0) jammy; urgency=medium
* Update to 2.47.0
+1 -1
View File
@@ -1 +1 @@
fastfetch_2.47.0_source.buildinfo universe/utils optional
fastfetch_2.49.0_source.buildinfo universe/utils optional
+962 -179
View File
File diff suppressed because it is too large Load Diff
+5 -4
View File
@@ -12,10 +12,11 @@
"type": ["bar", "hide-others"]
},
"bar": {
"borderLeft": "",
"borderRight": "",
"charElapsed": "█",
"charTotal": "░",
"border": null,
"char": {
"elapsed": "█",
"total": "░"
},
"width": 40
},
"constants": [
+94 -20
View File
@@ -6,11 +6,13 @@
"keys": "blue"
},
"separator": "",
// Constants are reusable strings referenced by {$1}, {$2}, etc.
// These contain ANSI escape codes for cursor positioning
"constants": [
"──────────────────────────────────────────────",
"\u001b[47D",
"\u001b[47C",
"\u001b[46C"
"──────────────────────────────────────────────", // {$1} - horizontal line for borders
"\u001b[47D", // {$2} - move cursor left 47 columns
"\u001b[47C", // {$3} - move cursor right 47 columns
"\u001b[46C" // {$4} - move cursor right 46 columns
],
"brightColor": false
},
@@ -22,6 +24,24 @@
},
{
"type": "os",
// Key format breakdown for OS module:
// "│ {icon} \u001b[s{sysname}\u001b[u\u001b[10C│{$3}│{$2}"
//
// │ - Left border of key block
// {icon} - OS icon (defined internally by fastfetch)
// \u001b[s - ANSI escape: save cursor position (ESC[s)
// {sysname} - Format variable: system name (e.g., "Linux", "Darwin")
// \u001b[u - ANSI escape: restore cursor to saved position (ESC[u)
// Necessary because the length of `{sysname}` differs between different platforms
// \u001b[10C - ANSI escape: move cursor right 10 columns (ESC[10C)
// │ - Right border of key block (always 10 columns from left border)
// {$3} - Reference to constants[2]: move cursor right 47 columns
// │ - Right border of value block
// {$2} - Reference to constants[1]: move cursor left 47 columns
//
// This creates a fixed-width layout where the key block is exactly 10 columns wide,
// regardless of the actual content length. The cursor manipulation ensures proper
// alignment for the table-like structure.
"key": "│ {icon} \u001b[s{sysname}\u001b[u\u001b[10C│{$3}│{$2}"
},
{
@@ -34,7 +54,7 @@
"key": "│ {icon} Locale │{$3}│{$2}"
},
// Hardware
// Hardware section with cyan color theme
{
"type": "custom",
"key": "│{#cyan}┌──────────────┬{$1}┐{#keys}│\u001b[37D",
@@ -42,6 +62,11 @@
},
{
"type": "chassis",
// Similar structure but with cyan color formatting:
// │{#cyan}│ - Left border with cyan color
// {icon} - Chassis icon
// Chassis - Fixed label text
// │{$4}│{#keys}│{$2} - Positioning and borders for value area
"key": "│{#cyan}│ {icon} Chassis │{$4}│{#keys}│{$2}"
},
{
@@ -76,7 +101,7 @@
"format": ""
},
// Desktop
// Desktop section with green color theme
{
"type": "custom",
"key": "│{#green}┌──────────────┬{$1}┐{#keys}│\u001b[37D",
@@ -106,7 +131,7 @@
"format": ""
},
// Terminal
// Terminal section with yellow color theme
{
"type": "custom",
"key": "│{#yellow}┌──────────────┬{$1}┐{#keys}│\u001b[37D",
@@ -138,7 +163,7 @@
"format": ""
},
// Development
// Development section with red color theme
{
"type": "custom",
"key": "│{#red}┌──────────────┬{$1}┐{#keys}│\u001b[39D",
@@ -146,31 +171,44 @@
},
{
"type": "command",
"keyIcon": "",
"keyIcon": "", // Custom icon override
"key": "│{#red}│ {icon} Rust │{$4}│{#keys}│{$2}",
"text": "rustc --version | cut -d' ' -f2",
"format": "rustc {}"
"text": "rustc --version",
"format": "rustc {~6,13}" // Print 6th to 13th characters (version number)
},
{
"type": "command",
"condition": {
"!system": "Windows" // Posix version
},
"keyIcon": "",
"key": "│{#red}│ {icon} Clang │{$4}│{#keys}│{$2}",
"text": "clang --version | head -1 | awk '{print $NF}'",
"format": "clang {}"
},
{
"type": "command",
"condition": {
"system": "Windows" // Windows version
},
"keyIcon": "",
"key": "│{#red}│ {icon} Clang │{$4}│{#keys}│{$2}",
"text": "clang --version | findstr version", // Finds the line with "version"
"format": "clang {~-6}" // Prints the last 6 characters (version number)
},
{
"type": "command",
"keyIcon": "",
"key": "│{#red}│ {icon} NodeJS │{$4}│{#keys}│{$2}",
"text": "node --version",
"format": "node {~1}"
"format": "node {~1}" // {~1} removes first character (v)
},
{
"type": "command",
"keyIcon": "",
"key": "│{#red}│ {icon} Go │{$4}│{#keys}│{$2}",
"text": "go version | cut -d' ' -f3",
"format": "go {~2}"
"format": "go {~2}" // {~2} removes first 2 characters (go)
},
{
"type": "command",
@@ -200,7 +238,7 @@
"format": ""
},
// Uptime
// Uptime section with magenta color theme
{
"type": "custom",
"key": "│{#magenta}┌──────────────┬{$1}┐{#keys}│\u001b[36D",
@@ -212,15 +250,28 @@
},
{
"type": "users",
"myselfOnly": true,
"myselfOnly": true, // Only show current user
"keyIcon": "",
"key": "│{#magenta}│ {icon} Login │{$4}│{#keys}│{$2}"
},
{
"condition": { // Conditional module: only show on non-macOS
"!system": "macOS"
},
"type": "disk",
"keyIcon": "",
"key": "│{#magenta}│ {icon} OS Age │{$4}│{#keys}│{$2}",
"folders": "/", // On macOS, "/System/Volumes/VM" works for me
"folders": "/", // Check root filesystem
"format": "{create-time:10} [{days} days]" // Show creation time and age in days
},
{
"condition": { // Conditional module: only show on macOS
"system": "macOS"
},
"type": "disk",
"keyIcon": "",
"key": "│{#magenta}│ {icon} OS Age │{$4}│{#keys}│{$2}",
"folders": "/System/Volumes/VM", // Work around for APFS on macOS
"format": "{create-time:10} [{days} days]"
},
{
@@ -230,12 +281,35 @@
},
{
"type": "custom",
"key": "└─────────────────{$1}┘",
"key": "└─────────────────{$1}┘", // Bottom border of the entire layout
"format": ""
},
// End
"break",
"colors"
// End with color palette and line break
"break", // Add a blank line
"colors" // Display color palette
]
}
/*
Key Format Structure Explanation:
The key format uses a combination of:
1. Unicode box drawing characters ( ) for borders
2. ANSI escape codes for cursor positioning (\u001b[...)
3. Format variables ({icon}, {sysname}, etc.)
4. Constant references ({$1}, {$2}, etc.)
5. Color formatting ({#color})
ANSI Escape Codes Used:
- \u001b[s - Save cursor position (ESC[s)
- \u001b[u - Restore cursor position (ESC[u)
- \u001b[nC - Move cursor right n columns (ESC[nC)
- \u001b[nD - Move cursor left n columns (ESC[nD)
This creates a table-like layout with fixed column widths and proper alignment,
regardless of the actual content length in each field.
For more ANSI escape code reference, see:
https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797#cursor-controls
*/
+63
View File
@@ -0,0 +1,63 @@
{
"$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json",
"logo": {
"type": "small"
},
"display": {
"separator": " ",
"key": {
"type": "both"
},
"bar": {
"border": {
"left": "\uee00",
"leftElapsed": "\uee03",
"right": "\uee02",
"rightElapsed": "\uee05"
},
"char": {
"total": "\uee01",
"elapsed": "\uee04"
},
"color": {
"total": null
}
},
"percent": {
"type": [
"bar",
"bar-monochrome"
]
}
},
"modules": [
"title",
"separator",
{
"type": "memory",
"key": "MEM"
},
{
"type": "swap",
"key": "SWP"
},
{
"type": "disk",
"folders": "/",
"key": "DSK"
},
{
"type": "battery",
"key": "BAT"
},
{
"type": "brightness",
"key": "BGT"
},
{
"type": "colors",
"paddingLeft": 6,
"symbol": "circle"
}
]
}
+136
View File
@@ -0,0 +1,136 @@
// #1887
{
"$schema": "file:///Users/carter/fastfetch/doc/json_schema.json",
"logo": null,
"display": {
"constants": [
"\u001b[s\u001b[33C│\u001b[u",
" » "
],
"separator": "",
"percent": {
"type": ["num", "bar"]
},
"brightColor": false,
"bar": {
"border": {
"left": "[",
"leftElapsed": "[",
"right": "]",
"rightElapsed": "]"
},
"char": {
"elapsed": "─",
"total": "─"
},
"color": {
"elapsed": "default",
"total": "light_black"
},
"width": 16
},
"color": {
"separator": "default",
"keys": "default",
"output": "default"
}
},
"modules": [
"title",
{
"type": "custom",
"format": "┌────「 {#1}OS{#} 」────────────────────────────┐"
},
{
"type": "os",
"key": "│ {icon}{$2}{$1}"
},
{
"type": "disk",
"folders": "/",
"key": "│ {$1}",
"format": "{size-percentage-bar} {size-percentage}"
},
{
"type": "disk",
"folders": "/",
"key": "│ {$1}",
"format": "{size-used} / {size-total}"
},
{
"type": "custom",
"format": "└────────────────────────────────────────┘"
},
"break",
{
"type": "custom",
"format": "┌────「 {#1}UI{#} 」────────────────────────────┐"
},
{
"type": "wm",
"key": "│ {icon}{$2}{$1}"
},
{
"type": "wmtheme",
"key": "│ {icon}{$2}{$1}"
},
{
"type": "custom",
"key": "│ {$1}"
},
{
"type": "display",
"key": "│ {icon}{$2}{$1}",
"format": "{width}x{height} @ {refresh-rate} Hz"
},
{
"type": "custom",
"key": "│ {$1}"
},
{
"type": "terminal",
"key": "│ {icon}{$2}{$1}"
},
{
"type": "terminalfont",
"key": "│ {icon}{$2}{$1}"
},
{
"type": "custom",
"format": "└────────────────────────────────────────┘"
},
"break",
{
"type": "custom",
"format": "┌────「 {#1}HW{#} 」────────────────────────────┐"
},
{
"type": "cpu",
"key": "│ {icon}{$2}{$1}",
"format": "{name}"
},
{
"type": "gpu",
"key": "│ {icon}{$2}{$1}",
"format": "{name}"
},
{
"type": "custom",
"key": "│ {$1}"
},
{
"type": "memory",
"key": "│ {icon}{$2}{$1}",
"format": "{percentage-bar} {percentage}"
},
{
"type": "memory",
"key": "│ {$1}",
"format": "{used} / {total}"
},
{
"type": "custom",
"format": "└────────────────────────────────────────┘"
}
]
}
+4 -2
View File
@@ -8,8 +8,10 @@
"width": 11
},
"bar": {
"charElapsed": "=",
"charTotal": "-",
"char": {
"elapsed": "=",
"total": "-"
},
"width": 13
},
"percent": {
+13 -4
View File
@@ -3,7 +3,12 @@
"display": {
"size": {
"maxPrefix": "MB",
"ndigits": 0
"ndigits": 0,
"spaceBeforeUnit": "never"
},
"freq": {
"ndigits": 3,
"spaceBeforeUnit": "never"
}
},
"modules": [
@@ -16,7 +21,10 @@
"format": "{release}"
},
"uptime",
"packages",
{
"type": "packages",
"combined": true
},
"shell",
{
"type": "display",
@@ -36,11 +44,12 @@
"cpu",
{
"type": "gpu",
"key": "GPU"
"key": "GPU",
"format": "{name}"
},
{
"type": "memory",
"format": "{} / {}"
"format": "{used} / {total}"
},
"break",
"colors"
+43 -29
View File
@@ -10,21 +10,8 @@
#include <ctype.h>
#include <inttypes.h>
bool ffParseModuleOptions(const char* key, const char* value)
{
if (!ffStrStartsWith(key, "--") || !ffCharIsEnglishAlphabet(key[2])) return false;
for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(key[2]) - 'A']; *modules; ++modules)
{
FFModuleBaseInfo* baseInfo = *modules;
if (baseInfo->parseCommandOptions(baseInfo, key, value)) return true;
}
return false;
}
void ffPrepareCommandOption(FFdata* data)
{
FFOptionsModules* const options = &instance.config.modules;
//If we don't have a custom structure, use the default one
if(data->structure.length == 0)
ffStrbufAppendS(&data->structure, FASTFETCH_DATATEXT_STRUCTURE); // Cannot use `ffStrbufSetStatic` here because we will modify the string
@@ -33,54 +20,78 @@ void ffPrepareCommandOption(FFdata* data)
ffPrepareCPUUsage();
if(ffStrbufContainIgnCaseS(&data->structure, FF_DISKIO_MODULE_NAME))
ffPrepareDiskIO(&options->diskIo);
{
__attribute__((__cleanup__(ffDestroyDiskIOOptions))) FFDiskIOOptions options;
ffInitDiskIOOptions(&options);
ffPrepareDiskIO(&options);
}
if(ffStrbufContainIgnCaseS(&data->structure, FF_NETIO_MODULE_NAME))
ffPrepareNetIO(&options->netIo);
{
__attribute__((__cleanup__(ffDestroyNetIOOptions))) FFNetIOOptions options;
ffInitNetIOOptions(&options);
ffPrepareNetIO(&options);
}
if(instance.config.general.multithreading)
{
if(ffStrbufContainIgnCaseS(&data->structure, FF_PUBLICIP_MODULE_NAME))
ffPreparePublicIp(&options->publicIP);
{
__attribute__((__cleanup__(ffDestroyPublicIpOptions))) FFPublicIPOptions options;
ffInitPublicIpOptions(&options);
ffPreparePublicIp(&options);
}
if(ffStrbufContainIgnCaseS(&data->structure, FF_WEATHER_MODULE_NAME))
ffPrepareWeather(&options->weather);
{
__attribute__((__cleanup__(ffDestroyWeatherOptions))) FFWeatherOptions options;
ffInitWeatherOptions(&options);
ffPrepareWeather(&options);
}
}
}
static void genJsonConfig(FFModuleBaseInfo* baseInfo, yyjson_mut_doc* doc)
static void genJsonConfig(FFModuleBaseInfo* baseInfo, void* options, yyjson_mut_doc* doc)
{
yyjson_mut_val* modules = yyjson_mut_obj_get(doc->root, "modules");
if (!modules)
modules = yyjson_mut_obj_add_arr(doc, doc->root, "modules");
yyjson_mut_val* module = yyjson_mut_obj(doc);
FF_STRBUF_AUTO_DESTROY type = ffStrbufCreateS(baseInfo->name);
ffStrbufLowerCase(&type);
yyjson_mut_obj_add_strbuf(doc, module, "type", &type);
if (baseInfo->generateJsonConfig)
baseInfo->generateJsonConfig(baseInfo, doc, module);
if (instance.state.fullConfig)
{
yyjson_mut_val* module = yyjson_mut_obj(doc);
yyjson_mut_obj_add_strbuf(doc, module, "type", &type);
if (yyjson_mut_obj_size(module) > 1)
yyjson_mut_arr_add_val(modules, module);
if (baseInfo->generateJsonConfig)
baseInfo->generateJsonConfig(options, doc, module);
if (yyjson_mut_obj_size(module) > 1)
yyjson_mut_arr_add_val(modules, module);
else
yyjson_mut_arr_add_strbuf(doc, modules, &type);
}
else
{
yyjson_mut_arr_add_strbuf(doc, modules, &type);
}
}
static void genJsonResult(FFModuleBaseInfo* baseInfo, yyjson_mut_doc* doc)
static void genJsonResult(FFModuleBaseInfo* baseInfo, void* options, yyjson_mut_doc* doc)
{
yyjson_mut_val* module = yyjson_mut_arr_add_obj(doc, doc->root);
yyjson_mut_obj_add_str(doc, module, "type", baseInfo->name);
if (baseInfo->generateJsonResult)
baseInfo->generateJsonResult(baseInfo, doc, module);
baseInfo->generateJsonResult(options, doc, module);
else
yyjson_mut_obj_add_str(doc, module, "error", "Unsupported for JSON format");
}
static void parseStructureCommand(
const char* line,
void (*fn)(FFModuleBaseInfo *baseInfo, yyjson_mut_doc* jsonDoc),
void (*fn)(FFModuleBaseInfo* baseInfo, void* options, yyjson_mut_doc* jsonDoc),
yyjson_mut_doc* jsonDoc
)
{
@@ -91,10 +102,13 @@ static void parseStructureCommand(
FFModuleBaseInfo* baseInfo = *modules;
if (ffStrEqualsIgnCase(line, baseInfo->name))
{
uint8_t optionBuf[FF_OPTION_MAX_SIZE];
baseInfo->initOptions(optionBuf);
if (__builtin_expect(jsonDoc != NULL, false))
fn(baseInfo, jsonDoc);
fn(baseInfo, optionBuf, jsonDoc);
else
baseInfo->printModule(baseInfo);
baseInfo->printModule(optionBuf);
baseInfo->destroyOptions(optionBuf);
return;
}
}
-1
View File
@@ -9,7 +9,6 @@ typedef struct FFdata
bool configLoaded;
} FFdata;
bool ffParseModuleOptions(const char* key, const char* value);
void ffPrepareCommandOption(FFdata* data);
void ffPrintCommandOption(FFdata* data, yyjson_mut_doc* jsonDoc);
void ffMigrateCommandOptionToJsonc(FFdata* data, yyjson_mut_doc* jsonDoc);
+87
View File
@@ -0,0 +1,87 @@
#include "duration.h"
void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result)
{
const FFOptionsDisplay* options = &instance.config.display;
const char* space = instance.config.display.durationSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER ? " " : "";
if(totalSeconds < 60)
{
ffStrbufAppendF(result, options->durationAbbreviation ? "%u%ssec" : "%u%ssecond", (unsigned) totalSeconds, space);
if (totalSeconds != 1)
ffStrbufAppendC(result, 's');
return;
}
uint32_t seconds = (uint32_t) (totalSeconds % 60);
totalSeconds /= 60;
if (seconds >= 30)
totalSeconds++;
uint32_t minutes = (uint32_t) (totalSeconds % 60);
totalSeconds /= 60;
uint32_t hours = (uint32_t) (totalSeconds % 24);
totalSeconds /= 24;
uint32_t days = (uint32_t) totalSeconds;
if(days > 0)
{
if(options->durationAbbreviation)
{
ffStrbufAppendF(result, "%u%sd", days, space);
if(hours > 0 || minutes > 0)
ffStrbufAppendC(result, ' ');
}
else
{
ffStrbufAppendF(result, "%u%sday", days, space);
if(days > 1)
ffStrbufAppendC(result, 's');
if(days >= 100)
ffStrbufAppendS(result, "(!)");
if(hours > 0 || minutes > 0)
ffStrbufAppendS(result, ", ");
}
}
if(hours > 0)
{
if(options->durationAbbreviation)
{
ffStrbufAppendF(result, "%u%sh", hours, space);
if (minutes > 0)
ffStrbufAppendC(result, ' ');
}
else
{
ffStrbufAppendF(result, "%u%shour", hours, space);
if(hours > 1)
ffStrbufAppendC(result, 's');
if(minutes > 0)
ffStrbufAppendS(result, ", ");
}
}
if(minutes > 0)
{
if(options->durationAbbreviation)
{
ffStrbufAppendF(result, "%u%sm", minutes, space);
}
else
{
ffStrbufAppendF(result, "%u%smin", minutes, space);
if(minutes > 1)
ffStrbufAppendC(result, 's');
}
}
}
+3
View File
@@ -0,0 +1,3 @@
#include "fastfetch.h"
void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result);
+2 -2
View File
@@ -113,8 +113,8 @@ static inline void appendInvalidPlaceholder(FFstrbuf* buffer, const char* start,
static inline bool formatArgSet(const FFformatarg* arg)
{
return arg->value != NULL && (
(arg->type == FF_FORMAT_ARG_TYPE_DOUBLE && *(double*)arg->value > 0.0) || //Also is false for NaN
(arg->type == FF_FORMAT_ARG_TYPE_FLOAT && *(float*)arg->value > 0.0) || //Also is false for NaN
(arg->type == FF_FORMAT_ARG_TYPE_DOUBLE && *(double*)arg->value > 0.0) ||
(arg->type == FF_FORMAT_ARG_TYPE_FLOAT && *(float*)arg->value > 0.0) ||
(arg->type == FF_FORMAT_ARG_TYPE_INT && *(int*)arg->value > 0) ||
(arg->type == FF_FORMAT_ARG_TYPE_STRBUF && ((FFstrbuf*)arg->value)->length > 0) ||
(arg->type == FF_FORMAT_ARG_TYPE_STRING && ffStrSet((char*)arg->value)) ||
+17
View File
@@ -0,0 +1,17 @@
#include "frequency.h"
bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result)
{
if (mhz == 0)
return false;
const FFOptionsDisplay* options = &instance.config.display;
const char* space = options->freqSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " ";
int8_t ndigits = options->freqNdigits;
if (ndigits >= 0)
ffStrbufAppendF(result, "%.*f%sGHz", ndigits, mhz / 1000., space);
else
ffStrbufAppendF(result, "%u%sMHz", (unsigned) mhz, space);
return true;
}
+3
View File
@@ -0,0 +1,3 @@
#include "fastfetch.h"
bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result);
+2 -8
View File
@@ -25,6 +25,7 @@ static void initState(FFstate* state)
state->logoHeight = 0;
state->keysHeight = 0;
state->terminalLightTheme = false;
state->titleFqdn = false;
ffPlatformInit(&state->platform);
state->configDoc = NULL;
@@ -42,14 +43,13 @@ static void defaultConfig(void)
{
ffOptionsInitLogo(&instance.config.logo);
ffOptionsInitGeneral(&instance.config.general);
ffOptionsInitModules(&instance.config.modules);
ffOptionsInitDisplay(&instance.config.display);
}
void ffInitInstance(void)
{
#ifdef WIN32
//https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?source=recommendations&view=msvc-170#utf-8-support
// https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?source=recommendat>
setlocale(LC_ALL, ".UTF8");
#else
// Never use `setlocale(LC_ALL, "")`
@@ -96,11 +96,6 @@ static void chldSignalHandler(FF_MAYBE_UNUSED int signal)
void ffStart(void)
{
#ifdef FF_START_DETECTION_THREADS
if(instance.config.general.multithreading)
startDetectionThreads();
#endif
ffDisableLinewrap = instance.config.display.disableLinewrap && !instance.config.display.pipe && !instance.state.resultDoc;
ffHideCursor = instance.config.display.hideCursor && !instance.config.display.pipe && !instance.state.resultDoc;
@@ -150,7 +145,6 @@ static void destroyConfig(void)
{
ffOptionsDestroyLogo(&instance.config.logo);
ffOptionsDestroyGeneral(&instance.config.general);
ffOptionsDestroyModules(&instance.config.modules);
ffOptionsDestroyDisplay(&instance.config.display);
}
+21 -1
View File
@@ -31,6 +31,7 @@ static inline FFNativeFD FFUnixFD2NativeFD(int unixfd)
#endif
}
FF_C_NONNULL(3)
static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize, const void* data)
{
#ifndef _WIN32
@@ -41,18 +42,22 @@ static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize, const void* dat
#endif
}
FF_C_NONNULL(2)
static inline bool ffWriteFDBuffer(FFNativeFD fd, const FFstrbuf* content)
{
return ffWriteFDData(fd, content->length, content->chars);
}
FF_C_NONNULL(1, 3)
bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data);
FF_C_NONNULL(1, 2)
static inline bool ffWriteFileBuffer(const char* fileName, const FFstrbuf* buffer)
{
return ffWriteFileData(fileName, buffer->length, buffer->chars);
}
FF_C_NONNULL(3)
static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSize, void* data)
{
#ifndef _WIN32
@@ -66,26 +71,32 @@ static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSize, void* data)
#endif
}
FF_C_NONNULL(1, 3)
ssize_t ffReadFileData(const char* fileName, size_t dataSize, void* data);
FF_C_NONNULL(2, 4)
ssize_t ffReadFileDataRelative(FFNativeFD dfd, const char* fileName, size_t dataSize, void* data);
FF_C_NONNULL(2)
bool ffAppendFDBuffer(FFNativeFD fd, FFstrbuf* buffer);
FF_C_NONNULL(1, 2)
bool ffAppendFileBuffer(const char* fileName, FFstrbuf* buffer);
FF_C_NONNULL(2, 3)
bool ffAppendFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer);
FF_C_NONNULL(1, 2)
static inline bool ffReadFileBuffer(const char* fileName, FFstrbuf* buffer)
{
ffStrbufClear(buffer);
return ffAppendFileBuffer(fileName, buffer);
}
FF_C_NONNULL(2, 3)
static inline bool ffReadFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer)
{
ffStrbufClear(buffer);
return ffAppendFileBufferRelative(dfd, fileName, buffer);
}
//Bit flags, combine with |
typedef enum __attribute__((__packed__)) FFPathType
{
FF_PATHTYPE_FILE = 1 << 0,
@@ -94,6 +105,7 @@ typedef enum __attribute__((__packed__)) FFPathType
FF_PATHTYPE_FORCE_UNSIGNED = UINT8_MAX,
} FFPathType;
FF_C_NONNULL(1)
static inline bool ffPathExists(const char* path, FFPathType pathType)
{
#ifdef _WIN32
@@ -136,11 +148,13 @@ static inline bool ffPathExists(const char* path, FFPathType pathType)
return false;
}
FF_C_NONNULL(1, 2)
bool ffPathExpandEnv(const char* in, FFstrbuf* out);
#define FF_IO_TERM_RESP_WAIT_MS 100 // #554
FF_C_SCANF(3, 4)
FF_C_NONNULL(1, 3)
const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...);
// Not thread safe!
@@ -157,6 +171,7 @@ static inline void ffUnsuppressIO(bool* suppressed)
void ffListFilesRecursively(const char* path, bool pretty);
FF_C_NONNULL(1)
static inline bool wrapClose(FFNativeFD* pfd)
{
assert(pfd);
@@ -176,6 +191,7 @@ static inline bool wrapClose(FFNativeFD* pfd)
}
#define FF_AUTO_CLOSE_FD __attribute__((__cleanup__(wrapClose)))
FF_C_NONNULL(1)
static inline bool wrapFclose(FILE** pfile)
{
assert(pfile);
@@ -186,6 +202,7 @@ static inline bool wrapFclose(FILE** pfile)
}
#define FF_AUTO_CLOSE_FILE __attribute__((__cleanup__(wrapFclose)))
FF_C_NONNULL(1)
#ifndef _WIN32
static inline bool wrapClosedir(DIR** pdir)
{
@@ -207,6 +224,7 @@ static inline bool wrapClosedir(HANDLE* pdir)
#endif
#define FF_AUTO_CLOSE_DIR __attribute__((__cleanup__(wrapClosedir)))
FF_C_NONNULL(1, 2, 3)
static inline bool ffSearchUserConfigFile(const FFlist* configDirs, const char* fileSubpath, FFstrbuf* result)
{
// configDirs is a list of FFstrbufs include the trailing slash
@@ -222,6 +240,8 @@ static inline bool ffSearchUserConfigFile(const FFlist* configDirs, const char*
return false;
}
FFNativeFD ffGetNullFD(void);
#ifdef _WIN32
// Only O_RDONLY is supported
HANDLE openat(HANDLE dfd, const char* fileName, bool directory);
+9
View File
@@ -358,3 +358,12 @@ void ffListFilesRecursively(const char* path, bool pretty)
ffStrbufEnsureEndsWithC(&folder, '/');
listFilesRecursively(folder.length, &folder, 0, NULL, pretty);
}
FFNativeFD ffGetNullFD(void)
{
static FFNativeFD hNullFile = -1;
if (hNullFile != -1)
return hNullFile;
hNullFile = open("/dev/null", O_WRONLY | O_CLOEXEC);
return hNullFile;
}
+21 -2
View File
@@ -175,7 +175,7 @@ bool ffSuppressIO(bool suppress)
static bool init = false;
static HANDLE hOrigOut = INVALID_HANDLE_VALUE;
static HANDLE hOrigErr = INVALID_HANDLE_VALUE;
static HANDLE hNullFile = INVALID_HANDLE_VALUE;
HANDLE hNullFile = ffGetNullFD();
static int fOrigOut = -1;
static int fOrigErr = -1;
static int fNullFile = -1;
@@ -187,7 +187,6 @@ bool ffSuppressIO(bool suppress)
hOrigOut = GetStdHandle(STD_OUTPUT_HANDLE);
hOrigErr = GetStdHandle(STD_ERROR_HANDLE);
hNullFile = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL);
fOrigOut = _dup(STDOUT_FILENO);
fOrigErr = _dup(STDERR_FILENO);
fNullFile = _open_osfhandle((intptr_t) hNullFile, 0);
@@ -352,3 +351,23 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
return NULL;
}
FFNativeFD ffGetNullFD(void)
{
static FFNativeFD hNullFile = INVALID_HANDLE_VALUE;
if (hNullFile != INVALID_HANDLE_VALUE)
return hNullFile;
hNullFile = CreateFileW(
L"NUL",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
0,
&(SECURITY_ATTRIBUTES){
.nLength = sizeof(SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = NULL,
.bInheritHandle = TRUE,
});
return hNullFile;
}
+88 -30
View File
@@ -4,6 +4,7 @@
#include "common/printing.h"
#include "common/io/io.h"
#include "common/time.h"
#include "detection/version/version.h"
#include "modules/modules.h"
#include "util/stringUtils.h"
@@ -11,52 +12,57 @@
#include <ctype.h>
#include <inttypes.h>
bool ffJsonConfigParseModuleArgs(const char* key, yyjson_val* val, FFModuleArgs* moduleArgs)
bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs)
{
if(ffStrEqualsIgnCase(key, "key"))
if (unsafe_yyjson_equals_str(key, "type") || unsafe_yyjson_equals_str(key, "condition"))
return true;
if (unsafe_yyjson_equals_str(key, "key"))
{
ffStrbufSetNS(&moduleArgs->key, (uint32_t) yyjson_get_len(val), yyjson_get_str(val));
ffStrbufSetJsonVal(&moduleArgs->key, val);
return true;
}
else if(ffStrEqualsIgnCase(key, "format"))
else if (unsafe_yyjson_equals_str(key, "format"))
{
ffStrbufSetNS(&moduleArgs->outputFormat, (uint32_t) yyjson_get_len(val), yyjson_get_str(val));
ffStrbufSetJsonVal(&moduleArgs->outputFormat, val);
return true;
}
else if(ffStrEqualsIgnCase(key, "outputColor"))
else if (unsafe_yyjson_equals_str(key, "outputColor"))
{
ffOptionParseColor(yyjson_get_str(val), &moduleArgs->outputColor);
return true;
}
else if(ffStrEqualsIgnCase(key, "keyColor"))
else if (unsafe_yyjson_equals_str(key, "keyColor"))
{
ffOptionParseColor(yyjson_get_str(val), &moduleArgs->keyColor);
return true;
}
else if(ffStrEqualsIgnCase(key, "keyWidth"))
else if (unsafe_yyjson_equals_str(key, "keyWidth"))
{
moduleArgs->keyWidth = (uint32_t) yyjson_get_uint(val);
return true;
}
else if(ffStrEqualsIgnCase(key, "keyIcon"))
else if (unsafe_yyjson_equals_str(key, "keyIcon"))
{
ffStrbufSetS(&moduleArgs->keyIcon, yyjson_get_str(val));
ffStrbufSetJsonVal(&moduleArgs->keyIcon, val);
return true;
}
return false;
}
void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* defaultModuleArgs, FFModuleArgs* moduleArgs)
void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* moduleArgs)
{
if (!ffStrbufEqual(&defaultModuleArgs->key, &moduleArgs->key))
if (moduleArgs->key.length > 0)
yyjson_mut_obj_add_strbuf(doc, module, "key", &moduleArgs->key);
if (!ffStrbufEqual(&defaultModuleArgs->outputFormat, &moduleArgs->outputFormat))
if (moduleArgs->outputFormat.length > 0)
yyjson_mut_obj_add_strbuf(doc, module, "format", &moduleArgs->outputFormat);
if (!ffStrbufEqual(&defaultModuleArgs->keyColor, &moduleArgs->keyColor))
if (moduleArgs->outputColor.length > 0)
yyjson_mut_obj_add_strbuf(doc, module, "outputColor", &moduleArgs->outputColor);
if (moduleArgs->keyColor.length > 0)
yyjson_mut_obj_add_strbuf(doc, module, "keyColor", &moduleArgs->keyColor);
if (moduleArgs->keyWidth != defaultModuleArgs->keyWidth)
if (moduleArgs->keyWidth > 0)
yyjson_mut_obj_add_uint(doc, module, "keyWidth", moduleArgs->keyWidth);
if (!ffStrbufEqual(&defaultModuleArgs->keyIcon, &moduleArgs->keyIcon))
if (moduleArgs->keyIcon.length > 0)
yyjson_mut_obj_add_strbuf(doc, module, "keyIcon", &moduleArgs->keyIcon);
}
@@ -95,12 +101,12 @@ const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair p
return "Invalid enum value type; must be a string or integer";
}
static inline void genJsonResult(FFModuleBaseInfo* baseInfo, yyjson_mut_doc* doc)
static inline void genJsonResult(FFModuleBaseInfo* baseInfo, void* options, yyjson_mut_doc* doc)
{
yyjson_mut_val* module = yyjson_mut_arr_add_obj(doc, doc->root);
yyjson_mut_obj_add_str(doc, module, "type", baseInfo->name);
if (baseInfo->generateJsonResult)
baseInfo->generateJsonResult(baseInfo, doc, module);
baseInfo->generateJsonResult(options, doc, module);
else
yyjson_mut_obj_add_str(doc, module, "error", "Unsupported for JSON format");
}
@@ -114,11 +120,14 @@ static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_
FFModuleBaseInfo* baseInfo = *modules;
if (ffStrEqualsIgnCase(type, baseInfo->name))
{
if (jsonVal) baseInfo->parseJsonObject(baseInfo, jsonVal);
uint8_t optionBuf[FF_OPTION_MAX_SIZE];
baseInfo->initOptions(optionBuf);
if (jsonVal) baseInfo->parseJsonObject(optionBuf, jsonVal);
if (__builtin_expect(jsonDoc != NULL, false))
genJsonResult(baseInfo, jsonDoc);
genJsonResult(baseInfo, optionBuf, jsonDoc);
else
baseInfo->printModule(baseInfo);
baseInfo->printModule(optionBuf);
baseInfo->destroyOptions(optionBuf);
return true;
}
}
@@ -127,7 +136,6 @@ static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_
static void prepareModuleJsonObject(const char* type, yyjson_val* module)
{
FFconfig* cfg = &instance.config;
switch (type[0])
{
case 'b': case 'B': {
@@ -138,38 +146,65 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module)
case 'd': case 'D': {
if (ffStrEqualsIgnCase(type, FF_DISKIO_MODULE_NAME))
{
if (module) cfg->modules.diskIo.moduleInfo.parseJsonObject(&cfg->modules.diskIo, module);
ffPrepareDiskIO(&cfg->modules.diskIo);
__attribute__((__cleanup__(ffDestroyDiskIOOptions))) FFDiskIOOptions options;
ffInitDiskIOOptions(&options);
if (module) ffDiskIOModuleInfo.parseJsonObject(&options, module);
ffPrepareDiskIO(&options);
}
break;
}
case 'n': case 'N': {
if (ffStrEqualsIgnCase(type, FF_NETIO_MODULE_NAME))
{
if (module) cfg->modules.netIo.moduleInfo.parseJsonObject(&cfg->modules.netIo, module);
ffPrepareNetIO(&cfg->modules.netIo);
__attribute__((__cleanup__(ffDestroyNetIOOptions))) FFNetIOOptions options;
ffInitNetIOOptions(&options);
if (module) ffNetIOModuleInfo.parseJsonObject(&options, module);
ffPrepareNetIO(&options);
}
break;
}
case 'p': case 'P': {
if (ffStrEqualsIgnCase(type, FF_PUBLICIP_MODULE_NAME))
{
if (module) cfg->modules.publicIP.moduleInfo.parseJsonObject(&cfg->modules.publicIP, module);
ffPreparePublicIp(&cfg->modules.publicIP);
__attribute__((__cleanup__(ffDestroyPublicIpOptions))) FFPublicIPOptions options;
ffInitPublicIpOptions(&options);
if (module) ffPublicIPModuleInfo.parseJsonObject(&options, module);
ffPreparePublicIp(&options);
}
break;
}
case 'w': case 'W': {
if (ffStrEqualsIgnCase(type, FF_WEATHER_MODULE_NAME))
{
if (module) cfg->modules.weather.moduleInfo.parseJsonObject(&cfg->modules.weather, module);
ffPrepareWeather(&cfg->modules.weather);
__attribute__((__cleanup__(ffDestroyWeatherOptions))) FFWeatherOptions options;
ffInitWeatherOptions(&options);
if (module) ffWeatherModuleInfo.parseJsonObject(&options, module);
ffPrepareWeather(&options);
}
break;
}
}
}
static bool matchesJsonArray(const char* str, yyjson_val* val)
{
assert(val);
if (unsafe_yyjson_is_str(val))
return ffStrEqualsIgnCase(str, unsafe_yyjson_get_str(val));
if (!unsafe_yyjson_is_arr(val)) return false;
size_t idx, max;
yyjson_val* item;
yyjson_arr_foreach(val, idx, max, item)
{
if (yyjson_is_str(item) && ffStrEqualsIgnCase(str, unsafe_yyjson_get_str(item)))
return true;
}
return false;
}
static const char* printJsonConfig(bool prepare, yyjson_mut_doc* jsonDoc)
{
yyjson_val* const root = yyjson_doc_get_root(instance.state.configDoc);
@@ -197,6 +232,29 @@ static const char* printJsonConfig(bool prepare, yyjson_mut_doc* jsonDoc)
module = NULL;
else if (yyjson_is_obj(module))
{
yyjson_val* conditions = yyjson_obj_get(module, "condition");
if (conditions)
{
if (!yyjson_is_obj(conditions))
return "Property 'conditions' must be an object";
yyjson_val* system = yyjson_obj_get(conditions, "system");
if (system && !matchesJsonArray(ffVersionResult.sysName, system))
continue;
system = yyjson_obj_get(conditions, "!system");
if (system && matchesJsonArray(ffVersionResult.sysName, system))
continue;
yyjson_val* arch = yyjson_obj_get(conditions, "arch");
if (arch && !matchesJsonArray(ffVersionResult.architecture, arch))
continue;
arch = yyjson_obj_get(conditions, "!arch");
if (arch && matchesJsonArray(ffVersionResult.architecture, arch))
continue;
}
type = yyjson_get_str(yyjson_obj_get(module, "type"));
if (!type) return "module object must contain a \"type\" key ( case sensitive )";
if (yyjson_obj_size(module) == 1) // contains only Property type
+2 -2
View File
@@ -2,10 +2,10 @@
#include "fastfetch.h"
bool ffJsonConfigParseModuleArgs(const char* key, yyjson_val* val, FFModuleArgs* moduleArgs);
bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs);
const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair pairs[]);
void ffPrintJsonConfig(bool prepare, yyjson_mut_doc* jsonDoc);
void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* defaultModuleArgs, FFModuleArgs* moduleArgs);
void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* moduleArgs);
yyjson_api_inline yyjson_mut_val* yyjson_mut_strbuf(yyjson_mut_doc *doc, const FFstrbuf* buf) {
return yyjson_mut_strncpy(doc, buf->chars, buf->length);
+74 -74
View File
@@ -1,69 +1,69 @@
#include "fastfetch.h"
#include "modules/modules.h"
static FFModuleBaseInfo* A[] = {
NULL,
};
static FFModuleBaseInfo* B[] = {
(FFModuleBaseInfo*) &instance.config.modules.battery,
(FFModuleBaseInfo*) &instance.config.modules.bios,
(FFModuleBaseInfo*) &instance.config.modules.bluetooth,
(FFModuleBaseInfo*) &instance.config.modules.bluetoothRadio,
(FFModuleBaseInfo*) &instance.config.modules.board,
(FFModuleBaseInfo*) &instance.config.modules.bootmgr,
(FFModuleBaseInfo*) &instance.config.modules.break_,
(FFModuleBaseInfo*) &instance.config.modules.brightness,
(FFModuleBaseInfo*) &instance.config.modules.btrfs,
&ffBatteryModuleInfo,
&ffBiosModuleInfo,
&ffBluetoothModuleInfo,
&ffBluetoothRadioModuleInfo,
&ffBoardModuleInfo,
&ffBootmgrModuleInfo,
&ffBreakModuleInfo,
&ffBrightnessModuleInfo,
&ffBtrfsModuleInfo,
NULL,
};
static FFModuleBaseInfo* C[] = {
(FFModuleBaseInfo*) &instance.config.modules.camera,
(FFModuleBaseInfo*) &instance.config.modules.chassis,
(FFModuleBaseInfo*) &instance.config.modules.command,
(FFModuleBaseInfo*) &instance.config.modules.colors,
(FFModuleBaseInfo*) &instance.config.modules.cpu,
(FFModuleBaseInfo*) &instance.config.modules.cpuCache,
(FFModuleBaseInfo*) &instance.config.modules.cpuUsage,
(FFModuleBaseInfo*) &instance.config.modules.cursor,
(FFModuleBaseInfo*) &instance.config.modules.custom,
&ffCameraModuleInfo,
&ffChassisModuleInfo,
&ffCommandModuleInfo,
&ffColorsModuleInfo,
&ffCPUModuleInfo,
&ffCPUCacheModuleInfo,
&ffCPUUsageModuleInfo,
&ffCursorModuleInfo,
&ffCustomModuleInfo,
NULL,
};
static FFModuleBaseInfo* D[] = {
(FFModuleBaseInfo*) &instance.config.modules.dateTime,
(FFModuleBaseInfo*) &instance.config.modules.de,
(FFModuleBaseInfo*) &instance.config.modules.display,
(FFModuleBaseInfo*) &instance.config.modules.disk,
(FFModuleBaseInfo*) &instance.config.modules.diskIo,
(FFModuleBaseInfo*) &instance.config.modules.dns,
&ffDateTimeModuleInfo,
&ffDEModuleInfo,
&ffDisplayModuleInfo,
&ffDiskModuleInfo,
&ffDiskIOModuleInfo,
&ffDNSModuleInfo,
NULL,
};
static FFModuleBaseInfo* E[] = {
(FFModuleBaseInfo*) &instance.config.modules.editor,
&ffEditorModuleInfo,
NULL,
};
static FFModuleBaseInfo* F[] = {
(FFModuleBaseInfo*) &instance.config.modules.font,
&ffFontModuleInfo,
NULL,
};
static FFModuleBaseInfo* G[] = {
(FFModuleBaseInfo*) &instance.config.modules.gamepad,
(FFModuleBaseInfo*) &instance.config.modules.gpu,
&ffGamepadModuleInfo,
&ffGPUModuleInfo,
NULL,
};
static FFModuleBaseInfo* H[] = {
(FFModuleBaseInfo*) &instance.config.modules.host,
&ffHostModuleInfo,
NULL,
};
static FFModuleBaseInfo* I[] = {
(FFModuleBaseInfo*) &instance.config.modules.icons,
(FFModuleBaseInfo*) &instance.config.modules.initSystem,
&ffIconsModuleInfo,
&ffInitSystemModuleInfo,
NULL,
};
@@ -72,47 +72,47 @@ static FFModuleBaseInfo* J[] = {
};
static FFModuleBaseInfo* K[] = {
(FFModuleBaseInfo*) &instance.config.modules.kernel,
(FFModuleBaseInfo*) &instance.config.modules.keyboard,
&ffKernelModuleInfo,
&ffKeyboardModuleInfo,
NULL,
};
static FFModuleBaseInfo* L[] = {
(FFModuleBaseInfo*) &instance.config.modules.lm,
(FFModuleBaseInfo*) &instance.config.modules.loadavg,
(FFModuleBaseInfo*) &instance.config.modules.locale,
(FFModuleBaseInfo*) &instance.config.modules.localIP,
&ffLMModuleInfo,
&ffLoadavgModuleInfo,
&ffLocaleModuleInfo,
&ffLocalIPModuleInfo,
NULL,
};
static FFModuleBaseInfo* M[] = {
(FFModuleBaseInfo*) &instance.config.modules.media,
(FFModuleBaseInfo*) &instance.config.modules.memory,
(FFModuleBaseInfo*) &instance.config.modules.monitor,
(FFModuleBaseInfo*) &instance.config.modules.mouse,
&ffMediaModuleInfo,
&ffMemoryModuleInfo,
&ffMonitorModuleInfo,
&ffMouseModuleInfo,
NULL,
};
static FFModuleBaseInfo* N[] = {
(FFModuleBaseInfo*) &instance.config.modules.netIo,
&ffNetIOModuleInfo,
NULL,
};
static FFModuleBaseInfo* O[] = {
(FFModuleBaseInfo*) &instance.config.modules.openCL,
(FFModuleBaseInfo*) &instance.config.modules.openGL,
(FFModuleBaseInfo*) &instance.config.modules.os,
&ffOpenCLModuleInfo,
&ffOpenGLModuleInfo,
&ffOSModuleInfo,
NULL,
};
static FFModuleBaseInfo* P[] = {
(FFModuleBaseInfo*) &instance.config.modules.packages,
(FFModuleBaseInfo*) &instance.config.modules.physicalDisk,
(FFModuleBaseInfo*) &instance.config.modules.physicalMemory,
(FFModuleBaseInfo*) &instance.config.modules.player,
(FFModuleBaseInfo*) &instance.config.modules.powerAdapter,
(FFModuleBaseInfo*) &instance.config.modules.processes,
(FFModuleBaseInfo*) &instance.config.modules.publicIP,
&ffPackagesModuleInfo,
&ffPhysicalDiskModuleInfo,
&ffPhysicalMemoryModuleInfo,
&ffPlayerModuleInfo,
&ffPowerAdapterModuleInfo,
&ffProcessesModuleInfo,
&ffPublicIPModuleInfo,
NULL,
};
@@ -125,42 +125,42 @@ static FFModuleBaseInfo* R[] = {
};
static FFModuleBaseInfo* S[] = {
(FFModuleBaseInfo*) &instance.config.modules.separator,
(FFModuleBaseInfo*) &instance.config.modules.shell,
(FFModuleBaseInfo*) &instance.config.modules.sound,
(FFModuleBaseInfo*) &instance.config.modules.swap,
&ffSeparatorModuleInfo,
&ffShellModuleInfo,
&ffSoundModuleInfo,
&ffSwapModuleInfo,
NULL,
};
static FFModuleBaseInfo* T[] = {
(FFModuleBaseInfo*) &instance.config.modules.terminal,
(FFModuleBaseInfo*) &instance.config.modules.terminalFont,
(FFModuleBaseInfo*) &instance.config.modules.terminalSize,
(FFModuleBaseInfo*) &instance.config.modules.terminalTheme,
(FFModuleBaseInfo*) &instance.config.modules.title,
(FFModuleBaseInfo*) &instance.config.modules.theme,
(FFModuleBaseInfo*) &instance.config.modules.tpm,
&ffTerminalModuleInfo,
&ffTerminalFontModuleInfo,
&ffTerminalSizeModuleInfo,
&ffTerminalThemeModuleInfo,
&ffTitleModuleInfo,
&ffThemeModuleInfo,
&ffTPMModuleInfo,
NULL,
};
static FFModuleBaseInfo* U[] = {
(FFModuleBaseInfo*) &instance.config.modules.uptime,
(FFModuleBaseInfo*) &instance.config.modules.users,
&ffUptimeModuleInfo,
&ffUsersModuleInfo,
NULL,
};
static FFModuleBaseInfo* V[] = {
(FFModuleBaseInfo*) &instance.config.modules.version,
(FFModuleBaseInfo*) &instance.config.modules.vulkan,
&ffVersionModuleInfo,
&ffVulkanModuleInfo,
NULL,
};
static FFModuleBaseInfo* W[] = {
(FFModuleBaseInfo*) &instance.config.modules.wallpaper,
(FFModuleBaseInfo*) &instance.config.modules.weather,
(FFModuleBaseInfo*) &instance.config.modules.wm,
(FFModuleBaseInfo*) &instance.config.modules.wifi,
(FFModuleBaseInfo*) &instance.config.modules.wmTheme,
&ffWallpaperModuleInfo,
&ffWeatherModuleInfo,
&ffWMModuleInfo,
&ffWifiModuleInfo,
&ffWMThemeModuleInfo,
NULL,
};
@@ -173,7 +173,7 @@ static FFModuleBaseInfo* Y[] = {
};
static FFModuleBaseInfo* Z[] = {
(FFModuleBaseInfo*) &instance.config.modules.zpool,
&ffZpoolModuleInfo,
NULL,
};
+13 -19
View File
@@ -2,29 +2,23 @@
#ifndef _WIN32
#include <net/if.h>
#else
#define IF_NAMESIZE 0
#include <netinet/in.h>
#endif
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex);
enum { IF_INDEX_UNINITIALIZED = (uint32_t) -1, IF_INDEX_INVALID = (uint32_t) -2 };
static uint32_t ifIndex = IF_INDEX_UNINITIALIZED;
static char ifName[IF_NAMESIZE + 1];
static inline void init()
const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV4(void)
{
if (ifIndex == (uint32_t) IF_INDEX_UNINITIALIZED && !ffNetifGetDefaultRouteImpl(ifName, &ifIndex))
ifIndex = (uint32_t) IF_INDEX_INVALID;
static FFNetifDefaultRouteResult result;
if (result.status == FF_NETIF_UNINITIALIZED) {
result.status = ffNetifGetDefaultRouteImplV4(&result) ? FF_NETIF_OK : FF_NETIF_INVALID;
}
return &result;
}
const char* ffNetifGetDefaultRouteIfName()
const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV6(void)
{
init();
return ifName;
}
uint32_t ffNetifGetDefaultRouteIfIndex()
{
init();
return ifIndex;
static FFNetifDefaultRouteResult result;
if (result.status == FF_NETIF_UNINITIALIZED) {
result.status = ffNetifGetDefaultRouteImplV6(&result) ? FF_NETIF_OK : FF_NETIF_INVALID;
}
return &result;
}
+23 -2
View File
@@ -3,7 +3,28 @@
#include "fastfetch.h"
#ifndef _WIN32
const char* ffNetifGetDefaultRouteIfName();
#include <net/if.h>
#include <netinet/in.h>
#endif
uint32_t ffNetifGetDefaultRouteIfIndex();
typedef enum __attribute__((__packed__)) FFNetifDefaultRouteResultStatus {
FF_NETIF_UNINITIALIZED,
FF_NETIF_INVALID,
FF_NETIF_OK
} FFNetifDefaultRouteResultStatus;
typedef struct FFNetifDefaultRouteResult {
uint32_t ifIndex;
#ifndef _WIN32
char ifName[IF_NAMESIZE + 1];
uint32_t preferredSourceAddrV4;
#endif
enum FFNetifDefaultRouteResultStatus status;
} FFNetifDefaultRouteResult;
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result);
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result);
const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV4(void);
const FFNetifDefaultRouteResult* ffNetifGetDefaultRouteV6(void);
+201
View File
@@ -0,0 +1,201 @@
#include "netif.h"
#include "common/io/io.h"
#include "util/mallocHelper.h"
#include <net/if.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n))
#if __APPLE__
// https://github.com/apple-oss-distributions/network_cmds/blob/8f38231438e6a4d16ef8015e97e12c2c05105644/rtsol.tproj/if.c#L243
#define ROUNDUP(a) ROUNDUP2((a), sizeof(uint32_t))
#elif __sun
// https://github.com/illumos/illumos-gate/blob/95b8c88950fa7b19af46bc63230137cf96b0bff7/usr/src/cmd/cmd-inet/usr.sbin/route.c#L339
#define ROUNDUP(a) ROUNDUP2((a), sizeof(long))
#else
#error unknown platform
#endif
static struct sockaddr *
get_rt_address(struct rt_msghdr *rtm, int desired)
{
struct sockaddr *sa = (struct sockaddr *)(rtm + 1);
for (int i = 0; i < RTAX_MAX; i++)
{
if (rtm->rtm_addrs & (1 << i))
{
if ((1 << i) == desired)
return sa;
#ifndef __sun
uint32_t salen = sa->sa_len;
#else
uint32_t salen;
// https://github.com/illumos/illumos-gate/blob/95b8c88950fa7b19af46bc63230137cf96b0bff7/usr/src/cmd/cmd-inet/usr.sbin/route.c#L2941
switch (sa->sa_family) {
case AF_INET:
salen = sizeof (struct sockaddr_in);
break;
case AF_LINK:
salen = sizeof (struct sockaddr_dl);
break;
case AF_INET6:
salen = sizeof (struct sockaddr_in6);
break;
default:
salen = sizeof (struct sockaddr);
break;
}
#endif
sa = (struct sockaddr *)(ROUNDUP(salen) + (char *)sa);
}
}
return NULL;
}
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
//https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104
FF_AUTO_CLOSE_FD int pfRoute = socket(PF_ROUTE, SOCK_RAW, AF_INET);
if (pfRoute < 0)
return false;
{
struct timeval timeout = {1, 0};
setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
}
int pid = getpid();
struct {
struct rt_msghdr hdr;
struct sockaddr_in dst;
uint8_t data[512];
} rtmsg = {
.hdr = {
.rtm_type = RTM_GET,
.rtm_flags = RTF_UP | RTF_GATEWAY,
.rtm_version = RTM_VERSION,
.rtm_addrs = RTA_DST | RTA_IFP | RTA_IFA,
.rtm_msglen = sizeof(rtmsg.hdr) + sizeof(rtmsg.dst),
.rtm_pid = pid,
.rtm_seq = 1,
},
.dst = {
.sin_family = AF_INET,
#ifndef __sun
.sin_len = sizeof(rtmsg.dst),
#endif
},
};
if (send(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen, 0) != rtmsg.hdr.rtm_msglen)
return false;
while (recv(pfRoute, &rtmsg, sizeof(rtmsg), 0) > 0 && !(rtmsg.hdr.rtm_seq == 1 && rtmsg.hdr.rtm_pid == pid))
;
#ifndef __sun // On Solaris, the RTF_GATEWAY flag is not set for default routes for some reason
if ((rtmsg.hdr.rtm_flags & (RTF_UP | RTF_GATEWAY)) == (RTF_UP | RTF_GATEWAY))
#endif
{
struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(&rtmsg.hdr, RTA_IFP);
if (sdl
#ifndef __sun
&& sdl->sdl_len
#endif
)
{
assert(sdl->sdl_nlen <= IF_NAMESIZE);
memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen);
result->ifName[sdl->sdl_nlen] = '\0';
result->ifIndex = sdl->sdl_index;
// Get the preferred source address
struct sockaddr_in* src = (struct sockaddr_in*)get_rt_address(&rtmsg.hdr, RTA_IFA);
if (src && src->sin_family == AF_INET)
result->preferredSourceAddrV4 = src->sin_addr.s_addr;
return true;
}
return false;
}
return false;
}
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
//https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104
FF_AUTO_CLOSE_FD int pfRoute = socket(PF_ROUTE, SOCK_RAW, AF_INET6);
if (pfRoute < 0)
return false;
{
struct timeval timeout = {1, 0};
setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
}
int pid = getpid();
struct {
struct rt_msghdr hdr;
struct sockaddr_in6 dst;
uint8_t data[512];
} rtmsg = {
.hdr = {
.rtm_type = RTM_GET,
.rtm_flags = RTF_UP | RTF_GATEWAY,
.rtm_version = RTM_VERSION,
.rtm_addrs = RTA_DST | RTA_IFP,
.rtm_msglen = sizeof(rtmsg.hdr) + sizeof(rtmsg.dst),
.rtm_pid = pid,
.rtm_seq = 2,
},
.dst = {
.sin6_family = AF_INET6,
#ifndef __sun
.sin6_len = sizeof(rtmsg.dst),
#endif
},
};
if (send(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen, 0) != rtmsg.hdr.rtm_msglen)
return false;
while (recv(pfRoute, &rtmsg, sizeof(rtmsg), 0) > 0 && !(rtmsg.hdr.rtm_seq == 2 && rtmsg.hdr.rtm_pid == pid))
;
#ifndef __sun // On Solaris, the RTF_GATEWAY flag is not set for default routes for some reason
if ((rtmsg.hdr.rtm_flags & (RTF_UP | RTF_GATEWAY)) == (RTF_UP | RTF_GATEWAY))
#endif
{
struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(&rtmsg.hdr, RTA_IFP);
if (sdl
#ifndef __sun
&& sdl->sdl_len
#endif
)
{
assert(sdl->sdl_nlen <= IF_NAMESIZE);
memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen);
result->ifName[sdl->sdl_nlen] = '\0';
result->ifIndex = sdl->sdl_index;
return true;
}
return false;
}
return false;
}
+50 -74
View File
@@ -8,25 +8,24 @@
#include <net/route.h>
#include <netinet/in.h>
#include <sys/socket.h>
#if defined(__OpenBSD__) || defined(__DragonFly__)
#include <sys/sysctl.h>
#endif
#include <sys/sysctl.h>
#define ROUNDUP2(a, n) ((a) > 0 ? (1 + (((a) - 1U) | ((n) - 1))) : (n))
#if defined(__APPLE__)
# define ROUNDUP(a) ROUNDUP2((a), sizeof(int))
#elif defined(__NetBSD__)
# define ROUNDUP(a) ROUNDUP2((a), sizeof(uint64_t))
#elif defined(__FreeBSD__) || defined(__DragonFly__)
# define ROUNDUP(a) ROUNDUP2((a), sizeof(int))
#elif defined(__OpenBSD__)
# define ROUNDUP(a) ROUNDUP2((a), sizeof(int))
#elif defined(__sun)
# define ROUNDUP(a) ROUNDUP2((a), _SS_ALIGNSIZE)
#if __DragonFly__
// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/cf0aa2f1e47a3f0a6055fe427563cb3f3e627064/sys/net/route.h#L315C9-L315C19
#define ROUNDUP(a) ROUNDUP2((a), sizeof(long))
#elif __FreeBSD__
// https://github.com/freebsd/freebsd-src/blob/e4c0ecba44b20ebb2e4d80978c2cb6d16b730cb9/sys/net/route.h#L368C9-L368C16
#define ROUNDUP(a) ROUNDUP2((a), sizeof(long))
#elif __NetBSD__
// https://github.com/NetBSD/src/blob/29beb637d057520c0ed37ac2cde966f7cc0cadf4/sys/net/route.h#L330
#define ROUNDUP(a) ROUNDUP2((a), sizeof(uint64_t))
#elif __OpenBSD__
// https://github.com/openbsd/src/blob/ca647cfa4ec3ccb8360714bc0ebc32a394f7fb6a/regress/sys/netinet/bindconnect/bindconnect.c#L250
#define ROUNDUP(a) ROUNDUP2((a), sizeof(long))
#else
# error unknown platform
#error unknown platform
#endif
static struct sockaddr *
@@ -40,23 +39,18 @@ get_rt_address(struct rt_msghdr *rtm, int desired)
{
if ((1 << i) == desired)
return sa;
#ifdef __sun
sa = (struct sockaddr *)(ROUNDUP(sizeof(struct sockaddr)) + (char *)sa);
#else
sa = (struct sockaddr *)(ROUNDUP(sa->sa_len) + (char *)sa);
#endif
}
}
return NULL;
}
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
#if defined(__OpenBSD__) || defined(__DragonFly__)
int mib[6] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY};
size_t needed;
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0)
return false;
FF_AUTO_FREE char* buf = malloc(needed);
@@ -71,80 +65,62 @@ bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
rtm = (struct rt_msghdr *)next;
struct sockaddr* sa = (struct sockaddr *)(rtm + 1);
if ((rtm->rtm_flags & RTF_GATEWAY) && (sa->sa_family == AF_INET))
if ((rtm->rtm_flags & RTF_GATEWAY) && !(rtm->rtm_flags & RTF_REJECT) && (sa->sa_family == AF_INET))
{
struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(rtm, RTA_IFP);
if (sdl->sdl_family == AF_LINK)
if (sdl && sdl->sdl_family == AF_LINK)
{
assert(sdl->sdl_nlen <= IF_NAMESIZE);
memcpy(iface, sdl->sdl_data, sdl->sdl_nlen);
iface[sdl->sdl_nlen] = '\0';
*ifIndex = sdl->sdl_index;
memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen);
result->ifName[sdl->sdl_nlen] = '\0';
result->ifIndex = sdl->sdl_index;
// Get the preferred source address
struct sockaddr_in* src = (struct sockaddr_in*)get_rt_address(rtm, RTA_IFA);
if (src && src->sin_family == AF_INET)
result->preferredSourceAddrV4 = src->sin_addr.s_addr;
return true;
}
}
}
#else
//https://github.com/hashPirate/copenheimer-masscan-fork/blob/36f1ed9f7b751a7dccd5ed27874e2e703db7d481/src/rawsock-getif.c#L104
return false;
}
FF_AUTO_CLOSE_FD int pfRoute = socket(PF_ROUTE, SOCK_RAW, AF_INET);
if (pfRoute < 0)
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
int mib[6] = {CTL_NET, PF_ROUTE, 0, AF_INET6, NET_RT_FLAGS, RTF_GATEWAY};
size_t needed;
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0)
return false;
{
struct timeval timeout = {1, 0};
setsockopt(pfRoute, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
setsockopt(pfRoute, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
}
FF_AUTO_FREE char* buf = malloc(needed);
int pid = getpid();
struct {
struct rt_msghdr hdr;
struct sockaddr_in dst;
uint8_t data[512];
} rtmsg = {
.hdr = {
.rtm_type = RTM_GET,
.rtm_flags = RTF_UP | RTF_GATEWAY,
.rtm_version = RTM_VERSION,
.rtm_addrs = RTA_DST | RTA_IFP,
.rtm_msglen = sizeof(rtmsg.hdr) + sizeof(rtmsg.dst),
.rtm_pid = pid,
.rtm_seq = 1,
},
.dst = {
.sin_family = AF_INET,
#ifndef __sun
.sin_len = sizeof(rtmsg.dst),
#endif
},
};
if (write(pfRoute, &rtmsg, rtmsg.hdr.rtm_msglen) != rtmsg.hdr.rtm_msglen)
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
return false;
while (read(pfRoute, &rtmsg, sizeof(rtmsg)) > 0)
char* lim = buf + needed;
struct rt_msghdr* rtm;
for (char* next = buf; next < lim; next += rtm->rtm_msglen)
{
if (rtmsg.hdr.rtm_seq == 1 && rtmsg.hdr.rtm_pid == pid)
rtm = (struct rt_msghdr *)next;
struct sockaddr* sa = (struct sockaddr *)(rtm + 1);
if ((rtm->rtm_flags & RTF_GATEWAY) && !(rtm->rtm_flags & RTF_REJECT) && (sa->sa_family == AF_INET6))
{
struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(&rtmsg.hdr, RTA_IFP);
if (sdl
#ifndef __sun
&& sdl->sdl_len
#endif
)
struct sockaddr_dl* sdl = (struct sockaddr_dl *)get_rt_address(rtm, RTA_IFP);
if (sdl && sdl->sdl_family == AF_LINK)
{
assert(sdl->sdl_nlen <= IF_NAMESIZE);
memcpy(iface, sdl->sdl_data, sdl->sdl_nlen);
iface[sdl->sdl_nlen] = '\0';
*ifIndex = sdl->sdl_index;
memcpy(result->ifName, sdl->sdl_data, sdl->sdl_nlen);
result->ifName[sdl->sdl_nlen] = '\0';
result->ifIndex = sdl->sdl_index;
return true;
}
return false;
}
}
#endif
return false;
}
+55 -6
View File
@@ -11,9 +11,8 @@
// loosely based on Haiku's src/bin/network/route/route.cpp
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
// TODO: AF_INET6
FF_AUTO_CLOSE_FD int pfRoute = socket(AF_INET, SOCK_RAW, AF_INET);
if (pfRoute < 0)
return false;
@@ -42,8 +41,11 @@ bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
while (interface < end) {
if (interface->ifr_route.flags & RTF_DEFAULT) {
strlcpy(iface, interface->ifr_name, IF_NAMESIZE);
*ifIndex = if_nametoindex(interface->ifr_name);
// interface->ifr_metric?
strlcpy(result->ifName, interface->ifr_name, IF_NAMESIZE);
result->ifIndex = if_nametoindex(interface->ifr_name);
if (interface->ifr_route.source)
result->preferredSourceAddrV4 = ((struct sockaddr_in*)interface->ifr_route.source)->sin_addr.s_addr;
return true;
}
@@ -55,9 +57,56 @@ bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
if (interface->ifr_route.gateway != NULL)
addressSize += interface->ifr_route.gateway->sa_len;
interface = (struct ifreq*)((addr_t)interface + IF_NAMESIZE
+ sizeof(struct route_entry) + addressSize);
interface = (struct ifreq*)((addr_t)interface + IF_NAMESIZE + sizeof(struct route_entry) + addressSize);
}
return false;
}
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
FF_AUTO_CLOSE_FD int pfRoute = socket(AF_INET, SOCK_RAW, AF_INET6);
if (pfRoute < 0)
return false;
struct ifconf config;
config.ifc_len = sizeof(config.ifc_value);
if (ioctl(pfRoute, SIOCGRTSIZE, &config, sizeof(struct ifconf)) < 0)
return false;
int size = config.ifc_value;
if (size <= 0)
return false;
FF_AUTO_FREE void *buffer = malloc((size_t) size);
if (buffer == NULL) {
return false;
}
config.ifc_len = size;
config.ifc_buf = buffer;
if (ioctl(pfRoute, SIOCGRTTABLE, &config, sizeof(struct ifconf)) < 0)
return false;
struct ifreq *interface = (struct ifreq*)buffer;
struct ifreq *end = (struct ifreq*)((uint8_t*)buffer + size);
while (interface < end) {
if (interface->ifr_route.flags & RTF_DEFAULT) {
strlcpy(result->ifName, interface->ifr_name, IF_NAMESIZE);
result->ifIndex = if_nametoindex(interface->ifr_name);
return true;
}
size_t addressSize = 0;
if (interface->ifr_route.destination != NULL)
addressSize += interface->ifr_route.destination->sa_len;
if (interface->ifr_route.mask != NULL)
addressSize += interface->ifr_route.mask->sa_len;
if (interface->ifr_route.gateway != NULL)
addressSize += interface->ifr_route.gateway->sa_len;
interface = (struct ifreq*)((addr_t)interface + IF_NAMESIZE + sizeof(struct route_entry) + addressSize);
}
return false;
}
+383 -32
View File
@@ -1,52 +1,403 @@
#include "netif.h"
#include "common/io/io.h"
#include "util/mallocHelper.h"
#include "util/debug.h"
#include <arpa/inet.h>
#include <linux/rtnetlink.h>
#include <net/if.h>
#include <stdio.h>
#define FF_STR_INDIR(x) #x
#define FF_STR(x) FF_STR_INDIR(x)
static bool getDefaultRouteIPv4(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/net/route", "r");
if (!netRoute) return false;
FF_DEBUG("Starting IPv4 default route detection");
// skip first line
FF_UNUSED(fscanf(netRoute, "%*[^\n]\n"));
unsigned long long destination; //, gateway, flags, refCount, use, metric, mask, mtu, ...
while (fscanf(netRoute, "%" FF_STR(IF_NAMESIZE) "s%llx%*[^\n]", iface, &destination) == 2)
FF_AUTO_CLOSE_FD int sock_fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
if (sock_fd < 0)
{
if (destination != 0) continue;
*ifIndex = if_nametoindex(iface);
FF_DEBUG("Failed to create netlink socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Created netlink socket: fd=%d", sock_fd);
unsigned pid = (unsigned) getpid();
FF_DEBUG("Process PID: %u", pid);
// Bind socket
struct sockaddr_nl addr = {
.nl_family = AF_NETLINK,
.nl_pid = 0, // Let kernel choose PID
.nl_groups = 0, // No multicast groups
};
if (bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
FF_DEBUG("Failed to bind socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Successfully bound socket");
struct __attribute__((__packed__)) {
struct nlmsghdr nlh;
struct rtmsg rtm;
struct rtattr rta;
uint32_t table;
} req = {
// Netlink message header
.nlh = {
.nlmsg_len = sizeof(req),
.nlmsg_type = RTM_GETROUTE,
.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
.nlmsg_seq = 1,
.nlmsg_pid = pid,
},
// Route message
.rtm = {
.rtm_family = AF_INET,
.rtm_dst_len = 0, // Match all destinations
.rtm_src_len = 0, // Match all sources
.rtm_tos = 0,
.rtm_table = RT_TABLE_UNSPEC,
.rtm_protocol = RTPROT_UNSPEC,
.rtm_scope = RT_SCOPE_UNIVERSE,
.rtm_type = RTN_UNSPEC,
.rtm_flags = 0,
},
// Route attribute for main table
.rta = {
.rta_len = RTA_LENGTH(sizeof(uint32_t)),
.rta_type = RTA_TABLE,
},
.table = RT_TABLE_MAIN,
};
struct sockaddr_nl dest_addr = {
.nl_family = AF_NETLINK,
.nl_pid = 0, // Kernel
.nl_groups = 0, // No multicast groups
};
ssize_t sent = sendto(sock_fd, &req, sizeof(req), 0,
(struct sockaddr*)&dest_addr, sizeof(dest_addr));
if (sent != sizeof(req)) {
FF_DEBUG("Failed to send netlink request: sent=%zd, expected=%zu", sent, sizeof(req));
return false;
}
FF_DEBUG("Sent netlink request: %zd bytes", sent);
struct sockaddr_nl src_addr = {};
socklen_t src_addr_len = sizeof(src_addr);
uint8_t buffer[1024 * 16]; // 16 KB buffer should be sufficient
ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0,
(struct sockaddr*)&src_addr, &src_addr_len);
if (received < 0) {
FF_DEBUG("Failed to receive netlink response: %s", strerror(errno));
return false;
}
if (received >= (ssize_t)sizeof(buffer)) {
FF_DEBUG("Failed to receive complete message (possible truncation)");
return false;
}
FF_DEBUG("Received netlink response: %zd bytes", received);
struct {
uint32_t metric;
uint32_t ifindex;
uint32_t prefsrc;
} entry;
uint32_t minMetric = UINT32_MAX;
int routeCount = 0;
for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer;
NLMSG_OK(nlh, received);
nlh = NLMSG_NEXT(nlh, received)) {
if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid)
continue;
if (nlh->nlmsg_type == NLMSG_DONE)
{
FF_DEBUG("Received NLMSG_DONE, processed %d routes", routeCount);
break;
}
if (nlh->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr* err = (struct nlmsgerr*)NLMSG_DATA(nlh);
FF_DEBUG("Netlink reports error: %s", strerror(-err->error));
continue;
}
if (nlh->nlmsg_type != RTM_NEWROUTE)
continue;
routeCount++;
struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh);
if (rtm->rtm_family != AF_INET)
continue;
if (rtm->rtm_dst_len != 0)
continue;
FF_DEBUG("Processing IPv4 default route candidate #%d", routeCount);
entry = (__typeof__(entry)) { }; // Default to zero metric (no RTA_PRIORITY found)
// Parse route attributes
size_t rtm_len = RTM_PAYLOAD(nlh);
for (struct rtattr* rta = RTM_RTA(rtm);
RTA_OK(rta, rtm_len);
rta = RTA_NEXT(rta, rtm_len))
{
if (RTA_PAYLOAD(rta) < sizeof(uint32_t))
continue; // Skip invalid attributes
uint32_t rta_data = *(uint32_t*) RTA_DATA(rta);
switch (rta->rta_type) {
case RTA_DST:
FF_DEBUG("Unexpected RTA_DST: %s (len=%u)", inet_ntoa((struct in_addr) { .s_addr = rta_data }), rtm->rtm_dst_len);
goto next;
case RTA_OIF:
entry.ifindex = rta_data;
FF_DEBUG("Found interface index: %u", entry.ifindex);
break;
case RTA_GATEWAY:
FF_DEBUG("Found gateway: %s", inet_ntoa(*(struct in_addr*)&rta_data));
if (rta_data == 0) goto next;
break;
case RTA_PRIORITY:
FF_DEBUG("Found metric: %u", rta_data);
if (rta_data >= minMetric) goto next;
entry.metric = rta_data;
break;
case RTA_PREFSRC:
entry.prefsrc = rta_data;
FF_DEBUG("Found preferred source: %s", inet_ntoa(*(struct in_addr*)&rta_data));
break;
}
}
if (entry.ifindex == 0 || entry.metric >= minMetric)
{
next:
FF_DEBUG("Skipping route: ifindex=%u, metric=%u", entry.ifindex, entry.metric);
continue;
}
minMetric = entry.metric;
result->ifIndex = entry.ifindex;
FF_DEBUG("Updated best route: ifindex=%u, metric=%u, prefsrc=%x", entry.ifindex, entry.metric, entry.prefsrc);
result->preferredSourceAddrV4 = entry.prefsrc;
if (minMetric == 0)
{
FF_DEBUG("Found zero metric route, stopping further processing");
break; // Stop processing if we found a zero metric route
}
}
if (minMetric < UINT32_MAX)
{
if_indextoname(result->ifIndex, result->ifName);
FF_DEBUG("Found default IPv4 route: interface=%s, index=%u, metric=%u", result->ifName, result->ifIndex, minMetric);
return true;
}
iface[0] = '\0';
FF_DEBUG("No IPv4 default route found");
return false;
}
static bool getDefaultRouteIPv6(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/net/ipv6_route", "r");
if (!netRoute) return false;
FF_DEBUG("Starting IPv6 default route detection");
uint32_t prefixLen;
//destination, dest_prefix_len, source, src_prefix_len, next hop, metric, ref counter, use counter, flags, iface
while (fscanf(netRoute, "%*s %x %*s %*s %*s %*s %*s %*s %*s %" FF_STR(IF_NAMESIZE) "s", &prefixLen, iface) == 2)
FF_AUTO_CLOSE_FD int sock_fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
if (sock_fd < 0)
{
if (prefixLen != 0) continue;
*ifIndex = if_nametoindex(iface);
FF_DEBUG("Failed to create netlink socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Created netlink socket: fd=%d", sock_fd);
unsigned pid = (unsigned) getpid();
FF_DEBUG("Process PID: %u", pid);
// Bind socket
struct sockaddr_nl addr = {
.nl_family = AF_NETLINK,
.nl_pid = 0, // Let kernel choose PID
.nl_groups = 0, // No multicast groups
};
if (bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
FF_DEBUG("Failed to bind socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Successfully bound socket");
struct __attribute__((__packed__)) {
struct nlmsghdr nlh;
struct rtmsg rtm;
struct rtattr rta;
uint32_t table;
} req = {
// Netlink message header
.nlh = {
.nlmsg_len = sizeof(req),
.nlmsg_type = RTM_GETROUTE,
.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP,
.nlmsg_seq = 1,
.nlmsg_pid = pid,
},
// Route message
.rtm = {
.rtm_family = AF_INET6, // IPv6 instead of IPv4
.rtm_dst_len = 0, // Match all destinations
.rtm_src_len = 0, // Match all sources
.rtm_tos = 0,
.rtm_table = RT_TABLE_UNSPEC,
.rtm_protocol = RTPROT_UNSPEC,
.rtm_scope = RT_SCOPE_UNIVERSE,
.rtm_type = RTN_UNSPEC,
.rtm_flags = 0,
},
// Route attribute for main table
.rta = {
.rta_len = RTA_LENGTH(sizeof(uint32_t)),
.rta_type = RTA_TABLE,
},
.table = RT_TABLE_MAIN,
};
struct sockaddr_nl dest_addr = {
.nl_family = AF_NETLINK,
.nl_pid = 0, // Kernel
.nl_groups = 0, // No multicast groups
};
ssize_t sent = sendto(sock_fd, &req, sizeof(req), 0,
(struct sockaddr*)&dest_addr, sizeof(dest_addr));
if (sent != sizeof(req)) {
FF_DEBUG("Failed to send netlink request: sent=%zd, expected=%zu", sent, sizeof(req));
return false;
}
FF_DEBUG("Sent netlink request: %zd bytes", sent);
struct sockaddr_nl src_addr = {};
socklen_t src_addr_len = sizeof(src_addr);
uint8_t buffer[1024 * 16]; // 16 KB buffer should be sufficient
ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0,
(struct sockaddr*)&src_addr, &src_addr_len);
if (received < 0) {
FF_DEBUG("Failed to receive netlink response: %s", strerror(errno));
return false;
}
if (received >= (ssize_t)sizeof(buffer)) {
FF_DEBUG("Failed to receive complete message (possible truncation)");
return false;
}
struct {
uint32_t metric;
uint32_t ifindex;
} entry;
uint32_t minMetric = UINT32_MAX;
int routeCount = 0;
for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer;
NLMSG_OK(nlh, received);
nlh = NLMSG_NEXT(nlh, received)) {
if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid)
continue;
if (nlh->nlmsg_type == NLMSG_DONE)
{
FF_DEBUG("Received NLMSG_DONE, processed %d routes", routeCount);
break;
}
if (nlh->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr* err = (struct nlmsgerr*)NLMSG_DATA(nlh);
FF_DEBUG("Netlink reports error: %s", strerror(-err->error));
continue;
}
if (nlh->nlmsg_type != RTM_NEWROUTE)
continue;
routeCount++;
struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh);
if (rtm->rtm_family != AF_INET6)
continue;
if (rtm->rtm_dst_len != 0)
continue;
FF_DEBUG("Processing IPv6 default route candidate #%d", routeCount);
entry = (__typeof__(entry)) { }; // Default to zero metric (no RTA_PRIORITY found)
// Parse route attributes
size_t rtm_len = RTM_PAYLOAD(nlh);
for (struct rtattr* rta = RTM_RTA(rtm);
RTA_OK(rta, rtm_len);
rta = RTA_NEXT(rta, rtm_len))
{
switch (rta->rta_type) {
case RTA_DST:
if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) {
FF_MAYBE_UNUSED char str[INET6_ADDRSTRLEN];
FF_DEBUG("Unexpected RTA_DST: %s", inet_ntop(AF_INET6, RTA_DATA(rta), str, sizeof(str)));
goto next;
}
break;
case RTA_OIF:
if (RTA_PAYLOAD(rta) >= sizeof(uint32_t)) {
entry.ifindex = *(uint32_t*) RTA_DATA(rta);
FF_DEBUG("Found interface index: %u", entry.ifindex);
}
break;
case RTA_GATEWAY:
if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) {
struct in6_addr* gw = (struct in6_addr*) RTA_DATA(rta);
if (IN6_IS_ADDR_UNSPECIFIED(gw)) goto next;
FF_MAYBE_UNUSED char str[INET6_ADDRSTRLEN];
FF_DEBUG("Found gateway: %s", inet_ntop(AF_INET6, gw, str, sizeof(str)));
}
break;
case RTA_PRIORITY:
if (RTA_PAYLOAD(rta) >= sizeof(uint32_t)) {
uint32_t metric = *(uint32_t*) RTA_DATA(rta);
FF_DEBUG("Found metric: %u", metric);
if (metric >= minMetric) goto next;
entry.metric = metric;
}
break;
}
}
if (entry.ifindex == 0 || entry.metric >= minMetric)
{
next:
FF_DEBUG("Skipping route: ifindex=%u, metric=%u", entry.ifindex, entry.metric);
continue;
}
minMetric = entry.metric;
result->ifIndex = entry.ifindex;
FF_DEBUG("Updated best route: ifindex=%u, metric=%u", entry.ifindex, entry.metric);
if (minMetric == 0)
{
FF_DEBUG("Found zero metric route, stopping further processing");
break; // Stop processing if we found a zero metric route
}
}
if (minMetric < UINT32_MAX)
{
if_indextoname(result->ifIndex, result->ifName);
FF_DEBUG("Found default IPv6 route: interface=%s, index=%u, metric=%u", result->ifName, result->ifIndex, minMetric);
return true;
}
iface[0] = '\0';
FF_DEBUG("No IPv6 default route found");
return false;
}
bool ffNetifGetDefaultRouteImpl(char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
{
if (getDefaultRouteIPv4(iface, ifIndex))
return true;
return getDefaultRouteIPv6(iface, ifIndex);
}
+78 -11
View File
@@ -4,29 +4,96 @@
#include <ws2tcpip.h> // AF_INET6, IN6_IS_ADDR_UNSPECIFIED
#include <iphlpapi.h>
bool ffNetifGetDefaultRouteImpl(FF_MAYBE_UNUSED char iface[IF_NAMESIZE + 1], uint32_t* ifIndex)
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL;
DWORD result = GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable);
if (result != NO_ERROR)
if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable)))
return false;
bool foundDefault = false;
uint32_t smallestMetric = UINT32_MAX;
for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i)
{
MIB_IPFORWARD_ROW2* row = &pIpForwardTable->Table[i];
if ((row->DestinationPrefix.PrefixLength == 0) &&
((row->DestinationPrefix.Prefix.Ipv4.sin_family == AF_INET &&
row->DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr == 0) ||
(row->DestinationPrefix.Prefix.Ipv6.sin6_family == AF_INET6 &&
IN6_IS_ADDR_UNSPECIFIED(&row->DestinationPrefix.Prefix.Ipv6.sin6_addr))))
if (row->DestinationPrefix.PrefixLength == 0 &&
row->DestinationPrefix.Prefix.Ipv4.sin_family == AF_INET &&
row->DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr == 0)
{
*ifIndex = row->InterfaceIndex;
foundDefault = true;
break;
MIB_IF_ROW2 ifRow = {
.InterfaceIndex = row->InterfaceIndex,
};
if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) && ifRow.OperStatus == IfOperStatusUp)
{
MIB_IPINTERFACE_ROW ipInterfaceRow = {
.Family = AF_INET,
.InterfaceIndex = row->InterfaceIndex,
};
uint32_t realMetric = row->Metric /* Metric offset */;
if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow)))
realMetric += ipInterfaceRow.Metric /* Interface metric */;
if (realMetric < smallestMetric)
{
smallestMetric = realMetric;
result->ifIndex = row->InterfaceIndex;
foundDefault = true;
break;
}
}
}
}
FreeMibTable(pIpForwardTable);
return foundDefault;
}
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL;
if (!NETIO_SUCCESS(GetIpForwardTable2(AF_UNSPEC, &pIpForwardTable)))
return false;
bool foundDefault = false;
uint32_t smallestMetric = UINT32_MAX;
for (ULONG i = 0; i < pIpForwardTable->NumEntries; ++i)
{
MIB_IPFORWARD_ROW2* row = &pIpForwardTable->Table[i];
if (row->DestinationPrefix.PrefixLength == 0 &&
row->DestinationPrefix.Prefix.Ipv6.sin6_family == AF_INET6 &&
IN6_IS_ADDR_UNSPECIFIED(&row->DestinationPrefix.Prefix.Ipv6.sin6_addr))
{
MIB_IF_ROW2 ifRow = {
.InterfaceIndex = row->InterfaceIndex,
};
if (NETIO_SUCCESS(GetIfEntry2(&ifRow)) && ifRow.OperStatus == IfOperStatusUp)
{
MIB_IPINTERFACE_ROW ipInterfaceRow = {
.Family = AF_INET6,
.InterfaceIndex = row->InterfaceIndex,
};
uint32_t realMetric = row->Metric /* Metric offset */;
if (NETIO_SUCCESS(GetIpInterfaceEntry(&ipInterfaceRow)))
realMetric += ipInterfaceRow.Metric /* Interface metric */;
if (realMetric < smallestMetric)
{
smallestMetric = realMetric;
result->ifIndex = row->InterfaceIndex;
foundDefault = true;
}
}
}
}
+1 -1
View File
@@ -346,7 +346,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
FF_DEBUG("Multithreading mode enabled, creating connection thread");
state->thread = ffThreadCreate(connectAndSendThreadMain, state);
if (state->thread) {
FF_DEBUG("Thread creation successful: thread=%p", (void*)state->thread);
FF_DEBUG("Thread creation successful: thread=%p", (void*)(uintptr_t)state->thread);
return NULL;
}
FF_DEBUG("Thread creation failed");
+2 -49
View File
@@ -28,55 +28,6 @@ const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName)
return subKey;
}
bool ffOptionParseModuleArgs(const char* argumentKey, const char* subKey, const char* value, FFModuleArgs* result)
{
if(ffStrEqualsIgnCase(subKey, "key"))
{
ffOptionParseString(argumentKey, value, &result->key);
return true;
}
else if(ffStrEqualsIgnCase(subKey, "format"))
{
ffOptionParseString(argumentKey, value, &result->outputFormat);
return true;
}
else if(ffStrEqualsIgnCase(subKey, "output-color"))
{
if(value == NULL)
{
fprintf(stderr, "Error: usage: %s <str>\n", argumentKey);
exit(477);
}
ffOptionParseColor(value, &result->outputColor);
return true;
}
else if(ffStrStartsWithIgnCase(subKey, "key-"))
{
const char* subKey2 = subKey + strlen("key-");
if(ffStrEqualsIgnCase(subKey2, "color"))
{
if(value == NULL)
{
fprintf(stderr, "Error: usage: %s <str>\n", argumentKey);
exit(477);
}
ffOptionParseColor(value, &result->keyColor);
return true;
}
else if(ffStrEqualsIgnCase(subKey2, "width"))
{
result->keyWidth = ffOptionParseUInt32(argumentKey, value);
return true;
}
else if(ffStrEqualsIgnCase(subKey2, "icon"))
{
ffOptionParseString(argumentKey, value, &result->keyIcon);
return true;
}
}
return false;
}
void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer)
{
if(value == NULL)
@@ -157,6 +108,8 @@ bool ffOptionParseBoolean(const char* str)
void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer)
{
if (!value || value[0] == '\0') return;
// If value is already an ANSI escape code, use it
if (value[0] == '\e' && value[1] == '[')
{
+4 -2
View File
@@ -29,7 +29,8 @@ typedef struct FFModuleBaseInfo
// This is UB, because `void*` is not compatible with `FF*Options*`.
// However we can't do it better unless we move to C++, so that `option` becomes a `this` pointer
// https://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type
bool (*parseCommandOptions)(void* options, const char* key, const char* value);
void (*initOptions)(void* options);
void (*destroyOptions)(void* options);
void (*parseJsonObject)(void* options, struct yyjson_val *module);
void (*printModule)(void* options);
void (*generateJsonResult)(void* options, struct yyjson_mut_doc* doc, struct yyjson_mut_val* module);
@@ -63,7 +64,6 @@ typedef struct FFKeyValuePair
} FFKeyValuePair;
const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName);
bool ffOptionParseModuleArgs(const char* argumentKey, const char* pkey, const char* value, FFModuleArgs* result);
void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer);
FF_C_NODISCARD uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value);
FF_C_NODISCARD int32_t ffOptionParseInt32(const char* argumentKey, const char* value);
@@ -94,3 +94,5 @@ static inline void ffOptionDestroyModuleArg(FFModuleArgs* args)
ffStrbufDestroy(&args->outputFormat);
ffStrbufDestroy(&args->outputColor);
}
enum { FF_OPTION_MAX_SIZE = 1 << 8 }; // Maximum size of a single option value, used for static allocation
-106
View File
@@ -2,7 +2,6 @@
#include "common/parsing.h"
#include <ctype.h>
#include <inttypes.h>
#ifdef _WIN32
#pragma GCC diagnostic push
@@ -60,56 +59,6 @@ void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty)
ffStrbufAppendF(pretty, ".%u", version->patch);
}
static void parseSize(FFstrbuf* result, uint64_t bytes, uint32_t base, const char** prefixes)
{
double size = (double) bytes;
uint8_t counter = 0;
while(size >= base && counter < instance.config.display.sizeMaxPrefix && prefixes[counter + 1])
{
size /= base;
counter++;
}
if(counter == 0)
ffStrbufAppendF(result, "%" PRIu64 " %s", bytes, prefixes[0]);
else
ffStrbufAppendF(result, "%.*f %s", instance.config.display.sizeNdigits, size, prefixes[counter]);
}
void ffParseSize(uint64_t bytes, FFstrbuf* result)
{
switch (instance.config.display.sizeBinaryPrefix)
{
case FF_SIZE_BINARY_PREFIX_TYPE_IEC:
parseSize(result, bytes, 1024, (const char*[]) {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", NULL});
break;
case FF_SIZE_BINARY_PREFIX_TYPE_SI:
parseSize(result, bytes, 1000, (const char*[]) {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", NULL});
break;
case FF_SIZE_BINARY_PREFIX_TYPE_JEDEC:
parseSize(result, bytes, 1024, (const char*[]) {"B", "KB", "MB", "GB", "TB", NULL});
break;
default:
parseSize(result, bytes, 1024, (const char*[]) {"B", NULL});
break;
}
}
bool ffParseFrequency(uint32_t mhz, FFstrbuf* result)
{
if (mhz == 0)
return false;
int8_t ndigits = instance.config.display.freqNdigits;
if (ndigits >= 0)
ffStrbufAppendF(result, "%.*f GHz", ndigits, mhz / 1000.);
else
ffStrbufAppendF(result, "%u MHz", (unsigned) mhz);
return true;
}
void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, const FFstrbuf* gtk4)
{
if(gtk2->length > 0 && gtk3->length > 0 && gtk4->length > 0)
@@ -190,61 +139,6 @@ void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, co
}
}
void ffParseDuration(uint64_t totalSeconds, FFstrbuf* result)
{
if(totalSeconds < 60)
{
ffStrbufAppendF(result, "%u second", (unsigned) totalSeconds);
if (totalSeconds != 1)
ffStrbufAppendC(result, 's');
return;
}
uint32_t seconds = (uint32_t) (totalSeconds % 60);
totalSeconds /= 60;
if (seconds >= 30)
totalSeconds++;
uint32_t minutes = (uint32_t) (totalSeconds % 60);
totalSeconds /= 60;
uint32_t hours = (uint32_t) (totalSeconds % 24);
totalSeconds /= 24;
uint32_t days = (uint32_t) totalSeconds;
if(days > 0)
{
ffStrbufAppendF(result, "%u day", days);
if(days > 1)
ffStrbufAppendC(result, 's');
if(days >= 100)
ffStrbufAppendS(result, "(!)");
if(hours > 0 || minutes > 0)
ffStrbufAppendS(result, ", ");
}
if(hours > 0)
{
ffStrbufAppendF(result, "%u hour", hours);
if(hours > 1)
ffStrbufAppendC(result, 's');
if(minutes > 0)
ffStrbufAppendS(result, ", ");
}
if(minutes > 0)
{
ffStrbufAppendF(result, "%u min", minutes);
if(minutes > 1)
ffStrbufAppendC(result, 's');
}
}
#ifdef _WIN32
#pragma GCC diagnostic pop
#endif
-4
View File
@@ -24,7 +24,3 @@ void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, co
void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty);
int8_t ffVersionCompare(const FFVersion* version1, const FFVersion* version2);
void ffParseSize(uint64_t bytes, FFstrbuf* result);
bool ffParseFrequency(uint32_t mhz, FFstrbuf* result);
void ffParseDuration(uint64_t totalSeconds, FFstrbuf* result);
+78 -64
View File
@@ -60,23 +60,32 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf
const FFOptionsDisplay* options = &instance.config.display;
uint32_t blocksPercent = (uint32_t) (percent / 100.0 * options->barWidth + 0.5);
const bool borderAsValue = options->barBorderLeftElapsed.length && options->barBorderRightElapsed.length;
uint8_t blocksPercent = (uint8_t) (percent / 100.0 * options->barWidth + 0.5);
assert(blocksPercent <= options->barWidth);
if(options->barBorderLeft.length)
if(!borderAsValue && options->barBorderLeft.length)
{
if(!options->pipe)
ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_WHITE "m");
if(!options->pipe && options->barColorBorder.length > 0)
ffStrbufAppendF(buffer, "\e[%sm", options->barColorBorder.chars);
ffStrbufAppend(buffer, &options->barBorderLeft);
}
if (percent != percent)
if (percent == -DBL_MAX)
{
if(!options->pipe)
// Use total color for simplification
if(!options->pipe && options->barColorTotal.length > 0)
ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_BLACK "m");
for (uint32_t i = 0; i < options->barWidth; ++i)
ffStrbufAppend(buffer, &options->barCharElapsed);
for (uint8_t i = 0; i < options->barWidth; ++i)
{
ffStrbufAppend(buffer, borderAsValue && i == 0
? &options->barBorderLeft
: borderAsValue && i == options->barWidth - 1
? &options->barBorderRight
: &options->barCharTotal);
}
}
else
{
@@ -85,61 +94,72 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf
const char* colorRed = options->percentColorRed.chars;
FFPercentageTypeFlags percentType = config.type == 0 ? options->percentType : config.type;
bool monochrome = !!(percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT);
for (uint32_t i = 0; i < blocksPercent; ++i)
bool autoColorElapsed = ffStrbufIgnCaseEqualS(&options->barColorElapsed, "auto");
bool monochrome = (percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) || !autoColorElapsed;
if (!options->pipe && options->barColorElapsed.length > 0 && monochrome)
{
if(!options->pipe)
const char* color = NULL;
if (!autoColorElapsed)
color = options->barColorElapsed.chars;
else if (green <= yellow)
{
if (monochrome)
{
const char* color = NULL;
if (green <= yellow)
{
if (percent < green) color = colorGreen;
else if (percent < yellow) color = colorYellow;
else color = colorRed;
}
else
{
if (percent < yellow) color = colorRed;
else if (percent < green) color = colorYellow;
else color = colorGreen;
}
ffStrbufAppendF(buffer, "\e[%sm", color);
}
else
{
uint32_t section1Begin = (uint32_t) ((green <= yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
uint32_t section2Begin = (uint32_t) ((green > yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
if (i == section2Begin)
ffStrbufAppendF(buffer, "\e[%sm", (green > yellow ? colorGreen : colorRed));
else if (i == section1Begin)
ffStrbufAppendF(buffer, "\e[%sm", colorYellow);
else if (i == 0)
ffStrbufAppendF(buffer, "\e[%sm", (green <= yellow ? colorGreen : colorRed));
}
if (percent < green) color = colorGreen;
else if (percent < yellow) color = colorYellow;
else color = colorRed;
}
ffStrbufAppend(buffer, &options->barCharElapsed);
else
{
if (percent < yellow) color = colorRed;
else if (percent < green) color = colorYellow;
else color = colorGreen;
}
ffStrbufAppendF(buffer, "\e[%sm", color);
}
for (uint8_t i = 0; i < blocksPercent; ++i)
{
if (!options->pipe && options->barColorElapsed.length > 0 && !monochrome)
{
uint32_t section1Begin = (uint32_t) ((green <= yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
uint32_t section2Begin = (uint32_t) ((green > yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
if (i == section2Begin)
ffStrbufAppendF(buffer, "\e[%sm", (green > yellow ? colorGreen : colorRed));
else if (i == section1Begin)
ffStrbufAppendF(buffer, "\e[%sm", colorYellow);
else if (i == 0)
ffStrbufAppendF(buffer, "\e[%sm", (green <= yellow ? colorGreen : colorRed));
}
ffStrbufAppend(buffer, borderAsValue && i == 0
? &options->barBorderLeftElapsed
: borderAsValue && i == options->barWidth - 1
? &options->barBorderRightElapsed
: &options->barCharElapsed);
}
if (blocksPercent < options->barWidth)
{
if(!options->pipe)
ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_WHITE "m");
for (uint32_t i = blocksPercent; i < options->barWidth; ++i)
ffStrbufAppend(buffer, &options->barCharTotal);
if(!options->pipe && options->barColorTotal.length > 0)
ffStrbufAppendF(buffer, "\e[%sm", options->barColorTotal.chars);
for (uint8_t i = blocksPercent; i < options->barWidth; ++i)
{
ffStrbufAppend(buffer, borderAsValue && i == 0
? &options->barBorderLeft
: borderAsValue && i == options->barWidth - 1
? &options->barBorderRight
: &options->barCharTotal);
}
}
}
if(options->barBorderRight.length)
if(!borderAsValue && options->barBorderRight.length)
{
if(!options->pipe)
ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_WHITE "m");
if(!options->pipe && options->barColorBorder.length > 0)
ffStrbufAppendF(buffer, "\e[%sm", options->barColorBorder.chars);
ffStrbufAppend(buffer, &options->barBorderRight);
}
if(!options->pipe)
if(!options->pipe && (options->barColorElapsed.length > 0 || options->barColorTotal.length > 0 || options->barColorBorder.length > 0))
{
ffStrbufAppendS(buffer, FASTFETCH_TEXT_MODIFIER_RESET);
appendOutputColor(buffer, module);
@@ -165,7 +185,7 @@ void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConf
const char* colorYellow = options->percentColorYellow.chars;
const char* colorRed = options->percentColorRed.chars;
if(percent != percent)
if(percent == -DBL_MAX)
ffStrbufAppendS(buffer, "\e[" FF_COLOR_FG_LIGHT_BLACK "m");
else if(green <= yellow)
{
@@ -175,7 +195,6 @@ void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConf
ffStrbufAppendF(buffer, "\e[%sm", colorYellow);
else
ffStrbufAppendF(buffer, "\e[%sm", colorGreen);
}
else
{
@@ -187,7 +206,8 @@ void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConf
ffStrbufAppendF(buffer, "\e[%sm", colorGreen);
}
}
ffStrbufAppendF(buffer, "%.*f%%", options->percentNdigits, percent);
ffStrbufAppendF(buffer, "%*.*f%s%%", options->percentWidth, options->percentNdigits, percent,
options->percentSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : "");
if (colored && !options->pipe)
{
@@ -239,14 +259,14 @@ bool ffPercentParseCommandOptions(const char* key, const char* subkey, const cha
return false;
}
bool ffPercentParseJsonObject(const char* key, yyjson_val* value, FFPercentageModuleConfig* config)
bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageModuleConfig* config)
{
if (!ffStrEqualsIgnCase(key, "percent"))
if (!unsafe_yyjson_equals_str(key, "percent"))
return false;
if (!yyjson_is_obj(value))
{
fprintf(stderr, "Error: usage: %s must be an object\n", key);
fprintf(stderr, "Error: usage: %s must be an object\n", unsafe_yyjson_get_str(key));
exit(480);
}
@@ -288,16 +308,10 @@ bool ffPercentParseJsonObject(const char* key, yyjson_val* value, FFPercentageMo
return true;
}
void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig defaultConfig, FFPercentageModuleConfig config)
void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig config)
{
if (config.green == defaultConfig.green && config.yellow == defaultConfig.yellow)
return;
yyjson_mut_val* percent = yyjson_mut_obj_add_obj(doc, module, "percent");
if (config.green != defaultConfig.green)
yyjson_mut_obj_add_uint(doc, percent, "green", config.green);
if (config.yellow != defaultConfig.yellow)
yyjson_mut_obj_add_uint(doc, percent, "yellow", config.yellow);
if (config.type != defaultConfig.type)
yyjson_mut_obj_add_uint(doc, percent, "type", config.type);
yyjson_mut_obj_add_uint(doc, percent, "green", config.green);
yyjson_mut_obj_add_uint(doc, percent, "yellow", config.yellow);
yyjson_mut_obj_add_uint(doc, percent, "type", config.type);
}
+3 -3
View File
@@ -11,7 +11,7 @@ typedef enum __attribute__((__packed__)) FFPercentageTypeFlags
FF_PERCENTAGE_TYPE_BAR_BIT = 1 << 1,
FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT = 1 << 2,
FF_PERCENTAGE_TYPE_NUM_COLOR_BIT = 1 << 3,
FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT = FF_PERCENTAGE_TYPE_NUM_COLOR_BIT,
FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT = 1 << 4,
FF_PERCENTAGE_TYPE_FORCE_UNSIGNED_ = UINT8_MAX,
} FFPercentageTypeFlags;
static_assert(sizeof(FFPercentageTypeFlags) == 1, "");
@@ -40,6 +40,6 @@ typedef struct yyjson_val yyjson_val;
typedef struct yyjson_mut_doc yyjson_mut_doc;
typedef struct yyjson_mut_val yyjson_mut_val;
bool ffPercentParseCommandOptions(const char* key, const char* subkey, const char* value, FFPercentageModuleConfig* config);
bool ffPercentParseJsonObject(const char* key, yyjson_val* value, FFPercentageModuleConfig* config);
void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig defaultConfig, FFPercentageModuleConfig config);
bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageModuleConfig* config);
void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig config);
const char* ffPercentParseTypeJsonConfig(yyjson_val* value, FFPercentageTypeFlags* result);
+42 -4
View File
@@ -11,7 +11,10 @@
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#include <spawn.h>
#if !(__ANDROID__ || __OpenBSD__)
#include <spawn.h>
#endif
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <sys/types.h>
@@ -63,11 +66,21 @@ const char* ffProcessAppendOutput(FFstrbuf* buffer, char* const argv[], bool use
if(ffPipe2(pipes, O_CLOEXEC) == -1)
return "pipe() failed";
pid_t childPid = -1;
int nullFile = ffGetNullFD();
#if !(__ANDROID__ || __OpenBSD__)
// NetBSD / Darwin: native syscall
// Linux (glibc): clone3-execve
// FreeBSD: vfork-execve
// illumos: vforkx-execve
// OpenBSD / Android (bionic): fork-execve
posix_spawn_file_actions_t file_actions;
posix_spawn_file_actions_init(&file_actions);
posix_spawn_file_actions_adddup2(&file_actions, pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO);
posix_spawn_file_actions_addopen(&file_actions, useStdErr ? STDOUT_FILENO : STDERR_FILENO, "/dev/null", O_WRONLY, 0);
pid_t childPid = -1;
posix_spawn_file_actions_adddup2(&file_actions, nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO);
static char* oldLang = NULL;
static int langIndex = -1;
@@ -113,13 +126,38 @@ const char* ffProcessAppendOutput(FFstrbuf* buffer, char* const argv[], bool use
posix_spawn_file_actions_destroy(&file_actions);
close(pipes[1]);
if (ret != 0)
{
close(pipes[0]);
close(pipes[1]);
return "posix_spawnp() failed";
}
#else
// https://github.com/termux/termux-packages/issues/25369
childPid = fork();
if(childPid == -1)
{
close(pipes[0]);
close(pipes[1]);
return "fork() failed";
}
if(childPid == 0)
{
//Child
dup2(pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO);
dup2(nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO);
putenv("LANG=C.UTF-8");
execvp(argv[0], argv);
_exit(127);
}
#endif
close(pipes[1]);
int FF_AUTO_CLOSE_FD childPipeFd = pipes[0];
char str[FF_PIPE_BUFSIZ];
+7 -1
View File
@@ -81,7 +81,7 @@ const char* ffProcessAppendOutput(FFstrbuf* buffer, char* const argv[], bool use
if (hChildPipeWrite == INVALID_HANDLE_VALUE)
return "CreateFileW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed";
PROCESS_INFORMATION piProcInfo = {0};
PROCESS_INFORMATION piProcInfo = {};
BOOL success;
@@ -91,9 +91,15 @@ const char* ffProcessAppendOutput(FFstrbuf* buffer, char* const argv[], bool use
.dwFlags = STARTF_USESTDHANDLES,
};
if (useStdErr)
{
siStartInfo.hStdOutput = ffGetNullFD();
siStartInfo.hStdError = hChildPipeWrite;
}
else
{
siStartInfo.hStdOutput = hChildPipeWrite;
siStartInfo.hStdError = ffGetNullFD();
}
FF_STRBUF_AUTO_DESTROY cmdline = ffStrbufCreate();
argvToCmdline(argv, &cmdline);
+42
View File
@@ -0,0 +1,42 @@
#include "size.h"
#include <inttypes.h>
static void appendNum(FFstrbuf* result, uint64_t bytes, uint32_t base, const char** prefixes)
{
const FFOptionsDisplay* options = &instance.config.display;
double size = (double) bytes;
uint8_t counter = 0;
while(size >= base && counter < options->sizeMaxPrefix && prefixes[counter + 1])
{
size /= base;
counter++;
}
const char* space = options->sizeSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " ";
if(counter == 0)
ffStrbufAppendF(result, "%" PRIu64 "%s%s", bytes, space, prefixes[0]);
else
ffStrbufAppendF(result, "%.*f%s%s", options->sizeNdigits, size, space, prefixes[counter]);
}
void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result)
{
const FFOptionsDisplay* options = &instance.config.display;
switch (options->sizeBinaryPrefix)
{
case FF_SIZE_BINARY_PREFIX_TYPE_IEC:
appendNum(result, bytes, 1024, (const char*[]) {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", NULL});
break;
case FF_SIZE_BINARY_PREFIX_TYPE_SI:
appendNum(result, bytes, 1000, (const char*[]) {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", NULL});
break;
case FF_SIZE_BINARY_PREFIX_TYPE_JEDEC:
appendNum(result, bytes, 1024, (const char*[]) {"B", "KB", "MB", "GB", "TB", NULL});
break;
default:
appendNum(result, bytes, 1024, (const char*[]) {"B", NULL});
break;
}
}
+3
View File
@@ -0,0 +1,3 @@
#include "fastfetch.h"
void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result);
+15 -21
View File
@@ -5,7 +5,7 @@
void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig config, const FFModuleArgs* module)
{
if (celsius != celsius) // ignores NaN
if (celsius == -DBL_MAX) // ignores invalid value
return;
const FFOptionsDisplay* options = &instance.config.display;
@@ -41,13 +41,16 @@ void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig confi
{
case FF_TEMPERATURE_UNIT_DEFAULT:
case FF_TEMPERATURE_UNIT_CELSIUS:
ffStrbufAppendF(buffer, "%.*f°C", options->tempNdigits, celsius);
ffStrbufAppendF(buffer, "%.*f%s°C", options->tempNdigits, celsius,
options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : "");
break;
case FF_TEMPERATURE_UNIT_FAHRENHEIT:
ffStrbufAppendF(buffer, "%.*f°F", options->tempNdigits, celsius * 1.8 + 32);
ffStrbufAppendF(buffer, "%.*f%s°F", options->tempNdigits, celsius * 1.8 + 32,
options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_ALWAYS ? " " : "");
break;
case FF_TEMPERATURE_UNIT_KELVIN:
ffStrbufAppendF(buffer, "%.*f K", options->tempNdigits, celsius + 273.15);
ffStrbufAppendF(buffer, "%.*f%sK", options->tempNdigits, celsius + 273.15,
options->tempSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " ");
break;
}
@@ -104,9 +107,9 @@ bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char*
return false;
}
bool ffTempsParseJsonObject(const char* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config)
bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config)
{
if (!ffStrEqualsIgnCase(key, "temp"))
if (!unsafe_yyjson_equals_str(key, "temp"))
return false;
if (yyjson_is_bool(value))
@@ -123,7 +126,7 @@ bool ffTempsParseJsonObject(const char* key, yyjson_val* value, bool* useTemp, F
if (!yyjson_is_obj(value))
{
fprintf(stderr, "Error: usage: %s must be an object or a boolean\n", key);
fprintf(stderr, "Error: usage: %s must be an object or a boolean\n", unsafe_yyjson_get_str(key));
exit(480);
}
@@ -156,23 +159,14 @@ bool ffTempsParseJsonObject(const char* key, yyjson_val* value, bool* useTemp, F
return true;
}
void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FF_MAYBE_UNUSED bool defaultTemp, FFColorRangeConfig defaultConfig, bool temp, FFColorRangeConfig config)
void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, bool temp, FFColorRangeConfig config)
{
assert(defaultTemp == false); // assume defaultTemp is always false
if (!temp)
return;
if (config.green != defaultConfig.green || config.yellow != defaultConfig.yellow)
{
yyjson_mut_val* temp = yyjson_mut_obj_add_obj(doc, module, "temp");
if (config.green != defaultConfig.green)
yyjson_mut_obj_add_uint(doc, temp, "green", config.green);
if (config.yellow != defaultConfig.yellow)
yyjson_mut_obj_add_uint(doc, temp, "yellow", config.yellow);
}
yyjson_mut_obj_add_bool(doc, module, "temp", false);
else
{
yyjson_mut_obj_add_bool(doc, module, "temp", true);
yyjson_mut_val* temp = yyjson_mut_obj_add_obj(doc, module, "temp");
yyjson_mut_obj_add_uint(doc, temp, "green", config.green);
yyjson_mut_obj_add_uint(doc, temp, "yellow", config.yellow);
}
}
+2 -2
View File
@@ -5,5 +5,5 @@
void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig config, const FFModuleArgs* module);
bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char* value, bool* useTemp, FFColorRangeConfig* config);
bool ffTempsParseJsonObject(const char* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config);
void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FF_MAYBE_UNUSED bool defaultTemp, FFColorRangeConfig defaultConfig, bool temp, FFColorRangeConfig config);
bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config);
void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, bool temp, FFColorRangeConfig config);
+126 -887
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -1,8 +1,9 @@
#pragma once
#include "fastfetch.h"
#include "modules/battery/option.h"
#define FF_BATTERY_TEMP_UNSET (0/0.0)
#define FF_BATTERY_TEMP_UNSET (-DBL_MAX)
typedef struct FFBatteryResult
{
@@ -15,7 +16,7 @@ typedef struct FFBatteryResult
double capacity;
double temperature;
uint32_t cycleCount;
int32_t timeRemaining;
int32_t timeRemaining; // in seconds, -1 if unknown
} FFBatteryResult;
const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results);
+4 -3
View File
@@ -96,6 +96,7 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results)
battery->temperature = FF_BATTERY_TEMP_UNSET;
battery->cycleCount = 0;
battery->timeRemaining = -1;
battery->capacity = 0;
ffStrbufInit(&battery->manufacturer);
ffStrbufInit(&battery->modelName);
ffStrbufInit(&battery->status);
@@ -124,11 +125,11 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results)
{
double level = 0, scale = 0;
if (ffParsePropLines(start, "level: ", &temp))
level = ffStrbufToDouble(&temp);
level = ffStrbufToDouble(&temp, -DBL_MAX);
ffStrbufClear(&temp);
if (ffParsePropLines(start, "scale: ", &temp))
scale = ffStrbufToDouble(&temp);
scale = ffStrbufToDouble(&temp, -DBL_MAX);
ffStrbufClear(&temp);
if (level > 0 && scale > 0)
@@ -138,7 +139,7 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results)
if(options->temp)
{
if (ffParsePropLines(start, "temperature: ", &temp))
battery->temperature = ffStrbufToDouble(&temp);
battery->temperature = ffStrbufToDouble(&temp, FF_BATTERY_TEMP_UNSET);
ffStrbufClear(&temp);
}
+6 -2
View File
@@ -45,7 +45,7 @@ static void parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFl
return;
FFBatteryResult* result = ffListAdd(results);
result->capacity = ffStrbufToDouble(&tmpBuffer);
result->capacity = ffStrbufToDouble(&tmpBuffer, 0);
//At this point, we have a battery. Try to get as much values as possible.
@@ -154,7 +154,11 @@ static void parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFl
if (options->temp)
{
if (ffReadFileBufferRelative(dfd, "temp", &tmpBuffer))
result->temperature = ffStrbufToDouble(&tmpBuffer) / 10;
{
result->temperature = ffStrbufToDouble(&tmpBuffer, FF_BATTERY_TEMP_UNSET);
if (result->temperature != FF_BATTERY_TEMP_UNSET)
result->temperature /= 10;
}
}
}
+1 -1
View File
@@ -103,7 +103,7 @@ static const char* detectWithCmApi(FFBatteryOptions* options, FFlist* results)
battery->cycleCount = bi.CycleCount;
battery->temperature = 0.0/0.0;
battery->temperature = FF_BATTERY_TEMP_UNSET;
if(options->temp)
{
bqi.InformationLevel = BatteryTemperature;
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/bios/option.h"
typedef struct FFBiosResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/bluetooth/option.h"
typedef struct FFBluetoothResult
{
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/bluetoothradio/option.h"
typedef struct FFBluetoothRadioResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/board/option.h"
typedef struct FFBoardResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/bootmgr/option.h"
typedef struct FFBootmgrResult
{
+1 -1
View File
@@ -1,7 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "util/FFlist.h"
#include "modules/brightness/option.h"
typedef struct FFBrightnessResult
{
+2 -2
View File
@@ -32,7 +32,7 @@ static const char* detectWithBacklight(FFlist* result)
ffStrbufAppendS(&backlightDir, "/brightness");
if(ffReadFileBuffer(backlightDir.chars, &buffer))
{
double actualBrightness = ffStrbufToDouble(&buffer);
double actualBrightness = ffStrbufToDouble(&buffer, 0);
ffStrbufSubstrBefore(&backlightDir, backlightDirLength);
ffStrbufAppendS(&backlightDir, entry->d_name);
ffStrbufAppendS(&backlightDir, "/max_brightness");
@@ -71,7 +71,7 @@ static const char* detectWithBacklight(FFlist* result)
}
else
ffStrbufInitS(&brightness->name, entry->d_name);
brightness->max = ffStrbufToDouble(&buffer);
brightness->max = ffStrbufToDouble(&buffer, 0);
brightness->min = 0;
brightness->current = actualBrightness;
brightness->builtin = true;
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/btrfs/option.h"
typedef struct FFBtrfsDiskUsage
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/camera/option.h"
typedef struct FFCameraResult
{
+1 -1
View File
@@ -45,7 +45,7 @@ const char* ffDetectCamera(FF_MAYBE_UNUSED FFlist* result)
ffStrbufInitStatic(&camera->name, "Unknown");
}
ffStrbufInit(&camera->vendor);
ffStrbufInitS(&camera->id, yyjson_get_str(yyjson_obj_get(device, "id")));
ffStrbufInitJsonVal(&camera->id, yyjson_obj_get(device, "id"));
yyjson_val* sizes = yyjson_arr_get_first(yyjson_obj_get(device, "jpeg_output_sizes"));
if (yyjson_is_obj(sizes))
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/chassis/option.h"
typedef struct FFChassisResult
{
+2 -1
View File
@@ -1,8 +1,9 @@
#pragma once
#include "fastfetch.h"
#include "modules/cpu/option.h"
#define FF_CPU_TEMP_UNSET (0/0.0)
#define FF_CPU_TEMP_UNSET (-DBL_MAX)
typedef struct FFCPUCore
{
+74 -81
View File
@@ -28,19 +28,19 @@ static double parseHwmonDir(FFstrbuf* dir, FFstrbuf* buffer)
ffStrbufAppendS(dir, "temp1_input");
if(!ffReadFileBuffer(dir->chars, buffer))
return 0.0/0.0;
return FF_CPU_TEMP_UNSET;
}
ffStrbufSubstrBefore(dir, dirLength);
double value = ffStrbufToDouble(buffer);// millidegree Celsius
double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET);// millidegree Celsius
if(value != value)
return 0.0/0.0;
if(value == FF_CPU_TEMP_UNSET)
return FF_CPU_TEMP_UNSET;
ffStrbufAppendS(dir, "name");
if (!ffReadFileBuffer(dir->chars, buffer))
return 0.0/0.0;
return FF_CPU_TEMP_UNSET;
ffStrbufTrimRightSpace(buffer);
@@ -51,14 +51,17 @@ static double parseHwmonDir(FFstrbuf* dir, FFstrbuf* buffer)
ffStrbufEqualS(buffer, "coretemp") // Intel
) return value / 1000.;
return 0.0/0.0;
return FF_CPU_TEMP_UNSET;
}
static double detectTZTemp(FFstrbuf* buffer)
{
if (ffReadFileBuffer("/sys/class/thermal/thermal_zone0/temp", buffer))
return ffStrbufToDouble(buffer) / 1000.;
return 0.0/0.0;
{
double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET);// millidegree Celsius
return value != FF_CPU_TEMP_UNSET ? value / 1000. : FF_CPU_TEMP_UNSET;
}
return FF_CPU_TEMP_UNSET;
}
static double detectCPUTemp(void)
@@ -72,7 +75,7 @@ static double detectCPUTemp(void)
FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir.chars);
if(dirp == NULL)
return 0.0/0.0;
return FF_CPU_TEMP_UNSET;
struct dirent* entry;
while((entry = readdir(dirp)) != NULL)
@@ -84,7 +87,7 @@ static double detectCPUTemp(void)
ffStrbufAppendC(&baseDir, '/');
double result = parseHwmonDir(&baseDir, &buffer);
if (result == result)
if (result != FF_CPU_TEMP_UNSET)
return result;
ffStrbufSubstrBefore(&baseDir, baseDirLength);
@@ -100,85 +103,75 @@ static void detectQualcomm(FFCPUResult* cpu)
{
// https://en.wikipedia.org/wiki/List_of_Qualcomm_Snapdragon_systems_on_chips
if (ffStrbufEqualS(&cpu->name, "SM8750-AC"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Elite for Galaxy [SM8750-AC]");
else if (ffStrbufEqualS(&cpu->name, "SM8750-3"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Elite [SM8750-3]");
else if (ffStrbufEqualS(&cpu->name, "SM8750"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Elite [SM8750]");
else if (ffStrbufEqualS(&cpu->name, "SM8635"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8s Gen 3 [SM8635]");
else if (ffStrbufEqualS(&cpu->name, "SM8650-AC"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Gen 3 for Galaxy [SM8650-AC]");
else if (ffStrbufEqualS(&cpu->name, "SM8650"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Gen 3 [SM8650]");
else if (ffStrbufEqualS(&cpu->name, "SM8550-AC"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Gen 2 for Galaxy [SM8550-AC]");
else if (ffStrbufEqualS(&cpu->name, "SM8550"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Gen 2 [SM8550]");
else if (ffStrbufEqualS(&cpu->name, "SM8475"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8+ Gen 1 [SM8475]");
else if (ffStrbufEqualS(&cpu->name, "SM8450"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 8 Gen 1 [SM8450]");
uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, NULL, 10);
const char* name = NULL;
else if (ffStrbufEqualS(&cpu->name, "SM7675"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 7+ Gen 3 [SM7675]");
else if (ffStrbufEqualS(&cpu->name, "SM7635"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 7s Gen 3 [SM7635]");
else if (ffStrbufEqualS(&cpu->name, "SM7550"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 7 Gen 3 [SM7550]");
else if (ffStrbufEqualS(&cpu->name, "SM7475"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 7+ Gen 2 [SM7550]");
else if (ffStrbufEqualS(&cpu->name, "SM7435"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 7s Gen 2 [SM7435]");
else if (ffStrbufEqualS(&cpu->name, "SM7450"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 7 Gen 1 [SM7450]");
switch (code)
{
case 8735: name = "8s Gen 4"; break;
case 8750: name = "8 Elite"; break;
case 8635: name = "8s Gen 3"; break;
case 8650: name = "8 Gen 3"; break;
case 8550: name = "8 Gen 2"; break;
case 8475: name = "8+ Gen 1"; break;
case 8450: name = "8 Gen 1"; break;
case 7750: name = "7 Gen 4"; break;
case 7675: name = "7+ Gen 3"; break;
case 7635: name = "7s Gen 3"; break;
case 7550: name = "7 Gen 3"; break;
case 7475: name = "7+ Gen 2"; break;
case 7435: name = "7s Gen 2"; break;
case 7450: name = "7 Gen 1"; break;
case 6650: name = "6 Gen 4"; break;
case 6375: name = "6s Gen 3"; break;
case 6475: name = "6 Gen 3"; break;
case 6115: name = "6s Gen 1"; break;
case 6450: name = "6 Gen 1"; break;
case 4635: name = "4s Gen 2"; break;
case 4450: name = "4 Gen 2"; break;
case 4375: name = "4 Gen 1"; break;
}
else if (ffStrbufEqualS(&cpu->name, "SM6375-AC"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 6s Gen 3 [SM6375-AC]");
else if (ffStrbufEqualS(&cpu->name, "SM6475"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 6 Gen 3 [SM6475]");
else if (ffStrbufEqualS(&cpu->name, "SM6115"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 6s Gen 1 [SM6115]");
else if (ffStrbufEqualS(&cpu->name, "SM6450"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 6 Gen 1 [SM6450]");
else if (ffStrbufEqualS(&cpu->name, "SM4635"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 4s Gen 2 [SM4635]");
else if (ffStrbufEqualS(&cpu->name, "SM4450"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 4 Gen 2 [SM4450]");
else if (ffStrbufEqualS(&cpu->name, "SM4375"))
ffStrbufSetStatic(&cpu->name, "Qualcomm Snapdragon 4 Gen 1 [SM4375]");
if (name)
{
char str[32];
ffStrCopy(str, cpu->name.chars, sizeof(str));
ffStrbufSetF(&cpu->name, "Qualcomm Snapdragon %s [%s]", name, str);
return;
}
}
static void detectMediaTek(FFCPUResult* cpu)
{
// https://en.wikipedia.org/wiki/List_of_MediaTek_systems_on_chips
if (ffStrbufEqualS(&cpu->name, "MT6991"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9400 [MT6991]");
else if (ffStrbufEqualS(&cpu->name, "MT6991Z"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9400 [MT6991Z]");
else if (ffStrbufEqualS(&cpu->name, "MT6989Z"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9300+ [MT6989Z]");
else if (ffStrbufEqualS(&cpu->name, "MT8796Z"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9300+ [MT8796Z]");
else if (ffStrbufEqualS(&cpu->name, "MT6989"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9300 [MT6989]");
else if (ffStrbufEqualS(&cpu->name, "MT8796"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9300 [MT8796]");
else if (ffStrbufEqualS(&cpu->name, "MT6985W"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9200+ [MT6985W]");
else if (ffStrbufEqualS(&cpu->name, "MT6985"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9200 [MT6985]");
else if (ffStrbufEqualS(&cpu->name, "MT6983W"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9000+ [MT6983W]");
else if (ffStrbufEqualS(&cpu->name, "MT8798Z/T"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9000+ [MT8798Z/T]");
else if (ffStrbufEqualS(&cpu->name, "MT6983Z"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9000 [MT6983Z]");
else if (ffStrbufEqualS(&cpu->name, "MT8798Z/C"))
ffStrbufSetStatic(&cpu->name, "MediaTek Dimensity 9000 [MT8798Z/C]");
uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, NULL, 10);
const char* name = NULL;
switch (code) // The SOC code of MTK Dimensity series is full of mess
{
case 6991: name = "9400"; break;
case 6989:
case 8796: name = "9300"; break;
case 6985: name = "9200"; break;
case 6983:
case 8798: name = "9000"; break;
case 6899: name = "8400"; break;
case 6897:
case 8792: name = "8300"; break;
case 6896: name = "8200"; break;
case 8795: name = "8100"; break;
case 6895: name = "8000"; break;
}
if (name)
{
char str[32];
ffStrCopy(str, cpu->name.chars, sizeof(str));
ffStrbufSetF(&cpu->name, "MediaTek Dimensity %s [%s]", name, str);
return;
}
}
static void detectAndroid(FFCPUResult* cpu)
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/cpucache/option.h"
typedef enum __attribute__((__packed__)) FFCPUCacheType
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/cpuusage/option.h"
typedef struct FFCpuUsageInfo {
uint64_t inUseAll;
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/cursor/option.h"
typedef struct FFCursorResult
{
+23 -12
View File
@@ -2,19 +2,30 @@
#import <Foundation/Foundation.h>
static void appendColor(FFstrbuf* str, NSDictionary* color)
static void appendColor(FFstrbuf* str, NSDictionary* dict)
{
int r = (int) (((NSNumber*) color[@"red"]).doubleValue * 255);
int g = (int) (((NSNumber*) color[@"green"]).doubleValue * 255);
int b = (int) (((NSNumber*) color[@"blue"]).doubleValue * 255);
int a = (int) (((NSNumber*) color[@"alpha"]).doubleValue * 255);
uint32_t r = (uint32_t) (((NSNumber*) dict[@"red"]).doubleValue * 255 + .5);
uint32_t g = (uint32_t) (((NSNumber*) dict[@"green"]).doubleValue * 255 + .5);
uint32_t b = (uint32_t) (((NSNumber*) dict[@"blue"]).doubleValue * 255 + .5);
uint32_t a = (uint32_t) (((NSNumber*) dict[@"alpha"]).doubleValue * 255 + .5);
uint32_t color = (r << 24) | (g << 16) | (b << 8) | a;
if (r == 255 && g == 255 && b == 255 && a == 255)
ffStrbufAppendS(str, "White");
else if (r == 0 && g == 0 && b == 0 && a == 255)
ffStrbufAppendS(str, "Black");
else
ffStrbufAppendF(str, "#%02X%02X%02X%02X", r, g, b, a);
switch (color)
{
case 0x000000FF: ffStrbufAppendS(str, "Black"); return;
case 0x0433FFFF: ffStrbufAppendS(str, "Blue"); return;
case 0xAA7942FF: ffStrbufAppendS(str, "Brown"); return;
case 0x00FDFFFF: ffStrbufAppendS(str, "Cyan"); return;
case 0x00F900FF: ffStrbufAppendS(str, "Green"); return;
case 0xFF40FFFF: ffStrbufAppendS(str, "Magenta"); return;
case 0xFF9300FF: ffStrbufAppendS(str, "Orange"); return;
case 0x942192FF: ffStrbufAppendS(str, "Purple"); return;
case 0xFF2600FF: ffStrbufAppendS(str, "Red"); return;
case 0xFFFB00FF: ffStrbufAppendS(str, "Yellow"); return;
case 0xFFFFFFFF: ffStrbufAppendS(str, "White"); return;
case 0x00000000: ffStrbufAppendS(str, "Transparent"); return;
default: ffStrbufAppendF(str, "#%08X", color); return;
}
}
void ffDetectCursor(FFCursorResult* result)
@@ -46,7 +57,7 @@ void ffDetectCursor(FFCursorResult* result)
NSNumber* mouseDriverCursorSize = dict[@"mouseDriverCursorSize"];
if (mouseDriverCursorSize)
ffStrbufAppendF(&result->size, "%d", (int) (mouseDriverCursorSize.doubleValue * 32));
ffStrbufAppendF(&result->size, "%d", (int) (mouseDriverCursorSize.doubleValue * 32 + 0.5));
else
ffStrbufAppendS(&result->size, "32");
}
+1
View File
@@ -1,5 +1,6 @@
#pragma once
#include "fastfetch.h"
#include "modules/de/option.h"
const char* ffDetectDEVersion(const FFstrbuf* deName, FFstrbuf* result, FFDEOptions* options);
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/disk/option.h"
typedef struct FFDisk
{
+3
View File
@@ -55,6 +55,9 @@ static bool isPhysicalDevice(const struct mntent* device)
ffStrStartsWith(device->mnt_fsname + 5, "fd") //Ignore fd devices
) return false;
if (ffStrStartsWith(device->mnt_dir, "/bedrock/")) // Ignore Bedrock Linux subvolumes
return false;
struct stat deviceStat;
if(stat(device->mnt_fsname, &deviceStat) != 0)
return false;
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/diskio/option.h"
typedef struct FFDiskIOResult
{
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/display/option.h"
#define FF_DE_PRETTY_PLASMA "KDE Plasma"
#define FF_DE_PRETTY_GNOME "GNOME"
+27 -1
View File
@@ -6,6 +6,7 @@
#include "common/time.h"
#include "util/edidHelper.h"
#include "util/mallocHelper.h"
#include "util/stringUtils.h"
#include <stdlib.h>
#include <string.h>
@@ -24,6 +25,9 @@ typedef struct XcbPropertyData
FF_LIBRARY_SYMBOL(xcb_get_atom_name_name)
FF_LIBRARY_SYMBOL(xcb_get_atom_name_name_length)
FF_LIBRARY_SYMBOL(xcb_get_atom_name_reply)
FF_LIBRARY_SYMBOL(xcb_get_setup)
FF_LIBRARY_SYMBOL(xcb_setup_vendor)
FF_LIBRARY_SYMBOL(xcb_setup_vendor_length)
} XcbPropertyData;
static bool xcbInitPropertyData(FF_MAYBE_UNUSED void* libraryHandle, XcbPropertyData* propertyData)
@@ -38,6 +42,9 @@ static bool xcbInitPropertyData(FF_MAYBE_UNUSED void* libraryHandle, XcbProperty
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, xcb_get_atom_name_name, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, xcb_get_atom_name_name_length, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, xcb_get_atom_name_reply, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, xcb_get_setup, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, xcb_setup_vendor, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, xcb_setup_vendor_length, false)
return true;
}
@@ -86,6 +93,23 @@ static void xcbDetectWMfromEWMH(XcbPropertyData* data, xcb_connection_t* connect
ffStrbufSetS(&result->wmProcessName, wmName);
}
static void xcbFetchServerVendor(XcbPropertyData* data, xcb_connection_t* connection, FFDisplayServerResult* result)
{
const xcb_setup_t* setup = data->ffxcb_get_setup(connection);
int length = data->ffxcb_setup_vendor_length(setup);
if(length <= 0)
return;
FF_STRBUF_AUTO_DESTROY serverVendor = ffStrbufCreateNS((uint32_t) length, data->ffxcb_setup_vendor(setup));
if (!ffStrbufEqualS(&serverVendor, "The X.Org Foundation")) // Original
{
ffStrbufDestroy(&result->wmProtocolName);
ffStrbufInitMove(&result->wmProtocolName, &serverVendor);
}
}
typedef struct XcbRandrData
{
FF_LIBRARY_SYMBOL(xcb_randr_get_screen_resources_current)
@@ -381,8 +405,10 @@ const char* ffdsConnectXcbRandr(FFDisplayServerResult* result)
xcb_screen_iterator_t iterator = ffxcb_setup_roots_iterator(ffxcb_get_setup(data.connection));
if(iterator.rem > 0 && propertyDataInitialized)
if(iterator.rem > 0 && propertyDataInitialized) {
xcbDetectWMfromEWMH(&data.propData, data.connection, iterator.data->root, result);
xcbFetchServerVendor(&data.propData, data.connection, result);
}
while(iterator.rem > 0)
+15 -1
View File
@@ -14,6 +14,7 @@ typedef struct X11PropertyData
{
FF_LIBRARY_SYMBOL(XInternAtom)
FF_LIBRARY_SYMBOL(XGetWindowProperty)
FF_LIBRARY_SYMBOL(XServerVendor)
FF_LIBRARY_SYMBOL(XFree)
} X11PropertyData;
@@ -21,6 +22,7 @@ static bool x11InitPropertyData(FF_MAYBE_UNUSED void* libraryHandle, X11Property
{
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, XInternAtom, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, XGetWindowProperty, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, XServerVendor, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(libraryHandle, propertyData, XFree, false)
return true;
@@ -62,6 +64,16 @@ static void x11DetectWMFromEWMH(X11PropertyData* data, Display* display, FFDispl
data->ffXFree(wmWindow);
}
static void x11FetchServerVendor(X11PropertyData* data, Display* display, FFDisplayServerResult* result)
{
const char* serverVendor = data->ffXServerVendor(display);
if (serverVendor && !ffStrEquals(serverVendor, "The X.Org Foundation")) {
ffStrbufSetS(&result->wmProtocolName, serverVendor);
}
}
typedef struct XrandrData
{
FF_LIBRARY_SYMBOL(XInternAtom)
@@ -305,8 +317,10 @@ const char* ffdsConnectXrandr(FFDisplayServerResult* result)
if(data.display == NULL)
return "XOpenDisplay() failed";
if(propertyDataInitialized && ScreenCount(data.display) > 0)
if(propertyDataInitialized && ScreenCount(data.display) > 0) {
x11DetectWMFromEWMH(&propertyData, data.display, result);
x11FetchServerVendor(&propertyData, data.display, result);
}
data.result = result;
+1
View File
@@ -1,5 +1,6 @@
#pragma once
#include "fastfetch.h"
#include "modules/dns/option.h"
const char* ffDetectDNS(FFDNSOptions* options, FFlist* results /* list of FFstrbuf */);
+1 -1
View File
@@ -37,7 +37,7 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results)
return "GetAdaptersAddresses() failed";
}
uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteIfIndex();
uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex;
// Iterate through all of the adapters
for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next)
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/editor/option.h"
typedef struct FFEditorResult
{
+2 -1
View File
@@ -1,8 +1,9 @@
#pragma once
#include "fastfetch.h"
#include "modules/font/option.h"
#define FF_DETECT_FONT_NUM_FONTS 4
enum { FF_DETECT_FONT_NUM_FONTS = 4 };
typedef struct FFFontResult
{
+5 -1
View File
@@ -2,6 +2,7 @@
#include "detection/vulkan/vulkan.h"
#include "detection/opencl/opencl.h"
#include "detection/opengl/opengl.h"
#include "modules/opengl/opengl.h"
const char* FF_GPU_VENDOR_NAME_APPLE = "Apple";
const char* FF_GPU_VENDOR_NAME_AMD = "AMD";
@@ -56,7 +57,10 @@ const char* detectByOpenGL(FFlist* gpus)
ffStrbufInit(&result.slv);
ffStrbufInit(&result.library);
const char* error = ffDetectOpenGL(&instance.config.modules.openGL, &result);
__attribute__((__cleanup__(ffDestroyOpenGLOptions))) FFOpenGLOptions options;
ffInitOpenGLOptions(&options);
const char* error = ffDetectOpenGL(&options, &result);
if (!error)
{
FFGPUResult* gpu = (FFGPUResult*) ffListAdd(gpus);
+4 -2
View File
@@ -1,12 +1,13 @@
#pragma once
#include "fastfetch.h"
#include "modules/gpu/option.h"
#define FF_GPU_TEMP_UNSET (0/0.0)
#define FF_GPU_TEMP_UNSET (-DBL_MAX)
#define FF_GPU_CORE_COUNT_UNSET -1
#define FF_GPU_VMEM_SIZE_UNSET ((uint64_t)-1)
#define FF_GPU_FREQUENCY_UNSET 0
#define FF_GPU_CORE_USAGE_UNSET (0/0.0)
#define FF_GPU_CORE_USAGE_UNSET (-DBL_MAX)
#define FF_GPU_INDEX_UNSET ((uint32_t)-1)
extern const char* FF_GPU_VENDOR_NAME_APPLE;
@@ -67,6 +68,7 @@ const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, con
const char* ffDrmDetectI915(FFGPUResult* gpu, int fd);
const char* ffDrmDetectXe(FFGPUResult* gpu, int fd);
const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd);
const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd);
#endif // FF_HAVE_DRM
const char* ffGPUDetectDriverSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFGpuDriverPciBusId pciBusId);
+1 -3
View File
@@ -1,6 +1,4 @@
#include "gpu.h"
#include "common/library.h"
#include "detection/cpu/cpu.h"
#include "util/apple/cf_helpers.h"
#include "util/apple/smc_temps.h"
@@ -109,7 +107,7 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus)
gpu->type = FF_GPU_TYPE_UNKNOWN;
gpu->frequency = FF_GPU_FREQUENCY_UNSET;
IORegistryEntryGetRegistryEntryID(registryEntry, &gpu->deviceId);
ffStrbufInitStatic(&gpu->platformApi, "Metal");
ffStrbufInitStatic(&gpu->platformApi, "IOKit");
ffStrbufInit(&gpu->driver); // Ok for both Apple and Intel
ffCfDictGetString(properties, CFSTR("CFBundleIdentifier"), &gpu->driver);
+3
View File
@@ -60,10 +60,13 @@ const char* ffGpuDetectMetal(FFlist* gpus)
else if ([device supportsFeatureSet:MTLFeatureSet_macOS_GPUFamily1_v1])
ffStrbufSetStatic(&gpu->platformApi, "Metal Feature Set 1");
#else // MAC_OS_X_VERSION_10_15
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
if ([device supportsFamily:MTLGPUFamilyMetal4])
ffStrbufSetStatic(&gpu->platformApi, "Metal 4");
else if ([device supportsFamily:MTLGPUFamilyMetal3])
ffStrbufSetStatic(&gpu->platformApi, "Metal 3");
#pragma clang diagnostic pop
else if ([device supportsFamily:MTLGPUFamilyCommon3])
ffStrbufSetStatic(&gpu->platformApi, "Metal Common 3");
else if ([device supportsFamily:MTLGPUFamilyCommon2])
+6 -1
View File
@@ -106,7 +106,10 @@ static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus)
.name_len = ARRAY_SIZE(driverName),
};
if (ioctl(fd, DRM_IOCTL_VERSION, &ver) == 0)
ffStrbufSetF(&gpu->driver, "%*s %d.%d.%d", (int) ver.name_len, ver.name, ver.version_major, ver.version_minor, ver.version_patchlevel);
{
driverName[ver.name_len] = '\0';
ffStrbufSetF(&gpu->driver, "%s %d.%d.%d", ver.name, ver.version_major, ver.version_minor, ver.version_patchlevel);
}
if (ffStrStartsWith(driverName, "i915"))
ffDrmDetectI915(gpu, fd);
@@ -118,6 +121,8 @@ static const char* detectByDrm(const FFGPUOptions* options, FFlist* gpus)
ffDrmDetectXe(gpu, fd);
else if (ffStrStartsWith(driverName, "asahi"))
ffDrmDetectAsahi(gpu, fd);
else if (ffStrStartsWith(driverName, "nouveau"))
ffDrmDetectNouveau(gpu, fd);
else if (dev->bustype == DRM_BUS_PCI)
{
ffGPUDetectDriverSpecific(options, gpu, (FFGpuDriverPciBusId) {
+24
View File
@@ -13,6 +13,7 @@
#include "intel_drm.h"
#include "asahi_drm.h"
#include <radeon_drm.h>
#include <nouveau_drm.h>
const char* ffDrmDetectRadeon(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath)
{
@@ -343,6 +344,29 @@ const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd)
return "Failed to query Asahi GPU information";
}
#ifndef DRM_IOCTL_NOUVEAU_GETPARAM
#define DRM_IOCTL_NOUVEAU_GETPARAM DRM_IOWR(DRM_COMMAND_BASE + DRM_NOUVEAU_GETPARAM, struct drm_nouveau_getparam)
#endif
const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd)
{
struct drm_nouveau_getparam getparam = { };
getparam.param = NOUVEAU_GETPARAM_FB_SIZE;
if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0)
gpu->dedicated.total = getparam.value;
getparam.param = NOUVEAU_GETPARAM_AGP_SIZE;
if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0)
gpu->shared.total = getparam.value;
getparam.param = NOUVEAU_GETPARAM_GRAPH_UNITS;
if (ioctl(fd, DRM_IOCTL_NOUVEAU_GETPARAM, &getparam) == 0 && getparam.value < INT32_MAX)
gpu->coreCount = (int32_t) getparam.value;
return NULL;
}
#endif // FF_HAVE_DRM
#include "gpu_driver_specific.h"
+11 -10
View File
@@ -10,7 +10,7 @@ struct FFIgclData {
FF_LIBRARY_SYMBOL(ctlEnumerateDevices)
FF_LIBRARY_SYMBOL(ctlGetDeviceProperties)
FF_LIBRARY_SYMBOL(ctlEnumTemperatureSensors)
FF_LIBRARY_SYMBOL(ctlTemperatureGetState)
FF_LIBRARY_SYMBOL(ctlTemperatureGetProperties)
FF_LIBRARY_SYMBOL(ctlEnumMemoryModules)
FF_LIBRARY_SYMBOL(ctlMemoryGetProperties)
FF_LIBRARY_SYMBOL(ctlMemoryGetState)
@@ -41,7 +41,7 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlEnumerateDevices)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlGetDeviceProperties)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlEnumTemperatureSensors)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlTemperatureGetState)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlTemperatureGetProperties)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlEnumMemoryModules)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlMemoryGetProperties)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libigcl, igclData, ctlMemoryGetState)
@@ -204,19 +204,20 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe
uint32_t sensorCount = ARRAY_SIZE(sensors);
if (igclData.ffctlEnumTemperatureSensors(device, &sensorCount, sensors) == CTL_RESULT_SUCCESS && sensorCount > 0)
{
double sumValue = 0;
uint32_t availableCount = 0;
for (uint32_t iSensor = 0; iSensor < sensorCount; iSensor++)
{
double value;
if (igclData.ffctlTemperatureGetState(sensors[iSensor], &value) == CTL_RESULT_SUCCESS)
ctl_temp_properties_t props = { .Size = sizeof(props) };
// The official sample code does not set Version
// https://github.com/intel/drivers.gpu.control-library/blob/1bbacbf3814f2fd0d2b930cdf42fad83f3628db9/Samples/Telemetry_Samples/Sample_TelemetryAPP.cpp#L256
if (igclData.ffctlTemperatureGetProperties(sensors[iSensor], &props) == CTL_RESULT_SUCCESS)
{
sumValue += value;
availableCount++;
if (props.type == CTL_TEMP_SENSORS_GPU)
{
*result.temp = props.maxTemperature;
break;
}
}
}
if (availableCount > 0)
*result.temp = sumValue / availableCount;
}
}
+49
View File
@@ -263,6 +263,49 @@ static const char* drmDetectIntelSpecific(FFGPUResult* gpu, const char* drmKey,
#endif
}
static const char* pciDetectNouveauSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFstrbuf* pciDir, FFstrbuf* buffer)
{
if (options->temp)
{
const uint32_t pciDirLen = pciDir->length;
ffStrbufAppendS(pciDir, "/hwmon/");
FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDir->chars);
if (dirp)
{
struct dirent* entry;
while ((entry = readdir(dirp)))
{
if (entry->d_name[0] == '.') continue;
ffStrbufAppendS(pciDir, entry->d_name);
ffStrbufAppendS(pciDir, "/temp1_input");
if (ffReadFileBuffer(pciDir->chars, buffer))
{
uint64_t value = ffStrbufToUInt(buffer, 0);
if (value > 0) gpu->temperature = (double) value / 1000.0;
}
break;
}
}
ffStrbufSubstrBefore(pciDir, pciDirLen);
}
return NULL;
}
static const char* drmDetectNouveauSpecific(FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer)
{
#if FF_HAVE_DRM
ffStrbufSetS(buffer, "/dev/dri/");
ffStrbufAppendS(buffer, drmKey);
FF_AUTO_CLOSE_FD int fd = open(buffer->chars, O_RDONLY | O_CLOEXEC);
if (fd < 0) return "Failed to open drm device";
return ffDrmDetectNouveau(gpu, fd);
#else
FF_UNUSED(gpu, drmKey, buffer);
return "Fastfetch is not compiled with drm support";
#endif
}
static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf* buffer, FFstrbuf* deviceDir, const char* drmKey)
{
const uint32_t drmDirPathLength = deviceDir->length;
@@ -369,6 +412,12 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf
if (options->driverSpecific && drmKey)
drmDetectIntelSpecific(gpu, drmKey, buffer);
}
else if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_NVIDIA && ffStrbufEqualS(&gpu->driver, "nouveau"))
{
pciDetectNouveauSpecific(options, gpu, deviceDir, buffer);
if (options->driverSpecific && drmKey)
drmDetectNouveauSpecific(gpu, drmKey, buffer);
}
else
{
ffGPUDetectDriverSpecific(options, gpu, (FFGpuDriverPciBusId) {
+194 -32
View File
@@ -4,13 +4,11 @@
#include "util/windows/unicode.h"
#include "util/windows/registry.h"
#include "util/mallocHelper.h"
#define INITGUID
#include <cfgmgr32.h>
#include <ntddvdeo.h>
#include <devpkey.h>
#include "util/debug.h"
#include "util/windows/nt.h"
#include <cfgmgr32.h>
#define FF_EMPTY_GUID_STR L"{00000000-0000-0000-0000-000000000000}"
enum { FF_GUID_STRLEN = sizeof(FF_EMPTY_GUID_STR) / sizeof(wchar_t) - 1 };
@@ -19,35 +17,55 @@ const uint32_t regDirectxKeyPrefixLength = (uint32_t) __builtin_strlen("SOFTWARE
wchar_t regDriverKey[] = L"SYSTEM\\CurrentControlSet\\Control\\Class\\" FF_EMPTY_GUID_STR L"\\0000";
const uint32_t regDriverKeyPrefixLength = (uint32_t) __builtin_strlen("SYSTEM\\CurrentControlSet\\Control\\Class\\");
#define GUID_DEVCLASS_DISPLAY_STRING L"{4d36e968-e325-11ce-bfc1-08002be10318}" // Found in <devguid.h>
const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist* gpus)
{
ULONG devInfListSize = 0;
if (CM_Get_Device_Interface_List_SizeW(&devInfListSize, (LPGUID)&GUID_DEVINTERFACE_DISPLAY_ADAPTER, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT) != CR_SUCCESS || devInfListSize <= 1)
return "No display devices found";
FF_DEBUG("Starting GPU detection");
FF_AUTO_FREE DEVINSTID_W devInfList = malloc(devInfListSize * sizeof(*devInfList));
if (CM_Get_Device_Interface_ListW((LPGUID)&GUID_DEVINTERFACE_DISPLAY_ADAPTER, NULL, devInfList, devInfListSize, CM_GET_DEVICE_INTERFACE_LIST_PRESENT) != CR_SUCCESS)
return "CM_Get_Device_Interface_ListW failed";
for (wchar_t* devInf = devInfList; *devInf; devInf += wcslen(devInf) + 1)
ULONG devIdListSize = 0;
if (CM_Get_Device_ID_List_SizeW(&devIdListSize, GUID_DEVCLASS_DISPLAY_STRING, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) != CR_SUCCESS || devIdListSize <= 1)
{
if (wcsncmp(devInf, L"\\\\?\\ROOT#BasicDisplay#", 22) == 0)
continue; // Skip Microsoft Basic Display Adapter
FF_DEBUG("No display devices found, list size: %lu", devIdListSize);
return "No display devices found";
}
FF_DEBUG("Found device ID list size: %lu", devIdListSize);
FF_AUTO_FREE DEVINSTID_W devIdList = malloc(devIdListSize * sizeof(*devIdList));
if (CM_Get_Device_ID_ListW(GUID_DEVCLASS_DISPLAY_STRING, devIdList, devIdListSize, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) != CR_SUCCESS)
{
FF_DEBUG("CM_Get_Device_ID_ListW failed");
return "CM_Get_Device_ID_ListW failed";
}
int deviceCount = 0;
for (wchar_t* devId = devIdList; *devId; devId += wcslen(devId) + 1)
{
FF_DEBUG("Processing device ID: %ls", devId);
if (wcsncmp(devId, L"SWD\\", 4) == 0)
{
FF_DEBUG("Skipping SWD device interface to avoid duplicates");
continue;
}
DEVINST devInst = 0;
wchar_t buffer[256];
ULONG bufferLen = 0;
{
DEVPROPTYPE propertyType;
bufferLen = sizeof(buffer);
if (CM_Get_Device_Interface_PropertyW(devInf, &DEVPKEY_Device_InstanceId, &propertyType, (PBYTE) buffer, &bufferLen, 0) != CR_SUCCESS ||
CM_Locate_DevNodeW(&devInst, buffer, CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS)
if (CM_Locate_DevNodeW(&devInst, devId, CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS)
{
FF_DEBUG("Failed to get device instance ID or locate device node");
continue;
}
FF_DEBUG("Device instance ID: %lu", devInst);
}
FFGPUResult* gpu = (FFGPUResult*)ffListAdd(gpus);
deviceCount++;
FF_DEBUG("Added GPU #%d to list", deviceCount);
ffStrbufInit(&gpu->vendor);
ffStrbufInit(&gpu->name);
ffStrbufInit(&gpu->driver);
@@ -63,8 +81,15 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
gpu->frequency = FF_GPU_FREQUENCY_UNSET;
unsigned vendorId = 0, deviceId = 0, subSystemId = 0, revId = 0;
if (swscanf(buffer, L"PCI\\VEN_%x&DEV_%x&SUBSYS_%x&REV_%x", &vendorId, &deviceId, &subSystemId, &revId) == 4)
if (swscanf(devId, L"PCI\\VEN_%x&DEV_%x&SUBSYS_%x&REV_%x", &vendorId, &deviceId, &subSystemId, &revId) == 4)
{
FF_DEBUG("Parsed PCI IDs - Vendor: 0x%x, Device: 0x%x, SubSystem: 0x%x, Rev: 0x%x", vendorId, deviceId, subSystemId, revId);
ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(vendorId));
}
else
{
FF_DEBUG("Failed to parse PCI device information from instance ID");
}
uint32_t pciBus = 0, pciAddr = 0, pciDev = 0, pciFunc = 0;
@@ -78,53 +103,87 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
pciFunc = pciAddr & 0xFFFF;
gpu->deviceId = (pciBus * 1000ull) + (pciDev * 10ull) + pciFunc;
pciAddr = 1; // Set to 1 to indicate that the device is a PCI device
FF_DEBUG("PCI location - Bus: %u, Device: %u, Function: %u, DeviceID: %llu", pciBus, pciDev, pciFunc, gpu->deviceId);
}
else
{
FF_DEBUG("Failed to get PCI address");
}
}
else
{
FF_DEBUG("Failed to get PCI bus number");
}
uint64_t adapterLuid = 0;
FF_HKEY_AUTO_DESTROY hVideoIdKey = NULL;
wchar_t buffer[256];
ULONG bufferLen = 0;
if (CM_Open_DevNode_Key(devInst, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hVideoIdKey, CM_REGISTRY_HARDWARE) == CR_SUCCESS)
{
FF_DEBUG("Opened device node registry key");
bufferLen = sizeof(buffer);
if (RegGetValueW(hVideoIdKey, NULL, L"VideoID", RRF_RT_REG_SZ, NULL, buffer, &bufferLen) == ERROR_SUCCESS &&
bufferLen == (FF_GUID_STRLEN + 1) * sizeof(wchar_t))
{
FF_DEBUG("Found VideoID: %ls", buffer);
wmemcpy(regDirectxKey + regDirectxKeyPrefixLength, buffer, FF_GUID_STRLEN);
FF_HKEY_AUTO_DESTROY hDirectxKey = NULL;
if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regDirectxKey, &hDirectxKey, NULL))
{
FF_DEBUG("Opened DirectX registry key");
if (gpu->vendor.length == 0)
{
uint32_t vendorId = 0;
if(ffRegReadUint(hDirectxKey, L"VendorId", &vendorId, NULL) && vendorId)
{
FF_DEBUG("Found vendor ID from DirectX registry: 0x%x", vendorId);
ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(vendorId));
}
}
ffRegReadStrbuf(hDirectxKey, L"Description", &gpu->name, NULL);
if (ffRegReadStrbuf(hDirectxKey, L"Description", &gpu->name, NULL))
FF_DEBUG("Found GPU description: %s", gpu->name.chars);
if (ffRegReadUint64(hDirectxKey, L"DedicatedVideoMemory", &gpu->dedicated.total, NULL))
FF_DEBUG("Found dedicated video memory: %llu bytes", gpu->dedicated.total);
ffRegReadUint64(hDirectxKey, L"DedicatedVideoMemory", &gpu->dedicated.total, NULL);
if (ffRegReadUint64(hDirectxKey, L"DedicatedSystemMemory", &gpu->shared.total, NULL))
{
FF_DEBUG("Found dedicated system memory: %llu bytes", gpu->shared.total);
uint64_t sharedSystemMemory = 0;
if (ffRegReadUint64(hDirectxKey, L"SharedSystemMemory", &sharedSystemMemory, NULL))
{
gpu->shared.total += sharedSystemMemory;
FF_DEBUG("Added shared system memory: %llu bytes, total shared: %llu bytes", sharedSystemMemory, gpu->shared.total);
}
}
if (ffRegReadUint64(hDirectxKey, L"AdapterLuid", &adapterLuid, NULL))
{
FF_DEBUG("Found adapter LUID: %llu", adapterLuid);
if (!gpu->deviceId) gpu->deviceId = adapterLuid;
}
uint32_t featureLevel = 0;
if(ffRegReadUint(hDirectxKey, L"MaxD3D12FeatureLevel", &featureLevel, NULL) && featureLevel)
{
FF_DEBUG("Found D3D12 feature level: 0x%x", featureLevel);
ffStrbufSetF(&gpu->platformApi, "Direct3D 12.%u", (featureLevel & 0x0F00) >> 8);
}
else if(ffRegReadUint(hDirectxKey, L"MaxD3D11FeatureLevel", &featureLevel, NULL) && featureLevel)
{
FF_DEBUG("Found D3D11 feature level: 0x%x", featureLevel);
ffStrbufSetF(&gpu->platformApi, "Direct3D 11.%u", (featureLevel & 0x0F00) >> 8);
}
uint64_t driverVersion = 0;
if(ffRegReadUint64(hDirectxKey, L"DriverVersion", &driverVersion, NULL) && driverVersion)
{
FF_DEBUG("Found driver version: %llu", driverVersion);
ffStrbufSetF(&gpu->driver, "%u.%u.%u.%u",
(unsigned) (driverVersion >> 48) & 0xFFFF,
(unsigned) (driverVersion >> 32) & 0xFFFF,
@@ -133,21 +192,38 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
);
}
}
else
{
FF_DEBUG("Failed to open DirectX registry key");
}
}
else
{
FF_DEBUG("Failed to get VideoID or invalid buffer length");
}
}
else
{
FF_DEBUG("Failed to open device node registry key");
}
if (gpu->vendor.length == 0 || gpu->name.length == 0)
{
FF_DEBUG("Trying fallback registry method for vendor/name");
bufferLen = sizeof(buffer);
if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_DRIVER, NULL, buffer, &bufferLen, 0) == CR_SUCCESS &&
bufferLen == (FF_GUID_STRLEN + strlen("\\0000") + 1) * 2)
{
FF_DEBUG("Found driver GUID: %ls", buffer);
wmemcpy(regDriverKey + regDriverKeyPrefixLength, buffer, FF_GUID_STRLEN + strlen("\\0000"));
FF_HKEY_AUTO_DESTROY hRegDriverKey = NULL;
if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regDriverKey, &hRegDriverKey, NULL))
{
FF_DEBUG("Opened driver registry key");
if (gpu->vendor.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"ProviderName", &gpu->vendor, NULL))
{
FF_DEBUG("Found provider name: %s", gpu->vendor.chars);
if (ffStrbufContainS(&gpu->vendor, "Intel"))
ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_INTEL);
else if (ffStrbufContainS(&gpu->vendor, "NVIDIA"))
@@ -155,20 +231,35 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
else if (ffStrbufContainS(&gpu->vendor, "AMD") || ffStrbufContainS(&gpu->vendor, "ATI"))
ffStrbufSetStatic(&gpu->vendor, FF_GPU_VENDOR_NAME_AMD);
}
if (gpu->name.length == 0)
ffRegReadStrbuf(hRegDriverKey, L"DriverDesc", &gpu->name, NULL);
if (gpu->driver.length == 0)
ffRegReadStrbuf(hRegDriverKey, L"DriverVersion", &gpu->driver, NULL);
if (gpu->name.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"DriverDesc", &gpu->name, NULL))
FF_DEBUG("Found driver description: %s", gpu->name.chars);
if (gpu->driver.length == 0 && ffRegReadStrbuf(hRegDriverKey, L"DriverVersion", &gpu->driver, NULL))
FF_DEBUG("Found driver version: %s", gpu->driver.chars);
if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET)
{
if (!ffRegReadUint64(hRegDriverKey, L"HardwareInformation.qwMemorySize", &gpu->dedicated.total, NULL))
{
uint32_t memorySize = 0;
if (ffRegReadUint(hRegDriverKey, L"HardwareInformation.MemorySize", &memorySize, NULL))
{
gpu->dedicated.total = memorySize;
FF_DEBUG("Found memory size from hardware info: %u bytes", memorySize);
}
}
else
{
FF_DEBUG("Found qwMemorySize from hardware info: %llu bytes", gpu->dedicated.total);
}
}
}
else
{
FF_DEBUG("Failed to open driver registry key");
}
}
else
{
FF_DEBUG("Failed to get driver GUID or invalid buffer length");
}
}
@@ -177,6 +268,7 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
if (options->driverSpecific && getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &dllName))
{
FF_DEBUG("Calling driver-specific detection function for vendor: %s, DLL: %s", gpu->vendor.chars, dllName);
detectFn(
&(FFGpuDriverCondition) {
.type = (deviceId > 0 ? FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID : 0)
@@ -210,17 +302,31 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
},
dllName
);
FF_DEBUG("Driver-specific detection completed");
}
else if (options->driverSpecific)
{
FF_DEBUG("No driver-specific detection function found for vendor: %s", gpu->vendor.chars);
}
if (!gpu->name.length)
{
FF_DEBUG("Trying to get device description as fallback");
bufferLen = sizeof(buffer);
if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_DEVICEDESC, NULL, buffer, &bufferLen, 0) == CR_SUCCESS)
{
ffStrbufSetWS(&gpu->name, buffer);
FF_DEBUG("Found device description: %s", gpu->name.chars);
}
else
{
FF_DEBUG("Failed to get device description");
}
}
if (gpu->type == FF_GPU_TYPE_UNKNOWN && adapterLuid > 0)
{
FF_DEBUG("Trying to determine GPU type using D3DKMT APIs");
HMODULE hgdi32 = GetModuleHandleW(L"gdi32.dll");
if (hgdi32)
{
@@ -230,6 +336,8 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
D3DKMT_OPENADAPTERFROMLUID openAdapterFromLuid = { .AdapterLuid = *(LUID*)&adapterLuid };
if (NT_SUCCESS(ffD3DKMTOpenAdapterFromLuid(&openAdapterFromLuid)))
{
FF_DEBUG("Successfully opened adapter from LUID");
D3DKMT_ADAPTERTYPE adapterType = {};
D3DKMT_QUERYADAPTERINFO queryAdapterInfo = {
.hAdapter = openAdapterFromLuid.hAdapter,
@@ -239,14 +347,20 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
};
if (NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo))) // Vista and later
{
FF_DEBUG("Queried adapter type - HybridDiscrete: %d, HybridIntegrated: %d", adapterType.HybridDiscrete, adapterType.HybridIntegrated);
if (adapterType.HybridDiscrete)
gpu->type = FF_GPU_TYPE_DISCRETE;
else if (adapterType.HybridIntegrated)
gpu->type = FF_GPU_TYPE_INTEGRATED;
}
else
{
FF_DEBUG("Failed to query adapter type");
}
if (gpu->frequency == FF_GPU_FREQUENCY_UNSET)
{
FF_DEBUG("Trying to get GPU frequency information");
for (ULONG nodeIdx = 0; ; nodeIdx++)
{
D3DKMT_NODEMETADATA nodeMetadata = {
@@ -258,8 +372,16 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
.pPrivateDriverData = &nodeMetadata,
.PrivateDriverDataSize = sizeof(nodeMetadata),
};
if (!NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo))) break; // Windows 10 and later
if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) continue;
if (!NT_SUCCESS(D3DKMTQueryAdapterInfo(&queryAdapterInfo)))
{
FF_DEBUG("No more nodes to query (index %lu)", nodeIdx);
break; // Windows 10 and later
}
if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D)
{
FF_DEBUG("Skipping node %lu (not 3D engine)", nodeIdx);
continue;
}
D3DKMT_QUERYSTATISTICS queryStatistics = {
.Type = D3DKMT_QUERYSTATISTICS_NODE2,
@@ -269,18 +391,29 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics))) // Windows 11 (22H2) and later
{
gpu->frequency = (uint32_t) (queryStatistics.QueryResult.NodeInformation.NodePerfData.MaxFrequency / 1000 / 1000);
FF_DEBUG("Found GPU frequency: %u MHz", gpu->frequency);
break;
}
else
{
FF_DEBUG("Failed to query node statistics for node %lu", nodeIdx);
}
}
}
D3DKMT_CLOSEADAPTER closeAdapter = { .hAdapter = openAdapterFromLuid.hAdapter };
(void) D3DKMTCloseAdapter(&closeAdapter);
openAdapterFromLuid.hAdapter = 0;
FF_DEBUG("Closed adapter handle");
}
else
{
FF_DEBUG("Failed to open adapter from LUID");
}
if (options->temp && gpu->temperature != gpu->temperature)
if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET)
{
FF_DEBUG("Trying to get GPU temperature");
D3DKMT_QUERYSTATISTICS queryStatistics = {
.Type = D3DKMT_QUERYSTATISTICS_PHYSICAL_ADAPTER,
.AdapterLuid = *(LUID*)&adapterLuid,
@@ -288,20 +421,49 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
};
if (NT_SUCCESS(D3DKMTQueryStatistics(&queryStatistics)) &&
queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature != 0)
{
gpu->temperature = queryStatistics.QueryResult.PhysAdapterInformation.AdapterPerfData.Temperature / 10.0;
FF_DEBUG("Found GPU temperature: %.1f°C", gpu->temperature);
}
else
{
FF_DEBUG("Failed to get GPU temperature or temperature is 0");
}
}
}
else
{
FF_DEBUG("D3DKMTOpenAdapterFromLuid not available");
}
}
else
{
FF_DEBUG("Failed to get gdi32.dll module handle");
}
}
if (gpu->type == FF_GPU_TYPE_UNKNOWN)
{
FF_DEBUG("Using fallback GPU type detection");
if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_INTEL)
{
gpu->type = gpu->deviceId == 20 ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE;
FF_DEBUG("Intel GPU type determined: %s", gpu->type == FF_GPU_TYPE_INTEGRATED ? "Integrated" : "Discrete");
}
else if (gpu->dedicated.total != FF_GPU_VMEM_SIZE_UNSET)
{
gpu->type = gpu->dedicated.total >= 1024 * 1024 * 1024 ? FF_GPU_TYPE_DISCRETE : FF_GPU_TYPE_INTEGRATED;
FF_DEBUG("GPU type determined by memory size (%llu bytes): %s", gpu->dedicated.total, gpu->type == FF_GPU_TYPE_DISCRETE ? "Discrete" : "Integrated");
}
else
{
FF_DEBUG("Unable to determine GPU type");
}
}
FF_DEBUG("Completed processing GPU #%d - Vendor: %s, Name: %s, Type: %d", deviceCount, gpu->vendor.chars, gpu->name.chars, gpu->type);
}
FF_DEBUG("GPU detection completed, found %d devices", deviceCount);
return NULL;
}
+22 -2
View File
@@ -120,8 +120,28 @@ typedef struct ctl_temp_handle_t* ctl_temp_handle_t;
// https://intel.github.io/drivers.gpu.control-library/Control/api.html#ctlenumtemperaturesensors
extern ctl_result_t ctlEnumTemperatureSensors(ctl_device_adapter_handle_t hDAhandle, uint32_t* pCount, ctl_temp_handle_t* phTemperature);
// https://intel.github.io/drivers.gpu.control-library/Control/api.html#ctltemperaturegetstate
extern ctl_result_t ctlTemperatureGetState(ctl_temp_handle_t hTemperature, double* pTemperature);
// https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv427ctlTemperatureGetProperties17ctl_temp_handle_tP21ctl_temp_properties_t
typedef enum ctl_temp_sensors_t
{
CTL_TEMP_SENSORS_GLOBAL = 0,
CTL_TEMP_SENSORS_GPU = 1,
CTL_TEMP_SENSORS_MEMORY = 2,
CTL_TEMP_SENSORS_GLOBAL_MIN = 3,
CTL_TEMP_SENSORS_GPU_MIN = 4,
CTL_TEMP_SENSORS_MEMORY_MIN = 5,
CTL_TEMP_SENSORS_MAX
} ctl_temp_sensors_t;
typedef struct _ctl_temp_properties_t
{
uint32_t Size;
uint8_t Version;
ctl_temp_sensors_t type;
double maxTemperature;
} ctl_temp_properties_t;
extern ctl_result_t ctlTemperatureGetProperties(ctl_temp_handle_t hTemperature, ctl_temp_properties_t* pTemperature);
// https://intel.github.io/drivers.gpu.control-library/Control/api.html#_CPPv420ctlEnumMemoryModules27ctl_device_adapter_handle_tP8uint32_tP16ctl_mem_handle_t
typedef struct ctl_mem_handle_t* ctl_mem_handle_t;
+36 -6
View File
@@ -140,18 +140,45 @@ static void detectQtCt(char qver, FFQtResult* result)
// by the same author and qt6ct understands qt5ct in qt6 applications as well.
char file[] = "qtXct/qtXct.conf";
file[2] = file[8] = qver;
FF_STRBUF_AUTO_DESTROY font = ffStrbufCreate();
ffParsePropFileConfigValues(file, 3, (FFpropquery[]) {
{"style=", &result->widgetStyle},
{"icon_theme=", &result->icons},
{"general=", &result->font}
{"general=", &font}
});
if (ffStrbufStartsWithC(&result->font, '@'))
if (ffStrbufStartsWithC(&font, '@'))
{
// See QVariant notes on https://doc.qt.io/qt-5/qsettings.html and
// https://github.com/fastfetch-cli/fastfetch/issues/1053#issuecomment-2197254769
// Thankfully, newer versions use the more common font encoding.
ffStrbufSetNS(&result->font, 5, file);
ffStrbufSetNS(&font, 5, file);
}
else if (qver == '5')
{
// #1864
const char *p = font.chars;
while (*p)
{
if (p[0] == '\\' && p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3]) && isxdigit(p[4]) && isxdigit(p[5]))
{
uint32_t codepoint = (uint32_t)strtoul((char[]) { p[2], p[3], p[4], p[5], '\0' }, NULL, 16);
ffStrbufAppendUtf32CodePoint(&result->font, codepoint);
p += 6;
}
else
{
ffStrbufAppendC(&result->font, *p++);
}
}
}
else
{
ffStrbufDestroy(&result->font);
ffStrbufInitMove(&result->font, &font);
}
}
@@ -178,14 +205,17 @@ const FFQtResult* ffDetectQt(void)
ffStrbufInit(&result.wallpaper);
const FFDisplayServerResult* wmde = ffConnectDisplayServer();
const char *qplatformtheme = getenv("QT_QPA_PLATFORMTHEME");
if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_PLASMA))
detectPlasma(&result);
else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_LXQT))
detectLXQt(&result);
else if(ffStrSet(qplatformtheme) && (ffStrEquals(qplatformtheme, "qt5ct") || ffStrEquals(qplatformtheme, "qt6ct")))
detectQtCt(qplatformtheme[2], &result);
else
{
const char *qPlatformTheme = getenv("QT_QPA_PLATFORMTHEME");
if(qPlatformTheme && (ffStrEquals(qPlatformTheme, "qt5ct") || ffStrEquals(qPlatformTheme, "qt6ct")))
detectQtCt(qPlatformTheme[2], &result);
}
if(ffStrbufEqualS(&result.widgetStyle, "kvantum") || ffStrbufEqualS(&result.widgetStyle, "kvantum-dark"))
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/host/option.h"
typedef struct FFHostResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/icons/option.h"
typedef struct FFIconsResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/initsystem/option.h"
typedef struct FFInitSystemResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/lm/option.h"
typedef struct FFLMResult
{
+4 -3
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/localip/option.h"
typedef struct FFLocalIpResult
{
@@ -10,8 +11,8 @@ typedef struct FFLocalIpResult
FFstrbuf mac;
FFstrbuf flags;
int32_t mtu;
int32_t speed;
bool defaultRoute;
int32_t speed; // in Mbps
FFLocalIpType defaultRoute;
} FFLocalIpResult;
typedef struct FFLocalIpNIFlag
@@ -20,7 +21,7 @@ typedef struct FFLocalIpNIFlag
const char *name;
} FFLocalIpNIFlag;
static inline void ffLocalIpFillNIFlags(FFstrbuf *buf, uint32_t flag, const FFLocalIpNIFlag names[])
static inline void ffLocalIpFillNIFlags(FFstrbuf *buf, uint64_t flag, const FFLocalIpNIFlag names[])
{
for (const FFLocalIpNIFlag *nf = names; flag && nf->name; ++nf)
{
+535 -137
View File
@@ -2,6 +2,7 @@
#include "common/io/io.h"
#include "common/netif/netif.h"
#include "util/stringUtils.h"
#include "util/debug.h"
#include <string.h>
#include <ctype.h>
@@ -11,11 +12,18 @@
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <inttypes.h>
#include <fcntl.h>
#ifdef __linux__
#include <linux/ethtool.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <linux/if_addr.h>
#endif
#if __has_include(<netinet6/in6_var.h>)
#include <netinet6/in6_var.h>
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__NetBSD__) || defined(__HAIKU__)
@@ -27,212 +35,550 @@
#if defined(__sun) || defined(__HAIKU__)
#include <sys/sockio.h>
#endif
#if defined(__sun)
#include <kstat.h>
static inline void kstatFreeWrap(kstat_ctl_t** pkc)
{
assert(pkc);
if (*pkc)
kstat_close(*pkc);
}
#endif
#define FF_LOCALIP_NIFLAG(name) { IFF_##name, #name }
static const FFLocalIpNIFlag niFlagOptions[] = {
{ IFF_UP, "UP" },
{ IFF_BROADCAST, "BROADCAST" },
FF_LOCALIP_NIFLAG(UP),
FF_LOCALIP_NIFLAG(BROADCAST),
#ifdef IFF_DEBUG
{ IFF_DEBUG, "DEBUG" },
FF_LOCALIP_NIFLAG(DEBUG),
#endif
{ IFF_LOOPBACK, "LOOPBACK" },
{ IFF_POINTOPOINT, "POINTOPOINT" },
FF_LOCALIP_NIFLAG(LOOPBACK),
FF_LOCALIP_NIFLAG(POINTOPOINT),
#ifdef IFF_RUNNING
{ IFF_RUNNING, "RUNNING" },
FF_LOCALIP_NIFLAG(RUNNING),
#endif
{ IFF_NOARP, "NOARP" },
{ IFF_PROMISC, "PROMISC" },
{ IFF_ALLMULTI, "ALLMULTI" },
{ IFF_MULTICAST, "MULTICAST" },
FF_LOCALIP_NIFLAG(NOARP),
FF_LOCALIP_NIFLAG(PROMISC),
FF_LOCALIP_NIFLAG(ALLMULTI),
#ifdef IFF_INTELLIGENT
FF_LOCALIP_NIFLAG(INTELLIGENT),
#endif
FF_LOCALIP_NIFLAG(MULTICAST),
#ifdef IFF_NOTRAILERS
{ IFF_NOTRAILERS, "NOTRAILERS" },
FF_LOCALIP_NIFLAG(NOTRAILERS),
#endif
#ifdef __linux__
{ IFF_MASTER, "MASTER" },
{ IFF_SLAVE, "SLAVE" },
{ IFF_PORTSEL, "PORTSEL" },
{ IFF_AUTOMEDIA, "AUTOMEDIA" },
{ IFF_DYNAMIC, "DYNAMIC" },
{ IFF_LOWER_UP, "LOWER_UP" },
{ IFF_DORMANT, "DORMANT" },
{ IFF_ECHO, "ECHO" },
FF_LOCALIP_NIFLAG(MASTER),
FF_LOCALIP_NIFLAG(SLAVE),
FF_LOCALIP_NIFLAG(PORTSEL),
FF_LOCALIP_NIFLAG(AUTOMEDIA),
FF_LOCALIP_NIFLAG(DYNAMIC),
FF_LOCALIP_NIFLAG(LOWER_UP),
FF_LOCALIP_NIFLAG(DORMANT),
FF_LOCALIP_NIFLAG(ECHO),
#endif
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__)
{ IFF_OACTIVE, "OACTIVE" },
{ IFF_SIMPLEX, "SIMPLEX" },
{ IFF_LINK0, "LINK0" },
{ IFF_LINK1, "LINK1" },
{ IFF_LINK2, "LINK2" },
FF_LOCALIP_NIFLAG(OACTIVE),
FF_LOCALIP_NIFLAG(SIMPLEX),
FF_LOCALIP_NIFLAG(LINK0),
FF_LOCALIP_NIFLAG(LINK1),
FF_LOCALIP_NIFLAG(LINK2),
#endif
#ifdef IFF_ALTPHYS
{ IFF_ALTPHYS, "ALTPHYS" },
FF_LOCALIP_NIFLAG(ALTPHYS),
#endif
#ifdef IFF_CANTCONFIG
{ IFF_CANTCONFIG, "CANTCONFIG" },
FF_LOCALIP_NIFLAG(CANTCONFIG),
#endif
#ifdef __HAIKU__
{ IFF_AUTOUP, "IAUTOUP" },
{ IFF_SIMPLEX, "SIMPLEX" },
{ IFF_LINK, "LINK" },
{ IFF_AUTO_CONFIGURED, "AUTO_CONFIGURED" },
{ IFF_CONFIGURING, "CONFIGURING" },
FF_LOCALIP_NIFLAG(AUTOUP),
FF_LOCALIP_NIFLAG(SIMPLEX),
FF_LOCALIP_NIFLAG(LINK),
FF_LOCALIP_NIFLAG(AUTO_CONFIGURED),
FF_LOCALIP_NIFLAG(CONFIGURING),
#endif
#ifdef __sun
FF_LOCALIP_NIFLAG(MULTI_BCAST),
FF_LOCALIP_NIFLAG(UNNUMBERED),
FF_LOCALIP_NIFLAG(DHCPRUNNING),
FF_LOCALIP_NIFLAG(PRIVATE),
#endif
// sentinel
{},
};
static void addNewIp(FFlist* list, const char* name, const char* addr, int type, bool defaultRoute, uint32_t flags, bool firstOnly)
typedef enum __attribute__((__packed__)) FFIPv6Type
{
FFLocalIpResult* ip = NULL;
FF_IPV6_Other,
FF_IPV6_GUA = 0b0001,
FF_IPV6_GUA_SECONDARY = 0b0101,
FF_IPV6_ULA = 0b0010,
FF_IPV6_ULA_SECONDARY = 0b0110,
FF_IPV6_TYPE_MASK = 0b0011,
FF_IPV6_SECONDARY_FLAG = 0b1100,
FF_IPV6_PREFERRED = UINT8_MAX,
} FFIPv6Type;
FF_LIST_FOR_EACH(FFLocalIpResult, temp, *list)
static FFIPv6Type getIpType(struct ifaddrs* ifa)
{
struct sockaddr_in6* addr = (struct sockaddr_in6*) ifa->ifa_addr;
FF_DEBUG("Checking IPv6 type for interface %s", ifa->ifa_name);
#ifndef IN6_IS_ADDR_GLOBAL
#define IN6_IS_ADDR_GLOBAL(a) \
((((const uint32_t *) (a))[0] & htonl(0x70000000)) == htonl(0x20000000))
#endif
#ifndef IN6_IS_ADDR_UNIQUE_LOCAL
#define IN6_IS_ADDR_UNIQUE_LOCAL(a) \
((((const uint32_t *) (a))[0] & htonl(0xfe000000)) == htonl(0xfc000000))
#endif
FFIPv6Type result = FF_IPV6_Other;
if (IN6_IS_ADDR_GLOBAL(&addr->sin6_addr))
{
if (!ffStrbufEqualS(&temp->name, name)) continue;
ip = temp;
break;
result = FF_IPV6_GUA;
FF_DEBUG("Interface %s has Global Unicast Address", ifa->ifa_name);
}
if (!ip)
else if (IN6_IS_ADDR_UNIQUE_LOCAL(&addr->sin6_addr))
{
ip = (FFLocalIpResult*) ffListAdd(list);
ffStrbufInitS(&ip->name, name);
ffStrbufInit(&ip->ipv4);
ffStrbufInit(&ip->ipv6);
ffStrbufInit(&ip->mac);
ffStrbufInit(&ip->flags);
ip->defaultRoute = defaultRoute;
ip->mtu = -1;
ip->speed = -1;
ffLocalIpFillNIFlags(&ip->flags, flags, niFlagOptions);
result = FF_IPV6_ULA;
FF_DEBUG("Interface %s has Unique Local Address", ifa->ifa_name);
}
else
{
FF_DEBUG("Interface %s has other IPv6 address type", ifa->ifa_name);
return FF_IPV6_Other;
}
switch (type)
#ifdef SIOCGIFAFLAG_IN6
static int sockfd = 0;
if (sockfd == 0)
{
case AF_INET:
if (ip->ipv4.length)
{
if (firstOnly) return;
ffStrbufAppendC(&ip->ipv4, ',');
}
ffStrbufAppendS(&ip->ipv4, addr);
break;
case AF_INET6:
if (ip->ipv6.length)
{
if (firstOnly) return;
ffStrbufAppendC(&ip->ipv6, ',');
}
ffStrbufAppendS(&ip->ipv6, addr);
break;
case -1:
ffStrbufSetS(&ip->mac, addr);
break;
sockfd = socket(AF_INET6, SOCK_DGRAM
#ifdef SOCK_CLOEXEC
| SOCK_CLOEXEC
#endif
, 0);
#ifndef SOCK_CLOEXEC
if (sockfd > 0) fcntl(sockfd, F_SETFD, FD_CLOEXEC);
#endif
}
if (sockfd < 0) return result;
struct in6_ifreq ifr6 = {};
ffStrCopy(ifr6.ifr_name, ifa->ifa_name, IFNAMSIZ);
ifr6.ifr_addr = *addr;
if (ioctl(sockfd, SIOCGIFAFLAG_IN6, &ifr6) != 0)
return result;
#ifdef IN6_IFF_PREFER_SOURCE
if (ifr6.ifr_ifru.ifru_flags6 & IN6_IFF_PREFER_SOURCE)
return FF_IPV6_PREFERRED;
#endif
if (ifr6.ifr_ifru.ifru_flags6 & (IN6_IFF_DEPRECATED | IN6_IFF_TEMPORARY | IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED
#ifdef IN6_IFF_OPTIMISTIC
| IN6_IFF_OPTIMISTIC
#endif
)) result |= FF_IPV6_SECONDARY_FLAG;
return result;
#elif __linux__
static FFlist addresses = {};
if (addresses.elementSize == 0)
{
ffListInit(&addresses, sizeof(struct in6_addr));
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
if (!ffReadFileBuffer("/proc/net/if_inet6", &buffer))
return result;
char* line = NULL;
size_t len = 0;
while (ffStrbufGetline(&line, &len, &buffer))
{
struct in6_addr* entry = (struct in6_addr*) ffListAdd(&addresses);
uint8_t flags;
if (sscanf(line, "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 "%2" SCNx8 " %*s %*s %*s %" SCNx8 " %*s",
&entry->s6_addr[0], &entry->s6_addr[1], &entry->s6_addr[2], &entry->s6_addr[3],
&entry->s6_addr[4], &entry->s6_addr[5], &entry->s6_addr[6], &entry->s6_addr[7],
&entry->s6_addr[8], &entry->s6_addr[9], &entry->s6_addr[10], &entry->s6_addr[11],
&entry->s6_addr[12], &entry->s6_addr[13], &entry->s6_addr[14], &entry->s6_addr[15],
&flags) != 17 ||
(!IN6_IS_ADDR_GLOBAL(entry) && !IN6_IS_ADDR_UNIQUE_LOCAL(entry)) ||
(flags & (IFA_F_DEPRECATED | IFA_F_TEMPORARY | IFA_F_TENTATIVE | IFA_F_DADFAILED | IFA_F_OPTIMISTIC))
)
--addresses.length;
}
}
if (addresses.capacity == 0) return result;
FF_LIST_FOR_EACH(struct in6_addr, entry, addresses)
{
if (memcmp(&addr->sin6_addr, entry, sizeof(struct in6_addr)) == 0)
return result;
}
result |= FF_IPV6_SECONDARY_FLAG;
return result;
#elif __sun
if (ifa->ifa_flags & IFF_PREFERRED)
return FF_IPV6_PREFERRED;
if (ifa->ifa_flags & (IFF_DEPRECATED | IFF_TEMPORARY | IFF_DUPLICATE))
result |= FF_IPV6_SECONDARY_FLAG;
return result;
#else
return result;
#endif
}
typedef struct {
struct ifaddrs* mac;
FFlist /*<struct ifaddrs*>*/ ipv4;
FFlist /*<struct ifaddrs*>*/ ipv6;
} FFAdapter;
static void appendIpv4(const FFLocalIpOptions* options, FFstrbuf* buffer, const struct ifaddrs* ifa)
{
struct sockaddr_in* ipv4 = (struct sockaddr_in*) ifa->ifa_addr;
char addressBuffer[INET_ADDRSTRLEN + 16];
inet_ntop(AF_INET, &ipv4->sin_addr, addressBuffer, INET_ADDRSTRLEN);
FF_DEBUG("Adding IPv4 address %s for interface %s", addressBuffer, ifa->ifa_name);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
{
struct sockaddr_in* netmask = (struct sockaddr_in*) ifa->ifa_netmask;
int cidr = __builtin_popcount(netmask->sin_addr.s_addr);
if (cidr != 0)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
}
}
if (buffer->length) ffStrbufAppendC(buffer, ',');
ffStrbufAppendS(buffer, addressBuffer);
}
static void appendIpv6(const FFLocalIpOptions* options, FFstrbuf* buffer, const struct ifaddrs* ifa)
{
struct sockaddr_in6* ipv6 = (struct sockaddr_in6*) ifa->ifa_addr;
char addressBuffer[INET6_ADDRSTRLEN + 16];
inet_ntop(AF_INET6, &ipv6->sin6_addr, addressBuffer, INET6_ADDRSTRLEN);
FF_DEBUG("Adding IPv6 address %s for interface %s", addressBuffer, ifa->ifa_name);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
{
struct sockaddr_in6* netmask = (struct sockaddr_in6*) ifa->ifa_netmask;
int cidr = 0;
static_assert(sizeof(netmask->sin6_addr) % sizeof(uint64_t) == 0, "");
for (uint32_t i = 0; i < sizeof(netmask->sin6_addr) / sizeof(uint64_t); ++i)
cidr += __builtin_popcountll(((uint64_t*) &netmask->sin6_addr)[i]);
if (cidr != 0)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
}
}
if (buffer->length) ffStrbufAppendC(buffer, ',');
ffStrbufAppendS(buffer, addressBuffer);
}
const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
{
FF_DEBUG("Starting local IP detection with showType=0x%x, namePrefix='%s'",
options->showType, options->namePrefix.chars);
struct ifaddrs* ifAddrStruct = NULL;
if(getifaddrs(&ifAddrStruct) < 0)
{
FF_DEBUG("getifaddrs() failed");
return "getifaddrs(&ifAddrStruct) failed";
}
const char* defaultRouteIfName = ffNetifGetDefaultRouteIfName();
FF_DEBUG("Successfully retrieved interface addresses");
FF_LIST_AUTO_DESTROY adapters = ffListCreate(sizeof(FFAdapter));
for (struct ifaddrs* ifa = ifAddrStruct; ifa; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
{
FF_DEBUG("Skipping interface %s (no address)", ifa->ifa_name);
continue;
#ifdef IFF_RUNNING
if (!(ifa->ifa_flags & IFF_RUNNING))
continue;
#endif
}
bool isDefaultRoute = ffStrEquals(defaultRouteIfName, ifa->ifa_name);
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
#ifdef IFF_RUNNING
if (!(ifa->ifa_flags & IFF_RUNNING))
{
FF_DEBUG("Skipping interface %s (not running)", ifa->ifa_name);
continue;
}
#endif
if ((ifa->ifa_flags & IFF_LOOPBACK) && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT))
{
FF_DEBUG("Skipping loopback interface %s", ifa->ifa_name);
continue;
}
if (options->namePrefix.length && strncmp(ifa->ifa_name, options->namePrefix.chars, options->namePrefix.length) != 0)
{
FF_DEBUG("Skipping interface %s (doesn't match prefix '%s')",
ifa->ifa_name, options->namePrefix.chars);
continue;
}
uint32_t flags = options->showType & FF_LOCALIP_TYPE_FLAGS_BIT ? ifa->ifa_flags : 0;
if (ifa->ifa_addr->sa_family == AF_INET)
if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT) &&
ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6)
{
if (!(options->showType & FF_LOCALIP_TYPE_IPV4_BIT))
continue;
FF_DEBUG("Skipping interface %s (unsupported address family %d)",
ifa->ifa_name, ifa->ifa_addr->sa_family);
continue;
}
struct sockaddr_in* ipv4 = (struct sockaddr_in*) ifa->ifa_addr;
char addressBuffer[INET_ADDRSTRLEN + 16];
inet_ntop(AF_INET, &ipv4->sin_addr, addressBuffer, INET_ADDRSTRLEN);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
// If the interface is not the default route for either IPv4 or IPv6, skip it
if (!((options->showType & FF_LOCALIP_TYPE_IPV4_BIT) && ffStrEquals(ffNetifGetDefaultRouteV4()->ifName, ifa->ifa_name)) &&
!((options->showType & FF_LOCALIP_TYPE_IPV6_BIT) && ffStrEquals(ffNetifGetDefaultRouteV6()->ifName, ifa->ifa_name)))
{
struct sockaddr_in* netmask = (struct sockaddr_in*) ifa->ifa_netmask;
int cidr = __builtin_popcount(netmask->sin_addr.s_addr);
if (cidr != 0)
FF_DEBUG("Skipping interface %s (not default route interface)", ifa->ifa_name);
continue;
}
}
FF_DEBUG("Processing interface %s (family=%d, flags=0x%x)",
ifa->ifa_name, ifa->ifa_addr->sa_family, ifa->ifa_flags);
FFAdapter* adapter = NULL;
FF_LIST_FOR_EACH(FFAdapter, x, adapters)
{
if (ffStrEquals(x->mac->ifa_name, ifa->ifa_name))
{
adapter = x;
break;
}
}
if (!adapter)
{
adapter = ffListAdd(&adapters);
*adapter = (FFAdapter) {
.mac = ifa,
.ipv4 = ffListCreate(sizeof(struct ifaddrs*)),
.ipv6 = ffListCreate(sizeof(struct ifaddrs*)),
};
FF_DEBUG("Created new adapter entry for interface %s", ifa->ifa_name);
}
switch (ifa->ifa_addr->sa_family)
{
case AF_INET:
if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
*FF_LIST_ADD(struct ifaddrs*, adapter->ipv4) = ifa;
FF_DEBUG("Added IPv4 entry for interface %s", ifa->ifa_name);
}
break;
case AF_INET6:
if (options->showType & FF_LOCALIP_TYPE_IPV6_BIT)
{
*FF_LIST_ADD(struct ifaddrs*, adapter->ipv6) = ifa;
FF_DEBUG("Added IPv6 entry for interface %s", ifa->ifa_name);
}
break;
#if __FreeBSD__ || __OpenBSD__ || __APPLE__ || __NetBSD__ || __HAIKU__
case AF_LINK:
adapter->mac = ifa;
FF_DEBUG("Updated MAC entry for interface %s", ifa->ifa_name);
break;
#elif !__sun
case AF_PACKET:
adapter->mac = ifa;
FF_DEBUG("Updated MAC entry for interface %s", ifa->ifa_name);
break;
#endif
}
}
FF_DEBUG("Found %u network adapters", adapters.length);
FF_LIST_FOR_EACH(FFAdapter, adapter, adapters)
{
FF_DEBUG("Processing adapter %s (IPv4 entries: %u, IPv6 entries: %u)",
adapter->mac->ifa_name, adapter->ipv4.length, adapter->ipv6.length);
FFLocalIpResult* item = FF_LIST_ADD(FFLocalIpResult, *results);
ffStrbufInitS(&item->name, adapter->mac->ifa_name);
ffStrbufInit(&item->ipv4);
ffStrbufInit(&item->ipv6);
ffStrbufInit(&item->mac);
ffStrbufInit(&item->flags);
item->defaultRoute = FF_LOCALIP_TYPE_NONE;
item->mtu = -1;
item->speed = -1;
if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT)
{
ffLocalIpFillNIFlags(&item->flags, adapter->mac->ifa_flags, niFlagOptions);
FF_DEBUG("Added flags for interface %s: %s", adapter->mac->ifa_name, item->flags.chars);
}
if ((options->showType & FF_LOCALIP_TYPE_IPV4_BIT))
{
const FFNetifDefaultRouteResult* defaultRouteV4 = ffNetifGetDefaultRouteV4();
bool isDefaultRouteIf = ffStrEquals(defaultRouteV4->ifName, adapter->mac->ifa_name);
if (isDefaultRouteIf)
{
item->defaultRoute |= FF_LOCALIP_TYPE_IPV4_BIT;
FF_DEBUG("Interface %s is IPv4 default route", adapter->mac->ifa_name);
}
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
if (!isDefaultRouteIf)
{
FF_DEBUG("Skipping IPv4 for interface %s (not default route)", adapter->mac->ifa_name);
goto v6;
}
}
addNewIp(results, ifa->ifa_name, addressBuffer, AF_INET, isDefaultRoute, flags, !(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT));
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
if (!(options->showType & FF_LOCALIP_TYPE_IPV6_BIT))
continue;
struct sockaddr_in6* ipv6 = (struct sockaddr_in6 *)ifa->ifa_addr;
char addressBuffer[INET6_ADDRSTRLEN + 16];
inet_ntop(AF_INET6, &ipv6->sin6_addr, addressBuffer, INET6_ADDRSTRLEN);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT))
{
struct sockaddr_in6* netmask = (struct sockaddr_in6*) ifa->ifa_netmask;
int cidr = 0;
static_assert(sizeof(netmask->sin6_addr) % sizeof(uint64_t) == 0, "");
for (uint32_t i = 0; i < sizeof(netmask->sin6_addr) / sizeof(uint64_t); ++i)
cidr += __builtin_popcountll(((uint64_t*) &netmask->sin6_addr)[i]);
if (cidr != 0)
struct ifaddrs* ifa = NULL;
if (isDefaultRouteIf && defaultRouteV4->preferredSourceAddrV4 != 0)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv4)
{
struct sockaddr_in* ipv4 = (struct sockaddr_in*) (*pifa)->ifa_addr;
if (ipv4->sin_addr.s_addr == defaultRouteV4->preferredSourceAddrV4)
{
ifa = *pifa;
FF_DEBUG("Found preferred IPv4 source address for interface %s", adapter->mac->ifa_name);
break;
}
}
}
if (ifa)
appendIpv4(options, &item->ipv4, ifa);
else if (adapter->ipv4.length > 0)
{
appendIpv4(options, &item->ipv4, *FF_LIST_GET(struct ifaddrs*, adapter->ipv4, 0));
FF_DEBUG("Using first IPv4 address for interface %s", adapter->mac->ifa_name);
}
}
else
{
FF_DEBUG("Adding all IPv4 addresses for interface %s", adapter->mac->ifa_name);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv4)
appendIpv4(options, &item->ipv4, *pifa);
}
}
v6:
if ((options->showType & FF_LOCALIP_TYPE_IPV6_BIT))
{
const FFNetifDefaultRouteResult* defaultRouteV6 = ffNetifGetDefaultRouteV6();
bool isDefaultRouteIf = ffStrEquals(defaultRouteV6->ifName, adapter->mac->ifa_name);
if (isDefaultRouteIf)
{
item->defaultRoute |= FF_LOCALIP_TYPE_IPV6_BIT;
FF_DEBUG("Interface %s is IPv6 default route", adapter->mac->ifa_name);
}
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
if (!isDefaultRouteIf)
{
FF_DEBUG("Skipping IPv6 for interface %s (not default route)", adapter->mac->ifa_name);
goto mac;
}
}
addNewIp(results, ifa->ifa_name, addressBuffer, AF_INET6, isDefaultRoute, flags, !(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT));
}
#if __FreeBSD__ || __OpenBSD__ || __APPLE__ || __NetBSD__ || __HAIKU__
else if (ifa->ifa_addr->sa_family == AF_LINK)
{
if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT))
continue;
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT))
{
struct ifaddrs* selected = NULL;
struct ifaddrs* secondary = NULL;
char addressBuffer[32];
uint8_t* ptr = (uint8_t*) LLADDR((struct sockaddr_dl *)ifa->ifa_addr);
snprintf(addressBuffer, ARRAY_SIZE(addressBuffer), "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
addNewIp(results, ifa->ifa_name, addressBuffer, -1, isDefaultRoute, flags, false);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6)
{
FFIPv6Type type = getIpType(*pifa);
if (type == FF_IPV6_PREFERRED)
{
selected = *pifa;
FF_DEBUG("Found preferred IPv6 address for interface %s", adapter->mac->ifa_name);
break;
}
else if (type == FF_IPV6_GUA && !selected)
{
selected = *pifa;
FF_DEBUG("Found GUA IPv6 address for interface %s", adapter->mac->ifa_name);
}
else if (type == FF_IPV6_ULA && !secondary)
{
secondary = *pifa;
FF_DEBUG("Found ULA IPv6 address for interface %s", adapter->mac->ifa_name);
}
}
if (!selected) selected = secondary;
if (selected)
appendIpv6(options, &item->ipv6, selected);
else if (adapter->ipv6.length > 0)
{
appendIpv6(options, &item->ipv6, *FF_LIST_GET(struct ifaddrs*, adapter->ipv6, 0));
FF_DEBUG("Using first IPv6 address for interface %s", adapter->mac->ifa_name);
}
}
else
{
FF_DEBUG("Adding all IPv6 addresses for interface %s", adapter->mac->ifa_name);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6)
appendIpv6(options, &item->ipv6, *pifa);
}
}
mac:
#ifndef __sun
if (options->showType & FF_LOCALIP_TYPE_MAC_BIT)
{
if (adapter->mac->ifa_addr)
{
#if __FreeBSD__ || __OpenBSD__ || __APPLE__ || __NetBSD__ || __HAIKU__
uint8_t* ptr = (uint8_t*) LLADDR((struct sockaddr_dl *)adapter->mac->ifa_addr);
#else
uint8_t* ptr = ((struct sockaddr_ll *)adapter->mac->ifa_addr)->sll_addr;
#endif
ffStrbufSetF(&item->mac, "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
FF_DEBUG("Added MAC address %s for interface %s", item->mac.chars, adapter->mac->ifa_name);
}
else
{
FF_DEBUG("No MAC address available for interface %s", adapter->mac->ifa_name);
}
}
#else
else if (ifa->ifa_addr->sa_family == AF_PACKET)
{
if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT))
continue;
char addressBuffer[32];
uint8_t* ptr = ((struct sockaddr_ll *)ifa->ifa_addr)->sll_addr;
snprintf(addressBuffer, ARRAY_SIZE(addressBuffer), "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
addNewIp(results, ifa->ifa_name, addressBuffer, -1, isDefaultRoute, flags, false);
}
(void) adapter;
#endif
}
if (ifAddrStruct) freeifaddrs(ifAddrStruct);
FF_LIST_FOR_EACH(FFAdapter, adapter, adapters)
{
ffListDestroy(&adapter->ipv4);
ffListDestroy(&adapter->ipv6);
}
if (ifAddrStruct)
{
freeifaddrs(ifAddrStruct);
ifAddrStruct = NULL;
FF_DEBUG("Cleaned up interface address structures");
}
if ((options->showType & FF_LOCALIP_TYPE_MTU_BIT) || (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
#ifdef __sun
@@ -240,18 +586,26 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
#endif
)
{
FF_DEBUG("Retrieving additional interface properties (MTU/Speed/MAC)");
FF_AUTO_CLOSE_FD int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd > 0)
{
FF_LIST_FOR_EACH(FFLocalIpResult, iface, *results)
{
struct ifreq ifr;
struct ifreq ifr = {};
ffStrCopy(ifr.ifr_name, iface->name.chars, IFNAMSIZ);
if (options->showType & FF_LOCALIP_TYPE_MTU_BIT)
{
if (ioctl(sockfd, SIOCGIFMTU, &ifr) == 0)
{
iface->mtu = (int32_t) ifr.ifr_mtu;
FF_DEBUG("Interface %s MTU: %d", iface->name.chars, iface->mtu);
}
else
{
FF_DEBUG("Failed to get MTU for interface %s", iface->name.chars);
}
}
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
@@ -260,12 +614,21 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
struct ethtool_cmd edata = { .cmd = ETHTOOL_GSET };
ifr.ifr_data = (void*) &edata;
if (ioctl(sockfd, SIOCETHTOOL, &ifr) == 0)
iface->speed = (edata.speed_hi << 16) | edata.speed; // ethtool_cmd_speed is not available on Android
{
iface->speed = (edata.speed_hi << 16) | edata.speed;
FF_DEBUG("Interface %s speed: %d Mbps", iface->name.chars, iface->speed);
}
else
{
// ethtool_cmd_speed is not available on Android
FF_DEBUG("Failed to get speed for interface %s via ethtool", iface->name.chars);
}
#elif __FreeBSD__ || __APPLE__ || __OpenBSD__ || __NetBSD__
struct ifmediareq ifmr = {};
ffStrCopy(ifmr.ifm_name, iface->name.chars, IFNAMSIZ);
if (ioctl(sockfd, SIOCGIFMEDIA, &ifmr) == 0 && (IFM_TYPE(ifmr.ifm_active) & IFM_ETHER))
{
FF_DEBUG("Interface %s media type: 0x%x", iface->name.chars, IFM_SUBTYPE(ifmr.ifm_active));
switch (IFM_SUBTYPE(ifmr.ifm_active))
{
#ifdef IFM_HPNA_1
@@ -630,7 +993,15 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
iface->speed = 56000; break;
default:
iface->speed = -1;
FF_DEBUG("Unknown media subtype for interface %s", iface->name.chars);
break;
}
if (iface->speed > 0)
FF_DEBUG("Interface %s speed: %d Mbps", iface->name.chars, iface->speed);
}
else
{
FF_DEBUG("Failed to get media info for interface %s", iface->name.chars);
}
#endif
}
@@ -641,11 +1012,38 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
const uint8_t* ptr = (uint8_t*) ifr.ifr_addr.sa_data; // NOT ifr_enaddr
ffStrbufSetF(&iface->mac, "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
FF_DEBUG("Added MAC address %s for interface %s (Solaris)", iface->mac.chars, iface->name.chars);
}
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
{
__attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open();
for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next)
{
if (!ffStrEquals(ks->ks_class, "net") || !ffStrEquals(ks->ks_module, "link")) continue;
if (ffStrbufEqualS(&iface->name, ks->ks_name))
{
if (kstat_read(kc, ks, NULL) >= 0)
{
kstat_named_t* ifspeed = (kstat_named_t*) kstat_data_lookup(ks, "ifspeed");
if (ifspeed)
{
iface->speed = (int32_t) (ifspeed->value.ui64 / 1000 / 1000);
FF_DEBUG("Interface %s speed: %d Mbps (kstat)", iface->name.chars, iface->speed);
}
}
break;
}
}
}
#endif
}
}
else
{
FF_DEBUG("Failed to create socket for interface property retrieval");
}
}
FF_DEBUG("Local IP detection completed, found %u interfaces", results->length);
return NULL;
}
+151 -79
View File
@@ -4,62 +4,31 @@
#include "common/netif/netif.h"
#include "util/mallocHelper.h"
#include "util/windows/unicode.h"
#include "util/debug.h"
#include "localip.h"
#define FF_LOCALIP_NIFLAG(name) { IP_ADAPTER_##name, #name }
static const FFLocalIpNIFlag niFlagOptions[] = {
{ IP_ADAPTER_DDNS_ENABLED, "DDNS_ENABLED" },
{ IP_ADAPTER_REGISTER_ADAPTER_SUFFIX, "REGISTER_ADAPTER_SUFFIX" },
{ IP_ADAPTER_DHCP_ENABLED, "DHCP_ENABLED" },
{ IP_ADAPTER_RECEIVE_ONLY, "RECEIVE_ONLY" },
{ IP_ADAPTER_NO_MULTICAST, "NO_MULTICAST" },
{ IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG, "IPV6_OTHER_STATEFUL_CONFIG" },
{ IP_ADAPTER_NETBIOS_OVER_TCPIP_ENABLED, "NETBIOS_OVER_TCPIP_ENABLED" },
{ IP_ADAPTER_IPV4_ENABLED, "IPV4_ENABLED" },
{ IP_ADAPTER_IPV6_ENABLED, "IPV6_ENABLED" },
{ IP_ADAPTER_IPV6_MANAGE_ADDRESS_CONFIG, "IPV6_MANAGE_ADDRESS_CONFIG" },
FF_LOCALIP_NIFLAG(DDNS_ENABLED),
FF_LOCALIP_NIFLAG(REGISTER_ADAPTER_SUFFIX),
FF_LOCALIP_NIFLAG(DHCP_ENABLED),
FF_LOCALIP_NIFLAG(RECEIVE_ONLY),
FF_LOCALIP_NIFLAG(NO_MULTICAST),
FF_LOCALIP_NIFLAG(IPV6_OTHER_STATEFUL_CONFIG),
FF_LOCALIP_NIFLAG(NETBIOS_OVER_TCPIP_ENABLED),
FF_LOCALIP_NIFLAG(IPV4_ENABLED),
FF_LOCALIP_NIFLAG(IPV6_ENABLED),
FF_LOCALIP_NIFLAG(IPV6_MANAGE_ADDRESS_CONFIG),
// sentinel
{},
};
static void addNewIp(FFlist* list, const char* name, const char* addr, int type, bool newIp, bool defaultRoute)
{
FFLocalIpResult* ip = NULL;
if (newIp)
{
ip = (FFLocalIpResult*) ffListAdd(list);
ffStrbufInitS(&ip->name, name);
ffStrbufInit(&ip->ipv4);
ffStrbufInit(&ip->ipv6);
ffStrbufInit(&ip->mac);
ffStrbufInit(&ip->flags);
ip->defaultRoute = defaultRoute;
ip->speed = -1;
ip->mtu = -1;
}
else
{
ip = FF_LIST_GET(FFLocalIpResult, *list, list->length - 1);
}
switch (type)
{
case AF_INET:
if (ip->ipv4.length) ffStrbufAppendC(&ip->ipv4, ',');
ffStrbufAppendS(&ip->ipv4, addr);
break;
case AF_INET6:
if (ip->ipv6.length) ffStrbufAppendC(&ip->ipv6, ',');
ffStrbufAppendS(&ip->ipv6, addr);
break;
case -1:
ffStrbufSetS(&ip->mac, addr);
break;
}
}
const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
{
FF_DEBUG("Starting local IP detection with showType=0x%X, namePrefix='%.*s'",
options->showType, (int)options->namePrefix.length, options->namePrefix.chars);
IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL;
// Multiple attempts in case interfaces change while
@@ -67,66 +36,134 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
DWORD adapter_addresses_buffer_size = 0;
for (int attempts = 0;; ++attempts)
{
FF_DEBUG("Attempt %d to get adapter addresses, buffer size: %lu", attempts + 1, adapter_addresses_buffer_size);
if (adapter_addresses_buffer_size)
{
adapter_addresses = (IP_ADAPTER_ADDRESSES*)realloc(adapter_addresses, adapter_addresses_buffer_size);
assert(adapter_addresses);
}
DWORD family = options->showType & FF_LOCALIP_TYPE_IPV4_BIT
? options->showType & FF_LOCALIP_TYPE_IPV6_BIT ? AF_UNSPEC : AF_INET
: AF_INET6;
FF_DEBUG("Calling GetAdaptersAddresses with family=%u, flags=0x%X", (unsigned)family,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER);
DWORD error = GetAdaptersAddresses(
options->showType & FF_LOCALIP_TYPE_IPV4_BIT
? options->showType & FF_LOCALIP_TYPE_IPV6_BIT ? AF_UNSPEC : AF_INET
: AF_INET6,
family,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
NULL,
adapter_addresses,
&adapter_addresses_buffer_size);
if (error == ERROR_SUCCESS)
{
FF_DEBUG("GetAdaptersAddresses succeeded on attempt %d", attempts + 1);
break;
}
else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4)
{
FF_DEBUG("Buffer overflow, need %lu bytes, retrying", adapter_addresses_buffer_size);
continue;
}
else
{
FF_DEBUG("GetAdaptersAddresses failed with error %lu after %d attempts", error, attempts + 1);
return "GetAdaptersAddresses() failed";
}
}
uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteIfIndex();
int adapterCount = 0;
int processedCount = 0;
// Iterate through all of the adapters
for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next)
{
bool isDefaultRoute = adapter->IfIndex == defaultRouteIfIndex;
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
adapterCount++;
FF_DEBUG("Processing adapter %d: IfIndex=%u, IfType=%u, OperStatus=%u",
adapterCount, (unsigned)adapter->IfIndex, (unsigned)adapter->IfType, (unsigned)adapter->OperStatus);
if (adapter->OperStatus != IfOperStatusUp)
{
FF_DEBUG("Skipping adapter %u (not operational, status=%d)", (unsigned)adapter->IfIndex, adapter->OperStatus);
continue;
}
bool isLoop = adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK;
if (isLoop && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT))
continue;
FF_DEBUG("Adapter %u: isLoopback=%s", (unsigned)adapter->IfIndex, isLoop ? "true" : "false");
bool newIp = true;
if (isLoop && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT))
{
FF_DEBUG("Skipping loopback adapter %u (loopback not requested)", (unsigned)adapter->IfIndex);
continue;
}
char name[128];
WideCharToMultiByte(CP_UTF8, 0, adapter->FriendlyName, -1, name, ARRAY_SIZE(name), NULL, NULL);
if (options->namePrefix.length && strncmp(name, options->namePrefix.chars, options->namePrefix.length) != 0)
continue;
FF_DEBUG("Adapter %u name: '%s'", (unsigned)adapter->IfIndex, name);
if (options->showType & FF_LOCALIP_TYPE_MAC_BIT && adapter->PhysicalAddressLength == 6)
if (options->namePrefix.length && strncmp(name, options->namePrefix.chars, options->namePrefix.length) != 0)
{
char addressBuffer[32];
uint8_t* ptr = adapter->PhysicalAddress;
snprintf(addressBuffer, ARRAY_SIZE(addressBuffer), "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
addNewIp(results, name, addressBuffer, -1, newIp, isDefaultRoute);
newIp = false;
FF_DEBUG("Skipping adapter %u (name doesn't match prefix '%.*s')",
(unsigned)adapter->IfIndex, (int)options->namePrefix.length, options->namePrefix.chars);
continue;
}
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
if (!((options->showType & FF_LOCALIP_TYPE_IPV4_BIT) && ffNetifGetDefaultRouteV4()->ifIndex == adapter->IfIndex) &&
!((options->showType & FF_LOCALIP_TYPE_IPV6_BIT) && ffNetifGetDefaultRouteV6()->ifIndex == adapter->IfIndex))
{
FF_DEBUG("Skipping interface %u (not default route interface)", (unsigned)adapter->IfIndex);
continue;
}
}
processedCount++;
FF_DEBUG("Creating result item for adapter %u ('%s')", (unsigned)adapter->IfIndex, name);
FFLocalIpResult* item = (FFLocalIpResult*) ffListAdd(results);
ffStrbufInitS(&item->name, name);
ffStrbufInit(&item->ipv4);
ffStrbufInit(&item->ipv6);
ffStrbufInit(&item->mac);
ffStrbufInit(&item->flags);
item->defaultRoute = FF_LOCALIP_TYPE_NONE;
item->speed = -1;
item->mtu = -1;
uint32_t typesToAdd = options->showType & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT);
FF_DEBUG("Types to add for adapter %u: 0x%X", (unsigned)adapter->IfIndex, typesToAdd);
int ipv4Count = 0, ipv6Count = 0;
for (IP_ADAPTER_UNICAST_ADDRESS* ifa = adapter->FirstUnicastAddress; ifa; ifa = ifa->Next)
{
FF_DEBUG("Processing unicast address: family=%d, DadState=%d",
ifa->Address.lpSockaddr->sa_family, ifa->DadState);
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT) && ifa->DadState != IpDadStatePreferred)
{
FF_DEBUG("Skipping address (DadState=%d, not preferred)", ifa->DadState);
continue;
}
if (ifa->Address.lpSockaddr->sa_family == AF_INET)
{
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT))) continue;
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT)))
{
FF_DEBUG("Skipping IPv4 address (not requested in typesToAdd=0x%X)", typesToAdd);
continue;
}
bool isDefaultRoute = ((options->showType & FF_LOCALIP_TYPE_IPV4_BIT) && ffNetifGetDefaultRouteV4()->ifIndex == adapter->IfIndex);
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
{
FF_DEBUG("Skipping IPv4 address (not on default route interface)");
continue;
}
SOCKADDR_IN* ipv4 = (SOCKADDR_IN*) ifa->Address.lpSockaddr;
char addressBuffer[INET_ADDRSTRLEN + 6];
@@ -138,15 +175,30 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
snprintf(addressBuffer + len, 6, "/%u", (unsigned) ifa->OnLinkPrefixLength);
}
addNewIp(results, name, addressBuffer, AF_INET, newIp, isDefaultRoute);
newIp = false;
FF_DEBUG("Adding IPv4 address: %s (isDefaultRoute=%s)", addressBuffer, isDefaultRoute ? "true" : "false");
if (item->ipv4.length) ffStrbufAppendC(&item->ipv4, ',');
ffStrbufAppendS(&item->ipv4, addressBuffer);
if (isDefaultRoute) item->defaultRoute |= FF_LOCALIP_TYPE_IPV4_BIT;
ipv4Count++;
typesToAdd &= ~(unsigned) FF_LOCALIP_TYPE_IPV4_BIT;
if (typesToAdd == 0) break;
}
else if (ifa->Address.lpSockaddr->sa_family == AF_INET6)
{
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT))) continue;
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT)))
{
FF_DEBUG("Skipping IPv6 address (not requested in typesToAdd=0x%X)", typesToAdd);
continue;
}
bool isDefaultRoute = ((options->showType & FF_LOCALIP_TYPE_IPV6_BIT) && ffNetifGetDefaultRouteV6()->ifIndex == adapter->IfIndex);
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
{
FF_DEBUG("Skipping IPv6 address (not on default route interface)");
continue;
}
SOCKADDR_IN6* ipv6 = (SOCKADDR_IN6*) ifa->Address.lpSockaddr;
char addressBuffer[INET6_ADDRSTRLEN + 6];
@@ -158,25 +210,45 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
snprintf(addressBuffer + len, 6, "/%u", (unsigned) ifa->OnLinkPrefixLength);
}
addNewIp(results, name, addressBuffer, AF_INET6, newIp, isDefaultRoute);
newIp = false;
FF_DEBUG("Adding IPv6 address: %s (isDefaultRoute=%s)", addressBuffer, isDefaultRoute ? "true" : "false");
if (item->ipv6.length) ffStrbufAppendC(&item->ipv6, ',');
ffStrbufAppendS(&item->ipv6, addressBuffer);
if (isDefaultRoute) item->defaultRoute |= FF_LOCALIP_TYPE_IPV6_BIT;
ipv6Count++;
typesToAdd &= ~(unsigned) FF_LOCALIP_TYPE_IPV6_BIT;
if (typesToAdd == 0) break;
}
}
if (!newIp)
FF_DEBUG("Adapter %u: collected %d IPv4 and %d IPv6 addresses", (unsigned)adapter->IfIndex, ipv4Count, ipv6Count);
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
{
FFLocalIpResult* result = FF_LIST_GET(FFLocalIpResult, *results, results->length - 1);
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
result->speed = (int32_t) (adapter->ReceiveLinkSpeed / 1000);
if (options->showType & FF_LOCALIP_TYPE_MTU_BIT)
result->mtu = (int32_t) adapter->Mtu;
if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT)
ffLocalIpFillNIFlags(&result->flags, adapter->Flags, niFlagOptions);
item->speed = (int32_t) (adapter->ReceiveLinkSpeed / 1000000);
FF_DEBUG("Adapter %u speed: %d Mbps (raw: %llu)", (unsigned)adapter->IfIndex, item->speed, adapter->ReceiveLinkSpeed);
}
if (options->showType & FF_LOCALIP_TYPE_MTU_BIT)
{
item->mtu = (int32_t) adapter->Mtu;
FF_DEBUG("Adapter %u MTU: %d", (unsigned)adapter->IfIndex, item->mtu);
}
if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT)
{
ffLocalIpFillNIFlags(&item->flags, adapter->Flags, niFlagOptions);
FF_DEBUG("Adapter %u flags: 0x%lX -> '%s'", (unsigned)adapter->IfIndex, adapter->Flags, item->flags.chars);
}
if (options->showType & FF_LOCALIP_TYPE_MAC_BIT && adapter->PhysicalAddressLength == 6)
{
uint8_t* ptr = adapter->PhysicalAddress;
ffStrbufSetF(&item->mac, "%02x:%02x:%02x:%02x:%02x:%02x", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
FF_DEBUG("Adapter %u MAC: %s", (unsigned)adapter->IfIndex, item->mac.chars);
}
}
FF_DEBUG("Local IP detection completed: scanned %d adapters, processed %d, results count: %u",
adapterCount, processedCount, results->length);
return NULL;
}
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/media/option.h"
typedef struct FFMediaResult
{
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "fastfetch.h"
#include "modules/memory/option.h"
typedef struct FFMemoryResult
{

Some files were not shown because too many files have changed in this diff Show More