#ifndef DWM_PLUGINS_PHONE_DATA_H #define DWM_PLUGINS_PHONE_DATA_H #include #include #include #ifndef _EVDEVK #define _EVDEVK(_v) (0x10081000 + (_v)) #endif #include "theme.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace bananarchy { constexpr int kScreenWidth = 240; constexpr int kScreenHeight = 320; constexpr int kTopBarHeight = 24; constexpr int kWinX = 0; constexpr int kWinY = kTopBarHeight; constexpr int kWinWidth = kScreenWidth; constexpr int kWinHeight = kScreenHeight - kTopBarHeight; // 296px flush below 24px dwm bar // Nerd Font PUA icons matching sxmo_hook_icons.sh & dwm ("Fira Code, DejaVuSansM Nerd Font") constexpr const char* kIconPhone = "\xef\x82\x95"; // U+F095 phone handset constexpr const char* kIconPhoneLog = "\xef\x82\x98"; // U+F098 phone square constexpr const char* kIconUser = "\xef\x80\x87"; // U+F007 user contact constexpr const char* kIconBook = "\xef\x83\x80"; // U+F0C0 address book / users constexpr const char* kIconClock = "\xef\x80\x97"; // U+F017 recent clock constexpr const char* kIconOutCall = "\xef\x85\xb8"; // U+F178 outgoing arrow constexpr const char* kIconInCall = "\xef\x85\xb5"; // U+F175 incoming arrow constexpr const char* kIconMissedCall = "\xef\x81\xb1"; // U+F071 missed/alert constexpr const char* kIconBackspace = "\xef\x86\x90"; // U+F190 left circle arrow constexpr const char* kIconSearch = "\xef\x80\x82"; // U+F002 search constexpr const char* kIconPlus = "\xef\x81\xa7"; // U+F067 plus/add constexpr const char* kIconEdit = "\xef\x81\x84"; // U+F044 edit constexpr const char* kIconTrash = "\xef\x87\xb8"; // U+F1F8 delete/trash constexpr const char* kIconSms = "\xef\x83\xa0"; // U+F0E0 envelope/SMS constexpr const char* kIconList = "\xef\x80\xba"; // U+F03A list constexpr const char* kIconCheck = "\xef\x80\x8c"; // U+F00C check constexpr const char* kIconFolder = "\xef\x81\xbb"; // U+F07B folder constexpr const char* kIconFolderOpen = "\xef\x81\xbc"; // U+F07C folder-open constexpr const char* kIconFile = "\xef\x80\x96"; // U+F016 file constexpr const char* kIconFileText = "\xef\x85\x9c"; // U+F15C file-text constexpr const char* kIconImage = "\xef\x80\xbe"; // U+F03E image constexpr const char* kIconMusic = "\xef\x80\x81"; // U+F001 music/audio constexpr const char* kIconTerm = "\xef\x84\xa0"; // U+F120 terminal constexpr const char* kIconCamera = "\xef\x80\xb0"; // U+F030 camera constexpr const char* kIconFlash = "\xef\x83\xa7"; // U+F0E7 bolt/flash constexpr const char* kIconSend = "\xef\x87\x98"; // U+F1D8 paper-plane constexpr const char* kIconCopy = "\xef\x83\x85"; // U+F0C5 copy constexpr const char* kIconInfo = "\xef\x81\x9a"; // U+F05A info-circle constexpr const char* kIconRefresh = "\xef\x80\xa1"; // U+F021 refresh constexpr const char* kIconSort = "\xef\x83\x9c"; // U+F0DC sort constexpr const char* kIconEye = "\xef\x81\xae"; // U+F06E eye/view constexpr const char* kIconPalette = "\xef\x87\xbc"; // U+F1FC paint-brush / theme constexpr const char* kIconSpeaker = "\xef\x80\xa8"; // U+F028 speaker constexpr const char* kIconEarpiece = "\xef\x8a\xa0"; // U+F2A0 earpiece constexpr const char* kIconSoundOff = "\xef\x91\xa6"; // U+F466 mute constexpr const char* kIconMicOn = "\xf3\xb0\x8d\xac"; // U+F036C mic on constexpr const char* kIconMicOff = "\xf3\xb0\x8d\xad"; // U+F036D mic off constexpr const char* kIconRecord = "\xef\x84\x91"; // U+F111 circle / record dot constexpr const char* kIconLock = "\xef\x80\xa3"; // U+F023 lock constexpr const char* kIconUnlock = "\xef\x82\x9c"; // U+F09C unlock constexpr const char* kIconSignal = "\xef\x80\x92"; // U+F012 signal bars constexpr const char* kIconWifi = "\xef\x87\xab"; // U+F1EB wifi constexpr const char* kIconBluetooth = "\xef\x8a\x94"; // U+F294 bluetooth constexpr const char* kIconGlobe = "\xef\x82\xac"; // U+F0AC globe / network constexpr const char* kIconSliders = "\xef\x87\x9e"; // U+F1DE sliders / config constexpr const char* kIconToggleOn = "\xef\x88\x85"; // U+F205 toggle on constexpr const char* kIconToggleOff = "\xef\x88\x84"; // U+F204 toggle off constexpr const char* kIconKey = "\xef\x82\x84"; // U+F084 key / PIN constexpr const char* kIconSim = "\xf3\xb0\x99\x95"; // U+F0655 nf-md-sim constexpr const char* kIconBell = "\xef\x83\xb3"; // U+F0F3 bell / ringtone constexpr const char* kIconBan = "\xef\x81\x9e"; // U+F05E ban / block constexpr const char* kIconShield = "\xef\x84\xb2"; // U+F132 shield / anti-spam constexpr const char* kIconGamepad = "\xef\x84\x9b"; // U+F11B gamepad / emulator inline int64_t nowMs() { struct timespec ts {}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000; } inline std::string getRuntimeFile(const char* name) { const char* rdir = std::getenv("XDG_RUNTIME_DIR"); std::string base = (rdir && rdir[0]) ? rdir : "/run/user/10000"; if (::access(base.c_str(), W_OK) != 0) { base = "/tmp"; } return base + "/" + name; } inline int readIntFile(const std::string& path, int fallback = -1) { int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); if (fd < 0) { return fallback; } char buf[64]; ssize_t n = ::read(fd, buf, sizeof(buf) - 1); ::close(fd); if (n <= 0) { return fallback; } buf[n] = '\0'; return std::atoi(buf); } inline bool writeIntFile(const std::string& path, int value) { int fd = ::open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0644); if (fd < 0) { return false; } char buf[32]; int len = std::snprintf(buf, sizeof(buf), "%d\n", value); ssize_t w = ::write(fd, buf, len); ::close(fd); return w == len; } inline bool isPidFileAlive(const std::string& path) { int pid = readIntFile(path, -1); return (pid > 0 && ::kill(pid, 0) == 0); } inline std::string getPluginFifoPath(const char* name) { return std::string("/tmp/dwm_plugin_") + name + ".fifo"; } inline std::string getPluginDaemonPidPath(const char* name) { return std::string("/tmp/dwm_plugin_") + name + ".pid"; } inline bool isPluginDaemonAlive(const char* name) { if (!name || !name[0]) { return false; } int pid = readIntFile(getPluginDaemonPidPath(name), -1); if (pid <= 0 || pid == static_cast(::getpid()) || ::kill(pid, 0) != 0) { return false; } char cmdPath[64]; std::snprintf(cmdPath, sizeof(cmdPath), "/proc/%d/cmdline", pid); int fd = ::open(cmdPath, O_RDONLY | O_CLOEXEC); if (fd < 0) { return false; } char buf[256]; ssize_t n = ::read(fd, buf, sizeof(buf) - 1); ::close(fd); if (n <= 0) { return false; } for (ssize_t i = 0; i < n; ++i) { if (buf[i] == '\0') { buf[i] = ' '; } } buf[n] = '\0'; return (std::strstr(buf, name) != nullptr); } inline int acquirePluginDaemonLock(const char* name) { if (!name || !name[0]) { return -1; } std::string lockPath = std::string("/tmp/dwm_plugin_") + name + ".lock"; int fd = ::open(lockPath.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666); if (fd < 0) { return -1; } if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { ::close(fd); return -1; } return fd; } inline bool sendPluginCommand(const char* name, const std::string& cmdLine) { if (!isPluginDaemonAlive(name)) { return false; } std::string fifoPath = getPluginFifoPath(name); int fd = -1; for (int attempt = 0; attempt < 6; ++attempt) { fd = ::open(fifoPath.c_str(), O_WRONLY | O_NONBLOCK | O_CLOEXEC); if (fd >= 0) { break; } ::usleep(25000); } if (fd < 0) { return false; } std::string msg = cmdLine + "\n"; ssize_t w = ::write(fd, msg.data(), msg.size()); ::close(fd); return w == static_cast(msg.size()); } inline int setupPluginDaemonFifo(const char* name) { std::string fifoPath = getPluginFifoPath(name); ::mkfifo(fifoPath.c_str(), 0666); ::chmod(fifoPath.c_str(), 0666); return ::open(fifoPath.c_str(), O_RDWR | O_NONBLOCK | O_CLOEXEC); } inline std::vector readFifoLines(int fifoFd) { std::vector lines; if (fifoFd < 0) { return lines; } char buf[512]; ssize_t n = ::read(fifoFd, buf, sizeof(buf) - 1); if (n <= 0) { return lines; } buf[n] = '\0'; std::stringstream ss(buf); std::string line; while (std::getline(ss, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (!line.empty()) { lines.push_back(line); } } return lines; } inline bool isCallRingingFast() { std::string jobPath = getRuntimeFile("sxmo_jobs/ringing"); if (::access(jobPath.c_str(), F_OK) == 0) { return true; } std::string ringPidFile = getRuntimeFile("sxmo.ring.pid"); int pid = readIntFile(ringPidFile, -1); if (pid > 0 && ::kill(pid, 0) == 0) { return true; } if (::access("/tmp/sxmo_call_ringing", F_OK) == 0) { return true; } return false; } inline bool isCallActiveOrRingingFast() { if (isCallRingingFast()) { return true; } if (::access("/tmp/sxmo_active_call", F_OK) == 0) { return true; } std::string callsDir = getRuntimeFile("sxmo_calls"); DIR* d = ::opendir(callsDir.c_str()); if (!d) { return false; } bool found = false; struct dirent* ent; while ((ent = ::readdir(d)) != nullptr) { if (ent->d_name[0] != '.' && ent->d_name[0] != '\0') { found = true; break; } } ::closedir(d); return found; } struct FileStamp { time_t sec = -1; long nsec = -1; off_t size = -1; bool checkAndUpdate(const std::string& path) { struct stat st {}; if (::stat(path.c_str(), &st) != 0) { if (sec != 0 || size != 0) { sec = 0; nsec = 0; size = 0; return true; } return false; } if (st.st_mtim.tv_sec != sec || st.st_mtim.tv_nsec != nsec || st.st_size != size) { sec = st.st_mtim.tv_sec; nsec = st.st_mtim.tv_nsec; size = st.st_size; return true; } return false; } }; inline void writeSoftkeySuppress(int64_t untilMs) { int fd = ::open("/tmp/sxmo_softkey_suppress", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd >= 0) { char buf[32]; int len = std::snprintf(buf, sizeof(buf), "%lld\n", static_cast(untilMs)); (void)::write(fd, buf, len); ::close(fd); } } inline int querySoftkeysDown(Display* d) { char km[32]; if (!XQueryKeymap(d, km)) { return 0; } int mask = 0; if (km[135 / 8] & (1 << (135 % 8))) { mask |= 1; } if (km[166 / 8] & (1 << (166 % 8))) { mask |= 2; } return mask; } inline bool isKeycodeDown(Display* d, int keycode) { if (keycode <= 0 || keycode >= 256) { return false; } char km[32]; if (!XQueryKeymap(d, km)) { return false; } return (km[keycode / 8] & (1 << (keycode % 8))) != 0; } inline void runAsyncCmd(const std::string& cmd) { pid_t pid = ::fork(); if (pid == 0) { if (::fork() == 0) { ::setsid(); int nullfd = ::open("/dev/null", O_RDWR); if (nullfd >= 0) { ::dup2(nullfd, STDIN_FILENO); ::dup2(nullfd, STDOUT_FILENO); ::dup2(nullfd, STDERR_FILENO); if (nullfd > 2) { ::close(nullfd); } } execl("/bin/sh", "sh", "-c", cmd.c_str(), static_cast(nullptr)); _exit(0); } _exit(0); } else if (pid > 0) { int st = 0; (void)::waitpid(pid, &st, 0); } } inline std::string shellQuote(const std::string& s) { std::string out = "'"; for (char c : s) { if (c == '\'') { out += "'\\''"; } else { out.push_back(c); } } out.push_back('\''); return out; } inline std::string runCaptureCmd(const std::string& cmd, int* exitCodeOut = nullptr) { FILE* fp = ::popen(cmd.c_str(), "r"); if (!fp) { if (exitCodeOut) { *exitCodeOut = -1; } return ""; } std::string out; char buf[512]; while (std::fgets(buf, sizeof(buf), fp) != nullptr) { out += buf; } int status = ::pclose(fp); if (exitCodeOut) { *exitCodeOut = status; } return out; } inline void runAsyncArgv(const char* prog, const char* arg1 = nullptr, const char* arg2 = nullptr, const char* arg3 = nullptr) { pid_t pid = ::fork(); if (pid == 0) { if (::fork() == 0) { ::setsid(); int nullfd = ::open("/dev/null", O_RDWR); if (nullfd >= 0) { ::dup2(nullfd, STDIN_FILENO); ::dup2(nullfd, STDOUT_FILENO); ::dup2(nullfd, STDERR_FILENO); if (nullfd > 2) { ::close(nullfd); } } if (arg1 && arg2 && arg3) { execlp(prog, prog, arg1, arg2, arg3, static_cast(nullptr)); std::string localBin = std::string("/home/user/.local/bin/") + prog; execl(localBin.c_str(), prog, arg1, arg2, arg3, static_cast(nullptr)); std::string usrBin = std::string("/usr/bin/") + prog; execl(usrBin.c_str(), prog, arg1, arg2, arg3, static_cast(nullptr)); } else if (arg1 && arg2) { execlp(prog, prog, arg1, arg2, static_cast(nullptr)); std::string localBin = std::string("/home/user/.local/bin/") + prog; execl(localBin.c_str(), prog, arg1, arg2, static_cast(nullptr)); std::string usrBin = std::string("/usr/bin/") + prog; execl(usrBin.c_str(), prog, arg1, arg2, static_cast(nullptr)); } else if (arg1) { execlp(prog, prog, arg1, static_cast(nullptr)); std::string localBin = std::string("/home/user/.local/bin/") + prog; execl(localBin.c_str(), prog, arg1, static_cast(nullptr)); std::string usrBin = std::string("/usr/bin/") + prog; execl(usrBin.c_str(), prog, arg1, static_cast(nullptr)); } else { execlp(prog, prog, static_cast(nullptr)); std::string localBin = std::string("/home/user/.local/bin/") + prog; execl(localBin.c_str(), prog, static_cast(nullptr)); std::string usrBin = std::string("/usr/bin/") + prog; execl(usrBin.c_str(), prog, static_cast(nullptr)); } _exit(0); } _exit(0); } else if (pid > 0) { int st = 0; (void)::waitpid(pid, &st, 0); } } inline char mapDialKey(KeySym sym, unsigned int keycode, unsigned int state) { if (state & (ControlMask | Mod1Mask | Mod4Mask)) { return '\0'; } // Keypad star (*) if (keycode == 63 || keycode == 530 || sym == XK_asterisk || sym == XK_KP_Multiply || static_cast(sym) == 0x1008ffaa) { return '*'; } // Keypad pound (#) if (keycode == 106 || keycode == 531 || sym == XK_numbersign || sym == XK_KP_Divide || static_cast(sym) == 0x1008ffab) { return '#'; } if (sym == XK_plus || sym == XK_KP_Add) { return '+'; } if (sym >= XK_0 && sym <= XK_9) { return static_cast('0' + (sym - XK_0)); } if (sym >= XK_KP_0 && sym <= XK_KP_9) { return static_cast('0' + (sym - XK_KP_0)); } if (keycode >= 10 && keycode <= 18) { return static_cast('1' + (keycode - 10)); } if (keycode == 19) { return '0'; } return '\0'; } inline bool isLeftSoftkey(KeySym sym, unsigned int keycode) { return sym == XK_Menu || sym == XF86XK_KbdLcdMenu1 || keycode == 135; } inline bool isRightSoftkey(KeySym sym, unsigned int keycode) { return sym == XF86XK_Back || sym == XF86XK_KbdLcdMenu2 || keycode == 166; } inline bool isStarKey(KeySym sym, unsigned int keycode) { return keycode == 63 || keycode == 530 || sym == XK_asterisk || sym == XK_KP_Multiply || static_cast(sym) == 0x1008ffaa; } inline bool isPoundKey(KeySym sym, unsigned int keycode) { return keycode == 106 || keycode == 531 || sym == XK_numbersign || sym == XK_KP_Divide || static_cast(sym) == 0x1008ffab; } inline std::string getHomeDir() { return getHomeDirPath(); } inline bool isPhonePasscodeLocked() { return ::access("/tmp/bananarchy_screen_locked", F_OK) == 0; } inline std::string trimStr(const std::string& s) { size_t b = 0; while (b < s.size() && std::isspace(static_cast(s[b]))) { ++b; } size_t e = s.size(); while (e > b && std::isspace(static_cast(s[e - 1]))) { --e; } return s.substr(b, e - b); } inline std::string normalizePhone(const std::string& raw) { std::string out; out.reserve(raw.size()); for (char c : raw) { if (std::isdigit(static_cast(c)) || c == '+' || c == '*' || c == '#') { out.push_back(c); } } return out; } inline std::string phoneSuffixKey(const std::string& norm) { std::string digits; for (char c : norm) { if (std::isdigit(static_cast(c))) { digits.push_back(c); } } if (digits.size() >= 9) { return digits.substr(digits.size() - 9); } return norm; } inline std::string toLowerStr(const std::string& s) { std::string out = s; for (char& c : out) { c = static_cast(std::tolower(static_cast(c))); } return out; } inline std::string toT9Digits(const std::string& name) { std::string out; out.reserve(name.size()); for (unsigned char uc : name) { char c = static_cast(std::tolower(uc)); if (c >= 'a' && c <= 'c') out.push_back('2'); else if (c >= 'd' && c <= 'f') out.push_back('3'); else if (c >= 'g' && c <= 'i') out.push_back('4'); else if (c >= 'j' && c <= 'l') out.push_back('5'); else if (c >= 'm' && c <= 'o') out.push_back('6'); else if (c >= 'p' && c <= 's') out.push_back('7'); else if (c >= 't' && c <= 'v') out.push_back('8'); else if (c >= 'w' && c <= 'z') out.push_back('9'); else if (c == ' ') out.push_back('0'); else if (std::isdigit(uc)) out.push_back(c); } return out; } inline std::string getContactsFilePath() { const char* env = std::getenv("SXMO_CONTACTFILE"); if (env && env[0]) { return env; } const char* xdg = std::getenv("XDG_CONFIG_HOME"); if (xdg && xdg[0]) { return std::string(xdg) + "/sxmo/contacts.tsv"; } const char* home = std::getenv("HOME"); return std::string(home && home[0] ? home : "/home/user") + "/.config/sxmo/contacts.tsv"; } inline std::string getModemLogFilePath() { const char* env = std::getenv("SXMO_LOGDIR"); if (env && env[0]) { return std::string(env) + "/modemlog.tsv"; } const char* xdg = std::getenv("XDG_DATA_HOME"); if (xdg && xdg[0]) { return std::string(xdg) + "/sxmo/modem/modemlog.tsv"; } const char* home = std::getenv("HOME"); return std::string(home && home[0] ? home : "/home/user") + "/.local/share/sxmo/modem/modemlog.tsv"; } struct ContactEntry { std::string name; std::string number; std::string normNumber; std::string t9Name; std::string lowerName; bool isRecent = false; }; class ContactBook { public: void load() { saved_.clear(); exactMap_.clear(); suffixMap_.clear(); std::ifstream cf(getContactsFilePath()); std::string line; while (std::getline(cf, line)) { if (line.empty()) { continue; } size_t tab = line.find('\t'); if (tab == std::string::npos) { continue; } std::string num = trimStr(line.substr(0, tab)); std::string name = trimStr(line.substr(tab + 1)); std::string norm = normalizePhone(num); if (norm.empty() || name.empty()) { continue; } ContactEntry e; e.name = name; e.number = num; e.normNumber = norm; e.t9Name = toT9Digits(name); e.lowerName = toLowerStr(name); e.isRecent = false; saved_.push_back(e); exactMap_[norm] = name; std::string sfx = phoneSuffixKey(norm); if (!sfx.empty()) { suffixMap_[sfx] = name; } } std::sort(saved_.begin(), saved_.end(), [](const ContactEntry& a, const ContactEntry& b) { return a.lowerName < b.lowerName; }); } std::string resolveName(const std::string& rawNumber) const { std::string norm = normalizePhone(rawNumber); if (norm.empty()) { return ""; } auto it = exactMap_.find(norm); if (it != exactMap_.end()) { return it->second; } std::string sfx = phoneSuffixKey(norm); if (!sfx.empty()) { auto sit = suffixMap_.find(sfx); if (sit != suffixMap_.end()) { return sit->second; } } return ""; } std::vector buildDialerList() const { std::vector out; std::unordered_set seenKey; // 1. Recent unique numbers from modemlog.tsv in reverse chronological order std::ifstream lf(getModemLogFilePath()); std::vector logLines; std::string line; while (std::getline(lf, line)) { if (!line.empty()) { logLines.push_back(line); } } for (auto it = logLines.rbegin(); it != logLines.rend(); ++it) { size_t t1 = it->find('\t'); if (t1 == std::string::npos) continue; size_t t2 = it->find('\t', t1 + 1); if (t2 == std::string::npos) continue; size_t t3 = it->find('\t', t2 + 1); std::string num = trimStr( t3 == std::string::npos ? it->substr(t2 + 1) : it->substr(t2 + 1, t3 - t2 - 1)); if (num.empty() || num == "NULL" || num.find('+', 1) != std::string::npos) { continue; } std::string norm = normalizePhone(num); if (norm.empty()) continue; std::string key = phoneSuffixKey(norm); if (seenKey.count(key) || seenKey.count(norm)) { continue; } seenKey.insert(key); seenKey.insert(norm); ContactEntry e; std::string cname = resolveName(num); e.name = cname.empty() ? num : cname; e.number = num; e.normNumber = norm; e.t9Name = toT9Digits(e.name); e.lowerName = toLowerStr(e.name); e.isRecent = true; out.push_back(e); } // 2. All saved contacts (skipping duplicates already added from recents) for (const auto& c : saved_) { std::string key = phoneSuffixKey(c.normNumber); if (seenKey.count(key) || seenKey.count(c.normNumber)) { continue; } seenKey.insert(key); seenKey.insert(c.normNumber); out.push_back(c); } return out; } const std::vector& savedContacts() const { return saved_; } std::vector unknownRecentNumbers() const { std::vector out; std::unordered_set seen; std::ifstream lf(getModemLogFilePath()); std::vector logLines; std::string line; while (std::getline(lf, line)) { if (!line.empty()) { logLines.push_back(line); } } for (auto it = logLines.rbegin(); it != logLines.rend(); ++it) { size_t t1 = it->find('\t'); if (t1 == std::string::npos) continue; size_t t2 = it->find('\t', t1 + 1); if (t2 == std::string::npos) continue; size_t t3 = it->find('\t', t2 + 1); std::string num = trimStr( t3 == std::string::npos ? it->substr(t2 + 1) : it->substr(t2 + 1, t3 - t2 - 1)); if (num.empty() || num == "NULL" || num.find('+', 1) != std::string::npos) { continue; } std::string norm = normalizePhone(num); if (norm.empty() || !resolveName(num).empty()) { continue; } std::string key = phoneSuffixKey(norm); if (seen.count(key) || seen.count(norm)) { continue; } seen.insert(key); seen.insert(norm); out.push_back(num); } return out; } static void ensureParentDir(const std::string& filePath) { size_t slash = filePath.rfind('/'); if (slash == std::string::npos || slash == 0) { return; } std::string dir = filePath.substr(0, slash); std::string cur; for (size_t i = 0; i < dir.size(); ++i) { cur.push_back(dir[i]); if (dir[i] == '/' && cur.size() > 1) { ::mkdir(cur.c_str(), 0755); } } ::mkdir(dir.c_str(), 0755); } bool addOrUpdateContact(const std::string& oldNumber, const std::string& oldName, const std::string& newNumberRaw, const std::string& newNameRaw) { std::string newNumber = trimStr(newNumberRaw); std::string newName = trimStr(newNameRaw); for (char& ch : newName) { if (ch == '\t' || ch == '\r' || ch == '\n') { ch = ' '; } } if (newNumber.empty() || newName.empty()) { return false; } std::string path = getContactsFilePath(); ensureParentDir(path); std::vector> rows; { std::ifstream in(path); std::string line; while (std::getline(in, line)) { if (line.empty()) continue; size_t tab = line.find('\t'); if (tab == std::string::npos) continue; std::string num = trimStr(line.substr(0, tab)); std::string name = trimStr(line.substr(tab + 1)); if (!num.empty() && !name.empty()) { rows.push_back({num, name}); } } } bool replaced = false; std::string oldNorm = normalizePhone(oldNumber); std::string newNorm = normalizePhone(newNumber); for (auto& r : rows) { if (!oldNumber.empty() && ((r.first == oldNumber && r.second == oldName) || (!oldNorm.empty() && normalizePhone(r.first) == oldNorm && r.second == oldName))) { r.first = newNumber; r.second = newName; replaced = true; break; } } if (!replaced && oldNumber.empty()) { for (auto& r : rows) { if (r.first == newNumber || (!newNorm.empty() && normalizePhone(r.first) == newNorm)) { r.first = newNumber; r.second = newName; replaced = true; break; } } } if (!replaced) { rows.push_back({newNumber, newName}); } std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return false; } for (const auto& r : rows) { out << r.first << "\t" << r.second << "\n"; } out.close(); load(); return true; } int importContactsBatch( const std::vector>& items) { if (items.empty()) { return 0; } std::string path = getContactsFilePath(); ensureParentDir(path); std::vector> rows; { std::ifstream in(path); std::string line; while (std::getline(in, line)) { if (line.empty()) continue; size_t tab = line.find('\t'); if (tab == std::string::npos) continue; std::string num = trimStr(line.substr(0, tab)); std::string name = trimStr(line.substr(tab + 1)); if (!num.empty() && !name.empty()) { rows.push_back({num, name}); } } } int count = 0; for (const auto& item : items) { std::string newNumber = trimStr(item.first); std::string newName = trimStr(item.second); for (char& ch : newName) { if (ch == '\t' || ch == '\r' || ch == '\n') { ch = ' '; } } std::string newNorm = normalizePhone(newNumber); if (newNorm.empty()) { continue; } if (newName.empty()) { newName = newNumber; } bool replaced = false; for (auto& r : rows) { if (r.first == newNumber || (!newNorm.empty() && normalizePhone(r.first) == newNorm)) { r.first = newNumber; r.second = newName; replaced = true; break; } } if (!replaced) { rows.push_back({newNumber, newName}); } ++count; } if (count <= 0) { return 0; } std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return -1; } for (const auto& r : rows) { out << r.first << "\t" << r.second << "\n"; } out.close(); load(); return count; } bool deleteContact(const std::string& number, const std::string& name) { std::string path = getContactsFilePath(); std::vector> rows; std::string targetNorm = normalizePhone(number); bool removed = false; { std::ifstream in(path); std::string line; while (std::getline(in, line)) { if (line.empty()) continue; size_t tab = line.find('\t'); if (tab == std::string::npos) continue; std::string num = trimStr(line.substr(0, tab)); std::string nm = trimStr(line.substr(tab + 1)); if (num.empty() || nm.empty()) continue; if (!removed && ((num == number && nm == name) || (!targetNorm.empty() && normalizePhone(num) == targetNorm && nm == name))) { removed = true; continue; } rows.push_back({num, nm}); } } if (!removed) { return false; } std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return false; } for (const auto& r : rows) { out << r.first << "\t" << r.second << "\n"; } out.close(); load(); return true; } private: std::vector saved_; std::unordered_map exactMap_; std::unordered_map suffixMap_; }; inline std::string getBlockFilePath() { const char* env = std::getenv("SXMO_BLOCKFILE"); if (env && env[0]) { return env; } const char* xdg = std::getenv("XDG_CONFIG_HOME"); if (xdg && xdg[0]) { return std::string(xdg) + "/sxmo/block.tsv"; } const char* home = std::getenv("HOME"); return std::string(home && home[0] ? home : "/home/user") + "/.config/sxmo/block.tsv"; } inline std::string getBlockDirPath() { const char* env = std::getenv("SXMO_BLOCKDIR"); if (env && env[0]) { return env; } const char* xdg = std::getenv("XDG_DATA_HOME"); if (xdg && xdg[0]) { return std::string(xdg) + "/sxmo/block"; } const char* home = std::getenv("HOME"); return std::string(home && home[0] ? home : "/home/user") + "/.local/share/sxmo/block"; } inline std::string getBlockedModemLogFilePath() { return getBlockDirPath() + "/modemlog.tsv"; } struct BlockEntry { std::string number; std::string normNumber; std::string label; }; class BlockList { public: void load() { entries_.clear(); exactSet_.clear(); suffixSet_.clear(); std::ifstream bf(getBlockFilePath()); std::string line; while (std::getline(bf, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty()) { continue; } size_t tab = line.find('\t'); std::string num = trimStr(tab == std::string::npos ? line : line.substr(0, tab)); std::string lbl = tab == std::string::npos ? "" : trimStr(line.substr(tab + 1)); std::string norm = normalizePhone(num); if (norm.empty()) { continue; } BlockEntry e; e.number = num; e.normNumber = norm; e.label = lbl.empty() ? "Blocked" : lbl; entries_.push_back(e); exactSet_.insert(norm); std::string sfx = phoneSuffixKey(norm); if (sfx.size() >= 7) { suffixSet_.insert(sfx); } } } bool isBlocked(const std::string& rawNumber) const { std::string norm = normalizePhone(rawNumber); if (norm.empty()) { return false; } if (exactSet_.count(norm) > 0) { return true; } std::string sfx = phoneSuffixKey(norm); if (sfx.size() >= 7 && suffixSet_.count(sfx) > 0) { return true; } for (const auto& e : entries_) { if (!e.normNumber.empty() && e.normNumber.back() == '*' && e.normNumber.size() > 1) { std::string prefix = e.normNumber.substr(0, e.normNumber.size() - 1); if (norm.rfind(prefix, 0) == 0) { return true; } } } return false; } bool blockNumber(const std::string& rawNumber, const std::string& labelRaw = "") { std::string num = trimStr(rawNumber); std::string norm = normalizePhone(num); if (norm.empty()) { return false; } if (num.find('\t') != std::string::npos || num.find('\n') != std::string::npos) { num = norm; } std::string label = trimStr(labelRaw); for (char& ch : label) { if (ch == '\t' || ch == '\r' || ch == '\n') { ch = ' '; } } if (label.empty()) { label = "Blocked"; } std::string path = getBlockFilePath(); ContactBook::ensureParentDir(path); std::vector> rows; { std::ifstream in(path); std::string line; while (std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty()) continue; size_t tab = line.find('\t'); std::string rNum = trimStr(tab == std::string::npos ? line : line.substr(0, tab)); std::string rLbl = tab == std::string::npos ? "Blocked" : trimStr(line.substr(tab + 1)); if (!normalizePhone(rNum).empty()) { rows.push_back({rNum, rLbl.empty() ? "Blocked" : rLbl}); } } } std::string sfx = phoneSuffixKey(norm); bool updated = false; for (auto& r : rows) { std::string rNorm = normalizePhone(r.first); std::string rSfx = phoneSuffixKey(rNorm); if (rNorm == norm || (sfx.size() >= 7 && rSfx == sfx)) { r.first = num; if (!labelRaw.empty()) { r.second = label; } updated = true; break; } } if (!updated) { rows.push_back({num, label}); } std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return false; } for (const auto& r : rows) { out << r.first << "\t" << r.second << "\n"; } out.close(); load(); return true; } bool unblockNumber(const std::string& rawNumber) { std::string norm = normalizePhone(rawNumber); if (norm.empty()) { return false; } std::string sfx = phoneSuffixKey(norm); std::string path = getBlockFilePath(); std::vector> rows; bool removed = false; { std::ifstream in(path); std::string line; while (std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty()) continue; size_t tab = line.find('\t'); std::string rNum = trimStr(tab == std::string::npos ? line : line.substr(0, tab)); std::string rLbl = tab == std::string::npos ? "Blocked" : trimStr(line.substr(tab + 1)); std::string rNorm = normalizePhone(rNum); if (rNorm.empty()) continue; std::string rSfx = phoneSuffixKey(rNorm); if (rNorm == norm || (sfx.size() >= 7 && rSfx == sfx)) { removed = true; continue; } rows.push_back({rNum, rLbl.empty() ? "Blocked" : rLbl}); } } if (!removed) { return false; } ContactBook::ensureParentDir(path); std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return false; } for (const auto& r : rows) { out << r.first << "\t" << r.second << "\n"; } out.close(); load(); return true; } bool clearAll() { std::string path = getBlockFilePath(); ContactBook::ensureParentDir(path); std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return false; } out.close(); load(); return true; } const std::vector& entries() const { return entries_; } private: std::vector entries_; std::unordered_set exactSet_; std::unordered_set suffixSet_; }; enum class CallDirection { Incoming = 0, Outgoing = 1, Missed = 2, Blocked = 3, }; struct CallLogItem { CallDirection direction; std::string number; std::string contactName; std::string displayTime; int durationSec = 0; bool isBlockedNumber = false; }; inline time_t parseIsoTime(const std::string& iso) { if (iso.size() < 19) { return 0; } struct tm tmVal {}; tmVal.tm_year = std::atoi(iso.substr(0, 4).c_str()) - 1900; tmVal.tm_mon = std::atoi(iso.substr(5, 2).c_str()) - 1; tmVal.tm_mday = std::atoi(iso.substr(8, 2).c_str()); tmVal.tm_hour = std::atoi(iso.substr(11, 2).c_str()); tmVal.tm_min = std::atoi(iso.substr(14, 2).c_str()); tmVal.tm_sec = std::atoi(iso.substr(17, 2).c_str()); tmVal.tm_isdst = -1; return mktime(&tmVal); } inline std::string formatShortTime(const std::string& iso) { if (iso.size() < 16) { return iso; } // Convert "YYYY-MM-DDTHH:MM:SS+0300" -> "MM-DD HH:MM" return iso.substr(5, 5) + " " + iso.substr(11, 5); } inline std::string formatDuration(int sec) { if (sec <= 0) { return ""; } char buf[32]; if (sec >= 3600) { std::snprintf(buf, sizeof(buf), "%dh%02dm", sec / 3600, (sec % 3600) / 60); } else if (sec >= 60) { std::snprintf(buf, sizeof(buf), "%dm%02ds", sec / 60, sec % 60); } else { std::snprintf(buf, sizeof(buf), "%ds", sec); } return buf; } inline std::vector loadCallLogFromFile(const ContactBook& book, const std::string& logPath, bool forceBlockedDir = false) { std::ifstream lf(logPath); std::string line; struct ActiveSession { bool active = false; CallDirection dir = CallDirection::Incoming; std::string number; std::string startTimeStr; time_t startEpoch = 0; time_t answerEpoch = 0; bool answered = false; }; std::vector history; ActiveSession cur; auto flushSession = [&]() { if (!cur.active || cur.number.empty()) { cur = ActiveSession{}; return; } CallLogItem item; item.direction = forceBlockedDir ? CallDirection::Blocked : cur.dir; item.number = cur.number; item.contactName = book.resolveName(cur.number); item.displayTime = formatShortTime(cur.startTimeStr); item.durationSec = 0; history.push_back(item); cur = ActiveSession{}; }; while (std::getline(lf, line)) { if (line.empty()) continue; size_t t1 = line.find('\t'); if (t1 == std::string::npos) continue; size_t t2 = line.find('\t', t1 + 1); if (t2 == std::string::npos) continue; size_t t3 = line.find('\t', t2 + 1); std::string ts = trimStr(line.substr(0, t1)); std::string evt = trimStr(line.substr(t1 + 1, t2 - t1 - 1)); std::string num = trimStr( t3 == std::string::npos ? line.substr(t2 + 1) : line.substr(t2 + 1, t3 - t2 - 1)); if (evt.rfind("call_", 0) != 0 && evt != "ring_muted") { continue; } if (num.empty() || num == "NULL") { continue; } time_t epoch = parseIsoTime(ts); if (evt == "call_blocked") { if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) { cur.dir = CallDirection::Blocked; flushSession(); } else { flushSession(); CallLogItem item; item.direction = CallDirection::Blocked; item.number = num; item.contactName = book.resolveName(num); item.displayTime = formatShortTime(ts); item.durationSec = 0; history.push_back(item); } } else if (evt == "call_ring") { flushSession(); cur.active = true; cur.dir = forceBlockedDir ? CallDirection::Blocked : CallDirection::Missed; cur.number = num; cur.startTimeStr = ts; cur.startEpoch = epoch; cur.answerEpoch = 0; cur.answered = false; } else if (evt == "call_start") { flushSession(); cur.active = true; cur.dir = CallDirection::Outgoing; cur.number = num; cur.startTimeStr = ts; cur.startEpoch = epoch; cur.answerEpoch = epoch; cur.answered = true; } else if (evt == "call_pickup") { if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) { cur.dir = CallDirection::Incoming; cur.answered = true; cur.answerEpoch = epoch; } else { flushSession(); cur.active = true; cur.dir = CallDirection::Incoming; cur.number = num; cur.startTimeStr = ts; cur.startEpoch = epoch; cur.answerEpoch = epoch; cur.answered = true; } } else if (evt == "call_missed") { if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) { cur.dir = forceBlockedDir ? CallDirection::Blocked : CallDirection::Missed; flushSession(); } else { flushSession(); CallLogItem item; item.direction = forceBlockedDir ? CallDirection::Blocked : CallDirection::Missed; item.number = num; item.contactName = book.resolveName(num); item.displayTime = formatShortTime(ts); item.durationSec = 0; history.push_back(item); } } else if (evt == "call_hangup" || evt == "call_finished" || evt == "call_discard") { if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) { if (evt == "call_discard" && !cur.answered && cur.dir != CallDirection::Outgoing) { cur.dir = forceBlockedDir ? CallDirection::Blocked : CallDirection::Missed; } CallLogItem item; item.direction = forceBlockedDir ? CallDirection::Blocked : cur.dir; item.number = cur.number; item.contactName = book.resolveName(cur.number); item.displayTime = formatShortTime(cur.startTimeStr); if (cur.answered && cur.answerEpoch > 0 && epoch >= cur.answerEpoch) { item.durationSec = static_cast(epoch - cur.answerEpoch); } history.push_back(item); cur = ActiveSession{}; } } } flushSession(); std::reverse(history.begin(), history.end()); return history; } inline std::vector loadCallLog(const ContactBook& book) { return loadCallLogFromFile(book, getModemLogFilePath(), false); } inline std::vector loadBlockedCallLog(const ContactBook& book) { return loadCallLogFromFile(book, getBlockedModemLogFilePath(), true); } inline bool clearCallLogFile(const std::string& logPath) { std::ifstream in(logPath); if (!in.is_open()) { return true; } std::vector keep; std::string line; while (std::getline(in, line)) { if (line.empty()) continue; size_t t1 = line.find('\t'); if (t1 == std::string::npos) continue; size_t t2 = line.find('\t', t1 + 1); if (t2 == std::string::npos) continue; std::string evt = trimStr(line.substr(t1 + 1, t2 - t1 - 1)); if (evt.rfind("call_", 0) == 0 || evt == "ring_muted") { continue; } keep.push_back(line); } in.close(); std::ofstream out(logPath, std::ios::trunc); if (!out.is_open()) { return false; } for (const auto& l : keep) { out << l << "\n"; } return true; } struct DualSimInfo { bool dualSimActive = false; bool slot1Present = false; bool slot2Present = false; int preferredSlot = 1; int primaryGwSlot = 1; int secondaryGwSlot = 0; std::string slot1Operator; std::string slot2Operator; std::string slot1Number; std::string slot2Number; std::string slot1Rat; std::string slot2Rat; std::string slot1Label; std::string slot2Label; std::string slot1Short; std::string slot2Short; }; inline DualSimInfo queryDualSimInfo(bool forceRefresh = false) { static DualSimInfo cached; static int64_t lastQueryMs = 0; int64_t now = nowMs(); if (!forceRefresh && lastQueryMs > 0 && (now - lastQueryMs) < 3000) { return cached; } DualSimInfo info; { std::ifstream conf("/etc/conf.d/msm-modem-uim-selection"); std::string line; while (std::getline(conf, line)) { if (line.rfind("preferred_sim_slot=", 0) == 0) { int v = std::atoi(line.c_str() + 19); if (v == 1 || v == 2) info.preferredSlot = v; } } } constexpr int kAfQipcrtr = 42; constexpr uint32_t kQrtrPortCtrl = 0xfffffffeu; constexpr uint32_t kQrtrTypeNewServer = 4; constexpr uint32_t kQrtrTypeNewLookup = 10; constexpr uint32_t kQmiServiceDms = 2; constexpr uint32_t kQmiServiceNas = 3; constexpr uint32_t kQmiServiceUim = 11; struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; }; struct QrtrCtrlPkt { uint32_t cmd; uint32_t service; uint32_t instance; uint32_t node; uint32_t port; } __attribute__((packed)); auto lookupService = [&](uint32_t sid, uint32_t& outNode, uint32_t& outPort) -> bool { int fd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (fd < 0) return false; SockAddrQrtr localSq {}; socklen_t sl = sizeof(localSq); if (::getsockname(fd, reinterpret_cast(&localSq), &sl) < 0) { ::close(fd); return false; } SockAddrQrtr ctrlSq { kAfQipcrtr, localSq.sq_node, kQrtrPortCtrl }; QrtrCtrlPkt lookup { kQrtrTypeNewLookup, sid, 0, 0, 0 }; if (::sendto(fd, &lookup, sizeof(lookup), 0, reinterpret_cast(&ctrlSq), sizeof(ctrlSq)) < 0) { ::close(fd); return false; } bool found = false; for (int i = 0; i < 12; ++i) { struct pollfd pfd { fd, POLLIN, 0 }; if (::poll(&pfd, 1, 40) <= 0) break; QrtrCtrlPkt pkt {}; ssize_t n = ::recv(fd, &pkt, sizeof(pkt), 0); if (n >= static_cast(sizeof(pkt)) && pkt.cmd == kQrtrTypeNewServer) { if (pkt.service == sid && pkt.port != 0) { outNode = pkt.node; outPort = pkt.port; found = true; } if (pkt.service == 0 && pkt.node == 0 && pkt.port == 0) break; } } ::close(fd); return found; }; uint32_t uimNode = 0, uimPort = 0; if (lookupService(kQmiServiceUim, uimNode, uimPort)) { int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (sfd >= 0) { SockAddrQrtr uimSq { kAfQipcrtr, uimNode, uimPort }; uint8_t req[7] = { 0x00, 0x01, 0x00, 0x2F, 0x00, 0x00, 0x00 }; if (::sendto(sfd, req, sizeof(req), 0, reinterpret_cast(&uimSq), sizeof(uimSq)) >= 0) { struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 60) > 0) { uint8_t buf[1024]; ssize_t rlen = ::recv(sfd, buf, sizeof(buf), 0); if (rlen >= 7 && buf[0] == 0x02 && buf[3] == 0x2F) { size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = buf[pos]; uint16_t tl = static_cast(buf[pos + 1]) | (static_cast(buf[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x10 && tl >= 9) { const uint8_t* p = buf + pos; uint16_t gwPri = static_cast(p[0]) | (static_cast(p[1]) << 8); uint16_t gwSec = static_cast(p[4]) | (static_cast(p[5]) << 8); if (gwPri != 0xFFFF) info.primaryGwSlot = ((gwPri >> 8) & 0xFF) + 1; if (gwSec != 0xFFFF) info.secondaryGwSlot = ((gwSec >> 8) & 0xFF) + 1; uint8_t numSlots = p[8]; size_t off = 9; for (uint8_t s = 0; s < numSlots && s < 2; ++s) { if (off + 6 > tl) break; uint8_t cstate = p[off]; if (s == 0) info.slot1Present = (cstate == 1); if (s == 1) info.slot2Present = (cstate == 1); uint8_t numApps = p[off + 5]; off += 6; for (uint8_t a = 0; a < numApps; ++a) { if (off + 7 > tl) break; uint8_t aidLen = p[off + 6]; if (off + 14 + aidLen > tl) break; off += 14 + aidLen; } } } pos += tl; } } } } ::close(sfd); } } info.dualSimActive = info.slot1Present && info.slot2Present && (info.primaryGwSlot == 1 || info.primaryGwSlot == 2) && (info.secondaryGwSlot == 1 || info.secondaryGwSlot == 2); uint32_t nasNode = 0, nasPort = 0; uint32_t dmsNode = 0, dmsPort = 0; bool hasNas = lookupService(kQmiServiceNas, nasNode, nasPort); bool hasDms = lookupService(kQmiServiceDms, dmsNode, dmsPort); auto recvQmiResp = [](int sfd, uint16_t expTxn, uint16_t expMsg, uint8_t* outBuf, size_t maxLen, int timeoutMs) -> ssize_t { int64_t deadline = nowMs() + timeoutMs; while (nowMs() < deadline) { int rem = static_cast(std::max(5, deadline - nowMs())); struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, rem) <= 0) break; ssize_t n = ::recv(sfd, outBuf, maxLen, 0); if (n >= 7 && outBuf[0] == 0x02) { uint16_t rTxn = static_cast(outBuf[1]) | (static_cast(outBuf[2]) << 8); uint16_t rMsg = static_cast(outBuf[3]) | (static_cast(outBuf[4]) << 8); if (rTxn == expTxn && rMsg == expMsg) { return n; } } } return -1; }; auto cleanPrintable = [](const std::string& s) -> std::string { std::string out; for (unsigned char c : s) { if (c >= 32 && c < 127) { out.push_back(static_cast(c)); } } return trimStr(out); }; auto querySubMeta = [&](int slot, int sub, std::string& outOp, std::string& outRat, std::string& outNum) { if (sub < 0) return; if (hasNas) { int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (sfd >= 0) { SockAddrQrtr nasSq { kAfQipcrtr, nasNode, nasPort }; uint8_t buf[1024]; uint8_t bindReq[11] = { 0x00, 0x01, 0x00, 0x45, 0x00, 0x04, 0x00, 0x01, 0x01, 0x00, static_cast(sub) }; ::sendto(sfd, bindReq, sizeof(bindReq), 0, reinterpret_cast(&nasSq), sizeof(nasSq)); recvQmiResp(sfd, 1, 0x0045, buf, sizeof(buf), 60); uint8_t sysReq[7] = { 0x00, 0x02, 0x00, 0x4D, 0x00, 0x00, 0x00 }; ::sendto(sfd, sysReq, sizeof(sysReq), 0, reinterpret_cast(&nasSq), sizeof(nasSq)); ssize_t rlen = recvQmiResp(sfd, 2, 0x004D, buf, sizeof(buf), 60); if (rlen >= 7) { size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = buf[pos]; uint16_t tl = static_cast(buf[pos + 1]) | (static_cast(buf[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tl >= 1 && buf[pos] == 2) { if (tt == 0x14) outRat = "4G"; else if (tt == 0x13 && outRat.empty()) outRat = "3G"; else if (tt == 0x12 && outRat.empty()) outRat = "2G"; } pos += tl; } } uint8_t opReq[7] = { 0x00, 0x03, 0x00, 0x39, 0x00, 0x00, 0x00 }; ::sendto(sfd, opReq, sizeof(opReq), 0, reinterpret_cast(&nasSq), sizeof(nasSq)); rlen = recvQmiResp(sfd, 3, 0x0039, buf, sizeof(buf), 60); if (rlen >= 7) { size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = buf[pos]; uint16_t tl = static_cast(buf[pos + 1]) | (static_cast(buf[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x10 && tl >= 2) { uint8_t slen = buf[pos + 1]; if (2 + slen <= tl && slen > 0) { std::string raw(reinterpret_cast(buf + pos + 2), slen); outOp = cleanPrintable(raw); } } else if (tt == 0x13 && tl > 0 && outOp.empty()) { std::string raw(reinterpret_cast(buf + pos), tl); outOp = cleanPrintable(raw); } pos += tl; } } ::close(sfd); } } if (hasDms) { int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (sfd >= 0) { SockAddrQrtr dmsSq { kAfQipcrtr, dmsNode, dmsPort }; uint8_t buf[512]; uint8_t bindReq[14] = { 0x00, 0x01, 0x00, 0x54, 0x00, 0x07, 0x00, 0x01, 0x04, 0x00, static_cast(sub + 1), 0x00, 0x00, 0x00 }; ::sendto(sfd, bindReq, sizeof(bindReq), 0, reinterpret_cast(&dmsSq), sizeof(dmsSq)); recvQmiResp(sfd, 1, 0x0054, buf, sizeof(buf), 60); uint8_t msReq[7] = { 0x00, 0x02, 0x00, 0x24, 0x00, 0x00, 0x00 }; ::sendto(sfd, msReq, sizeof(msReq), 0, reinterpret_cast(&dmsSq), sizeof(dmsSq)); ssize_t rlen = recvQmiResp(sfd, 2, 0x0024, buf, sizeof(buf), 60); if (rlen >= 7) { size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = buf[pos]; uint16_t tl = static_cast(buf[pos + 1]) | (static_cast(buf[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x01 && tl > 0) { std::string raw(reinterpret_cast(buf + pos), tl); std::string digits; for (char c : raw) { if ((c >= '0' && c <= '9') || (c == '+' && digits.empty())) { digits.push_back(c); } } if (!digits.empty()) { outNum = (digits.front() == '+') ? digits : ("+" + digits); } } pos += tl; } } ::close(sfd); } } (void)slot; }; int sub1 = (info.primaryGwSlot == 1) ? 0 : ((info.secondaryGwSlot == 1) ? 1 : -1); int sub2 = (info.primaryGwSlot == 2) ? 0 : ((info.secondaryGwSlot == 2) ? 1 : -1); querySubMeta(1, sub1, info.slot1Operator, info.slot1Rat, info.slot1Number); querySubMeta(2, sub2, info.slot2Operator, info.slot2Rat, info.slot2Number); auto formatSlotStrings = [](int s, const std::string& op, const std::string& rat, const std::string& num, std::string& outLabel, std::string& outShort) { (void)num; std::string base = "SIM " + std::to_string(s); outShort = op.empty() ? base : (base + " (" + op + ")"); outLabel = base; if (!op.empty()) { outLabel += ": " + op; } if (!rat.empty()) { outLabel += " [" + rat + "]"; } }; formatSlotStrings(1, info.slot1Operator, info.slot1Rat, info.slot1Number, info.slot1Label, info.slot1Short); formatSlotStrings(2, info.slot2Operator, info.slot2Rat, info.slot2Number, info.slot2Label, info.slot2Short); cached = info; lastQueryMs = now; return info; } inline void placePhoneCall(const std::string& rawNumber, int simSlot = 0) { std::string num = normalizePhone(rawNumber); if (num.empty()) { return; } if (simSlot == 0) { DualSimInfo dsi = queryDualSimInfo(); if (dsi.dualSimActive) { if (!sendPluginCommand("callscreen", "PROMPT_SIM " + num)) { runAsyncArgv("sxmo_modemdial.sh", num.c_str()); } return; } simSlot = (dsi.primaryGwSlot == 2) ? 2 : 1; } std::string simTag = "SIM" + std::to_string(simSlot); if (!sendPluginCommand("callscreen", "OUTGOING - " + num + " " + simTag)) { runAsyncArgv("xcallscreen", "outgoing", "-", num.c_str()); } std::string simStr = std::to_string(simSlot); runAsyncArgv("sxmo_modemdial.sh", "--sim", simStr.c_str(), num.c_str()); } inline void closeOtherPlugins(const char* selfPluginName) { struct PluginRef { const char* pidFile; const char* name; }; static const PluginRef kAllPlugins[] = { {"xdrawer.pid", "xdrawer"}, {"xdialer.pid", "dialer"}, {"xcalllog.pid", "calllog"}, {"xcallscreen.pid", "callscreen"}, {"xcontacts.pid", "contacts"}, {"xsms.pid", "sms"}, {"xfiles.pid", "files"}, {"xcamera.pid", "camera"}, {"xthemes.pid", "themes"}, {"xmodem.pid", "modem"}, {"xnetworks.pid", "networks"}, {"xringtones.pid", "ringtones"}, {"xwallpapers.pid", "wallpapers"}, {"xmusic.pid", "music"}, {"xsip.pid", "sip"}, {"xemail.pid", "email"}, {"xirc.pid", "irc"}, {"xtox.pid", "tox"}, {"xsmallweb.pid", "smallweb"}, {"xgps.pid", "gps"}, }; for (const auto& p : kAllPlugins) { if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) { continue; } if (isPidFileAlive(getRuntimeFile(p.pidFile))) { sendPluginCommand(p.name, "CLOSE"); } } if ((!selfPluginName || std::strcmp(selfPluginName, "dmenu") != 0) && ::access("/tmp/dwm_plugin_dmenu.active", F_OK) == 0) { sendPluginCommand("dmenu", "CLOSE"); } } inline bool isAnotherPluginActive(const char* selfPluginName) { struct PluginRef { const char* pidFile; const char* name; }; static const PluginRef kAllPlugins[] = { {"xlocker.pid", "locker"}, {"xdrawer.pid", "xdrawer"}, {"xdialer.pid", "dialer"}, {"xcalllog.pid", "calllog"}, {"xcallscreen.pid", "callscreen"}, {"xcontacts.pid", "contacts"}, {"xsms.pid", "sms"}, {"xfiles.pid", "files"}, {"xcamera.pid", "camera"}, {"xthemes.pid", "themes"}, {"xmodem.pid", "modem"}, {"xnetworks.pid", "networks"}, {"xringtones.pid", "ringtones"}, {"xwallpapers.pid", "wallpapers"}, {"xmusic.pid", "music"}, {"xsip.pid", "sip"}, {"xemail.pid", "email"}, {"xirc.pid", "irc"}, {"xtox.pid", "tox"}, {"xsmallweb.pid", "smallweb"}, {"xgps.pid", "gps"}, }; for (const auto& p : kAllPlugins) { if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) { continue; } if (isPidFileAlive(getRuntimeFile(p.pidFile))) { return true; } } if ((!selfPluginName || std::strcmp(selfPluginName, "dmenu") != 0) && ::access("/tmp/dwm_plugin_dmenu.active", F_OK) == 0) { return true; } return false; } inline void grabPluginKeyboard(Display* dpy, Window win) { for (int i = 0; i < 40; ++i) { if (XGrabKeyboard(dpy, win, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess) { break; } ::usleep(3000); } XSetInputFocus(dpy, win, RevertToPointerRoot, CurrentTime); } inline void broadcastThemeReload(const char* selfPluginName = nullptr) { static const char* kPlugins[] = { "dmenu", "locker", "xdrawer", "dialer", "calllog", "callscreen", "contacts", "sms", "files", "camera", "themes", "modem", "networks", "ringtones", "wallpapers", "music", "sip", "email", "irc", "tox", "smallweb", "gps", }; for (const char* name : kPlugins) { if (selfPluginName && std::strcmp(name, selfPluginName) == 0) { continue; } std::string fifoPath = getPluginFifoPath(name); int fd = ::open(fifoPath.c_str(), O_WRONLY | O_NONBLOCK | O_CLOEXEC); if (fd >= 0) { (void)::write(fd, "RELOAD_THEME\n", 13); ::close(fd); } } runAsyncCmd("pkill -USR1 -x st >/dev/null 2>&1"); } inline std::string getModemLogDirPath() { const char* env = std::getenv("SXMO_LOGDIR"); if (env && env[0]) { return env; } const char* xdg = std::getenv("XDG_DATA_HOME"); if (xdg && xdg[0]) { return std::string(xdg) + "/sxmo/modem"; } const char* home = std::getenv("HOME"); return std::string(home && home[0] ? home : "/home/user") + "/.local/share/sxmo/modem"; } struct SmsMessage { bool incoming = true; std::string sender; std::string isoTime; std::string displayTime; time_t epoch = 0; std::string text; }; struct SmsThread { std::string number; std::string normNumber; std::string contactName; std::string t9Name; std::string lowerName; std::string lastPreview; std::string lastDisplayTime; time_t lastEpoch = 0; bool lastIncoming = true; bool hasDraft = false; bool isBlocked = false; int messageCount = 0; }; inline bool parseSmsHeaderLine(const std::string& line, bool* outIncoming, std::string* outSender, std::string* outIsoTime) { if (line.empty() || line.back() != ':') { return false; } if (line.rfind("Received at ", 0) == 0 && line.size() > 13) { *outIncoming = true; outSender->clear(); *outIsoTime = line.substr(12, line.size() - 13); return true; } if (line.rfind("Received from ", 0) == 0) { size_t atPos = line.find(" at "); if (atPos != std::string::npos && atPos + 4 < line.size() - 1) { *outIncoming = true; *outSender = line.substr(14, atPos - 14); *outIsoTime = line.substr(atPos + 4, line.size() - (atPos + 4) - 1); return true; } } if (line.rfind("Sent at ", 0) == 0 && line.size() > 9) { *outIncoming = false; outSender->clear(); *outIsoTime = line.substr(8, line.size() - 9); return true; } return false; } inline std::vector loadSmsThreadMessages( const std::string& number, const std::string& customBaseDir = "") { std::vector msgs; std::string baseDir = customBaseDir.empty() ? getModemLogDirPath() : customBaseDir; std::string path = baseDir + "/" + number + "/sms.txt"; std::ifstream in(path); if (!in.is_open()) { return msgs; } std::string line; bool hasCur = false; SmsMessage cur; auto flushCur = [&]() { if (!hasCur) { return; } while (!cur.text.empty() && (cur.text.back() == '\n' || cur.text.back() == '\r')) { cur.text.pop_back(); } msgs.push_back(cur); cur = SmsMessage{}; hasCur = false; }; while (std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } bool inc = true; std::string sender; std::string iso; if (parseSmsHeaderLine(line, &inc, &sender, &iso)) { flushCur(); hasCur = true; cur.incoming = inc; cur.sender = sender.empty() ? number : sender; cur.isoTime = iso; cur.displayTime = formatShortTime(iso); cur.epoch = parseIsoTime(iso); cur.text.clear(); } else if (hasCur) { if (!cur.text.empty()) { cur.text.push_back('\n'); } cur.text += line; } else if (!trimStr(line).empty()) { hasCur = true; cur.incoming = true; cur.sender = number; cur.text = line; } } flushCur(); return msgs; } inline std::string loadSmsDraft(const std::string& number) { if (number.empty()) { return ""; } std::string path = getModemLogDirPath() + "/" + number + "/draft.txt"; std::ifstream in(path); if (!in.is_open()) { return ""; } std::ostringstream ss; ss << in.rdbuf(); std::string s = ss.str(); while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) { s.pop_back(); } if (s == "Enter message here") { return ""; } return s; } inline bool saveSmsDraft(const std::string& number, const std::string& text) { if (number.empty()) { return false; } std::string dir = getModemLogDirPath() + "/" + number; std::string path = dir + "/draft.txt"; if (trimStr(text).empty()) { ::unlink(path.c_str()); return true; } ContactBook::ensureParentDir(path); std::ofstream out(path, std::ios::trunc); if (!out.is_open()) { return false; } out << text << "\n"; return true; } inline void removeSmsDraft(const std::string& number) { if (number.empty()) { return; } std::string path = getModemLogDirPath() + "/" + number + "/draft.txt"; ::unlink(path.c_str()); } inline bool deleteSmsThread(const std::string& number, const std::string& customBaseDir = "") { if (number.empty()) { return false; } std::string baseDir = customBaseDir.empty() ? getModemLogDirPath() : customBaseDir; std::string dir = baseDir + "/" + number; std::string smsPath = dir + "/sms.txt"; std::string draftPath = dir + "/draft.txt"; ::unlink(smsPath.c_str()); ::unlink(draftPath.c_str()); ::rmdir(dir.c_str()); return true; } inline bool moveSmsThreadBetweenDirs(const std::string& number, const std::string& fromBaseDir, const std::string& toBaseDir) { if (number.empty()) { return false; } std::string srcPath = fromBaseDir + "/" + number + "/sms.txt"; std::ifstream in(srcPath); if (!in.is_open()) { return false; } std::ostringstream ss; ss << in.rdbuf(); in.close(); std::string content = ss.str(); if (content.empty()) { return false; } std::string dstPath = toBaseDir + "/" + number + "/sms.txt"; ContactBook::ensureParentDir(dstPath); std::ofstream out(dstPath, std::ios::app); if (!out.is_open()) { return false; } out << content; out.close(); deleteSmsThread(number, fromBaseDir); return true; } inline std::vector loadSmsThreads( const ContactBook& book, const std::string& customBaseDir = "") { std::vector threads; bool isSpamDir = !customBaseDir.empty(); std::string baseDir = isSpamDir ? customBaseDir : getModemLogDirPath(); DIR* d = ::opendir(baseDir.c_str()); if (!d) { return threads; } struct dirent* ent; while ((ent = ::readdir(d)) != nullptr) { std::string name = ent->d_name; if (name.empty() || name[0] == '.') { continue; } std::string subDir = baseDir + "/" + name; struct stat st {}; if (::stat(subDir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) { continue; } std::string smsPath = subDir + "/sms.txt"; std::string draftPath = subDir + "/draft.txt"; bool hasSms = (::access(smsPath.c_str(), R_OK) == 0); std::string draft = isSpamDir ? "" : loadSmsDraft(name); bool hasDraft = !draft.empty(); if (!hasSms && !hasDraft) { continue; } auto msgs = loadSmsThreadMessages(name, baseDir); if (msgs.empty() && !hasDraft) { continue; } SmsThread th; th.number = name; th.normNumber = normalizePhone(name); th.contactName = book.resolveName(name); std::string label = th.contactName.empty() ? name : th.contactName; th.t9Name = toT9Digits(label); th.lowerName = toLowerStr(label); th.hasDraft = hasDraft; th.messageCount = static_cast(msgs.size()); if (!msgs.empty()) { const auto& last = msgs.back(); th.lastIncoming = last.incoming; th.lastDisplayTime = last.displayTime; th.lastEpoch = last.epoch; std::string prev = last.text; for (char& c : prev) { if (c == '\n' || c == '\r' || c == '\t') { c = ' '; } } th.lastPreview = hasDraft ? ("[Draft] " + draft) : prev; } else { th.lastIncoming = false; th.lastPreview = "[Draft] " + draft; struct stat dst {}; if (::stat(draftPath.c_str(), &dst) == 0) { th.lastEpoch = dst.st_mtim.tv_sec; } } if (th.lastEpoch == 0 && ::stat(smsPath.c_str(), &st) == 0) { th.lastEpoch = st.st_mtim.tv_sec; } threads.push_back(th); } ::closedir(d); std::sort(threads.begin(), threads.end(), [](const SmsThread& a, const SmsThread& b) { if (a.lastEpoch != b.lastEpoch) { return a.lastEpoch > b.lastEpoch; } return a.number < b.number; }); return threads; } struct DeviceImeis { std::string imei1; std::string imei2; std::string imeiSv; }; inline bool queryQrtrDmsImeis(DeviceImeis& out) { constexpr int kAfQipcrtr = 42; constexpr uint32_t kQrtrPortCtrl = 0xfffffffeu; constexpr uint32_t kQrtrTypeNewServer = 4; constexpr uint32_t kQrtrTypeNewLookup = 10; constexpr uint32_t kQmiServiceDms = 2; struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; }; struct QrtrCtrlPkt { uint32_t cmd; uint32_t service; uint32_t instance; uint32_t node; uint32_t port; } __attribute__((packed)); int fd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (fd < 0) return false; SockAddrQrtr localSq {}; socklen_t sl = sizeof(localSq); if (::getsockname(fd, reinterpret_cast(&localSq), &sl) < 0) { ::close(fd); return false; } SockAddrQrtr ctrlSq {}; ctrlSq.sq_family = kAfQipcrtr; ctrlSq.sq_node = localSq.sq_node; ctrlSq.sq_port = kQrtrPortCtrl; QrtrCtrlPkt lookup {}; lookup.cmd = kQrtrTypeNewLookup; lookup.service = kQmiServiceDms; lookup.instance = 0; if (::sendto(fd, &lookup, sizeof(lookup), 0, reinterpret_cast(&ctrlSq), sizeof(ctrlSq)) < 0) { ::close(fd); return false; } uint32_t dmsNode = 0; uint32_t dmsPort = 0; bool foundDms = false; for (int i = 0; i < 8; ++i) { struct pollfd pfd { fd, POLLIN, 0 }; if (::poll(&pfd, 1, 60) <= 0) break; QrtrCtrlPkt pkt {}; ssize_t n = ::recv(fd, &pkt, sizeof(pkt), 0); if (n >= static_cast(sizeof(pkt)) && pkt.cmd == kQrtrTypeNewServer) { if (pkt.service == kQmiServiceDms && pkt.port != 0) { dmsNode = pkt.node; dmsPort = pkt.port; foundDms = true; break; } if (pkt.service == 0 && pkt.node == 0 && pkt.port == 0) { break; } } } ::close(fd); if (!foundDms) return false; auto querySubImei = [&](uint32_t subType, std::string& imeiOut, std::string& svOut) { int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (sfd < 0) return; SockAddrQrtr dmsSq {}; dmsSq.sq_family = kAfQipcrtr; dmsSq.sq_node = dmsNode; dmsSq.sq_port = dmsPort; // 1. QMI_DMS_BIND_SUBSCRIPTION (0x0054), TLV 0x01 = uint32_t(subType) if (subType > 0) { uint8_t bindReq[14] = { 0x00, 0x01, 0x00, // flags=0 (req), txn_id=1 0x54, 0x00, // msg_id = 0x0054 0x07, 0x00, // tlv_len = 7 0x01, 0x04, 0x00, // TLV 0x01, len 4 static_cast(subType & 0xFF), 0x00, 0x00, 0x00 }; ::sendto(sfd, bindReq, sizeof(bindReq), 0, reinterpret_cast(&dmsSq), sizeof(dmsSq)); struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 60) > 0) { uint8_t discard[256]; ::recv(sfd, discard, sizeof(discard), 0); } } // 2. QMI_DMS_GET_DEVICE_SERIAL_NUMBERS (0x0025) uint8_t getIdsReq[7] = { 0x00, 0x02, 0x00, // flags=0 (req), txn_id=2 0x25, 0x00, // msg_id = 0x0025 0x00, 0x00 // tlv_len = 0 }; if (::sendto(sfd, getIdsReq, sizeof(getIdsReq), 0, reinterpret_cast(&dmsSq), sizeof(dmsSq)) >= 0) { struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 80) > 0) { uint8_t buf[512]; ssize_t rlen = ::recv(sfd, buf, sizeof(buf), 0); if (rlen >= 7 && buf[0] == 0x02 && buf[3] == 0x25 && buf[4] == 0x00) { size_t tlvLen = static_cast(buf[5]) | (static_cast(buf[6]) << 8); size_t pos = 7; size_t end = std::min(static_cast(rlen), 7 + tlvLen); while (pos + 3 <= end) { uint8_t tType = buf[pos]; size_t tLen = static_cast(buf[pos + 1]) | (static_cast(buf[pos + 2]) << 8); pos += 3; if (pos + tLen > end) break; if (tType == 0x11 && tLen > 0) { imeiOut.assign(reinterpret_cast(buf + pos), tLen); imeiOut = trimStr(imeiOut); } else if (tType == 0x13 && tLen > 0 && svOut.empty()) { svOut.assign(reinterpret_cast(buf + pos), tLen); svOut = trimStr(svOut); } pos += tLen; } } } } ::close(sfd); }; querySubImei(1, out.imei1, out.imeiSv); if (out.imei1.empty()) { querySubImei(0, out.imei1, out.imeiSv); } querySubImei(2, out.imei2, out.imeiSv); return !out.imei1.empty() || !out.imei2.empty(); } inline DeviceImeis queryDeviceImeis() { static DeviceImeis cached; if (!cached.imei1.empty() && !cached.imei2.empty()) { return cached; } DeviceImeis res = cached; queryQrtrDmsImeis(res); if (res.imei1.empty() || res.imei2.empty()) { std::string helperOut = runCaptureCmd( "doas -n /usr/libexec/msm-modem-uim-selection imei 2>/dev/null"); std::istringstream ss(helperOut); std::string line; while (std::getline(ss, line)) { if (line.rfind("IMEI1=", 0) == 0 && res.imei1.empty()) { res.imei1 = trimStr(line.substr(6)); } else if (line.rfind("IMEI2=", 0) == 0 && res.imei2.empty()) { res.imei2 = trimStr(line.substr(6)); } else if (line.rfind("IMEI_SV=", 0) == 0 && res.imeiSv.empty()) { res.imeiSv = trimStr(line.substr(8)); } } } if (res.imei2.empty() && !res.imei1.empty()) { res.imei2 = res.imei1; } if (!res.imei1.empty()) { cached = res; } return res; } inline bool isUssdCode(const std::string& code) { std::string s = trimStr(code); return s.size() >= 3 && (s.front() == '*' || s.front() == '#') && s.back() == '#'; } inline std::string sendModemUssd(const std::string& input, bool isReply = false, bool* outSessionActive = nullptr, int simSlot = 0) { if (outSessionActive) *outSessionActive = false; std::string clean = trimStr(input); if (clean.empty()) return "Empty USSD request."; int rc = 0; std::string mode = (isReply && !isUssdCode(clean)) ? "respond" : "initiate"; std::string simArg = (simSlot == 1 || simSlot == 2) ? ("--sim " + std::to_string(simSlot) + " ") : ""; std::string cmd = "doas -n /usr/libexec/msm-modem-uim-selection ussd " + mode + " " + simArg + shellQuote(clean) + " 2>&1"; std::string out = trimStr(runCaptureCmd(cmd, &rc)); if (out.empty()) { out = (rc == 0) ? "USSD request completed." : "USSD request failed."; } if (outSessionActive) { std::ifstream stIn("/tmp/sxmo_ussd_session_state"); std::string qmiSt; if (stIn.is_open() && std::getline(stIn, qmiSt) && qmiSt.find("user-response") != std::string::npos) { *outSessionActive = true; } else { std::string stOut = runCaptureCmd( "mmcli -m any --3gpp-ussd-status -K 2>/dev/null | grep -E 'modem\\.3gpp\\.ussd\\.(status|state)'"); if (stOut.find("user-response") != std::string::npos) { *outSessionActive = true; } } } // Log USSD event to modemlog.tsv std::string logPath = getModemLogFilePath(); ContactBook::ensureParentDir(logPath); std::ofstream logOut(logPath, std::ios::app); if (logOut.is_open()) { std::time_t now = std::time(nullptr); struct tm tmNow {}; localtime_r(&now, &tmNow); char tbuf[32]; std::strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tmNow); std::string oneLine = out; for (char& c : oneLine) { if (c == '\n' || c == '\r' || c == '\t') c = ' '; } logOut << tbuf << "\tussd\t" << clean << "\t" << oneLine << "\n"; } return out; } inline void cancelModemUssd() { runAsyncCmd( "doas -n /usr/libexec/msm-modem-uim-selection ussd cancel >/dev/null 2>&1 " "|| mmcli -m any --3gpp-ussd-cancel >/dev/null 2>&1"); } inline bool decodeEfAdnRecord(const uint8_t* raw, size_t len, std::string& outNum, std::string& outName) { if (!raw || len < 14) return false; size_t alphaLen = len - 14; uint8_t bcdLen = raw[alphaLen]; uint8_t tonNpi = raw[alphaLen + 1]; if (bcdLen == 0 || bcdLen > 11 || bcdLen == 0xFF) return false; outNum.clear(); if (((tonNpi >> 4) & 0x07) == 1) { outNum.push_back('+'); } auto nibToChar = [](uint8_t nib) -> char { if (nib <= 9) return static_cast('0' + nib); if (nib == 0x0A) return '*'; if (nib == 0x0B) return '#'; if (nib == 0x0C) return 'p'; return '\0'; }; size_t bcdBytes = std::min(10, bcdLen - 1); for (size_t i = 0; i < bcdBytes; ++i) { uint8_t b = raw[alphaLen + 2 + i]; if (b == 0xFF) break; char d1 = nibToChar(b & 0x0F); if (!d1) break; outNum.push_back(d1); uint8_t hi = (b >> 4) & 0x0F; if (hi == 0x0F) break; char d2 = nibToChar(hi); if (!d2) break; outNum.push_back(d2); } if (outNum.empty() || outNum == "+") return false; size_t aEnd = alphaLen; while (aEnd > 0 && raw[aEnd - 1] == 0xFF) { --aEnd; } outName.clear(); if (aEnd > 0 && raw[0] == 0x80) { for (size_t i = 1; i + 1 < aEnd; i += 2) { uint16_t cp = (static_cast(raw[i]) << 8) | static_cast(raw[i + 1]); if (cp == 0xFFFF || cp == 0) break; if (cp < 0x80) { if (cp >= 32 && cp != '\t') outName.push_back(static_cast(cp)); } else if (cp < 0x800) { outName.push_back(static_cast(0xC0 | (cp >> 6))); outName.push_back(static_cast(0x80 | (cp & 0x3F))); } else { outName.push_back(static_cast(0xE0 | (cp >> 12))); outName.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); outName.push_back(static_cast(0x80 | (cp & 0x3F))); } } } else { for (size_t i = 0; i < aEnd; ++i) { uint8_t b = raw[i]; if (b == 0xFF) break; if (b >= 32 && b < 127 && b != '\t') { outName.push_back(static_cast(b)); } } } outName = trimStr(outName); if (outName.empty()) outName = outNum; return true; } inline bool encodeEfAdnRecord(const std::string& rawNum, const std::string& rawName, size_t recSize, std::vector& outRec) { if (recSize < 14) return false; outRec.assign(recSize, 0xFF); size_t alphaLen = recSize - 14; std::string cleanNum = normalizePhone(rawNum); if (cleanNum.empty()) return false; bool isIntl = (cleanNum.front() == '+'); uint8_t tonNpi = isIntl ? 0x91 : 0x81; std::vector nibs; for (char c : cleanNum) { if (c == '+') continue; if (c >= '0' && c <= '9') nibs.push_back(static_cast(c - '0')); else if (c == '*') nibs.push_back(0x0A); else if (c == '#') nibs.push_back(0x0B); if (nibs.size() >= 20) break; } if (nibs.empty()) return false; std::string name = trimStr(rawName); if (name.empty()) name = cleanNum; bool pureAscii = true; for (unsigned char uc : name) { if (uc >= 0x80) { pureAscii = false; break; } } if (pureAscii) { size_t n = std::min(name.size(), alphaLen); for (size_t i = 0; i < n; ++i) { unsigned char uc = static_cast(name[i]); outRec[i] = (uc >= 32 && uc < 127) ? uc : static_cast(' '); } } else if (alphaLen >= 3) { outRec[0] = 0x80; size_t outPos = 1; size_t i = 0; while (i < name.size() && outPos + 1 < alphaLen) { uint32_t cp = 0; unsigned char c0 = static_cast(name[i]); if (c0 < 0x80) { cp = c0; i += 1; } else if ((c0 & 0xE0) == 0xC0 && i + 1 < name.size()) { cp = ((c0 & 0x1F) << 6) | (static_cast(name[i + 1]) & 0x3F); i += 2; } else if ((c0 & 0xF0) == 0xE0 && i + 2 < name.size()) { cp = ((c0 & 0x0F) << 12) | ((static_cast(name[i + 1]) & 0x3F) << 6) | (static_cast(name[i + 2]) & 0x3F); i += 3; } else { i += 1; continue; } if (cp <= 0xFFFF) { outRec[outPos++] = static_cast((cp >> 8) & 0xFF); outRec[outPos++] = static_cast(cp & 0xFF); } } } size_t bcdBytes = (nibs.size() + 1) / 2; outRec[alphaLen] = static_cast(1 + bcdBytes); outRec[alphaLen + 1] = tonNpi; for (size_t i = 0; i < nibs.size(); ++i) { size_t bIdx = alphaLen + 2 + (i / 2); if ((i % 2) == 0) { outRec[bIdx] = (outRec[bIdx] & 0xF0) | (nibs[i] & 0x0F); } else { outRec[bIdx] = (outRec[bIdx] & 0x0F) | ((nibs[i] & 0x0F) << 4); } } return true; } inline bool openQrtrUimSocket(int& outSock, uint32_t& outNode, uint32_t& outPort) { constexpr int kAfQipcrtr = 42; constexpr uint32_t kQrtrPortCtrl = 0xfffffffeu; constexpr uint32_t kQrtrTypeNewServer = 4; constexpr uint32_t kQrtrTypeNewLookup = 10; constexpr uint32_t kQmiServiceUim = 11; struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; }; struct QrtrCtrlPkt { uint32_t cmd; uint32_t service; uint32_t instance; uint32_t node; uint32_t port; } __attribute__((packed)); int lfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (lfd < 0) return false; SockAddrQrtr localSq {}; socklen_t sl = sizeof(localSq); if (::getsockname(lfd, reinterpret_cast(&localSq), &sl) < 0) { ::close(lfd); return false; } SockAddrQrtr ctrlSq {}; ctrlSq.sq_family = kAfQipcrtr; ctrlSq.sq_node = localSq.sq_node; ctrlSq.sq_port = kQrtrPortCtrl; QrtrCtrlPkt lookup {}; lookup.cmd = kQrtrTypeNewLookup; lookup.service = kQmiServiceUim; lookup.instance = 0; if (::sendto(lfd, &lookup, sizeof(lookup), 0, reinterpret_cast(&ctrlSq), sizeof(ctrlSq)) < 0) { ::close(lfd); return false; } bool found = false; for (int i = 0; i < 16; ++i) { struct pollfd pfd { lfd, POLLIN, 0 }; if (::poll(&pfd, 1, 80) <= 0) break; QrtrCtrlPkt pkt {}; ssize_t n = ::recv(lfd, &pkt, sizeof(pkt), 0); if (n >= static_cast(sizeof(pkt)) && pkt.cmd == kQrtrTypeNewServer) { if (pkt.service == kQmiServiceUim && pkt.port != 0) { outNode = pkt.node; outPort = pkt.port; found = true; } if (pkt.service == 0 && pkt.node == 0 && pkt.port == 0) { break; } } } ::close(lfd); if (!found) return false; outSock = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); return outSock >= 0; } inline bool queryQrtrUimAdnGeometry(int sfd, uint32_t uimNode, uint32_t uimPort, int slotNum, uint8_t& outSessionType, std::vector& outFileTlvVal, uint16_t& outRecSize, uint16_t& outRecCount) { struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; } uimSq { 42, uimNode, uimPort }; uint8_t sessionCandidates[2] = { static_cast((slotNum == 2) ? 7 : 6), 0 }; struct FilePathSpec { uint16_t fileId; uint8_t pathLen; uint8_t pathBytes[6]; } fileSpecs[2] = { { 0x6F3A, 4, { 0x00, 0x3F, 0x10, 0x7F, 0x00, 0x00 } }, { 0x4F3A, 6, { 0x00, 0x3F, 0x10, 0x7F, 0x3A, 0x5F } } }; uint16_t txnId = 1; for (uint8_t stype : sessionCandidates) { for (const auto& fs : fileSpecs) { std::vector fval; fval.push_back(static_cast(fs.fileId & 0xFF)); fval.push_back(static_cast((fs.fileId >> 8) & 0xFF)); fval.push_back(fs.pathLen); for (uint8_t k = 0; k < fs.pathLen; ++k) { fval.push_back(fs.pathBytes[k]); } std::vector req(7); req[0] = 0x00; req[1] = static_cast(txnId & 0xFF); req[2] = static_cast((txnId >> 8) & 0xFF); ++txnId; req[3] = 0x24; req[4] = 0x00; // TLV 0x01: Session req.push_back(0x01); req.push_back(0x02); req.push_back(0x00); req.push_back(stype); req.push_back(0x00); // TLV 0x02: File req.push_back(0x02); req.push_back(static_cast(fval.size() & 0xFF)); req.push_back(static_cast((fval.size() >> 8) & 0xFF)); req.insert(req.end(), fval.begin(), fval.end()); uint16_t tlvTotal = static_cast(req.size() - 7); req[5] = static_cast(tlvTotal & 0xFF); req[6] = static_cast((tlvTotal >> 8) & 0xFF); if (::sendto(sfd, req.data(), req.size(), 0, reinterpret_cast(&uimSq), sizeof(uimSq)) < 0) { continue; } struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 120) <= 0) continue; uint8_t resp[512]; ssize_t rlen = ::recv(sfd, resp, sizeof(resp), 0); if (rlen < 14 || resp[0] != 0x02 || resp[3] != 0x24) continue; bool okResult = false; uint16_t rSize = 0; uint16_t rCount = 0; size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = resp[pos]; uint16_t tl = static_cast(resp[pos + 1]) | (static_cast(resp[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x02 && tl >= 4) { uint16_t res = static_cast(resp[pos]) | (static_cast(resp[pos + 1]) << 8); uint16_t err = static_cast(resp[pos + 2]) | (static_cast(resp[pos + 3]) << 8); if (res == 0 && err == 0) okResult = true; } else if (tt == 0x11 && tl >= 9) { rSize = static_cast(resp[pos + 5]) | (static_cast(resp[pos + 6]) << 8); rCount = static_cast(resp[pos + 7]) | (static_cast(resp[pos + 8]) << 8); } pos += tl; } if (okResult && rSize >= 14 && rCount >= 1) { outSessionType = stype; outFileTlvVal = fval; outRecSize = rSize; outRecCount = std::min(rCount, 500); return true; } } } return false; } inline bool qrtrReadSimRecord(int sfd, uint32_t uimNode, uint32_t uimPort, uint16_t txnId, uint8_t sessionType, const std::vector& fileTlvVal, uint16_t recNum, uint16_t recSize, std::vector& outData) { struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; } uimSq { 42, uimNode, uimPort }; std::vector req(7); req[0] = 0x00; req[1] = static_cast(txnId & 0xFF); req[2] = static_cast((txnId >> 8) & 0xFF); req[3] = 0x21; // QMI_UIM_READ_RECORD req[4] = 0x00; // TLV 0x01: Session req.push_back(0x01); req.push_back(0x02); req.push_back(0x00); req.push_back(sessionType); req.push_back(0x00); // TLV 0x02: File req.push_back(0x02); req.push_back(static_cast(fileTlvVal.size() & 0xFF)); req.push_back(static_cast((fileTlvVal.size() >> 8) & 0xFF)); req.insert(req.end(), fileTlvVal.begin(), fileTlvVal.end()); // TLV 0x03: Record (record_number u16 LE, record_length u16 LE) req.push_back(0x03); req.push_back(0x04); req.push_back(0x00); req.push_back(static_cast(recNum & 0xFF)); req.push_back(static_cast((recNum >> 8) & 0xFF)); req.push_back(static_cast(recSize & 0xFF)); req.push_back(static_cast((recSize >> 8) & 0xFF)); uint16_t tlvTotal = static_cast(req.size() - 7); req[5] = static_cast(tlvTotal & 0xFF); req[6] = static_cast((tlvTotal >> 8) & 0xFF); if (::sendto(sfd, req.data(), req.size(), 0, reinterpret_cast(&uimSq), sizeof(uimSq)) < 0) { return false; } struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 120) <= 0) return false; uint8_t resp[512]; ssize_t rlen = ::recv(sfd, resp, sizeof(resp), 0); if (rlen < 14 || resp[0] != 0x02 || resp[3] != 0x21) return false; bool okResult = false; outData.clear(); size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = resp[pos]; uint16_t tl = static_cast(resp[pos + 1]) | (static_cast(resp[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x02 && tl >= 4) { uint16_t res = static_cast(resp[pos]) | (static_cast(resp[pos + 1]) << 8); uint16_t err = static_cast(resp[pos + 2]) | (static_cast(resp[pos + 3]) << 8); if (res == 0 && err == 0) okResult = true; } else if (tt == 0x11 && tl >= 2) { uint16_t clen = static_cast(resp[pos]) | (static_cast(resp[pos + 1]) << 8); if (2 + clen <= tl) { outData.assign(resp + pos + 2, resp + pos + 2 + clen); } } pos += tl; } return okResult && !outData.empty(); } inline bool qrtrWriteSimRecord(int sfd, uint32_t uimNode, uint32_t uimPort, uint16_t txnId, uint8_t sessionType, const std::vector& fileTlvVal, uint16_t recNum, const std::vector& recData) { struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; } uimSq { 42, uimNode, uimPort }; std::vector req(7); req[0] = 0x00; req[1] = static_cast(txnId & 0xFF); req[2] = static_cast((txnId >> 8) & 0xFF); req[3] = 0x23; // QMI_UIM_WRITE_RECORD req[4] = 0x00; // TLV 0x01: Session req.push_back(0x01); req.push_back(0x02); req.push_back(0x00); req.push_back(sessionType); req.push_back(0x00); // TLV 0x02: File req.push_back(0x02); req.push_back(static_cast(fileTlvVal.size() & 0xFF)); req.push_back(static_cast((fileTlvVal.size() >> 8) & 0xFF)); req.insert(req.end(), fileTlvVal.begin(), fileTlvVal.end()); // TLV 0x03: Write Record (record_number u16 LE, data_len u16 LE, data[]) uint16_t wTlvLen = static_cast(4 + recData.size()); req.push_back(0x03); req.push_back(static_cast(wTlvLen & 0xFF)); req.push_back(static_cast((wTlvLen >> 8) & 0xFF)); req.push_back(static_cast(recNum & 0xFF)); req.push_back(static_cast((recNum >> 8) & 0xFF)); uint16_t dLen = static_cast(recData.size()); req.push_back(static_cast(dLen & 0xFF)); req.push_back(static_cast((dLen >> 8) & 0xFF)); req.insert(req.end(), recData.begin(), recData.end()); uint16_t tlvTotal = static_cast(req.size() - 7); req[5] = static_cast(tlvTotal & 0xFF); req[6] = static_cast((tlvTotal >> 8) & 0xFF); if (::sendto(sfd, req.data(), req.size(), 0, reinterpret_cast(&uimSq), sizeof(uimSq)) < 0) { return false; } struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 200) <= 0) return false; uint8_t resp[512]; ssize_t rlen = ::recv(sfd, resp, sizeof(resp), 0); if (rlen < 14 || resp[0] != 0x02 || resp[3] != 0x23) return false; bool okResult = false; size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = resp[pos]; uint16_t tl = static_cast(resp[pos + 1]) | (static_cast(resp[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x02 && tl >= 4) { uint16_t res = static_cast(resp[pos]) | (static_cast(resp[pos + 1]) << 8); uint16_t err = static_cast(resp[pos + 2]) | (static_cast(resp[pos + 3]) << 8); if (res == 0 && err == 0) okResult = true; } pos += tl; } return okResult; } inline bool qrtrReadSimContacts( int slotNum, std::vector>& outContacts, std::string& outErr) { outContacts.clear(); outErr.clear(); int sfd = -1; uint32_t uimNode = 0, uimPort = 0; if (!openQrtrUimSocket(sfd, uimNode, uimPort)) { outErr = "Modem UIM service unavailable"; return false; } uint8_t sessionType = 0; std::vector fileTlvVal; uint16_t recSize = 0, recCount = 0; if (!queryQrtrUimAdnGeometry(sfd, uimNode, uimPort, slotNum, sessionType, fileTlvVal, recSize, recCount)) { ::close(sfd); outErr = "SIM " + std::to_string(slotNum) + " phonebook not ready"; return false; } std::vector raw; for (uint16_t rnum = 1; rnum <= recCount; ++rnum) { if (qrtrReadSimRecord(sfd, uimNode, uimPort, static_cast(10 + rnum), sessionType, fileTlvVal, rnum, recSize, raw)) { std::string num, name; if (decodeEfAdnRecord(raw.data(), raw.size(), num, name)) { outContacts.push_back({num, name}); } } } ::close(sfd); return true; } inline bool qrtrWriteSimContacts( int slotNum, const std::vector>& contactsToWrite, int& outExported, std::string& outErr) { outExported = 0; outErr.clear(); if (contactsToWrite.empty()) { outErr = "No contacts to export"; return false; } int sfd = -1; uint32_t uimNode = 0, uimPort = 0; if (!openQrtrUimSocket(sfd, uimNode, uimPort)) { outErr = "Modem UIM service unavailable"; return false; } uint8_t sessionType = 0; std::vector fileTlvVal; uint16_t recSize = 0, recCount = 0; if (!queryQrtrUimAdnGeometry(sfd, uimNode, uimPort, slotNum, sessionType, fileTlvVal, recSize, recCount)) { ::close(sfd); outErr = "SIM " + std::to_string(slotNum) + " phonebook not ready"; return false; } std::unordered_map existingByNorm; std::unordered_map existingBySuffix; std::vector emptySlots; std::vector raw; for (uint16_t rnum = 1; rnum <= recCount; ++rnum) { if (qrtrReadSimRecord(sfd, uimNode, uimPort, static_cast(10 + rnum), sessionType, fileTlvVal, rnum, recSize, raw)) { std::string num, name; if (decodeEfAdnRecord(raw.data(), raw.size(), num, name)) { std::string norm = normalizePhone(num); if (!norm.empty()) { existingByNorm[norm] = rnum; std::string sfx = phoneSuffixKey(norm); if (!sfx.empty()) existingBySuffix[sfx] = rnum; } } else { emptySlots.push_back(rnum); } } } size_t emptyIdx = 0; uint16_t txnId = static_cast(1000); bool simFull = false; for (const auto& kv : contactsToWrite) { std::string norm = normalizePhone(kv.first); if (norm.empty()) continue; uint16_t targetRec = 0; auto it = existingByNorm.find(norm); if (it != existingByNorm.end()) { targetRec = it->second; } else { std::string sfx = phoneSuffixKey(norm); auto sit = sfx.empty() ? existingBySuffix.end() : existingBySuffix.find(sfx); if (sit != existingBySuffix.end()) { targetRec = sit->second; } else if (emptyIdx < emptySlots.size()) { targetRec = emptySlots[emptyIdx++]; } else { simFull = true; break; } } std::vector recData; if (!encodeEfAdnRecord(kv.first, kv.second, recSize, recData)) { continue; } if (qrtrWriteSimRecord(sfd, uimNode, uimPort, txnId++, sessionType, fileTlvVal, targetRec, recData)) { ++outExported; existingByNorm[norm] = targetRec; std::string sfx = phoneSuffixKey(norm); if (!sfx.empty()) existingBySuffix[sfx] = targetRec; } } ::close(sfd); if (outExported == 0 && simFull) { outErr = "SIM " + std::to_string(slotNum) + " phonebook is full"; return false; } return outExported > 0; } inline constexpr const char* kMultiTapPunct1 = ".,-_!?/@:;'\"+=*#$%^&()[]{}<>|\\~`1"; inline constexpr const char* kMultiTapStar = "*#+-=_/\\|~`@$%^&()[]{}<>'\".,!?:;"; } // namespace bananarchy #endif // DWM_PLUGINS_PHONE_DATA_H