#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif /* Bananarchy C++20 userspace VoWiFi (SWu IKEv2 + EAP-AKA/AKA' + UDP/4500 ESP + * 3GPP SIP/AMR-WB/SMS-over-IP) and userspace VoLTE IMS fallback daemon. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "amr_rtp.h" #include "vowifi_aka.h" #include "vowifi_ikev2.h" namespace { volatile sig_atomic_t g_stop = 0; void onSignal(int) { g_stop = 1; } int64_t monotonicMs() { struct timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000; } std::string trimCopy(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); } std::string toLowerCopy(std::string s) { for (char& c : s) c = static_cast(std::tolower(static_cast(c))); return s; } std::string md5HexBytes(const uint8_t* data, size_t len) { uint8_t digest[EVP_MAX_MD_SIZE]{}; unsigned int dlen = 0; EVP_MD_CTX* ctx = EVP_MD_CTX_new(); if (ctx) { if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) == 1 && EVP_DigestUpdate(ctx, data, len) == 1) { EVP_DigestFinal_ex(ctx, digest, &dlen); } EVP_MD_CTX_free(ctx); } return ba_vowifi::bytesToHex(digest, dlen); } std::string md5HexStr(const std::string& s) { return md5HexBytes(reinterpret_cast(s.data()), s.size()); } std::string base64Encode(const uint8_t* data, size_t len) { if (!data || len == 0) return ""; std::string out(((len + 2) / 3) * 4 + 4, '\0'); int n = EVP_EncodeBlock(reinterpret_cast(out.data()), data, static_cast(len)); if (n < 0) return ""; out.resize(static_cast(n)); return out; } std::vector base64Decode(const std::string& in) { std::string clean; clean.reserve(in.size()); for (char c : in) { if (!std::isspace(static_cast(c))) clean.push_back(c); } if (clean.empty()) return {}; std::vector out(clean.size(), 0); int n = EVP_DecodeBlock(out.data(), reinterpret_cast(clean.data()), static_cast(clean.size())); if (n < 0) return {}; size_t pad = 0; if (!clean.empty() && clean.back() == '=') pad++; if (clean.size() >= 2 && clean[clean.size() - 2] == '=') pad++; size_t actual = static_cast(n); if (pad <= actual) actual -= pad; out.resize(actual); return out; } std::string randomHex(size_t bytes) { std::vector v(bytes, 0); RAND_bytes(v.data(), static_cast(bytes)); return ba_vowifi::bytesToHex(v.data(), v.size()); } /* G.711 mu-law / A-law codecs for universal fallback. */ inline uint8_t linearToMulaw(int16_t s) { int sign = (s < 0) ? 0x80 : 0; int v = (s < 0) ? -static_cast(s) : static_cast(s); if (v > 32635) v = 32635; v += 0x84; int exp = 7; for (int mask = 0x4000; (v & mask) == 0 && exp > 0; --exp, mask >>= 1) {} int mant = (v >> (exp + 3)) & 0x0F; return static_cast(~(sign | (exp << 4) | mant)); } inline int16_t mulawToLinear(uint8_t u) { u = static_cast(~u); int t = ((u & 0x0F) << 3) + 0x84; t <<= (u & 0x70) >> 4; return static_cast((u & 0x80) ? (0x84 - t) : (t - 0x84)); } inline uint8_t linearToAlaw(int16_t s) { int mask = (s < 0) ? 0x55 : 0xD5; int v = (s < 0) ? (-static_cast(s) - 1) : static_cast(s); if (v > 32767) v = 32767; int seg = 0; if (v >= 256) { int sv = v >> 4; seg = 1; while (sv > 31 && seg < 7) { sv >>= 1; seg++; } } int aval = (seg == 0) ? (v >> 4) : ((seg << 4) | ((v >> (seg + 3)) & 0x0F)); return static_cast(aval ^ mask); } inline int16_t alawToLinear(uint8_t a) { a ^= 0x55; int t = (a & 0x0F) << 4; int seg = (a & 0x70) >> 4; if (seg == 0) t += 8; else if (seg == 1) t += 0x108; else { t += 0x108; t <<= (seg - 1); } return static_cast((a & 0x80) ? t : -t); } /* PulseAudio Simple dlopen wrapper (no target compile-time dep, graceful headless fallback). */ class PulseAudioStream { public: struct SampleSpec { int format; /* 3 = PA_SAMPLE_S16LE */ uint32_t rate; uint8_t channels; }; PulseAudioStream() { lib_ = dlopen("libpulse-simple.so.0", RTLD_LAZY | RTLD_LOCAL); if (!lib_) lib_ = dlopen("libpulse-simple.so", RTLD_LAZY | RTLD_LOCAL); if (lib_) { fnNew_ = reinterpret_cast(dlsym(lib_, "pa_simple_new")); fnFree_ = reinterpret_cast(dlsym(lib_, "pa_simple_free")); fnWrite_ = reinterpret_cast(dlsym(lib_, "pa_simple_write")); fnRead_ = reinterpret_cast(dlsym(lib_, "pa_simple_read")); } } ~PulseAudioStream() { close(); } bool open(uint32_t sampleRate) { close(); if (std::getenv("BANANARCHY_MOCK_AUDIO") || !fnNew_) { mock_ = true; return true; } SampleSpec ss{3 /* S16LE */, sampleRate, 1}; int err = 0; play_ = fnNew_(nullptr, "bananarchy-ims", 1 /* PLAYBACK */, nullptr, "Voice Call", &ss, nullptr, nullptr, &err); rec_ = fnNew_(nullptr, "bananarchy-ims", 2 /* RECORD */, nullptr, "Voice Mic", &ss, nullptr, nullptr, &err); return (play_ != nullptr || rec_ != nullptr); } void close() { if (play_ && fnFree_) fnFree_(play_); if (rec_ && fnFree_) fnFree_(rec_); play_ = nullptr; rec_ = nullptr; mock_ = false; } void writeSamples(const int16_t* pcm, size_t samples) { if (play_ && fnWrite_ && pcm && samples > 0) { int err = 0; fnWrite_(play_, pcm, samples * sizeof(int16_t), &err); } } bool readSamples(int16_t* pcm, size_t samples) { if (rec_ && fnRead_ && pcm && samples > 0) { int err = 0; return fnRead_(rec_, pcm, samples * sizeof(int16_t), &err) >= 0; } std::memset(pcm, 0, samples * sizeof(int16_t)); return true; } private: using FnNew = void* (*)(const char*, const char*, int, const char*, const char*, const void*, const void*, const void*, int*); using FnFree = void (*)(void*); using FnWrite = int (*)(void*, const void*, size_t, int*); using FnRead = int (*)(void*, void*, size_t, int*); void* lib_ = nullptr; FnNew fnNew_ = nullptr; FnFree fnFree_ = nullptr; FnWrite fnWrite_ = nullptr; FnRead fnRead_ = nullptr; void* play_ = nullptr; void* rec_ = nullptr; bool mock_ = false; }; /* 3GPP TS 24.341 + TS 23.040 RP-DATA / GSM-7 / UCS-2 SMS-over-IP helpers. */ std::vector encodeBcdNumber(const std::string& num, uint8_t& outLenBytes, uint8_t& outToa) { std::string digits; bool intl = false; for (size_t i = 0; i < num.size(); ++i) { if (i == 0 && num[i] == '+') intl = true; else if (std::isdigit(static_cast(num[i]))) digits.push_back(num[i]); } if (digits.empty()) digits = "0"; outToa = intl ? 0x91U : 0x81U; outLenBytes = static_cast(digits.size()); std::vector bcd; for (size_t i = 0; i < digits.size(); i += 2) { uint8_t lo = static_cast(digits[i] - '0'); uint8_t hi = (i + 1 < digits.size()) ? static_cast(digits[i + 1] - '0') : 0x0FU; bcd.push_back(static_cast((hi << 4) | lo)); } return bcd; } std::string decodeBcdNumber(const uint8_t* p, size_t digitsCount, uint8_t toa) { std::string out; if ((toa & 0x70U) == 0x10U) out.push_back('+'); size_t nbytes = (digitsCount + 1) / 2; for (size_t i = 0; i < nbytes; ++i) { uint8_t lo = p[i] & 0x0FU; uint8_t hi = (p[i] >> 4) & 0x0FU; if (lo <= 9) out.push_back(static_cast('0' + lo)); if (hi <= 9 && out.size() < digitsCount + (toa == 0x91U ? 1 : 0)) { out.push_back(static_cast('0' + hi)); } } return out; } std::vector packGsm7Septets(const std::string& text) { std::vector packed((text.size() * 7U + 7U) / 8U, 0); int bitPos = 0; for (unsigned char c : text) { uint8_t s = (c < 0x80U) ? c : '?'; for (int b = 0; b < 7; ++b) { if ((s >> b) & 1U) { packed[static_cast(bitPos >> 3)] |= static_cast(1U << (bitPos & 7)); } bitPos++; } } return packed; } std::string unpackGsm7Septets(const uint8_t* data, size_t nbytes, size_t nseptets) { std::string out; out.reserve(nseptets); int bitPos = 0; int totalBits = static_cast(nbytes) * 8; for (size_t i = 0; i < nseptets && bitPos + 7 <= totalBits; ++i) { uint8_t c = 0; for (int b = 0; b < 7; ++b) { uint8_t bit = (data[bitPos >> 3] >> (bitPos & 7)) & 1U; c |= static_cast(bit << b); bitPos++; } out.push_back(c >= 0x20U || c == '\n' ? static_cast(c) : ' '); } return out; } std::vector buildRpDataSubmit(uint8_t rpMr, const std::string& dest, const std::string& text) { bool asciiOnly = true; for (unsigned char c : text) { if (c >= 0x80U) { asciiOnly = false; break; } } uint8_t dLen = 0, toa = 0x81U; auto bcd = encodeBcdNumber(dest, dLen, toa); std::vector tpdu; tpdu.push_back(0x01U); /* TP-MTI = SMS-SUBMIT */ tpdu.push_back(rpMr); /* TP-MR */ tpdu.push_back(dLen); tpdu.push_back(toa); tpdu.insert(tpdu.end(), bcd.begin(), bcd.end()); tpdu.push_back(0x00U); /* TP-PID */ if (asciiOnly) { tpdu.push_back(0x00U); /* GSM-7 */ tpdu.push_back(static_cast(std::min(text.size(), 160))); auto ud = packGsm7Septets(text.substr(0, 160)); tpdu.insert(tpdu.end(), ud.begin(), ud.end()); } else { tpdu.push_back(0x08U); /* UCS-2 */ std::vector ucs2; for (size_t i = 0; i < text.size(); ) { uint32_t cp = 0x3F; unsigned char b0 = static_cast(text[i]); if (b0 < 0x80U) { cp = b0; i += 1; } else if ((b0 & 0xE0U) == 0xC0U && i + 1 < text.size()) { cp = ((b0 & 0x1FU) << 6) | (static_cast(text[i + 1]) & 0x3FU); i += 2; } else if ((b0 & 0xF0U) == 0xE0U && i + 2 < text.size()) { cp = ((b0 & 0x0FU) << 12) | ((static_cast(text[i + 1]) & 0x3FU) << 6) | (static_cast(text[i + 2]) & 0x3FU); i += 3; } else { i += 1; } if (cp <= 0xFFFFU) { ucs2.push_back(static_cast((cp >> 8) & 0xFFU)); ucs2.push_back(static_cast(cp & 0xFFU)); } if (ucs2.size() >= 140) break; } tpdu.push_back(static_cast(ucs2.size())); tpdu.insert(tpdu.end(), ucs2.begin(), ucs2.end()); } /* Wrap inside TS 24.011 RP-DATA (MS -> Network, MTI=0x00) */ std::vector rp; rp.push_back(0x00U); rp.push_back(rpMr); rp.push_back(0x00U); /* RP-OA len 0 */ std::vector rpDa = {0x91U, 0x00}; /* placeholder default SMSC address */ rp.push_back(static_cast(rpDa.size())); rp.insert(rp.end(), rpDa.begin(), rpDa.end()); rp.push_back(static_cast(tpdu.size())); rp.insert(rp.end(), tpdu.begin(), tpdu.end()); return rp; } bool parseRpDataDeliver(const uint8_t* rp, size_t len, std::string& outSender, std::string& outText, uint8_t& outRpMr) { if (!rp || len < 8) return false; uint8_t mti = rp[0]; outRpMr = rp[1]; if (mti != 0x01U && mti != 0x00U) return false; size_t pos = 2; if (pos >= len) return false; size_t rpOaLen = rp[pos++]; pos += rpOaLen; if (pos >= len) return false; size_t rpDaLen = rp[pos++]; pos += rpDaLen; if (pos >= len) return false; size_t tpduLen = rp[pos++]; if (pos + tpduLen > len || tpduLen < 6) return false; const uint8_t* tp = rp + pos; size_t tpos = 1; /* skip first octet */ if ((tp[0] & 0x03U) == 0x01U) tpos++; /* TP-MR in SUBMIT test */ if (tpos + 2 > tpduLen) return false; uint8_t oaDigits = tp[tpos++]; uint8_t oaToa = tp[tpos++]; size_t oaBytes = (oaDigits + 1U) / 2U; if (tpos + oaBytes + 3U > tpduLen) return false; outSender = decodeBcdNumber(tp + tpos, oaDigits, oaToa); tpos += oaBytes; tpos++; /* TP-PID */ uint8_t dcs = tp[tpos++]; if ((tp[0] & 0x03U) == 0x00U /* DELIVER */) { if (tpos + 7U > tpduLen) return false; tpos += 7; /* TP-SCTS */ } if (tpos >= tpduLen) return false; uint8_t udl = tp[tpos++]; const uint8_t* ud = tp + tpos; size_t udAvail = tpduLen - tpos; if ((dcs & 0x0CU) == 0x08U) { size_t n = std::min(udAvail, udl); outText.clear(); for (size_t i = 0; i + 1 < n; i += 2) { uint16_t u = static_cast((ud[i] << 8) | ud[i + 1]); if (u < 0x80U) outText.push_back(static_cast(u)); else if (u < 0x800U) { outText.push_back(static_cast(0xC0U | (u >> 6))); outText.push_back(static_cast(0x80U | (u & 0x3FU))); } else { outText.push_back(static_cast(0xE0U | (u >> 12))); outText.push_back(static_cast(0x80U | ((u >> 6) & 0x3FU))); outText.push_back(static_cast(0x80U | (u & 0x3FU))); } } } else { outText = unpackGsm7Septets(ud, udAvail, udl); } return true; } std::string getSxmoRuntimeDir() { const char* x = std::getenv("XDG_RUNTIME_DIR"); std::string base = (x && *x) ? x : "/run/user/10000"; if (::access(base.c_str(), W_OK) != 0) base = "/tmp"; return base; } std::string getSxmoLogDir() { const char* s = std::getenv("SXMO_LOGDIR"); if (s && *s) return s; const char* h = std::getenv("HOME"); std::string home = (h && *h) ? h : "/home/user"; return home + "/.local/share/sxmo/modem"; } bool isPhoneBlocked(const std::string& number) { const char* b = std::getenv("SXMO_BLOCKFILE"); std::string path = (b && *b) ? b : ""; if (path.empty()) { const char* x = std::getenv("XDG_CONFIG_HOME"); std::string cfg = (x && *x) ? x : (std::string(std::getenv("HOME") ? std::getenv("HOME") : "/home/user") + "/.config"); path = cfg + "/sxmo/block.tsv"; } FILE* fp = std::fopen(path.c_str(), "r"); if (!fp) return false; char line[256]; bool blocked = false; while (std::fgets(line, sizeof(line), fp)) { std::string l = trimCopy(line); if (!l.empty() && l.rfind(number, 0) == 0) { blocked = true; break; } } std::fclose(fp); return blocked; } void logSxmoSmsAndModem(const std::string& dir, const std::string& number, const std::string& text, int simSlot) { std::string logDir = getSxmoLogDir(); std::string numDir = logDir + "/" + number; ims_mkdir_p(numDir.c_str(), 0755); std::time_t now = std::time(nullptr); struct tm tmv{}; localtime_r(&now, &tmv); char ts[48]; std::strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%S%z", &tmv); std::string txtPath = numDir + "/sms.txt"; const char* verb = (dir == "recv_txt") ? "Received" : "Sent"; if (FILE* f = std::fopen(txtPath.c_str(), "a")) { std::fprintf(f, "%s at %s:\n%s\n\n", verb, ts, text.c_str()); std::fclose(f); } std::string tsvPath = logDir + "/modemlog.tsv"; if (FILE* f = std::fopen(tsvPath.c_str(), "a")) { std::fprintf(f, "%s\t%s\t%s\t[SIM %d] %zu chars\n", ts, dir.c_str(), number.c_str(), simSlot, text.size()); std::fclose(f); } if (dir == "recv_txt" && !std::getenv("BANANARCHY_NO_X11_LAUNCH") && ::access("/usr/share/sxmo/default_hooks/sxmo_hook_sms.sh", X_OK) == 0) { pid_t pid = ::fork(); if (pid == 0) { ::execl("/bin/sh", "sh", "-c", "PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " "sxmo_hook_statusbar.sh sms >/dev/null 2>&1 || true", static_cast(nullptr)); ::_exit(0); } } } void writeCallMarker(const std::string& cid, const std::string& ext, const std::string& number, int simSlot, const std::string& tech) { std::string callsDir = getSxmoRuntimeDir() + "/sxmo_calls"; ims_mkdir_p(callsDir.c_str(), 0755); std::string safeCid = cid; for (char& c : safeCid) { if (c == ':' || c == '/') c = '_'; } for (const char* oldExt : {"dialing", "ringing-in", "pickedupcall", "active", "hangedupcall"}) { std::string op = callsDir + "/" + safeCid + "." + oldExt; ::unlink(op.c_str()); } std::string path = callsDir + "/" + safeCid + "." + ext; char content[256]; std::snprintf(content, sizeof(content), "%s\nSIM %d %s\n", number.c_str(), simSlot, tech.c_str()); ims_write_atomic(path.c_str(), content, 0644); } void spawnCallscreenUi(bool incoming, const std::string& cid, const std::string& number, const std::string& simTagToken) { if (std::getenv("BANANARCHY_NO_X11_LAUNCH")) return; int fifoFd = ::open("/tmp/dwm_plugin_callscreen.fifo", O_WRONLY | O_NONBLOCK | O_CLOEXEC); if (fifoFd >= 0) { std::string line = std::string(incoming ? "INCOMING " : "OUTGOING ") + cid + " " + number + " " + simTagToken + "\n"; ssize_t w = ::write(fifoFd, line.data(), line.size()); ::close(fifoFd); if (w == static_cast(line.size())) { return; } } if (::access("/usr/bin/xcallscreen", X_OK) != 0) return; pid_t pid = ::fork(); if (pid == 0) { const char* modeArg = incoming ? "incoming" : "outgoing"; ::execl("/usr/bin/xcallscreen", "xcallscreen", modeArg, cid.c_str(), number.c_str(), simTagToken.c_str(), static_cast(nullptr)); ::_exit(0); } } struct SipPacket { bool isRequest = false; std::string method; std::string reqUri; int statusCode = 0; std::string callId; std::string cseqMethod; uint32_t cseqNum = 0; std::string via; std::string from; std::string to; std::string contact; std::string wwwAuth; std::string secServer; std::string require; std::string rseq; std::string contentType; std::vector body; }; SipPacket parseSip(const uint8_t* data, size_t len) { SipPacket p; std::string raw(reinterpret_cast(data), len); size_t hdrEnd = raw.find("\r\n\r\n"); size_t bodyStart = 0; if (hdrEnd == std::string::npos) { hdrEnd = raw.find("\n\n"); bodyStart = (hdrEnd == std::string::npos) ? len : hdrEnd + 2; } else { bodyStart = hdrEnd + 4; } std::string hdrs = raw.substr(0, hdrEnd == std::string::npos ? len : hdrEnd); if (bodyStart < len) { p.body.assign(data + bodyStart, data + len); } std::istringstream iss(hdrs); std::string line; bool first = true; while (std::getline(iss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (first) { first = false; if (line.rfind("SIP/2.0 ", 0) == 0) { p.isRequest = false; p.statusCode = std::atoi(line.c_str() + 8); } else { p.isRequest = true; size_t sp1 = line.find(' '); size_t sp2 = (sp1 == std::string::npos) ? std::string::npos : line.find(' ', sp1 + 1); if (sp1 != std::string::npos) { p.method = line.substr(0, sp1); p.reqUri = (sp2 != std::string::npos) ? line.substr(sp1 + 1, sp2 - sp1 - 1) : line.substr(sp1 + 1); } } continue; } size_t col = line.find(':'); if (col == std::string::npos) continue; std::string k = toLowerCopy(trimCopy(line.substr(0, col))); std::string v = trimCopy(line.substr(col + 1)); if (k == "call-id" || k == "i") p.callId = v; else if (k == "cseq") { p.cseqNum = static_cast(std::strtoul(v.c_str(), nullptr, 10)); size_t sp = v.find(' '); if (sp != std::string::npos) p.cseqMethod = trimCopy(v.substr(sp + 1)); } else if (k == "via" || k == "v") { if (p.via.empty()) p.via = v; } else if (k == "from" || k == "f") p.from = v; else if (k == "to" || k == "t") p.to = v; else if (k == "contact" || k == "m") p.contact = v; else if (k == "www-authenticate") p.wwwAuth = v; else if (k == "security-server") p.secServer = v; else if (k == "require") p.require = v; else if (k == "rseq") p.rseq = v; else if (k == "content-type" || k == "c") p.contentType = toLowerCopy(v); } return p; } std::string extractHeaderParam(const std::string& hdr, const std::string& key) { std::string lower = toLowerCopy(hdr); std::string pat = toLowerCopy(key) + "="; size_t pos = lower.find(pat); if (pos == std::string::npos) return ""; pos += pat.size(); if (pos < hdr.size() && hdr[pos] == '"') { size_t end = hdr.find('"', pos + 1); return (end != std::string::npos) ? hdr.substr(pos + 1, end - pos - 1) : hdr.substr(pos + 1); } size_t end = hdr.find_first_of(",; \t", pos); return (end != std::string::npos) ? hdr.substr(pos, end - pos) : hdr.substr(pos); } std::string extractSipUser(const std::string& uriHdr) { size_t pos = uriHdr.find("sip:"); if (pos == std::string::npos) pos = uriHdr.find("tel:"); if (pos == std::string::npos) return uriHdr; pos += 4; size_t end = uriHdr.find_first_of("@>; \t", pos); return (end != std::string::npos) ? uriHdr.substr(pos, end - pos) : uriHdr.substr(pos); } void parseSdpMedia(const std::vector& body, std::string& outIp, uint16_t& outPort, int& outPt, std::string& outCodec, bool& outOctetAligned, bool& outHasPrecond) { outPt = 0; outCodec = "pcmu"; outOctetAligned = true; outHasPrecond = false; std::string s(reinterpret_cast(body.data()), body.size()); std::istringstream iss(s); std::string line; std::vector offeredPts; int wbPtAlign = -1, wbPtBe = -1, nbPt = -1, pcmuPt = -1, pcmaPt = -1; bool align96 = true, align98 = false; while (std::getline(iss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (line.rfind("c=IN IP4 ", 0) == 0 || line.rfind("c=IN IP6 ", 0) == 0) { outIp = trimCopy(line.substr(9)); } else if (line.rfind("m=audio ", 0) == 0) { std::istringstream ms(line.substr(8)); ms >> outPort; std::string proto; ms >> proto; int pt = 0; while (ms >> pt) offeredPts.push_back(pt); } else if (line.rfind("a=rtpmap:", 0) == 0) { int pt = std::atoi(line.c_str() + 9); std::string low = toLowerCopy(line); if (low.find("amr-wb") != std::string::npos) { if (wbPtAlign < 0) wbPtAlign = pt; else wbPtBe = pt; } else if (low.find("amr/") != std::string::npos) { nbPt = pt; } else if (low.find("pcmu/") != std::string::npos) { pcmuPt = pt; } else if (low.find("pcma/") != std::string::npos) { pcmaPt = pt; } } else if (line.rfind("a=fmtp:", 0) == 0) { int pt = std::atoi(line.c_str() + 7); bool oa = (toLowerCopy(line).find("octet-align=1") != std::string::npos); if (pt == wbPtAlign) align96 = oa; else if (pt == wbPtBe) align98 = oa; } else if (line.rfind("a=curr:qos", 0) == 0 || line.rfind("a=des:qos", 0) == 0) { outHasPrecond = true; } } (void)offeredPts; auto& ldr = ba_amr::AmrLibraryLoader::instance(); if (wbPtAlign >= 0 && ldr.hasWbDec()) { outPt = wbPtAlign; outCodec = "amr-wb"; outOctetAligned = align96; } else if (wbPtBe >= 0 && ldr.hasWbDec()) { outPt = wbPtBe; outCodec = "amr-wb"; outOctetAligned = align98; } else if (nbPt >= 0 && ldr.hasNbDec() && ldr.hasNbEnc()) { outPt = nbPt; outCodec = "amr-nb"; outOctetAligned = true; } else if (pcmuPt >= 0) { outPt = pcmuPt; outCodec = "pcmu"; } else if (pcmaPt >= 0) { outPt = pcmaPt; outCodec = "pcma"; } } class VowifiDaemon { public: std::string mode = "vowifi"; /* vowifi | volte */ std::string stateDir; ims_config cfg{}; ims_runtime_state st{}; ba_vowifi::SimIdentity simId{}; std::unique_ptr aka; ba_vowifi::SwuIkev2Tunnel tunnel; int directSipFd = -1; int directRtpFd = -1; int ctlSrvFd = -1; std::string localIp = "127.0.0.1"; std::string pcscfIp; uint16_t pcscfPort = 5060; uint16_t localSipPort = 5062; uint16_t localRtpPort = 40002; bool registered = false; std::string regCallId; std::string regFromTag; uint32_t regCseq = 1; std::string secServerHdr; /* Active single-call state (3GPP voice call). */ enum class CallState { Idle, Outgoing, Incoming, Active }; CallState callState = CallState::Idle; std::string activeCid; std::string sipCallId; std::string remoteNumber; std::string remoteFrom; std::string remoteTo; std::string remoteVia; std::string remoteTag; std::string localTag; uint32_t inviteCseq = 1; std::string remoteRtpIp; uint16_t remoteRtpPort = 0; int negotiatedPt = 0; std::string negotiatedCodec = "pcmu"; bool negotiatedOctetAlign = true; bool micMuted = false; uint16_t rtpSeq = 1; uint32_t rtpTs = 0; uint32_t rtpSsrc = 0x42414E01U; int64_t nextRtpTxMs = 0; int64_t nextRegRetryMs = 0; int64_t regBackoffMs = 5000; uint8_t rpMrCounter = 1; uint32_t callCounter = 1; ba_amr::AmrCodecSession amrSession; PulseAudioStream audio; int init() { stateDir = ims_state_dir(); ims_mkdir_p(stateDir.c_str(), 0755); ims_config_load(&cfg, nullptr); ims_state_read(&st); if (!aka) { aka = std::make_unique(cfg.ims_sim_slot, stateDir); } if (simId.imsi.empty()) { simId = aka->readIdentity(st, cfg); } if (const char* p = std::getenv("BANANARCHY_PCSCF_PORT")) { int pv = std::atoi(p); if (pv > 0 && pv <= 65535) pcscfPort = static_cast(pv); } if (ctlSrvFd < 0 && openCtlSocket() != 0) return -1; if (mode == "vowifi") { std::string eHost = cfg.epdg_server[0] ? std::string(cfg.epdg_server) : defaultEpdgHost(); if (!tunnel.connect(eHost, simId, *aka)) { ims_str_copy(st.last_error, sizeof(st.last_error), tunnel.lastError.c_str()); ims_str_copy(st.epdg_host, sizeof(st.epdg_host), eHost.c_str()); ims_state_write(&st); nextRegRetryMs = monotonicMs() + regBackoffMs; regBackoffMs = std::min(regBackoffMs * 2, 300000); return 0; /* stay alive for retry on backed-off timer or STOP */ } localIp = !tunnel.tunIp.empty() ? tunnel.tunIp : (!tunnel.tunIp6.empty() ? tunnel.tunIp6 : "10.99.0.2"); pcscfIp = cfg.pcscf_override[0] ? std::string(cfg.pcscf_override) : (!tunnel.pcscfIp.empty() ? tunnel.pcscfIp : tunnel.pcscfIp6); if (pcscfIp.empty()) pcscfIp = tunnel.epdgIp; ims_str_copy(st.epdg_host, sizeof(st.epdg_host), eHost.c_str()); ims_str_copy(st.tun_ip, sizeof(st.tun_ip), localIp.c_str()); ims_str_copy(st.pcscf_addr, sizeof(st.pcscf_addr), pcscfIp.c_str()); st.vowifi_ipv6_epdg = tunnel.usingIpv6 ? 1 : 0; ims_state_write(&st); } else { /* Userspace VoLTE fallback on cellular ims APN bearer. */ const char* envIp = std::getenv("BANANARCHY_IMS_NET_IP"); const char* envPcscf = std::getenv("BANANARCHY_VOLTE_PCSCF"); localIp = (envIp && *envIp) ? envIp : (st.ims_apn_ip[0] ? st.ims_apn_ip : "127.0.0.1"); pcscfIp = cfg.pcscf_override[0] ? std::string(cfg.pcscf_override) : ((envPcscf && *envPcscf) ? envPcscf : "127.0.0.1"); openDirectSockets(); ims_str_copy(st.pcscf_addr, sizeof(st.pcscf_addr), pcscfIp.c_str()); ims_state_write(&st); } regCallId = randomHex(8) + "@" + localIp; regFromTag = randomHex(6); sendRegister("", "", 3600); return 0; } void run() { init(); while (!g_stop) { struct pollfd pfds[5]; nfds_t n = 0; int ctlIdx = static_cast(n); pfds[n++] = {ctlSrvFd, POLLIN, 0}; int udpIdx = -1; if (mode == "vowifi" && tunnel.udpFd >= 0) { udpIdx = static_cast(n); pfds[n++] = {tunnel.udpFd, POLLIN, 0}; } int tunIdx = -1; if (mode == "vowifi" && tunnel.tunFd >= 0) { tunIdx = static_cast(n); pfds[n++] = {tunnel.tunFd, POLLIN, 0}; } int dirSipIdx = -1; if (directSipFd >= 0) { dirSipIdx = static_cast(n); pfds[n++] = {directSipFd, POLLIN, 0}; } int dirRtpIdx = -1; if (directRtpFd >= 0) { dirRtpIdx = static_cast(n); pfds[n++] = {directRtpFd, POLLIN, 0}; } int timeoutMs = -1; if (callState == CallState::Active) { timeoutMs = 20; } else if (!registered && nextRegRetryMs > 0) { int64_t rem = nextRegRetryMs - monotonicMs(); timeoutMs = static_cast(std::clamp(rem, 100, 300000)); } int prc = ::poll(pfds, n, timeoutMs); if (prc < 0) { if (errno == EINTR) continue; break; } if (ctlIdx >= 0 && (pfds[ctlIdx].revents & POLLIN)) { handleCtlClient(); } if (udpIdx >= 0 && (pfds[udpIdx].revents & POLLIN)) { std::vector innerIp; if (tunnel.handleUdpRx(innerIp)) { uint16_t sp = 0, dp = 0; const uint8_t* pl = nullptr; size_t plen = 0; if (ba_vowifi::parseIpUdpPacket(innerIp.data(), innerIp.size(), sp, dp, pl, plen)) { if (dp == localSipPort) handleSipMessage(pl, plen); else if (dp == localRtpPort) handleRtpPacket(pl, plen); } } } if (tunIdx >= 0 && (pfds[tunIdx].revents & POLLIN)) { uint8_t pkt[2048]; ssize_t r = ::read(tunnel.tunFd, pkt, sizeof(pkt)); if (r > 20) tunnel.sendEspIpPacket(pkt, static_cast(r)); } if (dirSipIdx >= 0 && (pfds[dirSipIdx].revents & POLLIN)) { uint8_t buf[4096]; ssize_t r = ::recv(directSipFd, buf, sizeof(buf), 0); if (r > 0) handleSipMessage(buf, static_cast(r)); } if (dirRtpIdx >= 0 && (pfds[dirRtpIdx].revents & POLLIN)) { uint8_t buf[2048]; ssize_t r = ::recv(directRtpFd, buf, sizeof(buf), 0); if (r > 0) handleRtpPacket(buf, static_cast(r)); } int64_t now = monotonicMs(); if (callState == CallState::Active && now >= nextRtpTxMs) { sendRtpFrame(); nextRtpTxMs = now + 20; } else if (!registered && nextRegRetryMs > 0 && now >= nextRegRetryMs) { nextRegRetryMs = now + regBackoffMs; regBackoffMs = std::min(regBackoffMs * 2, 300000); if (mode == "vowifi" && !tunnel.connected) { init(); } else { sendRegister("", "", 3600); } } } if (registered) { sendRegister("", "", 0); } teardownActiveCall("Terminated"); tunnel.disconnect(); if (directSipFd >= 0) ::close(directSipFd); if (directRtpFd >= 0) ::close(directRtpFd); if (ctlSrvFd >= 0) ::close(ctlSrvFd); std::string sockPath = stateDir + "/vowifi.sock"; ::unlink(sockPath.c_str()); } private: std::string defaultEpdgHost() const { std::string mnc3 = simId.mnc; while (mnc3.size() < 3) mnc3 = "0" + mnc3; return "epdg.epc.mnc" + mnc3 + ".mcc" + simId.mcc + ".pub.3gppnetwork.org"; } std::string accessNetworkHeader() const { if (mode == "vowifi") { return "IEEE-802.11;i-wlan-node-id=000000000000"; } return "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=" + simId.mcc + simId.mnc + "00010001"; } void openDirectSockets() { auto bindUdp = [](uint16_t& port) -> int { int fd = ::socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (fd < 0) return -1; struct sockaddr_in sin{}; sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(port); if (::bind(fd, reinterpret_cast(&sin), sizeof(sin)) != 0) { sin.sin_port = 0; if (::bind(fd, reinterpret_cast(&sin), sizeof(sin)) != 0) { ::close(fd); return -1; } } socklen_t sl = sizeof(sin); if (::getsockname(fd, reinterpret_cast(&sin), &sl) == 0) { port = ntohs(sin.sin_port); } return fd; }; if (directSipFd < 0) directSipFd = bindUdp(localSipPort); if (directRtpFd < 0) directRtpFd = bindUdp(localRtpPort); } bool sendUdpInner(uint16_t srcPort, const std::string& dstIp, uint16_t dstPort, const uint8_t* payload, size_t len) { if (mode == "vowifi") { if (!tunnel.connected) return false; std::vector ipPkt = (dstIp.find(':') != std::string::npos) ? ba_vowifi::buildIpv6UdpPacket(localIp, srcPort, dstIp, dstPort, payload, len) : ba_vowifi::buildIpv4UdpPacket(localIp, srcPort, dstIp, dstPort, payload, len); return tunnel.sendEspIpPacket(ipPkt.data(), ipPkt.size()); } int fd = (srcPort == localRtpPort) ? directRtpFd : directSipFd; if (fd < 0) return false; struct sockaddr_in sin{}; sin.sin_family = AF_INET; sin.sin_port = htons(dstPort); inet_pton(AF_INET, dstIp.c_str(), &sin.sin_addr); return ::sendto(fd, payload, len, 0, reinterpret_cast(&sin), sizeof(sin)) == static_cast(len); } bool sendSipText(const std::string& sip) { return sendUdpInner(localSipPort, pcscfIp, pcscfPort, reinterpret_cast(sip.data()), sip.size()); } void sendRegister(const std::string& authHdr, const std::string& autsHdr, int expires) { if (pcscfIp.empty()) return; std::ostringstream oss; std::string branch = "z9hG4bK" + randomHex(6); oss << "REGISTER sip:" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=" << branch << ";rport\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << regFromTag << "\r\n" << "To: <" << simId.impu << ">\r\n" << "Call-ID: " << regCallId << "\r\n" << "CSeq: " << regCseq++ << " REGISTER\r\n" << "Contact: \r\n" << "P-Access-Network-Info: " << accessNetworkHeader() << "\r\n" << "Supported: path, gruu, outbound, sec-agree, 100rel\r\n" << "Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=1001; spi-s=1002; port-c=" << localSipPort << "; port-s=" << (localSipPort + 1) << "\r\n"; if (!authHdr.empty()) { oss << "Authorization: " << authHdr << "\r\n"; } else if (!autsHdr.empty()) { oss << "Authorization: " << autsHdr << "\r\n"; } oss << "Expires: " << expires << "\r\nContent-Length: 0\r\n\r\n"; sendSipText(oss.str()); nextRegRetryMs = monotonicMs() + 5000; } std::string buildSdpOffer(bool includePreconditions) { std::string cIp = localIp; std::string conn = (cIp.find(':') != std::string::npos) ? ("IN IP6 " + cIp) : ("IN IP4 " + cIp); std::ostringstream sdp; sdp << "v=0\r\n" << "o=- " << monotonicMs() << " 1 " << conn << "\r\n" << "s=Bananarchy IMS\r\n" << "c=" << conn << "\r\n" << "t=0 0\r\n" << "m=audio " << localRtpPort << " RTP/AVP 96 98 97 0 8 101\r\n" << "a=rtpmap:96 AMR-WB/16000\r\n" << "a=fmtp:96 mode-set=0,1,2,3,4,5,6,7,8; octet-align=1\r\n" << "a=rtpmap:98 AMR-WB/16000\r\n" << "a=fmtp:98 mode-set=0,1,2,3,4,5,6,7,8; octet-align=0\r\n" << "a=rtpmap:97 AMR/8000\r\n" << "a=fmtp:97 octet-align=1\r\n" << "a=rtpmap:0 PCMU/8000\r\n" << "a=rtpmap:8 PCMA/8000\r\n" << "a=rtpmap:101 telephone-event/16000\r\n" << "a=ptime:20\r\n" << "a=sendrecv\r\n"; if (includePreconditions) { sdp << "a=curr:qos local sendrecv\r\n" << "a=curr:qos remote none\r\n" << "a=des:qos mandatory local sendrecv\r\n" << "a=des:qos none remote sendrecv\r\n"; } return sdp.str(); } void sendSipReply(const SipPacket& req, int code, const std::string& reason, const std::string& extraHdrs, const std::string& sdpBody, const std::string& ctype = "application/sdp") { std::ostringstream oss; oss << "SIP/2.0 " << code << " " << reason << "\r\n" << "Via: " << req.via << "\r\n" << "From: " << req.from << "\r\n" << "To: " << req.to << (req.to.find(";tag=") == std::string::npos ? ";tag=" + localTag : "") << "\r\n" << "Call-ID: " << req.callId << "\r\n" << "CSeq: " << req.cseqNum << " " << req.cseqMethod << "\r\n" << "Contact: \r\n" << extraHdrs; if (!sdpBody.empty()) { oss << "Content-Type: " << ctype << "\r\n"; } oss << "Content-Length: " << sdpBody.size() << "\r\n\r\n" << sdpBody; sendSipText(oss.str()); } void handleSipMessage(const uint8_t* data, size_t len) { SipPacket sip = parseSip(data, len); if (!sip.isRequest) { if (sip.cseqMethod == "REGISTER") { if (sip.statusCode == 401) { if (!sip.secServer.empty()) secServerHdr = sip.secServer; handleRegister401(sip); } else if (sip.statusCode == 200) { registered = true; nextRegRetryMs = 0; regBackoffMs = 5000; ims_state_read(&st); if (mode == "vowifi") { st.vowifi_active = 1; st.vowifi_registered = 1; } else { st.volte_active = 1; st.volte_registered = 1; } ims_str_copy(st.pcscf_addr, sizeof(st.pcscf_addr), pcscfIp.c_str()); ims_str_copy(st.tun_ip, sizeof(st.tun_ip), localIp.c_str()); st.last_error[0] = '\0'; ims_state_write(&st); std::string isock = stateDir + "/imsd.sock"; int ifd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (ifd >= 0) { struct sockaddr_un iaddr{}; iaddr.sun_family = AF_UNIX; if (isock.size() < sizeof(iaddr.sun_path)) { std::memcpy(iaddr.sun_path, isock.c_str(), isock.size() + 1); if (::connect(ifd, reinterpret_cast(&iaddr), sizeof(iaddr)) == 0) { const char* r = "REFRESH\n"; ssize_t w = ::write(ifd, r, 8); (void)w; } } ::close(ifd); } } } else if (sip.cseqMethod == "INVITE") { if (sip.statusCode == 183) { if (!sip.body.empty()) { bool precond = false; parseSdpMedia(sip.body, remoteRtpIp, remoteRtpPort, negotiatedPt, negotiatedCodec, negotiatedOctetAlign, precond); if (sip.require.find("100rel") != std::string::npos && !sip.rseq.empty()) { std::ostringstream p; p << "PRACK sip:" << remoteNumber << "@" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=z9hG4bK" << randomHex(5) << "\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << localTag << "\r\n" << "To: " << sip.to << "\r\n" << "Call-ID: " << sip.callId << "\r\n" << "CSeq: " << ++inviteCseq << " PRACK\r\n" << "RAck: " << sip.rseq << " " << sip.cseqNum << " INVITE\r\n" << "Content-Length: 0\r\n\r\n"; sendSipText(p.str()); } if (precond) { std::string updSdp = buildSdpOffer(true); std::ostringstream u; u << "UPDATE sip:" << remoteNumber << "@" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=z9hG4bK" << randomHex(5) << "\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << localTag << "\r\n" << "To: " << sip.to << "\r\n" << "Call-ID: " << sip.callId << "\r\n" << "CSeq: " << ++inviteCseq << " UPDATE\r\n" << "Content-Type: application/sdp\r\n" << "Content-Length: " << updSdp.size() << "\r\n\r\n" << updSdp; sendSipText(u.str()); } } } else if (sip.statusCode == 200) { if (!sip.body.empty()) { bool precond = false; parseSdpMedia(sip.body, remoteRtpIp, remoteRtpPort, negotiatedPt, negotiatedCodec, negotiatedOctetAlign, precond); } remoteTo = sip.to; std::ostringstream ack; ack << "ACK sip:" << remoteNumber << "@" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=z9hG4bK" << randomHex(5) << "\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << localTag << "\r\n" << "To: " << sip.to << "\r\n" << "Call-ID: " << sip.callId << "\r\n" << "CSeq: " << sip.cseqNum << " ACK\r\n" << "Content-Length: 0\r\n\r\n"; sendSipText(ack.str()); startMediaCall(false); } else if (sip.statusCode >= 400) { teardownActiveCall("Rejected"); } } return; } if (sip.method == "INVITE") { std::string caller = extractSipUser(sip.from); if (isPhoneBlocked(caller)) { sendSipReply(sip, 603, "Decline", "", ""); return; } if (callState != CallState::Idle) { sendSipReply(sip, 486, "Busy Here", "", ""); return; } callState = CallState::Incoming; activeCid = (mode == "vowifi" ? "vowifi:" : "ims:") + std::to_string(callCounter++); sipCallId = sip.callId; remoteNumber = caller; remoteFrom = sip.from; remoteTo = sip.to; remoteVia = sip.via; localTag = randomHex(6); inviteCseq = sip.cseqNum; bool precond = false; parseSdpMedia(sip.body, remoteRtpIp, remoteRtpPort, negotiatedPt, negotiatedCodec, negotiatedOctetAlign, precond); if (remoteRtpIp.empty()) remoteRtpIp = pcscfIp; sendSipReply(sip, 180, "Ringing", "", ""); writeCallMarker(activeCid, "ringing-in", caller, cfg.ims_sim_slot, mode == "vowifi" ? "VoWiFi" : "VoLTE"); std::string tagToken = (mode == "vowifi" ? "VOWIFI" : "VOLTE") + std::to_string(cfg.ims_sim_slot); spawnCallscreenUi(true, activeCid, caller, tagToken); } else if (sip.method == "BYE" || sip.method == "CANCEL") { if (sip.callId == sipCallId) { sendSipReply(sip, 200, "OK", "", ""); teardownActiveCall("Remote Hangup"); } } else if (sip.method == "MESSAGE") { if (sip.contentType.find("application/vnd.3gpp.sms") != std::string::npos) { std::string sender, text; uint8_t rpMr = 0; if (parseRpDataDeliver(sip.body.data(), sip.body.size(), sender, text, rpMr)) { if (!isPhoneBlocked(sender)) { logSxmoSmsAndModem("recv_txt", sender, text, cfg.ims_sim_slot); } } } sendSipReply(sip, 200, "OK", "", ""); } } void handleRegister401(const SipPacket& sip) { std::string realm = extractHeaderParam(sip.wwwAuth, "realm"); if (realm.empty()) realm = simId.homeDomain; std::string nonceB64 = extractHeaderParam(sip.wwwAuth, "nonce"); std::string alg = toLowerCopy(extractHeaderParam(sip.wwwAuth, "algorithm")); std::string qop = extractHeaderParam(sip.wwwAuth, "qop"); std::string opaque = extractHeaderParam(sip.wwwAuth, "opaque"); std::string authPayload; if (alg.find("aka") != std::string::npos) { auto decoded = base64Decode(nonceB64); if (decoded.size() < 32) return; ba_vowifi::AkaResult res = aka->authenticate(decoded.data(), decoded.data() + 16); if (!res.ok) { ims_str_copy(st.last_error, sizeof(st.last_error), res.error.c_str()); ims_state_write(&st); return; } if (res.syncFailure) { std::string autsB64 = base64Encode(res.auts.data(), res.auts.size()); std::ostringstream hdr; hdr << "Digest username=\"" << simId.impi << "\", realm=\"" << realm << "\", nonce=\"" << nonceB64 << "\", uri=\"sip:" << simId.homeDomain << "\", response=\"\", algorithm=AKAv1-MD5, auts=\"" << autsB64 << "\""; sendRegister("", hdr.str(), 3600); return; } /* Compute AKAv1-MD5 response (password = raw RES bytes per RFC 3310) */ std::vector a1In; std::string a1Pre = simId.impi + ":" + realm + ":"; a1In.assign(a1Pre.begin(), a1Pre.end()); a1In.insert(a1In.end(), res.res.begin(), res.res.end()); std::string ha1 = md5HexBytes(a1In.data(), a1In.size()); std::string ha2 = md5HexStr("REGISTER:sip:" + simId.homeDomain); std::string cnonce = randomHex(4); std::string resp; if (qop.find("auth") != std::string::npos) { resp = md5HexStr(ha1 + ":" + nonceB64 + ":00000001:" + cnonce + ":auth:" + ha2); } else { resp = md5HexStr(ha1 + ":" + nonceB64 + ":" + ha2); } std::ostringstream hdr; hdr << "Digest username=\"" << simId.impi << "\", realm=\"" << realm << "\", nonce=\"" << nonceB64 << "\", uri=\"sip:" << simId.homeDomain << "\", response=\"" << resp << "\", algorithm=AKAv1-MD5"; if (qop.find("auth") != std::string::npos) { hdr << ", qop=auth, nc=00000001, cnonce=\"" << cnonce << "\""; } if (!opaque.empty()) hdr << ", opaque=\"" << opaque << "\""; sendRegister(hdr.str(), "", 3600); } } std::string buildAnswerSdp() { std::string cIp = localIp; std::string conn = (cIp.find(':') != std::string::npos) ? ("IN IP6 " + cIp) : ("IN IP4 " + cIp); std::ostringstream sdp; sdp << "v=0\r\n" << "o=- " << monotonicMs() << " 1 " << conn << "\r\n" << "s=Bananarchy IMS\r\n" << "c=" << conn << "\r\n" << "t=0 0\r\n" << "m=audio " << localRtpPort << " RTP/AVP " << negotiatedPt << "\r\n"; if (negotiatedCodec == "amr-wb") { sdp << "a=rtpmap:" << negotiatedPt << " AMR-WB/16000\r\n" << "a=fmtp:" << negotiatedPt << " mode-set=0,1,2,3,4,5,6,7,8; octet-align=" << (negotiatedOctetAlign ? "1" : "0") << "\r\n"; } else if (negotiatedCodec == "amr-nb") { sdp << "a=rtpmap:" << negotiatedPt << " AMR/8000\r\n" << "a=fmtp:" << negotiatedPt << " octet-align=1\r\n"; } else if (negotiatedCodec == "pcma") { sdp << "a=rtpmap:8 PCMA/8000\r\n"; } else { sdp << "a=rtpmap:0 PCMU/8000\r\n"; } sdp << "a=ptime:20\r\na=sendrecv\r\n"; return sdp.str(); } void startMediaCall(bool isIncoming) { (void)isIncoming; callState = CallState::Active; writeCallMarker(activeCid, "pickedupcall", remoteNumber, cfg.ims_sim_slot, mode == "vowifi" ? "VoWiFi" : "VoLTE"); if (negotiatedCodec == "amr-wb") amrSession.init(true); else if (negotiatedCodec == "amr-nb") amrSession.init(false); audio.open((negotiatedCodec == "amr-wb") ? 16000 : 8000); nextRtpTxMs = monotonicMs(); } void teardownActiveCall(const std::string&) { if (callState != CallState::Idle && !activeCid.empty()) { writeCallMarker(activeCid, "hangedupcall", remoteNumber, cfg.ims_sim_slot, mode == "vowifi" ? "VoWiFi" : "VoLTE"); } callState = CallState::Idle; activeCid.clear(); sipCallId.clear(); remoteNumber.clear(); micMuted = false; amrSession.close(); audio.close(); } void sendRtpFrame() { if (remoteRtpIp.empty() || remoteRtpPort == 0) return; bool wb = (negotiatedCodec == "amr-wb"); size_t nSamples = wb ? 320U : 160U; std::vector pcm(nSamples, 0); if (!micMuted) { audio.readSamples(pcm.data(), nSamples); } std::vector rtp(12, 0); rtp[0] = 0x80U; rtp[1] = static_cast(negotiatedPt & 0x7FU); ba_vowifi::putBe16(rtp, 2, rtpSeq++); ba_vowifi::putBe32(rtp, 4, rtpTs); ba_vowifi::putBe32(rtp, 8, rtpSsrc); rtpTs += static_cast(nSamples); if (wb || negotiatedCodec == "amr-nb") { std::vector pl; if (amrSession.canEncode()) { pl = amrSession.encodeRtp(pcm.data(), nSamples, negotiatedOctetAlign); } if (pl.empty()) { /* Fallback NO_DATA / silence frame if WB encoder unavailable */ pl = {0xF0U, 0x7CU}; } rtp.insert(rtp.end(), pl.begin(), pl.end()); } else if (negotiatedCodec == "pcma") { for (size_t i = 0; i < 160; ++i) rtp.push_back(linearToAlaw(pcm[i])); } else { for (size_t i = 0; i < 160; ++i) rtp.push_back(linearToMulaw(pcm[i])); } sendUdpInner(localRtpPort, remoteRtpIp, remoteRtpPort, rtp.data(), rtp.size()); } void handleRtpPacket(const uint8_t* pkt, size_t len) { if (callState != CallState::Active || len <= 12) return; uint8_t pt = pkt[1] & 0x7FU; const uint8_t* pl = pkt + 12; size_t plen = len - 12; if ((pt == 96 || pt == 98 || pt == 97 || negotiatedCodec.rfind("amr", 0) == 0) && amrSession.canDecode()) { auto pcm = amrSession.decodeRtp(pl, plen, negotiatedOctetAlign); if (!pcm.empty()) audio.writeSamples(pcm.data(), pcm.size()); } else if (pt == 8) { std::vector pcm(plen); for (size_t i = 0; i < plen; ++i) pcm[i] = alawToLinear(pl[i]); audio.writeSamples(pcm.data(), pcm.size()); } else if (pt == 0) { std::vector pcm(plen); for (size_t i = 0; i < plen; ++i) pcm[i] = mulawToLinear(pl[i]); audio.writeSamples(pcm.data(), pcm.size()); } } int openCtlSocket() { std::string sp = stateDir + "/vowifi.sock"; ::unlink(sp.c_str()); int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) return -1; struct sockaddr_un addr{}; addr.sun_family = AF_UNIX; if (sp.size() >= sizeof(addr.sun_path)) { ::close(fd); return -1; } std::memcpy(addr.sun_path, sp.c_str(), sp.size() + 1); if (::bind(fd, reinterpret_cast(&addr), sizeof(addr)) != 0 || ::listen(fd, 8) != 0) { ::close(fd); return -1; } ::chmod(sp.c_str(), 0666); ctlSrvFd = fd; return 0; } void handleCtlClient() { int cfd = ::accept4(ctlSrvFd, nullptr, nullptr, SOCK_CLOEXEC); if (cfd < 0) return; char buf[1024]; ssize_t n = ::read(cfd, buf, sizeof(buf) - 1); if (n <= 0) { ::close(cfd); return; } buf[n] = '\0'; std::string cmd = trimCopy(buf); std::string rsp = "ERR unknown\n"; if (cmd == "STATUS") { std::ostringstream o; o << "OK registered=" << (registered ? 1 : 0) << " active_calls=" << (callState != CallState::Idle ? 1 : 0) << " tech=" << mode << " ipv6=" << (tunnel.usingIpv6 ? 1 : 0) << " pcscf=" << pcscfIp << " tun_ip=" << localIp << " epdg=" << st.epdg_host << "\n"; rsp = o.str(); } else if (cmd == "STOP") { rsp = "OK\n"; g_stop = 1; } else if (cmd.rfind("DIAL ", 0) == 0) { std::string num = trimCopy(cmd.substr(5)); if (!registered || num.empty()) { rsp = "ERR not registered\n"; } else if (callState != CallState::Idle) { rsp = "ERR busy\n"; } else { callState = CallState::Outgoing; activeCid = (mode == "vowifi" ? "vowifi:" : "ims:") + std::to_string(callCounter++); sipCallId = randomHex(8) + "@" + localIp; remoteNumber = num; localTag = randomHex(6); inviteCseq = 1; std::string sdp = buildSdpOffer(false); std::ostringstream inv; inv << "INVITE sip:" << num << "@" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=z9hG4bK" << randomHex(5) << "\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << localTag << "\r\n" << "To: \r\n" << "Call-ID: " << sipCallId << "\r\n" << "CSeq: " << inviteCseq << " INVITE\r\n" << "Contact: \r\n" << "Supported: 100rel, precondition\r\n" << "P-Access-Network-Info: " << accessNetworkHeader() << "\r\n" << "Content-Type: application/sdp\r\n" << "Content-Length: " << sdp.size() << "\r\n\r\n" << sdp; sendSipText(inv.str()); writeCallMarker(activeCid, "dialing", num, cfg.ims_sim_slot, mode == "vowifi" ? "VoWiFi" : "VoLTE"); rsp = "OK " + activeCid + "\n"; } } else if (cmd.rfind("ACCEPT", 0) == 0) { if (callState == CallState::Incoming) { SipPacket req; req.via = remoteVia; req.from = remoteFrom; req.to = remoteTo; req.callId = sipCallId; req.cseqNum = inviteCseq; req.cseqMethod = "INVITE"; sendSipReply(req, 200, "OK", "", buildAnswerSdp()); startMediaCall(true); rsp = "OK\n"; } else { rsp = "ERR no incoming call\n"; } } else if (cmd.rfind("HANGUP", 0) == 0) { if (callState != CallState::Idle) { std::string method = (callState == CallState::Outgoing) ? "CANCEL" : "BYE"; if (callState == CallState::Incoming) { SipPacket req; req.via = remoteVia; req.from = remoteFrom; req.to = remoteTo; req.callId = sipCallId; req.cseqNum = inviteCseq; req.cseqMethod = "INVITE"; sendSipReply(req, 603, "Decline", "", ""); } else { std::ostringstream bye; bye << method << " sip:" << remoteNumber << "@" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=z9hG4bK" << randomHex(5) << "\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << localTag << "\r\n" << "To: " << (remoteTo.empty() ? "" : remoteTo) << "\r\n" << "Call-ID: " << sipCallId << "\r\n" << "CSeq: " << (method == "CANCEL" ? inviteCseq : ++inviteCseq) << " " << method << "\r\n" << "Content-Length: 0\r\n\r\n"; sendSipText(bye.str()); } teardownActiveCall("Hangup"); rsp = "OK\n"; } else { rsp = "OK idle\n"; } } else if (cmd.rfind("MUTE ", 0) == 0) { micMuted = (std::atoi(cmd.c_str() + 5) != 0); rsp = "OK\n"; } else if (cmd.rfind("DTMF ", 0) == 0 && cmd.size() >= 6) { if (callState == CallState::Active && !remoteRtpIp.empty()) { char digit = cmd[5]; int code = (digit >= '0' && digit <= '9') ? (digit - '0') : (digit == '*' ? 10 : (digit == '#' ? 11 : -1)); if (code >= 0) { std::vector rtp(16, 0); rtp[0] = 0x80U; rtp[1] = 101U; /* telephone-event */ ba_vowifi::putBe16(rtp, 2, rtpSeq++); ba_vowifi::putBe32(rtp, 4, rtpTs); ba_vowifi::putBe32(rtp, 8, rtpSsrc); rtp[12] = static_cast(code); rtp[13] = 0x8AU; /* End=1, vol=10 */ rtp[14] = 0x06U; rtp[15] = 0x40U; sendUdpInner(localRtpPort, remoteRtpIp, remoteRtpPort, rtp.data(), rtp.size()); rsp = "OK\n"; } } } else if (cmd.rfind("SMS_SEND ", 0) == 0) { std::string rest = trimCopy(cmd.substr(9)); size_t sp = rest.find(' '); if (!registered || sp == std::string::npos) { rsp = "ERR invalid args or offline\n"; } else { std::string dest = trimCopy(rest.substr(0, sp)); std::string txt = rest.substr(sp + 1); auto rp = buildRpDataSubmit(rpMrCounter++, dest, txt); std::ostringstream m; m << "MESSAGE sip:" << dest << "@" << simId.homeDomain << " SIP/2.0\r\n" << "Via: SIP/2.0/UDP " << localIp << ":" << localSipPort << ";branch=z9hG4bK" << randomHex(5) << "\r\n" << "Max-Forwards: 70\r\n" << "From: <" << simId.impu << ">;tag=" << randomHex(5) << "\r\n" << "To: \r\n" << "Call-ID: " << randomHex(8) << "@" << localIp << "\r\n" << "CSeq: 1 MESSAGE\r\n" << "P-Access-Network-Info: " << accessNetworkHeader() << "\r\n" << "Content-Type: application/vnd.3gpp.sms\r\n" << "Content-Transfer-Encoding: binary\r\n" << "Content-Length: " << rp.size() << "\r\n\r\n"; std::string pkt = m.str(); pkt.append(reinterpret_cast(rp.data()), rp.size()); if (sendSipText(pkt)) { if (std::getenv("BANANARCHY_LOG_SENT_SMS")) { logSxmoSmsAndModem("sent_txt", dest, txt, cfg.ims_sim_slot); } rsp = "OK\n"; } else { rsp = "ERR send failed\n"; } } } else if (cmd == "PROBE_SIM") { rsp = "OK sim=" + std::to_string(cfg.ims_sim_slot) + " impi=" + simId.impi + " domain=" + simId.homeDomain + "\n"; } ssize_t w = ::write(cfd, rsp.data(), rsp.size()); (void)w; ::close(cfd); } }; } // namespace int main(int argc, char** argv) { ::signal(SIGTERM, onSignal); ::signal(SIGINT, onSignal); ::signal(SIGPIPE, SIG_IGN); VowifiDaemon d; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--mode=volte") == 0) { d.mode = "volte"; } else if (std::strcmp(argv[i], "--mode=vowifi") == 0) { d.mode = "vowifi"; } } d.run(); return 0; }