#define _GNU_SOURCE #include "geminux-cell-proto.h" #include "geminux-ims-proto.h" #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 #include #include #include #include #include #include #include #include #include #include #include #define IMS_SOCK_PATH "/run/geminux/ims.sock" #define IMS_STATE_PATH "/run/geminux/ims-state" #define MODEM_SOCK_PATH "/run/geminux/modem.sock" #define CELL_CONF_PATH "/etc/geminux/cellular.conf" #define CELL_LOCK_PATH "/run/geminux/cellctl.lock" #define AIRPLANE_RUN_PATH "/run/geminux/airplane-mode" #define MD1_STATE_SYSFS "/sys/class/mt6797_ccci/md1/state" #define AT_DEV_PATH "/dev/ttyC1" #define AT_DEV_FALLBACK "/dev/ttyC0" #define SWANCTL_CONF "/run/geminux/swanctl-vowifi.conf" typedef enum { IMS_REG_OFF = 0, IMS_REG_DISCOVERING, IMS_REG_REGISTERING, IMS_REG_CHALLENGED, IMS_REG_REGISTERED, IMS_REG_STANDBY, } ims_reg_state_t; typedef enum { IMS_CALL_IDLE = 0, IMS_CALL_OUTGOING, IMS_CALL_INCOMING, IMS_CALL_ACTIVE, } ims_call_state_t; typedef enum { WORK_NONE = 0, WORK_DISCOVER, WORK_AKA_AUTH, } ims_work_kind_t; typedef struct { int epfd; int sig_fd; int srv_fd; int rt_fd; int ino_fd; int reg_tmr_fd; int rtp_tmr_fd; int sip_fd; int esp_raw_fd; int rtp_fd; int work_fd; pid_t work_pid; ims_work_kind_t work_kind; char work_buf[4096]; size_t work_len; bool xfrm_kernel; bool ims_enabled; bool airplane_mode; ims_reg_state_t reg_state; int bearer_mode; /* 0=none, 1=VoLTE, 2=VoWiFi */ int retry_backoff_s; char home_domain[128]; char epdg_fqdn[128]; char pcscf_ip[64]; char local_ip[64]; char smsc_e164[32]; char impi[192]; char impu[192]; char call_id_reg[96]; char reg_branch[64]; char reg_tag[32]; int reg_cseq; int reg_expires; uint16_t sip_local_port; uint16_t sip_remote_port; uint16_t rtp_local_port; /* Challenge / AKA state */ char auth_realm[128]; char auth_nonce[192]; char auth_qop[32]; uint32_t auth_nc; char sec_verify[512]; char service_route[256]; geminux_ims_sec_params_t cli_sec; geminux_ims_sec_params_t srv_sec; uint8_t sha1_key20[20]; uint8_t md5_key16[16]; uint8_t aes_key16[16]; bool sec_keys_valid; uint32_t esp_out_seq; /* Active SIP Call & RTP Media state */ ims_call_state_t call_state; char peer_uri[128]; char peer_num[64]; char call_id_dlg[96]; char call_from[192]; char call_to[192]; char call_via[256]; int call_cseq; uint16_t rseq; geminux_ims_sdp_info_t remote_sdp; bool call_muted; bool call_speaker; uint8_t sms_mr; /* Audio & RTP codecs */ snd_pcm_t *pcm_play; snd_pcm_t *pcm_cap; void *wb_enc; void *wb_dec; void *nb_enc; void *nb_dec; uint16_t rtp_seq; uint32_t rtp_ts; uint32_t rtp_ssrc; char last_written_state[64]; } ims_ctx_t; static uint64_t monotonic_ms(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); } static int read_file_line(const char *path, char *buf, size_t sz) { FILE *f = fopen(path, "r"); if (!f) return -1; if (!fgets(buf, (int)sz, f)) { fclose(f); return -1; } fclose(f); size_t n = strlen(buf); while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; return 0; } static void add_ep(int epfd, int fd) { if (fd < 0) return; struct epoll_event ev = { .events = EPOLLIN, .data.fd = fd }; epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev); } static void del_ep(int epfd, int fd) { if (fd >= 0) epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL); } static void arm_timer_ms(int tfd, uint64_t delay_ms, uint64_t interval_ms) { if (tfd < 0) return; struct itimerspec its; memset(&its, 0, sizeof(its)); its.it_value.tv_sec = (time_t)(delay_ms / 1000ULL); its.it_value.tv_nsec = (long)((delay_ms % 1000ULL) * 1000000ULL); its.it_interval.tv_sec = (time_t)(interval_ms / 1000ULL); its.it_interval.tv_nsec = (long)((interval_ms % 1000ULL) * 1000000ULL); timerfd_settime(tfd, 0, &its, NULL); } static void notify_modem_ctl(const char *msg) { int fd = socket(AF_UNIX, SOCK_STREAM | O_CLOEXEC, 0); if (fd < 0) return; struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", MODEM_SOCK_PATH); if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0) { dprintf(fd, "%s\n", msg); } close(fd); } static void write_ims_state(ims_ctx_t *ctx) { const char *s = "OFF\n"; if (ctx->airplane_mode || !ctx->ims_enabled) { s = "OFF\n"; } else if (ctx->reg_state == IMS_REG_REGISTERED) { s = (ctx->bearer_mode == 2) ? "VoWiFi\n" : "VoLTE\n"; } else { s = "IMS:STANDBY\n"; } if (strcmp(ctx->last_written_state, s) == 0) return; mkdir("/run/geminux", 0755); FILE *f = fopen(IMS_STATE_PATH, "w"); if (f) { fputs(s, f); fclose(f); chmod(IMS_STATE_PATH, 0644); snprintf(ctx->last_written_state, sizeof(ctx->last_written_state), "%s", s); } } static void load_config(ims_ctx_t *ctx) { ctx->ims_enabled = true; FILE *f = fopen(CELL_CONF_PATH, "r"); if (f) { char line[256]; while (fgets(line, sizeof(line), f)) { if (strncmp(line, "ims=", 4) == 0) { ctx->ims_enabled = (line[4] != '0'); } } fclose(f); } char air[16] = {0}; ctx->airplane_mode = (read_file_line(AIRPLANE_RUN_PATH, air, sizeof(air)) == 0 && air[0] == '1'); } static bool md1_is_ready(void) { char buf[16] = {0}; return (read_file_line(MD1_STATE_SYSFS, buf, sizeof(buf)) == 0 && atoi(buf) == 4); } static bool get_iface_ip(const char *ifname, char *ip_out, size_t ip_sz) { ip_out[0] = '\0'; int fd = socket(AF_INET, SOCK_DGRAM | O_CLOEXEC, 0); if (fd < 0) return false; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifname); bool up = (ioctl(fd, SIOCGIFFLAGS, &ifr) == 0 && (ifr.ifr_flags & IFF_UP) != 0); bool ok = false; if (up) { memset(&ifr, 0, sizeof(ifr)); snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifname); if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) { const struct sockaddr_in *sa = (const struct sockaddr_in *)&ifr.ifr_addr; if (inet_ntop(AF_INET, &sa->sin_addr, ip_out, (socklen_t)ip_sz) && ip_out[0]) { ok = true; } } } close(fd); return ok; } static void rand_hex(char *out, size_t hex_len) { static const char hx[] = "0123456789abcdef"; uint8_t b[32]; size_t need = hex_len / 2; if (need > sizeof(b)) need = sizeof(b); int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); if (fd >= 0) { ssize_t unused = read(fd, b, need); (void)unused; close(fd); } else { uint64_t t = monotonic_ms(); memcpy(b, &t, need < sizeof(t) ? need : sizeof(t)); } for (size_t i = 0; i < need; i++) { out[i * 2] = hx[(b[i] >> 4) & 0x0f]; out[i * 2 + 1] = hx[b[i] & 0x0f]; } out[need * 2] = '\0'; } /* ---------------- Kernel NETLINK_XFRM for ipsec-3gpp ---------------- */ static int nla_put(struct nlmsghdr *nh, size_t max_len, uint16_t type, const void *data, size_t len) { size_t alen = NLA_ALIGN(sizeof(struct nlattr) + len); if (nh->nlmsg_len + alen > max_len) return -1; struct nlattr *nla = (struct nlattr *)((uint8_t *)nh + NLMSG_ALIGN(nh->nlmsg_len)); nla->nla_type = type; nla->nla_len = (uint16_t)(sizeof(struct nlattr) + len); memcpy((uint8_t *)nla + sizeof(struct nlattr), data, len); nh->nlmsg_len = (uint32_t)(NLMSG_ALIGN(nh->nlmsg_len) + alen); return 0; } static int xfrm_add_sa_and_policy(ims_ctx_t *ctx, bool add) { if (!ctx->xfrm_kernel || !ctx->sec_keys_valid || !ctx->local_ip[0] || !ctx->pcscf_ip[0]) { return -1; } struct in_addr l4, r4; if (inet_pton(AF_INET, ctx->local_ip, &l4) != 1 || inet_pton(AF_INET, ctx->pcscf_ip, &r4) != 1) { return -1; } int fd = socket(PF_NETLINK, SOCK_RAW | O_CLOEXEC, NETLINK_XFRM); if (fd < 0) return -1; struct sockaddr_nl nl = { .nl_family = AF_NETLINK }; if (bind(fd, (struct sockaddr *)&nl, sizeof(nl)) < 0) { close(fd); return -1; } /* Add/Delete two unidirectional ESP transport SAs (UE->P-CSCF and P-CSCF->UE) */ for (int dir = 0; dir < 2; dir++) { uint8_t buf[1024]; memset(buf, 0, sizeof(buf)); struct nlmsghdr *nh = (struct nlmsghdr *)buf; nh->nlmsg_type = add ? XFRM_MSG_NEWSA : XFRM_MSG_DELSA; nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | (add ? (NLM_F_CREATE | NLM_F_REPLACE) : 0); nh->nlmsg_seq = (uint32_t)(dir + 1); nh->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_info)); struct xfrm_usersa_info *sa = (struct xfrm_usersa_info *)NLMSG_DATA(nh); sa->family = AF_INET; sa->mode = XFRM_MODE_TRANSPORT; sa->id.proto = IPPROTO_ESP; sa->id.spi = htonl(dir == 0 ? ctx->srv_sec.spi_s : ctx->cli_sec.spi_c); sa->saddr.a4 = (dir == 0) ? l4.s_addr : r4.s_addr; sa->id.daddr.a4 = (dir == 0) ? r4.s_addr : l4.s_addr; sa->lft.soft_byte_limit = XFRM_INF; sa->lft.hard_byte_limit = XFRM_INF; sa->lft.soft_packet_limit = XFRM_INF; sa->lft.hard_packet_limit = XFRM_INF; sa->replay_window = 32; if (add) { uint8_t auth_buf[sizeof(struct xfrm_algo_auth) + 32]; memset(auth_buf, 0, sizeof(auth_buf)); struct xfrm_algo_auth *aa = (struct xfrm_algo_auth *)auth_buf; if (ctx->srv_sec.alg == GEMINUX_IMS_ALG_HMAC_MD5_96) { snprintf(aa->alg_name, sizeof(aa->alg_name), "hmac(md5)"); aa->alg_key_len = 128; aa->alg_trunc_len = 96; memcpy(aa->alg_key, ctx->md5_key16, 16); nla_put(nh, sizeof(buf), XFRMA_ALG_AUTH_TRUNC, auth_buf, sizeof(struct xfrm_algo_auth) + 16); } else { snprintf(aa->alg_name, sizeof(aa->alg_name), "hmac(sha1)"); aa->alg_key_len = 160; aa->alg_trunc_len = 96; memcpy(aa->alg_key, ctx->sha1_key20, 20); nla_put(nh, sizeof(buf), XFRMA_ALG_AUTH_TRUNC, auth_buf, sizeof(struct xfrm_algo_auth) + 20); } uint8_t enc_buf[sizeof(struct xfrm_algo) + 16]; memset(enc_buf, 0, sizeof(enc_buf)); struct xfrm_algo *ea = (struct xfrm_algo *)enc_buf; if (ctx->srv_sec.ealg == GEMINUX_IMS_EALG_AES_CBC) { snprintf(ea->alg_name, sizeof(ea->alg_name), "cbc(aes)"); ea->alg_key_len = 128; memcpy(ea->alg_key, ctx->aes_key16, 16); nla_put(nh, sizeof(buf), XFRMA_ALG_CRYPT, enc_buf, sizeof(struct xfrm_algo) + 16); } else { snprintf(ea->alg_name, sizeof(ea->alg_name), "cipher_null"); ea->alg_key_len = 0; nla_put(nh, sizeof(buf), XFRMA_ALG_CRYPT, enc_buf, sizeof(struct xfrm_algo)); } } struct sockaddr_nl dst = { .nl_family = AF_NETLINK }; ssize_t unused_s = sendto(fd, buf, nh->nlmsg_len, 0, (struct sockaddr *)&dst, sizeof(dst)); (void)unused_s; uint8_t ack[256]; ssize_t unused_r = recv(fd, ack, sizeof(ack), 0); (void)unused_r; } /* Add/Delete outbound & inbound SP for UE<->P-CSCF protected ports */ for (int dir = 0; dir < 2; dir++) { uint8_t buf[512]; memset(buf, 0, sizeof(buf)); struct nlmsghdr *nh = (struct nlmsghdr *)buf; nh->nlmsg_type = add ? XFRM_MSG_NEWPOLICY : XFRM_MSG_DELPOLICY; nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | (add ? (NLM_F_CREATE | NLM_F_REPLACE) : 0); nh->nlmsg_seq = (uint32_t)(dir + 10); nh->nlmsg_len = NLMSG_LENGTH(sizeof(struct xfrm_userpolicy_info)); struct xfrm_userpolicy_info *pol = (struct xfrm_userpolicy_info *)NLMSG_DATA(nh); pol->sel.family = AF_INET; pol->sel.proto = IPPROTO_UDP; pol->sel.prefixlen_s = 32; pol->sel.prefixlen_d = 32; pol->sel.saddr.a4 = (dir == 0) ? l4.s_addr : r4.s_addr; pol->sel.daddr.a4 = (dir == 0) ? r4.s_addr : l4.s_addr; pol->sel.sport = htons(dir == 0 ? ctx->cli_sec.port_c : ctx->srv_sec.port_s); pol->sel.sport_mask = 0xffff; pol->sel.dport = htons(dir == 0 ? ctx->srv_sec.port_s : ctx->cli_sec.port_c); pol->sel.dport_mask = 0xffff; pol->dir = (dir == 0) ? XFRM_POLICY_OUT : XFRM_POLICY_IN; pol->action = XFRM_POLICY_ALLOW; pol->priority = 100; pol->lft.soft_byte_limit = XFRM_INF; pol->lft.hard_byte_limit = XFRM_INF; pol->lft.soft_packet_limit = XFRM_INF; pol->lft.hard_packet_limit = XFRM_INF; if (add) { struct xfrm_user_tmpl tmpl; memset(&tmpl, 0, sizeof(tmpl)); tmpl.family = AF_INET; tmpl.id.proto = IPPROTO_ESP; tmpl.id.spi = htonl(dir == 0 ? ctx->srv_sec.spi_s : ctx->cli_sec.spi_c); tmpl.saddr.a4 = pol->sel.saddr.a4; tmpl.id.daddr.a4 = pol->sel.daddr.a4; tmpl.mode = XFRM_MODE_TRANSPORT; tmpl.aalgos = ~0U; tmpl.ealgos = ~0U; tmpl.calgos = ~0U; nla_put(nh, sizeof(buf), XFRMA_TMPL, &tmpl, sizeof(tmpl)); } struct sockaddr_nl dst = { .nl_family = AF_NETLINK }; ssize_t unused_s = sendto(fd, buf, nh->nlmsg_len, 0, (struct sockaddr *)&dst, sizeof(dst)); (void)unused_s; uint8_t ack[256]; ssize_t unused_r = recv(fd, ack, sizeof(ack), 0); (void)unused_r; } close(fd); return 0; } /* ---------------- Codec & ALSA Media Lifecycle ---------------- */ static void close_media(ims_ctx_t *ctx) { arm_timer_ms(ctx->rtp_tmr_fd, 0, 0); if (ctx->rtp_fd >= 0) { del_ep(ctx->epfd, ctx->rtp_fd); close(ctx->rtp_fd); ctx->rtp_fd = -1; } if (ctx->pcm_play) { snd_pcm_drop(ctx->pcm_play); snd_pcm_close(ctx->pcm_play); ctx->pcm_play = NULL; } if (ctx->pcm_cap) { snd_pcm_drop(ctx->pcm_cap); snd_pcm_close(ctx->pcm_cap); ctx->pcm_cap = NULL; } if (ctx->wb_enc) { E_IF_exit(ctx->wb_enc); ctx->wb_enc = NULL; } if (ctx->wb_dec) { D_IF_exit(ctx->wb_dec); ctx->wb_dec = NULL; } if (ctx->nb_enc) { Encoder_Interface_exit(ctx->nb_enc); ctx->nb_enc = NULL; } if (ctx->nb_dec) { Decoder_Interface_exit(ctx->nb_dec); ctx->nb_dec = NULL; } } static void open_rtp_socket(ims_ctx_t *ctx) { if (ctx->rtp_fd >= 0) return; int fd = socket(AF_INET, SOCK_DGRAM | O_NONBLOCK | O_CLOEXEC, 0); if (fd < 0) return; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(ctx->rtp_local_port); if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) != 0) { sin.sin_port = 0; if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) != 0) { close(fd); return; } } socklen_t sl = sizeof(sin); if (getsockname(fd, (struct sockaddr *)&sin, &sl) == 0) { ctx->rtp_local_port = ntohs(sin.sin_port); } ctx->rtp_fd = fd; add_ep(ctx->epfd, ctx->rtp_fd); } static void start_media(ims_ctx_t *ctx) { open_rtp_socket(ctx); int rate = (ctx->remote_sdp.preferred_rate == 8000) ? 8000 : 16000; if (rate == 16000) { ctx->wb_enc = E_IF_init(); ctx->wb_dec = D_IF_init(); } else { ctx->nb_enc = Encoder_Interface_init(0); ctx->nb_dec = Decoder_Interface_init(); } if (snd_pcm_open(&ctx->pcm_play, "default", SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) == 0) { if (snd_pcm_set_params(ctx->pcm_play, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 1, (unsigned)rate, 1, 100000) < 0) { snd_pcm_close(ctx->pcm_play); ctx->pcm_play = NULL; } } if (snd_pcm_open(&ctx->pcm_cap, "default", SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) == 0) { if (snd_pcm_set_params(ctx->pcm_cap, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 1, (unsigned)rate, 1, 100000) < 0) { snd_pcm_close(ctx->pcm_cap); ctx->pcm_cap = NULL; } } ctx->rtp_seq = 1; ctx->rtp_ts = 0; ctx->rtp_ssrc = (uint32_t)(monotonic_ms() & 0xffffffffU); arm_timer_ms(ctx->rtp_tmr_fd, 20, 20); } static void handle_rtp_tick(ims_ctx_t *ctx) { if (ctx->call_state != IMS_CALL_ACTIVE || ctx->rtp_fd < 0 || !ctx->remote_sdp.valid) return; int rate = (ctx->remote_sdp.preferred_rate == 8000) ? 8000 : 16000; snd_pcm_uframes_t samples = (rate == 16000) ? 320 : 160; int16_t pcm[320]; memset(pcm, 0, sizeof(pcm)); if (!ctx->call_muted && ctx->pcm_cap) { snd_pcm_sframes_t r = snd_pcm_readi(ctx->pcm_cap, pcm, samples); if (r == -EPIPE) { snd_pcm_prepare(ctx->pcm_cap); } else if (r < 0) { memset(pcm, 0, sizeof(pcm)); } } uint8_t encoded[128], rtp[256]; int enc_len = 0; uint8_t pt = (uint8_t)ctx->remote_sdp.active_pt; uint8_t ft = 8; if (rate == 16000 && ctx->wb_enc) { enc_len = E_IF_encode(ctx->wb_enc, 8, pcm, encoded, 0); if (enc_len > 1) { ft = (uint8_t)((encoded[0] >> 3) & 0x0f); int rlen = geminux_ims_rtp_pack_amr(pt, ctx->rtp_seq++, ctx->rtp_ts, ctx->rtp_ssrc, false, 8, ft, true, encoded + 1, (size_t)(enc_len - 1), rtp, sizeof(rtp)); if (rlen > 0) { struct sockaddr_in dst; memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_port = htons(ctx->remote_sdp.remote_port); if (inet_pton(AF_INET, ctx->remote_sdp.remote_ip, &dst.sin_addr) == 1) { ssize_t unused = sendto(ctx->rtp_fd, rtp, (size_t)rlen, 0, (struct sockaddr *)&dst, sizeof(dst)); (void)unused; } } } } else if (rate == 8000 && ctx->nb_enc) { enc_len = Encoder_Interface_Encode(ctx->nb_enc, MR122, pcm, encoded, 0); if (enc_len > 1) { ft = (uint8_t)((encoded[0] >> 3) & 0x0f); int rlen = geminux_ims_rtp_pack_amr(pt, ctx->rtp_seq++, ctx->rtp_ts, ctx->rtp_ssrc, false, 7, ft, true, encoded + 1, (size_t)(enc_len - 1), rtp, sizeof(rtp)); if (rlen > 0) { struct sockaddr_in dst; memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_port = htons(ctx->remote_sdp.remote_port); if (inet_pton(AF_INET, ctx->remote_sdp.remote_ip, &dst.sin_addr) == 1) { ssize_t unused = sendto(ctx->rtp_fd, rtp, (size_t)rlen, 0, (struct sockaddr *)&dst, sizeof(dst)); (void)unused; } } } } ctx->rtp_ts += (uint32_t)samples; } static void handle_rtp_rx(ims_ctx_t *ctx) { uint8_t rtp[512]; ssize_t n; while ((n = recv(ctx->rtp_fd, rtp, sizeof(rtp), 0)) > 0) { uint8_t pt = 0, ft = 0; uint8_t speech[128]; bool qbit = true; int slen = geminux_ims_rtp_unpack_amr(rtp, (size_t)n, &pt, NULL, NULL, &ft, &qbit, speech, sizeof(speech)); if (slen <= 0) continue; uint8_t frame[129]; frame[0] = (uint8_t)(((ft & 0x0f) << 3) | (qbit ? 0x04 : 0x00)); memcpy(frame + 1, speech, (size_t)slen); int16_t pcm[320]; if (ctx->remote_sdp.preferred_rate == 8000 && ctx->nb_dec) { Decoder_Interface_Decode(ctx->nb_dec, frame, pcm, 0); if (ctx->pcm_play) { snd_pcm_sframes_t w = snd_pcm_writei(ctx->pcm_play, pcm, 160); if (w == -EPIPE) snd_pcm_prepare(ctx->pcm_play); } } else if (ctx->wb_dec) { D_IF_decode(ctx->wb_dec, frame, pcm, _good_frame); if (ctx->pcm_play) { snd_pcm_sframes_t w = snd_pcm_writei(ctx->pcm_play, pcm, 320); if (w == -EPIPE) snd_pcm_prepare(ctx->pcm_play); } } } } /* ---------------- SIP & Raw ESP Transport ---------------- */ static void open_sip_sockets(ims_ctx_t *ctx) { if (ctx->sip_fd < 0) { int fd = socket(AF_INET, SOCK_DGRAM | O_NONBLOCK | O_CLOEXEC, 0); if (fd >= 0) { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(ctx->sip_local_port); if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) == 0) { ctx->sip_fd = fd; add_ep(ctx->epfd, ctx->sip_fd); } else { close(fd); } } } if (!ctx->xfrm_kernel && ctx->esp_raw_fd < 0) { int rfd = socket(AF_INET, SOCK_RAW | O_NONBLOCK | O_CLOEXEC, IPPROTO_ESP); if (rfd >= 0) { ctx->esp_raw_fd = rfd; add_ep(ctx->epfd, ctx->esp_raw_fd); } } } static void close_sip_sockets(ims_ctx_t *ctx) { if (ctx->sip_fd >= 0) { del_ep(ctx->epfd, ctx->sip_fd); close(ctx->sip_fd); ctx->sip_fd = -1; } if (ctx->esp_raw_fd >= 0) { del_ep(ctx->epfd, ctx->esp_raw_fd); close(ctx->esp_raw_fd); ctx->esp_raw_fd = -1; } } static int send_sip_msg(ims_ctx_t *ctx, const char *sip_txt, size_t len, bool use_ipsec) { if (!ctx->pcscf_ip[0] || ctx->sip_fd < 0) return -1; struct sockaddr_in dst; memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; if (inet_pton(AF_INET, ctx->pcscf_ip, &dst.sin_addr) != 1) return -1; uint16_t dport = (use_ipsec && ctx->srv_sec.valid) ? ctx->srv_sec.port_s : ctx->sip_remote_port; uint16_t sport = (use_ipsec && ctx->cli_sec.valid) ? ctx->cli_sec.port_c : ctx->sip_local_port; if (use_ipsec && !ctx->xfrm_kernel && ctx->sec_keys_valid && ctx->esp_raw_fd >= 0) { uint8_t esp_pkt[GEMINUX_IMS_MAX_PKT]; uint8_t iv[16]; memset(iv, 0, sizeof(iv)); int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); if (fd >= 0) { ssize_t unused = read(fd, iv, sizeof(iv)); (void)unused; close(fd); } const uint8_t *ak = (ctx->srv_sec.alg == GEMINUX_IMS_ALG_HMAC_MD5_96) ? ctx->md5_key16 : ctx->sha1_key20; int elen = geminux_ims_esp_pack_udp(ctx->srv_sec.spi_s, ++ctx->esp_out_seq, ctx->srv_sec.ealg, ctx->srv_sec.alg, ctx->aes_key16, ak, iv, sport, dport, (const uint8_t *)sip_txt, len, esp_pkt, sizeof(esp_pkt)); if (elen > 0) { dst.sin_port = 0; ssize_t w = sendto(ctx->esp_raw_fd, esp_pkt, (size_t)elen, 0, (struct sockaddr *)&dst, sizeof(dst)); return (w == elen) ? 0 : -1; } } dst.sin_port = htons(dport); ssize_t w = sendto(ctx->sip_fd, sip_txt, len, 0, (struct sockaddr *)&dst, sizeof(dst)); return (w == (ssize_t)len) ? 0 : -1; } static void send_initial_register(ims_ctx_t *ctx) { if (!ctx->pcscf_ip[0] || !ctx->local_ip[0] || !ctx->home_domain[0] || !ctx->impi[0]) return; open_sip_sockets(ctx); ctx->reg_cseq++; rand_hex(ctx->reg_branch + 7, 16); memcpy(ctx->reg_branch, "z9hG4bK", 7); ctx->cli_sec.valid = true; ctx->cli_sec.alg = GEMINUX_IMS_ALG_HMAC_SHA1_96; ctx->cli_sec.ealg = GEMINUX_IMS_EALG_NULL; ctx->cli_sec.spi_c = 10001; ctx->cli_sec.spi_s = 10002; ctx->cli_sec.port_c = ctx->sip_local_port; ctx->cli_sec.port_s = (uint16_t)(ctx->sip_local_port + 1); char sip_buf[2048]; const char *ani = (ctx->bearer_mode == 2) ? "IEEE-802.11;i-wlan-node-id=000000000000" : "3GPP-E-UTRAN-FDD"; int len = geminux_ims_build_register(sip_buf, sizeof(sip_buf), ctx->pcscf_ip, ctx->home_domain, ctx->local_ip, ctx->sip_local_port, ctx->impi, ctx->impu, ctx->call_id_reg, ctx->reg_cseq, ctx->reg_branch, ctx->reg_tag, ctx->reg_expires, &ctx->cli_sec, NULL, NULL, ani); if (len > 0 && send_sip_msg(ctx, sip_buf, (size_t)len, false) == 0) { ctx->reg_state = IMS_REG_REGISTERING; } } /* ---------------- Forked Worker for AT / PDN / ePDG / AKA ---------------- */ static int run_capture(const char *const argv[], char *out, size_t out_sz) { if (out && out_sz) out[0] = '\0'; int pfd[2] = {-1, -1}; if (out && out_sz && pipe2(pfd, O_CLOEXEC | O_NONBLOCK) != 0) return -1; pid_t pid = fork(); if (pid < 0) { if (pfd[0] >= 0) { close(pfd[0]); close(pfd[1]); } return -1; } if (pid == 0) { int devnull = open("/dev/null", O_RDWR); if (devnull >= 0) { dup2(devnull, STDIN_FILENO); if (pfd[1] < 0) dup2(devnull, STDOUT_FILENO); dup2(devnull, STDERR_FILENO); if (devnull > 2) close(devnull); } if (pfd[1] >= 0) { close(pfd[0]); dup2(pfd[1], STDOUT_FILENO); if (pfd[1] > 2) close(pfd[1]); } execvp(argv[0], (char *const *)argv); _exit(127); } if (pfd[1] >= 0) close(pfd[1]); if (pfd[0] >= 0) { size_t pos = 0; uint64_t deadline = monotonic_ms() + 4000ULL; while (pos + 1 < out_sz && monotonic_ms() < deadline) { struct pollfd pf = { .fd = pfd[0], .events = POLLIN }; int pr = poll(&pf, 1, 100); if (pr <= 0) { if (waitpid(pid, NULL, WNOHANG) == pid) break; continue; } ssize_t r = read(pfd[0], out + pos, out_sz - 1 - pos); if (r <= 0) break; pos += (size_t)r; out[pos] = '\0'; } close(pfd[0]); } int st = 0; while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {} return WIFEXITED(st) ? WEXITSTATUS(st) : 1; } static int worker_at_cmd(int tty_fd, const char *cmd, char *resp, size_t resp_sz, int timeout_ms) { if (resp && resp_sz) resp[0] = '\0'; char tx[256]; int tlen = snprintf(tx, sizeof(tx), "%s\r", cmd); if (tlen <= 0) return -1; ssize_t unused = write(tty_fd, tx, (size_t)tlen); (void)unused; char lbuf[1024]; size_t lpos = 0, rpos = 0; uint64_t deadline = monotonic_ms() + (uint64_t)timeout_ms; while (monotonic_ms() < deadline) { struct pollfd pf = { .fd = tty_fd, .events = POLLIN }; if (poll(&pf, 1, 100) <= 0) continue; char rb[256]; ssize_t r = read(tty_fd, rb, sizeof(rb)); if (r <= 0) break; for (ssize_t i = 0; i < r; i++) { char ch = rb[i]; if (ch == '\r') continue; if (ch == '\n') { lbuf[lpos] = '\0'; size_t len = lpos; lpos = 0; if (len == 0) continue; if (strcmp(lbuf, "OK") == 0) return 0; if (strcmp(lbuf, "ERROR") == 0 || strncmp(lbuf, "+CME ERROR", 10) == 0) return 1; if (resp && rpos + 1 < resp_sz) { int w = snprintf(resp + rpos, resp_sz - rpos, "%s\n", lbuf); if (w > 0) rpos += (size_t)w < (resp_sz - rpos) ? (size_t)w : (resp_sz - rpos - 1); } } else if (lpos + 1 < sizeof(lbuf)) { lbuf[lpos++] = ch; } } } return -1; } static void extract_cgla_hex(const char *resp, char *hex_out, size_t hex_sz) { hex_out[0] = '\0'; const char *p = strstr(resp, "+CGLA:"); if (!p) return; const char *q1 = strchr(p, '"'); if (!q1) return; const char *q2 = strchr(q1 + 1, '"'); if (!q2) return; size_t n = (size_t)(q2 - q1 - 1); if (n >= hex_sz) n = hex_sz - 1; memcpy(hex_out, q1 + 1, n); hex_out[n] = '\0'; } static int parse_ccho_channel(const char *resp) { const char *p = strstr(resp, "+CCHO:"); if (!p) return -1; p += 6; while (*p == ' ') p++; return isdigit((unsigned char)*p) ? atoi(p) : -1; } static void extract_pcscf_from_rdp(const char *rdp, char *pcscf_out, size_t sz) { pcscf_out[0] = '\0'; /* AT+CGCONTRDP quote tokens after primary/secondary DNS (tokens 6 & 7) hold P-CSCF */ const char *tokens[12]; size_t lens[12]; int count = 0; const char *p = rdp; while (*p && count < 12) { const char *q1 = strchr(p, '"'); if (!q1) break; q1++; const char *q2 = strchr(q1, '"'); if (!q2) break; tokens[count] = q1; lens[count] = (size_t)(q2 - q1); count++; p = q2 + 1; } for (int idx = 6; idx < count; idx++) { if (lens[idx] > 3 && lens[idx] < sz) { struct in_addr a4; char cand[64]; memcpy(cand, tokens[idx], lens[idx]); cand[lens[idx]] = '\0'; if (inet_pton(AF_INET, cand, &a4) == 1) { snprintf(pcscf_out, sz, "%s", cand); return; } } } } static int open_ims_at_tty(void) { int fd = open(AT_DEV_PATH, O_RDWR | O_NOCTTY | O_CLOEXEC); if (fd < 0) fd = open(AT_DEV_FALLBACK, O_RDWR | O_NOCTTY | O_CLOEXEC); if (fd < 0) return -1; struct termios tio; if (tcgetattr(fd, &tio) == 0) { cfmakeraw(&tio); cfsetispeed(&tio, B115200); cfsetospeed(&tio, B115200); tcsetattr(fd, TCSANOW, &tio); } return fd; } static void read_isim_ef_string(int tty, int ch, const char *ef_hex, char *out, size_t sz) { char cmd[128], resp[512], hbuf[512]; /* Select EF under current DF_ISIM ADF and read binary */ snprintf(cmd, sizeof(cmd), "AT+CGLA=%d,14,\"00A4020402%s\"", ch, ef_hex); if (worker_at_cmd(tty, cmd, resp, sizeof(resp), 1200) != 0) return; snprintf(cmd, sizeof(cmd), "AT+CGLA=%d,10,\"00B00000FF\"", ch); if (worker_at_cmd(tty, cmd, resp, sizeof(resp), 1200) == 0) { extract_cgla_hex(resp, hbuf, sizeof(hbuf)); geminux_ims_parse_isim_tlv(hbuf, out, sz); } } static void read_isim_identity(int tty, char *dom, size_t dom_sz, char *impi, size_t impi_sz, char *impu, size_t impu_sz) { char resp[512]; if (worker_at_cmd(tty, "AT+CCHO=\"A0000000871004FFFFFFFF89041900FF\"", resp, sizeof(resp), 1500) != 0) { return; } int ch = parse_ccho_channel(resp); if (ch <= 0) return; read_isim_ef_string(tty, ch, "6F02", impi, impi_sz); if (!dom[0]) read_isim_ef_string(tty, ch, "6F03", dom, dom_sz); read_isim_ef_string(tty, ch, "6F04", impu, impu_sz); char ccmd[32]; snprintf(ccmd, sizeof(ccmd), "AT+CCHC=%d", ch); worker_at_cmd(tty, ccmd, resp, sizeof(resp), 600); } static void configure_ccmni1_iface(const char *lip) { char cidr[48]; snprintf(cidr, sizeof(cidr), "%s/32", lip); const char *up[] = {"ip", "link", "set", "dev", "ccmni1", "mtu", "1500", "up", NULL}; const char *ad[] = {"ip", "-4", "addr", "replace", cidr, "dev", "ccmni1", NULL}; const char *rt[] = {"ip", "-4", "route", "replace", "default", "dev", "ccmni1", "table", "201", NULL}; const char *rd[] = {"ip", "-4", "rule", "del", "from", cidr, "lookup", "201", NULL}; const char *ra[] = {"ip", "-4", "rule", "add", "from", cidr, "lookup", "201", "priority", "201", NULL}; run_capture(up, NULL, 0); run_capture(ad, NULL, 0); run_capture(rt, NULL, 0); run_capture(rd, NULL, 0); run_capture(ra, NULL, 0); } static void start_discover_worker(ims_ctx_t *ctx) { if (ctx->work_pid > 0) return; int pfd[2]; if (pipe2(pfd, O_NONBLOCK | O_CLOEXEC) != 0) return; bool can_xfrm = ctx->xfrm_kernel; pid_t pid = fork(); if (pid < 0) { close(pfd[0]); close(pfd[1]); return; } if (pid == 0) { close(pfd[0]); int outfd = pfd[1]; char bearer[16] = "none", dom[128] = "", epdg[128] = "", pcscf[64] = "", lip[64] = ""; char impi[192] = "", impu[192] = ""; /* 1. Try querying PLMN MCC/MNC safely from mmcli without disturbing ModemManager */ int mcc = 0; char mnc_str[8] = ""; char mm_out[2048] = {0}; const char *mm_cmd[] = {"mmcli", "-m", "any", "-K", NULL}; if (run_capture(mm_cmd, mm_out, sizeof(mm_out)) == 0 && mm_out[0]) { const char *oc = strstr(mm_out, "modem.3gpp.operator-code"); if (oc) { const char *col = strchr(oc, ':'); if (col) { col++; while (*col == ' ') col++; if (strlen(col) >= 5 && isdigit((unsigned char)col[0])) { char m3[4] = {col[0], col[1], col[2], '\0'}; mcc = atoi(m3); size_t mn = 0; while (isdigit((unsigned char)col[3 + mn]) && mn < 3) { mnc_str[mn] = col[3 + mn]; mn++; } mnc_str[mn] = '\0'; } } } } if (mcc >= 100 && mnc_str[0]) { geminux_ims_derive_domains(mcc, mnc_str, dom, sizeof(dom), epdg, sizeof(epdg)); } /* 2. Check existing ccmni1 IP or try AT on dedicated ttyC1 (fallback ttyC0) */ if (get_iface_ip("ccmni1", lip, sizeof(lip)) && lip[0]) { snprintf(bearer, sizeof(bearer), "volte"); } if (md1_is_ready()) { int lfd = open(CELL_LOCK_PATH, O_CREAT | O_RDWR | O_CLOEXEC, 0600); if (lfd >= 0 && flock(lfd, LOCK_EX | LOCK_NB) == 0) { int tty = open_ims_at_tty(); if (tty >= 0) { char resp[1024]; worker_at_cmd(tty, "ATE0", resp, sizeof(resp), 600); read_isim_identity(tty, dom, sizeof(dom), impi, sizeof(impi), impu, sizeof(impu)); if (!impi[0] && dom[0]) { /* Only read IMSI inside C RAM when ISIM EF_IMPI absent; never log or write to disk */ if (worker_at_cmd(tty, "AT+CIMI", resp, sizeof(resp), 1000) == 0) { size_t ipos = 0; char imsi[24] = ""; for (const char *p = resp; *p && ipos + 1 < sizeof(imsi); p++) { if (isdigit((unsigned char)*p)) imsi[ipos++] = *p; } imsi[ipos] = '\0'; if (ipos >= 6) { geminux_ims_derive_identities(imsi, dom, impi, sizeof(impi), impu, sizeof(impu)); } memset(imsi, 0, sizeof(imsi)); } } if (worker_at_cmd(tty, "AT+CGDCONT=2,\"IPV4V6\",\"ims\"", resp, sizeof(resp), 1500) == 0 && worker_at_cmd(tty, "AT+CGACT=1,2", resp, sizeof(resp), 6000) == 0) { if (worker_at_cmd(tty, "AT+CGPADDR=2", resp, sizeof(resp), 1200) == 0) { char v4[32] = {0}, gw[32] = {0}, d1[32] = {0}, d2[32] = {0}; if (geminux_parse_cgpaddr_and_rdp(resp, v4, sizeof(v4), gw, sizeof(gw), d1, sizeof(d1), d2, sizeof(d2)) == 0 && v4[0]) { snprintf(lip, sizeof(lip), "%s", v4); snprintf(bearer, sizeof(bearer), "volte"); configure_ccmni1_iface(lip); if (worker_at_cmd(tty, "AT+CGCONTRDP=2", resp, sizeof(resp), 1200) == 0) { extract_pcscf_from_rdp(resp, pcscf, sizeof(pcscf)); } } } } close(tty); } flock(lfd, LOCK_UN); } if (lfd >= 0) close(lfd); } /* 3. VoWiFi SWu fallback if VoLTE P-CSCF absent and wlan0 is up */ char wlip[64] = {0}; if (!pcscf[0] && get_iface_ip("wlan0", wlip, sizeof(wlip)) && wlip[0] && epdg[0]) { snprintf(lip, sizeof(lip), "%s", wlip); if (can_xfrm && access("/usr/sbin/swanctl", X_OK) == 0) { FILE *sf = fopen(SWANCTL_CONF, "w"); if (sf) { fprintf(sf, "connections {\n" " geminux-vowifi {\n" " version = 2\n" " remote_addrs = %s\n" " vips = 0.0.0.0\n" " local { auth = eap-aka }\n" " remote { auth = pubkey }\n" " children {\n" " ims-swu {\n" " local_ts = dynamic\n" " remote_ts = 0.0.0.0/0\n" " }\n" " }\n" " }\n" "}\n", epdg); fclose(sf); chmod(SWANCTL_CONF, 0600); } } struct addrinfo hints, *res = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; if (getaddrinfo(epdg, NULL, &hints, &res) == 0 && res) { const struct sockaddr_in *s4 = (const struct sockaddr_in *)res->ai_addr; inet_ntop(AF_INET, &s4->sin_addr, pcscf, sizeof(pcscf)); freeaddrinfo(res); } if (pcscf[0]) snprintf(bearer, sizeof(bearer), "vowifi"); } dprintf(outfd, "bearer=%s\ndom=%s\nepdg=%s\npcscf=%s\nlip=%s\nimpi=%s\nimpu=%s\n", bearer, dom, epdg, pcscf, lip, impi, impu); memset(impi, 0, sizeof(impi)); memset(impu, 0, sizeof(impu)); close(outfd); _exit(0); } close(pfd[1]); ctx->work_pid = pid; ctx->work_fd = pfd[0]; ctx->work_kind = WORK_DISCOVER; ctx->work_len = 0; ctx->work_buf[0] = '\0'; add_ep(ctx->epfd, ctx->work_fd); ctx->reg_state = IMS_REG_DISCOVERING; } static void start_aka_worker(ims_ctx_t *ctx, const uint8_t rand16[16], const uint8_t autn16[16]) { if (ctx->work_pid > 0) return; int pfd[2]; if (pipe2(pfd, O_NONBLOCK | O_CLOEXEC) != 0) return; uint8_t rcopy[16], acopy[16]; memcpy(rcopy, rand16, 16); memcpy(acopy, autn16, 16); pid_t pid = fork(); if (pid < 0) { close(pfd[0]); close(pfd[1]); return; } if (pid == 0) { close(pfd[0]); int outfd = pfd[1]; char res_hex[64] = "", ck_hex[33] = "", ik_hex[33] = "", auts[64] = ""; int sync = 0; int lfd = open(CELL_LOCK_PATH, O_CREAT | O_RDWR | O_CLOEXEC, 0600); if (lfd >= 0 && flock(lfd, LOCK_EX | LOCK_NB) == 0) { int tty = open(AT_DEV_PATH, O_RDWR | O_NOCTTY | O_CLOEXEC); if (tty >= 0) { struct termios tio; if (tcgetattr(tty, &tio) == 0) { cfmakeraw(&tio); cfsetispeed(&tio, B115200); cfsetospeed(&tio, B115200); tcsetattr(tty, TCSANOW, &tio); } char resp[1024], apdu[96], cgla_cmd[160], hex_rsp[512]; worker_at_cmd(tty, "ATE0", resp, sizeof(resp), 500); if (worker_at_cmd(tty, "AT+CCHO=\"A0000000871004FFFFFFFF89041900FF\"", resp, sizeof(resp), 1500) != 0) { worker_at_cmd(tty, "AT+CCHO=\"A0000000871002FFFFFFFF8907090000\"", resp, sizeof(resp), 1500); } int ch = parse_ccho_channel(resp); if (ch > 0 && geminux_ims_build_auth_apdu(rcopy, acopy, apdu, sizeof(apdu)) == 0) { snprintf(cgla_cmd, sizeof(cgla_cmd), "AT+CGLA=%d,%zu,\"%s\"", ch, strlen(apdu), apdu); if (worker_at_cmd(tty, cgla_cmd, resp, sizeof(resp), 2000) == 0) { extract_cgla_hex(resp, hex_rsp, sizeof(hex_rsp)); uint8_t rbin[32], ck[16], ik[16]; size_t rlen = sizeof(rbin); bool sf = false; int pr = geminux_ims_parse_auth_resp(hex_rsp, rbin, &rlen, ck, ik, auts, sizeof(auts), &sf); if (pr == 0) { geminux_ims_hex_encode(rbin, rlen, res_hex, sizeof(res_hex)); geminux_ims_hex_encode(ck, 16, ck_hex, sizeof(ck_hex)); geminux_ims_hex_encode(ik, 16, ik_hex, sizeof(ik_hex)); } else if (pr == 1 && sf) { sync = 1; } } snprintf(cgla_cmd, sizeof(cgla_cmd), "AT+CCHC=%d", ch); worker_at_cmd(tty, cgla_cmd, resp, sizeof(resp), 800); } close(tty); } flock(lfd, LOCK_UN); } if (lfd >= 0) close(lfd); dprintf(outfd, "sync=%d\nres=%s\nck=%s\nik=%s\nauts=%s\n", sync, res_hex, ck_hex, ik_hex, auts); memset(res_hex, 0, sizeof(res_hex)); memset(ck_hex, 0, sizeof(ck_hex)); memset(ik_hex, 0, sizeof(ik_hex)); close(outfd); _exit(0); } close(pfd[1]); ctx->work_pid = pid; ctx->work_fd = pfd[0]; ctx->work_kind = WORK_AKA_AUTH; ctx->work_len = 0; ctx->work_buf[0] = '\0'; add_ep(ctx->epfd, ctx->work_fd); } static void cleanup_registration(ims_ctx_t *ctx) { if (ctx->call_state != IMS_CALL_IDLE) { close_media(ctx); ctx->call_state = IMS_CALL_IDLE; } if (ctx->xfrm_kernel && ctx->sec_keys_valid) { xfrm_add_sa_and_policy(ctx, false); } close_sip_sockets(ctx); ctx->sec_keys_valid = false; ctx->srv_sec.valid = false; ctx->reg_state = (ctx->ims_enabled && !ctx->airplane_mode) ? IMS_REG_STANDBY : IMS_REG_OFF; ctx->bearer_mode = 0; memset(ctx->sha1_key20, 0, sizeof(ctx->sha1_key20)); memset(ctx->md5_key16, 0, sizeof(ctx->md5_key16)); memset(ctx->aes_key16, 0, sizeof(ctx->aes_key16)); write_ims_state(ctx); } static void schedule_registration(ims_ctx_t *ctx, int delay_s) { if (ctx->airplane_mode || !ctx->ims_enabled) { arm_timer_ms(ctx->reg_tmr_fd, 0, 0); cleanup_registration(ctx); return; } arm_timer_ms(ctx->reg_tmr_fd, (uint64_t)delay_s * 1000ULL, 0); } static void handle_worker_done(ims_ctx_t *ctx) { del_ep(ctx->epfd, ctx->work_fd); close(ctx->work_fd); ctx->work_fd = -1; int st = 0; if (ctx->work_pid > 0) { waitpid(ctx->work_pid, &st, 0); ctx->work_pid = -1; } ims_work_kind_t kind = ctx->work_kind; ctx->work_kind = WORK_NONE; if (kind == WORK_DISCOVER) { char bearer[16] = "none"; char *save = NULL; for (char *ln = strtok_r(ctx->work_buf, "\r\n", &save); ln; ln = strtok_r(NULL, "\r\n", &save)) { if (strncmp(ln, "bearer=", 7) == 0) snprintf(bearer, sizeof(bearer), "%s", ln + 7); else if (strncmp(ln, "dom=", 4) == 0 && ln[4]) snprintf(ctx->home_domain, sizeof(ctx->home_domain), "%s", ln + 4); else if (strncmp(ln, "epdg=", 5) == 0 && ln[5]) snprintf(ctx->epdg_fqdn, sizeof(ctx->epdg_fqdn), "%s", ln + 5); else if (strncmp(ln, "pcscf=", 6) == 0) snprintf(ctx->pcscf_ip, sizeof(ctx->pcscf_ip), "%s", ln + 6); else if (strncmp(ln, "lip=", 4) == 0) snprintf(ctx->local_ip, sizeof(ctx->local_ip), "%s", ln + 4); else if (strncmp(ln, "impi=", 5) == 0 && ln[5]) snprintf(ctx->impi, sizeof(ctx->impi), "%s", ln + 5); else if (strncmp(ln, "impu=", 5) == 0 && ln[5]) snprintf(ctx->impu, sizeof(ctx->impu), "%s", ln + 5); } memset(ctx->work_buf, 0, sizeof(ctx->work_buf)); if (ctx->airplane_mode || !ctx->ims_enabled) { cleanup_registration(ctx); return; } if (strcmp(bearer, "volte") == 0) ctx->bearer_mode = 1; else if (strcmp(bearer, "vowifi") == 0) ctx->bearer_mode = 2; else ctx->bearer_mode = 0; if (ctx->bearer_mode != 0 && ctx->pcscf_ip[0] && ctx->local_ip[0] && ctx->impi[0]) { ctx->retry_backoff_s = 15; send_initial_register(ctx); schedule_registration(ctx, 15); } else { ctx->reg_state = IMS_REG_STANDBY; write_ims_state(ctx); if (ctx->retry_backoff_s < 60) ctx->retry_backoff_s = 60; else if (ctx->retry_backoff_s < 300) ctx->retry_backoff_s *= 2; if (ctx->retry_backoff_s > 300) ctx->retry_backoff_s = 300; schedule_registration(ctx, ctx->retry_backoff_s); } } else if (kind == WORK_AKA_AUTH) { int sync = 0; char res_hex[64] = "", ck_hex[33] = "", ik_hex[33] = "", auts[64] = ""; char *save = NULL; for (char *ln = strtok_r(ctx->work_buf, "\r\n", &save); ln; ln = strtok_r(NULL, "\r\n", &save)) { if (strncmp(ln, "sync=", 5) == 0) sync = atoi(ln + 5); else if (strncmp(ln, "res=", 4) == 0) snprintf(res_hex, sizeof(res_hex), "%s", ln + 4); else if (strncmp(ln, "ck=", 3) == 0) snprintf(ck_hex, sizeof(ck_hex), "%s", ln + 3); else if (strncmp(ln, "ik=", 3) == 0) snprintf(ik_hex, sizeof(ik_hex), "%s", ln + 3); else if (strncmp(ln, "auts=", 5) == 0) snprintf(auts, sizeof(auts), "%s", ln + 5); } memset(ctx->work_buf, 0, sizeof(ctx->work_buf)); uint8_t res[32], ck[16], ik[16]; int rlen = res_hex[0] ? geminux_ims_hex_decode(res_hex, res, sizeof(res)) : -1; if (ck_hex[0] && ik_hex[0] && geminux_ims_hex_decode(ck_hex, ck, 16) == 16 && geminux_ims_hex_decode(ik_hex, ik, 16) == 16) { geminux_ims_derive_ipsec_keys(ck, ik, ctx->sha1_key20, ctx->md5_key16, ctx->aes_key16); ctx->sec_keys_valid = true; if (ctx->xfrm_kernel && ctx->srv_sec.valid) { xfrm_add_sa_and_policy(ctx, true); } } char auth_hdr[640] = "", cnonce[24] = "", resp33[33] = "", uri[160] = ""; snprintf(uri, sizeof(uri), "sip:%s", ctx->home_domain); rand_hex(cnonce, 16); if (sync && auts[0]) { snprintf(auth_hdr, sizeof(auth_hdr), "Digest username=\"%s\",realm=\"%s\",nonce=\"%s\",uri=\"%s\",auts=\"%s\",algorithm=AKAv1-MD5", ctx->impi, ctx->auth_realm, ctx->auth_nonce, uri, auts); } else if (rlen > 0) { ctx->auth_nc++; char ncbuf[16]; snprintf(ncbuf, sizeof(ncbuf), "%08x", ctx->auth_nc); if (geminux_ims_akav1_md5_response(ctx->impi, ctx->auth_realm, res, (size_t)rlen, "REGISTER", uri, ctx->auth_nonce, ncbuf, cnonce, ctx->auth_qop[0] ? ctx->auth_qop : "auth", resp33) == 0) { snprintf(auth_hdr, sizeof(auth_hdr), "Digest username=\"%s\",realm=\"%s\",nonce=\"%s\",uri=\"%s\",response=\"%s\"," "algorithm=AKAv1-MD5,qop=auth,nc=%s,cnonce=\"%s\"", ctx->impi, ctx->auth_realm, ctx->auth_nonce, uri, resp33, ncbuf, cnonce); } } memset(res, 0, sizeof(res)); memset(ck, 0, sizeof(ck)); memset(ik, 0, sizeof(ik)); memset(res_hex, 0, sizeof(res_hex)); memset(ck_hex, 0, sizeof(ck_hex)); memset(ik_hex, 0, sizeof(ik_hex)); if (auth_hdr[0]) { ctx->reg_cseq++; rand_hex(ctx->reg_branch + 7, 16); memcpy(ctx->reg_branch, "z9hG4bK", 7); char sip_buf[2048]; int len = geminux_ims_build_register(sip_buf, sizeof(sip_buf), ctx->pcscf_ip, ctx->home_domain, ctx->local_ip, ctx->sip_local_port, ctx->impi, ctx->impu, ctx->call_id_reg, ctx->reg_cseq, ctx->reg_branch, ctx->reg_tag, ctx->reg_expires, &ctx->cli_sec, ctx->sec_verify, auth_hdr, (ctx->bearer_mode == 2) ? "IEEE-802.11;i-wlan-node-id=000000000000" : "3GPP-E-UTRAN-FDD"); if (len > 0) { send_sip_msg(ctx, sip_buf, (size_t)len, ctx->sec_keys_valid && ctx->srv_sec.valid); } } } } /* ---------------- Incoming SIP Signaling Handler ---------------- */ static void send_sip_simple_response(ims_ctx_t *ctx, const geminux_ims_sip_msg_t *req, int code, const char *reason, const char *content_type, const char *body) { char buf[2048]; size_t blen = body ? strlen(body) : 0; int n = snprintf(buf, sizeof(buf), "SIP/2.0 %d %s\r\n" "Via: %s\r\n" "From: %s\r\n" "To: %s;tag=gem1\r\n" "Call-ID: %s\r\n" "CSeq: %d %s\r\n" "%s%s%s" "Content-Length: %zu\r\n\r\n%s", code, reason, req->via, req->from_hdr, req->to_hdr, req->call_id, req->cseq_num, req->cseq_method, (content_type && content_type[0]) ? "Content-Type: " : "", (content_type && content_type[0]) ? content_type : "", (content_type && content_type[0]) ? "\r\n" : "", blen, body ? body : ""); if (n > 0) { send_sip_msg(ctx, buf, (size_t)n, ctx->sec_keys_valid && ctx->srv_sec.valid); } } static void extract_uri_user(const char *hdr, char *out, size_t out_sz) { out[0] = '\0'; const char *p = strstr(hdr, "sip:"); if (!p) p = strstr(hdr, "tel:"); if (!p) { snprintf(out, out_sz, "Unknown"); return; } p += 4; size_t pos = 0; while (p[pos] && p[pos] != '@' && p[pos] != '>' && p[pos] != ';' && pos + 1 < out_sz) { out[pos] = p[pos]; pos++; } out[pos] = '\0'; if (!out[0]) snprintf(out, out_sz, "Unknown"); } static void process_sip_packet(ims_ctx_t *ctx, const uint8_t *raw, size_t len) { geminux_ims_sip_msg_t msg; if (geminux_ims_parse_sip(raw, len, &msg) != 0) return; if (!msg.is_request) { if (strcasecmp(msg.cseq_method, "REGISTER") == 0) { if (msg.status_code == 401 && msg.www_auth[0]) { geminux_ims_extract_digest_param(msg.www_auth, "realm", ctx->auth_realm, sizeof(ctx->auth_realm)); geminux_ims_extract_digest_param(msg.www_auth, "nonce", ctx->auth_nonce, sizeof(ctx->auth_nonce)); geminux_ims_extract_digest_param(msg.www_auth, "qop", ctx->auth_qop, sizeof(ctx->auth_qop)); if (msg.sec_server[0]) { snprintf(ctx->sec_verify, sizeof(ctx->sec_verify), "%s", msg.sec_server); geminux_ims_parse_security_server(msg.sec_server, &ctx->srv_sec); } uint8_t rand16[16], autn16[16]; if (geminux_ims_extract_aka_challenge(ctx->auth_nonce, rand16, autn16) == 0) { ctx->reg_state = IMS_REG_CHALLENGED; start_aka_worker(ctx, rand16, autn16); } } else if (msg.status_code == 200) { if (msg.service_route[0]) snprintf(ctx->service_route, sizeof(ctx->service_route), "%s", msg.service_route); int refresh = (msg.expires > 120) ? (msg.expires / 2) : 1800; ctx->reg_state = IMS_REG_REGISTERED; write_ims_state(ctx); schedule_registration(ctx, refresh); } } else if (strcasecmp(msg.cseq_method, "INVITE") == 0) { if (msg.status_code == 200 && ctx->call_state == IMS_CALL_OUTGOING) { if (msg.body && msg.body_len > 0) { char sdp_str[2048]; size_t sl = msg.body_len < sizeof(sdp_str) - 1 ? msg.body_len : sizeof(sdp_str) - 1; memcpy(sdp_str, msg.body, sl); sdp_str[sl] = '\0'; geminux_ims_parse_sdp(sdp_str, &ctx->remote_sdp); } ctx->call_state = IMS_CALL_ACTIVE; start_media(ctx); char ack[1024]; int n = snprintf(ack, sizeof(ack), "ACK %s SIP/2.0\r\n" "Via: %s\r\n" "From: %s\r\n" "To: %s\r\n" "Call-ID: %s\r\n" "CSeq: %d ACK\r\n" "Max-Forwards: 70\r\n" "Content-Length: 0\r\n\r\n", ctx->peer_uri, msg.via, msg.from_hdr, msg.to_hdr, msg.call_id, msg.cseq_num); if (n > 0) send_sip_msg(ctx, ack, (size_t)n, ctx->sec_keys_valid && ctx->srv_sec.valid); } } return; } /* Incoming SIP requests */ if (strcmp(msg.method, "INVITE") == 0) { if (ctx->call_state != IMS_CALL_IDLE) { send_sip_simple_response(ctx, &msg, 486, "Busy Here", NULL, NULL); return; } ctx->call_state = IMS_CALL_INCOMING; snprintf(ctx->call_id_dlg, sizeof(ctx->call_id_dlg), "%s", msg.call_id); snprintf(ctx->call_from, sizeof(ctx->call_from), "%s", msg.from_hdr); snprintf(ctx->call_to, sizeof(ctx->call_to), "%s", msg.to_hdr); snprintf(ctx->call_via, sizeof(ctx->call_via), "%s", msg.via); ctx->call_cseq = msg.cseq_num; extract_uri_user(msg.from_hdr, ctx->peer_num, sizeof(ctx->peer_num)); if (msg.body && msg.body_len > 0) { char sdp_str[2048]; size_t sl = msg.body_len < sizeof(sdp_str) - 1 ? msg.body_len : sizeof(sdp_str) - 1; memcpy(sdp_str, msg.body, sl); sdp_str[sl] = '\0'; geminux_ims_parse_sdp(sdp_str, &ctx->remote_sdp); } send_sip_simple_response(ctx, &msg, 180, "Ringing", NULL, NULL); char ntf[96]; snprintf(ntf, sizeof(ntf), "ims-ring %s", ctx->peer_num); notify_modem_ctl(ntf); } else if (strcmp(msg.method, "BYE") == 0 || strcmp(msg.method, "CANCEL") == 0) { send_sip_simple_response(ctx, &msg, 200, "OK", NULL, NULL); if (ctx->call_state != IMS_CALL_IDLE) { close_media(ctx); ctx->call_state = IMS_CALL_IDLE; notify_modem_ctl("ims-ended"); } } else if (strcmp(msg.method, "MESSAGE") == 0) { send_sip_simple_response(ctx, &msg, 200, "OK", NULL, NULL); if (msg.body && msg.body_len > 0 && strstr(msg.content_type, "3gpp.sms")) { uint8_t rp_mr = 0; char sender[32] = "unknown", text[256] = ""; if (geminux_ims_decode_rp_sms_deliver(msg.body, msg.body_len, &rp_mr, sender, sizeof(sender), text, sizeof(text)) == 0) { char ntf[320]; snprintf(ntf, sizeof(ntf), "ims-sms %s %s", sender[0] ? sender : "unknown", text); notify_modem_ctl(ntf); } } else if (msg.body && msg.body_len > 0 && strstr(msg.content_type, "text/plain")) { char sender[64] = "unknown", text[256] = ""; extract_uri_user(msg.from_hdr, sender, sizeof(sender)); size_t tl = msg.body_len < sizeof(text) - 1 ? msg.body_len : sizeof(text) - 1; memcpy(text, msg.body, tl); text[tl] = '\0'; char ntf[340]; snprintf(ntf, sizeof(ntf), "ims-sms %s %s", sender, text); notify_modem_ctl(ntf); } } else if (strcmp(msg.method, "OPTIONS") == 0) { send_sip_simple_response(ctx, &msg, 200, "OK", NULL, NULL); } } /* ---------------- Control Socket Commands ---------------- */ static void handle_client_cmd(ims_ctx_t *ctx, int cfd) { char buf[512] = {0}; ssize_t n = read(cfd, buf, sizeof(buf) - 1); if (n <= 0) return; while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; if (strcmp(buf, "status") == 0) { const char *rn = (ctx->reg_state == IMS_REG_REGISTERED) ? "registered" : (ctx->reg_state == IMS_REG_REGISTERING || ctx->reg_state == IMS_REG_CHALLENGED) ? "registering" : (ctx->reg_state == IMS_REG_STANDBY) ? "standby" : "off"; const char *bn = (ctx->bearer_mode == 1) ? "volte" : (ctx->bearer_mode == 2) ? "vowifi" : "none"; dprintf(cfd, "enabled=%d airplane=%d reg=%s bearer=%s xfrm_kernel=%d esp_userspace=%d call=%d\n", ctx->ims_enabled ? 1 : 0, ctx->airplane_mode ? 1 : 0, rn, bn, ctx->xfrm_kernel ? 1 : 0, ctx->xfrm_kernel ? 0 : 1, (ctx->call_state != IMS_CALL_IDLE) ? 1 : 0); } else if (strcmp(buf, "register") == 0) { load_config(ctx); ctx->retry_backoff_s = 15; if (!ctx->airplane_mode && ctx->ims_enabled) { start_discover_worker(ctx); dprintf(cfd, "OK register queued\n"); } else { cleanup_registration(ctx); dprintf(cfd, "OK ims=off\n"); } } else if (strcmp(buf, "deregister") == 0) { arm_timer_ms(ctx->reg_tmr_fd, 0, 0); cleanup_registration(ctx); dprintf(cfd, "OK deregistered\n"); } else if (strncmp(buf, "dial ", 5) == 0) { if (ctx->reg_state != IMS_REG_REGISTERED || ctx->call_state != IMS_CALL_IDLE) { dprintf(cfd, "ERR ims not registered or busy\n"); return; } snprintf(ctx->peer_num, sizeof(ctx->peer_num), "%.*s", 60, buf + 5); snprintf(ctx->peer_uri, sizeof(ctx->peer_uri), "sip:%s@%s;user=phone", ctx->peer_num, ctx->home_domain); open_rtp_socket(ctx); char sdp[1024]; geminux_ims_build_sdp_offer(ctx->local_ip, ctx->rtp_local_port, sdp, sizeof(sdp)); rand_hex(ctx->call_id_dlg, 16); rand_hex(ctx->reg_branch + 7, 16); memcpy(ctx->reg_branch, "z9hG4bK", 7); ctx->call_cseq = 1; char inv[3072]; int in = snprintf(inv, sizeof(inv), "INVITE %s SIP/2.0\r\n" "Via: SIP/2.0/UDP %s:%u;branch=%s;rport\r\n" "From: <%s>;tag=inv1\r\n" "To: <%s>\r\n" "Call-ID: %s@%s\r\n" "CSeq: %d INVITE\r\n" "Contact: ;+g.3gpp.icsi-ref=\"urn%%3Aurn-7%%3A3gpp-service.ims.icsi.mmtel\"\r\n" "Content-Type: application/sdp\r\n" "Content-Length: %zu\r\n\r\n%s", ctx->peer_uri, ctx->local_ip, (unsigned)ctx->sip_local_port, ctx->reg_branch, ctx->impu, ctx->peer_uri, ctx->call_id_dlg, ctx->home_domain, ctx->call_cseq, ctx->impi, ctx->local_ip, (unsigned)ctx->sip_local_port, strlen(sdp), sdp); if (in > 0 && send_sip_msg(ctx, inv, (size_t)in, ctx->sec_keys_valid && ctx->srv_sec.valid) == 0) { ctx->call_state = IMS_CALL_OUTGOING; dprintf(cfd, "OK ims dialing\n"); } else { close_media(ctx); dprintf(cfd, "ERR invite send failed\n"); } } else if (strcmp(buf, "answer") == 0) { if (ctx->call_state != IMS_CALL_INCOMING) { dprintf(cfd, "ERR no incoming ims call\n"); return; } open_rtp_socket(ctx); char sdp[1024]; geminux_ims_build_sdp_offer(ctx->local_ip, ctx->rtp_local_port, sdp, sizeof(sdp)); geminux_ims_sip_msg_t dummy; memset(&dummy, 0, sizeof(dummy)); snprintf(dummy.via, sizeof(dummy.via), "%s", ctx->call_via); snprintf(dummy.from_hdr, sizeof(dummy.from_hdr), "%s", ctx->call_from); snprintf(dummy.to_hdr, sizeof(dummy.to_hdr), "%s", ctx->call_to); snprintf(dummy.call_id, sizeof(dummy.call_id), "%s", ctx->call_id_dlg); dummy.cseq_num = ctx->call_cseq; snprintf(dummy.cseq_method, sizeof(dummy.cseq_method), "INVITE"); send_sip_simple_response(ctx, &dummy, 200, "OK", "application/sdp", sdp); ctx->call_state = IMS_CALL_ACTIVE; start_media(ctx); dprintf(cfd, "OK ims answered\n"); } else if (strcmp(buf, "hangup") == 0) { if (ctx->call_state == IMS_CALL_IDLE) { dprintf(cfd, "ERR no active ims call\n"); return; } if (ctx->call_state == IMS_CALL_ACTIVE && ctx->peer_uri[0]) { char bye[1024]; int bn = snprintf(bye, sizeof(bye), "BYE %s SIP/2.0\r\n" "Via: SIP/2.0/UDP %s:%u;branch=z9hG4bKbye%d\r\n" "From: <%s>;tag=inv1\r\n" "To: <%s>\r\n" "Call-ID: %s\r\n" "CSeq: %d BYE\r\n" "Content-Length: 0\r\n\r\n", ctx->peer_uri, ctx->local_ip, (unsigned)ctx->sip_local_port, ++ctx->call_cseq, ctx->impu, ctx->peer_uri, ctx->call_id_dlg, ctx->call_cseq); if (bn > 0) send_sip_msg(ctx, bye, (size_t)bn, ctx->sec_keys_valid && ctx->srv_sec.valid); } close_media(ctx); ctx->call_state = IMS_CALL_IDLE; dprintf(cfd, "OK ims hangup\n"); } else if (strncmp(buf, "dtmf ", 5) == 0 && buf[5]) { if (ctx->call_state != IMS_CALL_ACTIVE || ctx->rtp_fd < 0 || !ctx->remote_sdp.valid) { dprintf(cfd, "ERR no active ims call\n"); return; } uint8_t pt = (uint8_t)(ctx->remote_sdp.pt_dtmf_wb >= 0 ? ctx->remote_sdp.pt_dtmf_wb : 99); uint8_t pkt[32]; int dn = geminux_ims_rtp_pack_dtmf(pt, ctx->rtp_seq++, ctx->rtp_ts, ctx->rtp_ssrc, buf[5], true, 1280, pkt, sizeof(pkt)); if (dn > 0) { struct sockaddr_in dst; memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_port = htons(ctx->remote_sdp.remote_port); if (inet_pton(AF_INET, ctx->remote_sdp.remote_ip, &dst.sin_addr) == 1) { ssize_t unused = sendto(ctx->rtp_fd, pkt, (size_t)dn, 0, (struct sockaddr *)&dst, sizeof(dst)); (void)unused; } } dprintf(cfd, "OK dtmf\n"); } else if (strcmp(buf, "mute on") == 0 || strcmp(buf, "mute off") == 0) { ctx->call_muted = (strcmp(buf, "mute on") == 0); dprintf(cfd, "OK mute=%d\n", ctx->call_muted ? 1 : 0); } else if (strcmp(buf, "speaker on") == 0 || strcmp(buf, "speaker off") == 0) { ctx->call_speaker = (strcmp(buf, "speaker on") == 0); dprintf(cfd, "OK speaker=%d\n", ctx->call_speaker ? 1 : 0); } else if (strncmp(buf, "sms-send ", 9) == 0) { if (ctx->reg_state != IMS_REG_REGISTERED) { dprintf(cfd, "ERR ims not registered\n"); return; } char *sp = strchr(buf + 9, ' '); if (!sp) { dprintf(cfd, "ERR usage sms-send \n"); return; } *sp = '\0'; uint8_t rp[256]; int rlen = geminux_ims_encode_rp_sms_submit(++ctx->sms_mr, ctx->smsc_e164, buf + 9, sp + 1, rp, sizeof(rp)); if (rlen <= 0) { dprintf(cfd, "ERR invalid sms payload\n"); return; } char cid[48], branch[32], hdr[1024], pkt[1536]; rand_hex(cid, 16); rand_hex(branch, 12); int hn = snprintf(hdr, sizeof(hdr), "MESSAGE sip:%s SIP/2.0\r\n" "Via: SIP/2.0/UDP %s:%u;branch=z9hG4bK%s\r\n" "From: <%s>;tag=sms1\r\n" "To: \r\n" "Call-ID: %s@%s\r\n" "CSeq: 1 MESSAGE\r\n" "Content-Type: application/vnd.3gpp.sms\r\n" "Content-Length: %d\r\n\r\n", ctx->home_domain, ctx->local_ip, (unsigned)ctx->sip_local_port, branch, ctx->impu, buf + 9, cid, ctx->home_domain, rlen); if (hn > 0 && (size_t)hn + (size_t)rlen <= sizeof(pkt)) { memcpy(pkt, hdr, (size_t)hn); memcpy(pkt + hn, rp, (size_t)rlen); send_sip_msg(ctx, pkt, (size_t)(hn + rlen), ctx->sec_keys_valid && ctx->srv_sec.valid); dprintf(cfd, "OK ims sms sent\n"); } else { dprintf(cfd, "ERR sms packet overflow\n"); } } else { dprintf(cfd, "ERR unknown command\n"); } } static int setup_unix_server(void) { mkdir("/run/geminux", 0755); unlink(IMS_SOCK_PATH); int fd = socket(AF_UNIX, SOCK_STREAM | O_NONBLOCK | O_CLOEXEC, 0); if (fd < 0) return -1; struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", IMS_SOCK_PATH); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 8) != 0) { close(fd); return -1; } struct group *gr = getgrnam("wheel"); if (gr) chown(IMS_SOCK_PATH, 0, gr->gr_gid); chmod(IMS_SOCK_PATH, 0660); return fd; } int main(void) { signal(SIGPIPE, SIG_IGN); ims_ctx_t ctx; memset(&ctx, 0, sizeof(ctx)); ctx.sip_fd = -1; ctx.esp_raw_fd = -1; ctx.rtp_fd = -1; ctx.work_fd = -1; ctx.work_pid = -1; ctx.sip_local_port = 5060; ctx.sip_remote_port = 5060; ctx.rtp_local_port = 49100; ctx.reg_expires = 3600; ctx.retry_backoff_s = 15; rand_hex(ctx.call_id_reg, 20); rand_hex(ctx.reg_tag, 12); int xfd = socket(PF_NETLINK, SOCK_RAW | O_CLOEXEC, NETLINK_XFRM); ctx.xfrm_kernel = (xfd >= 0); if (xfd >= 0) close(xfd); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGHUP); sigprocmask(SIG_BLOCK, &mask, NULL); ctx.sig_fd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC); ctx.srv_fd = setup_unix_server(); ctx.rt_fd = socket(AF_NETLINK, SOCK_DGRAM | O_NONBLOCK | O_CLOEXEC, NETLINK_ROUTE); if (ctx.rt_fd >= 0) { struct sockaddr_nl nl = { .nl_family = AF_NETLINK, .nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR }; bind(ctx.rt_fd, (struct sockaddr *)&nl, sizeof(nl)); } ctx.ino_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); if (ctx.ino_fd >= 0) { mkdir("/etc/geminux", 0755); mkdir("/run/geminux", 0755); inotify_add_watch(ctx.ino_fd, "/etc/geminux", IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE); inotify_add_watch(ctx.ino_fd, "/run/geminux", IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE); } ctx.reg_tmr_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); ctx.rtp_tmr_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); ctx.epfd = epoll_create1(EPOLL_CLOEXEC); int fixed[6] = {ctx.sig_fd, ctx.srv_fd, ctx.rt_fd, ctx.ino_fd, ctx.reg_tmr_fd, ctx.rtp_tmr_fd}; for (int i = 0; i < 6; i++) add_ep(ctx.epfd, fixed[i]); load_config(&ctx); write_ims_state(&ctx); if (ctx.ims_enabled && !ctx.airplane_mode) { schedule_registration(&ctx, 2); } struct epoll_event events[16]; bool running = true; while (running) { int n = epoll_wait(ctx.epfd, events, 16, -1); if (n < 0) { if (errno == EINTR) continue; break; } for (int i = 0; i < n; i++) { int fd = events[i].data.fd; if (fd == ctx.sig_fd) { struct signalfd_siginfo si; while (read(ctx.sig_fd, &si, sizeof(si)) > 0) { if (si.ssi_signo == SIGHUP) { load_config(&ctx); schedule_registration(&ctx, 1); } else { running = false; } } } else if (fd == ctx.srv_fd) { int cfd; while ((cfd = accept4(ctx.srv_fd, NULL, NULL, SOCK_CLOEXEC)) >= 0) { handle_client_cmd(&ctx, cfd); close(cfd); } } else if (fd == ctx.reg_tmr_fd) { uint64_t exp = 0; while (read(ctx.reg_tmr_fd, &exp, sizeof(exp)) > 0) {} load_config(&ctx); if (!ctx.airplane_mode && ctx.ims_enabled) { start_discover_worker(&ctx); } else { cleanup_registration(&ctx); } } else if (fd == ctx.rtp_tmr_fd) { uint64_t exp = 0; while (read(ctx.rtp_tmr_fd, &exp, sizeof(exp)) > 0) {} handle_rtp_tick(&ctx); } else if (fd == ctx.rt_fd) { char buf[1024]; while (recv(ctx.rt_fd, buf, sizeof(buf), 0) > 0) {} if (!ctx.airplane_mode && ctx.ims_enabled && ctx.reg_state != IMS_REG_REGISTERED) { schedule_registration(&ctx, 2); } } else if (fd == ctx.ino_fd) { char buf[1024]; while (read(ctx.ino_fd, buf, sizeof(buf)) > 0) {} bool prev_air = ctx.airplane_mode, prev_ims = ctx.ims_enabled; load_config(&ctx); if (ctx.airplane_mode || !ctx.ims_enabled) { schedule_registration(&ctx, 0); } else if (prev_air != ctx.airplane_mode || prev_ims != ctx.ims_enabled) { ctx.retry_backoff_s = 15; schedule_registration(&ctx, 2); } } else if (fd == ctx.work_fd) { char buf[512]; ssize_t r; bool eof = false; while ((r = read(ctx.work_fd, buf, sizeof(buf))) > 0) { if (ctx.work_len + 1 < sizeof(ctx.work_buf)) { size_t cp = (size_t)r; if (cp > sizeof(ctx.work_buf) - 1 - ctx.work_len) { cp = sizeof(ctx.work_buf) - 1 - ctx.work_len; } memcpy(ctx.work_buf + ctx.work_len, buf, cp); ctx.work_len += cp; ctx.work_buf[ctx.work_len] = '\0'; } } if (r == 0 || (r < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { eof = true; } if (eof || (events[i].events & (EPOLLHUP | EPOLLERR))) { handle_worker_done(&ctx); } } else if (fd == ctx.sip_fd) { uint8_t pkt[4096]; ssize_t r; while ((r = recv(ctx.sip_fd, pkt, sizeof(pkt), 0)) > 0) { process_sip_packet(&ctx, pkt, (size_t)r); } } else if (fd == ctx.esp_raw_fd) { uint8_t pkt[4096]; ssize_t r; while ((r = recv(ctx.esp_raw_fd, pkt, sizeof(pkt), 0)) > 20) { size_t ip_hl = (size_t)((pkt[0] & 0x0f) * 4); if (ip_hl >= 20 && (size_t)r > ip_hl && ctx.sec_keys_valid) { uint8_t sip[4096]; const uint8_t *ak = (ctx.srv_sec.alg == GEMINUX_IMS_ALG_HMAC_MD5_96) ? ctx.md5_key16 : ctx.sha1_key20; int sl = geminux_ims_esp_unpack_udp(pkt + ip_hl, (size_t)r - ip_hl, ctx.cli_sec.spi_c, ctx.srv_sec.ealg, ctx.srv_sec.alg, ctx.aes_key16, ak, NULL, NULL, sip, sizeof(sip)); if (sl > 0) process_sip_packet(&ctx, sip, (size_t)sl); } } } else if (fd == ctx.rtp_fd) { handle_rtp_rx(&ctx); } } } cleanup_registration(&ctx); if (ctx.work_pid > 0) { kill(ctx.work_pid, SIGTERM); waitpid(ctx.work_pid, NULL, 0); } unlink(IMS_SOCK_PATH); close(ctx.epfd); return 0; }