# Calls with No Signal: Building VoWiFi from Scratch on a Raspberry Pi (3)

- URL: https://wuming.si/blog/4090/
- Author: Wuming
- Published: 2026-10-19
- Language: en
- Categories: Technology, English

> Previous: [An SMS and eSIM Gateway on a Raspberry Pi](https://wuming.si/blog/4089) | Next: [USB Handsets, Browser Calls and an ESP32](https://wuming.si/blog/4091) | 中文版：[从零实现 VoWiFi](https://wuming.si/blog/4004)

Your phone's settings have a switch called "Wi-Fi Calling". Turn it on, and in a basement, an elevator, or a dead zone, as long as there is Wi-Fi you can still make calls and get texts. The formal name for this feature is VoWiFi.

It does not work by turning your phone call into a WhatsApp-style voice call. What the phone actually does is connect back to the carrier's core network, encrypted, over any broadband link, and then use the SIM card to prove "I am this number". From then on every call and every text behaves exactly as it would over cellular: the other side still sees your phone number, and incoming calls still ring your number.

This post builds that whole thing on a Raspberry Pi. The SIM card sits in a 4G module, but **it is used only for authentication**; all the data goes over the Pi's wired network. The cellular radio can stay in airplane mode the entire time.

For a SIM that is permanently roaming, that means: no roaming charges at all, and reliable texting, calling and receiving calls at home.

This is the post in the series with the most pitfalls. Almost every one of the dozen-plus traps I fell into along the way maps to a single sentence in some specification.

## How it works

The whole thing has three layers, from the bottom up:

```
 ┌───────────────────────── Layer 3: services (SIP) ────────────────────┐
 │  REGISTER → 401 challenge → 200 OK     MESSAGE (SMS)    INVITE (call) │
 └────────────────────────── protected channel ─────────────────────────┘
      Layer 2: IPsec encryption + user-space network stack
 ┌────────────────────────── Layer 1: SWu tunnel ───────────────────────┐
 │  IKEv2 handshake + EAP-AKA auth with the SIM → encrypted tunnel → inner address │
 └──────────── public UDP 500/4500 to the carrier's ePDG gateway ───────┘
```

**Layer 1: build the tunnel.** The carrier runs a gateway on the public internet called the ePDG, whose job is to accept phones coming in from any network. You set up an IPsec tunnel with it using the IKEv2 protocol, and authentication uses the SIM card rather than a password; this scheme is called EAP-AKA. The SIM holds a secret key the carrier also knows, both sides compute an answer independently, and if the answers match you are authenticated. Once the tunnel is up you get an inner address, and from the carrier's point of view the device is now "inside its network".

**Layer 2: encryption.** Inside the tunnel there is a second layer of IPsec protection, specifically for the signaling above it.

**Layer 3: services.** The SIP protocol runs inside the protected channel. SIP is the general-purpose signaling protocol of internet telephony: registration uses `REGISTER`, texts use `MESSAGE` (carrying 3GPP SMS data), calls use `INVITE`, and the voice stream itself is RTP.

The carrier's core network for all of this is called IMS. The everyday calls your phone makes (VoLTE) go through it too; the only difference is that they reach it over cellular instead of Wi-Fi.

## Choosing a library, plus a free lesson in licensing

Writing IKEv2 from scratch was not realistic, so I looked for existing libraries first:

| Library | Result |
|---|---|
| A public VoWiFi library | The key-exchange algorithm in the first handshake step is hard-coded to X25519, while the carrier's gateway wants traditional MODP. The other side simply replies "no proposal chosen". It is also AGPL-3.0 |
| A public SWu tunnel library | After three patches it brings up a real tunnel, but the layer above it doesn't work |
| A complete UE-side implementation | Both the tunnel and IMS work against a real carrier; the license is PolyForm Noncommercial |

I went with the third, switched the project's license to PolyForm Noncommercial along with it, and **deliberately removed the AGPL library**: section 7 of the AGPL does not allow attaching a restriction like "non-commercial use only" when distributing, so the two cannot be combined in one distributed work. This is worth keeping in mind when integrating open source: a license is not decoration, it decides whether you can put two libraries in the same repository at all.

### A sneaky class of bug: a library offering algorithms it can't use

The three reasons the SWu library failed to build a tunnel were, at heart, the same problem: **during negotiation it advertised algorithms it couldn't actually implement, and the moment the other side picked one, it died.**

A protocol handshake usually goes "I support A, B and C, you pick one". If A is merely listed but not implemented in code, and the other side happens to pick A, every later step fails in ways that look completely unrelated.

| Where | Symptom | Fix |
|---|---|---|
| Handshake key-exchange group | The list included MODP-3072 and 1024, but only group 14 was implemented. The other side chose 3072 and replied "invalid KE payload"; the library doesn't handle that retry, and the error it reported was "mandatory payload missing from response" | Propose only group 14 |
| Handshake encryption algorithm | It proposed AES-GCM, but the key derivation was wrong, and decryption failed with `cipher: message authentication failed` | Propose only AES-CBC |
| Data tunnel encryption | AES-GCM was the first choice; outgoing traffic was fine, but every incoming packet failed authentication | Propose only AES-CBC |

The combination finally negotiated was AES-CBC-256 with SHA2-256 and MODP-2048, and the handshake takes 1.5 to 1.9 seconds.

There is a general way to debug this kind of problem: **cut the proposal list down to a single algorithm you are confident is implemented correctly.** If that works, the problem is in negotiation; if not, look elsewhere.

## Be careful with the word "ready"

The backend has four status flags:

```text
vowifi_enabled = true      # only means the feature is turned on in config
tunnel_ready   = true      # the tunnel is up
ims_ready      = true      # registration succeeded
sms_ready      = true
```

**Only when the last three are all true can you actually receive texts and calls.** After a service restart, the tunnel takes 10 to 130 seconds to get there. A failed test before that point tells you nothing. This wasted a fair amount of time, because people always go and test right after a restart.

### Trap: `Start` returns success but has done nothing

**Symptom**: the log says plainly that everything is ready, but when you look at the system there is no tunnel interface, the IPsec state table is empty, and not even a port is listening.

**Cause**: the library has two lines of code to the effect of "no registrar passed in, so treat registration as successful" and "SMS status hard-coded to true". In logic this is called **vacuous truth**: the condition is empty, so the check passes. On top of that, if the data-plane mode isn't configured, it skips building the tunnel entirely and still returns success.

**Fix**: explicitly configure the data-plane mode and pass in a registrar; "registered" must check both the tunnel flag and the registration flag. The more important rule is: **confirm every "ready" out of band**: check whether the interface exists, whether the IPsec state table has entries, whether the port is listening. This lesson will save the day again and again in later posts.

### Trap: the library's built-in "auto-recovery" restarts the radio

**Symptom**: a unit test running against a fake interface took 14 seconds, and the command log showed four rounds of turning the radio off and back on.

**Cause**: when the library fails to read the SIM identity, its default recovery strategy is to power-cycle the radio. On real hardware that drops any call in progress and makes the module re-attach to the network, which for a roaming SIM is exactly the thing you most want to avoid.

**Fix**: implement a recovery hook that just returns an error, so the library falls back to deriving the identity from configuration.

**As an aside**: a unit test taking 14 seconds is a signal in itself. A passing test doesn't mean nothing is wrong; a slow test often means the code is quietly doing something real and expensive.

## Traps in registration

Registration is telling the carrier "I'm here, send calls to this address". If this step is wrong, incoming calls will simply never arrive.

### Is the MNC two digits or three?

The IMSI is the SIM's identity number, and its first few digits are the country code and the network code. The network code is three digits in North America and two in many other places. The library cuts it at three digits as long as the IMSI is long enough, and if it cuts in the wrong place, the identity is built wrong. The fix is to use `AT+CRSM` to read a file on the card that gives the real number of digits. Don't guess.

### `400 Bad Request` and `421 Extension Required`

Two protocol details, each of which took ages to track down:

- The first registration request must carry an **empty authorization header** (with the identity filled in and the password left empty). This is required by RFC 3310, and the server relies on it to know which challenge to send. The library only filled in this header after receiving a challenge, so the very first request was rejected.
- When the server replies `421` and echoes `Require: sec-agree`, it means "you also need to tell the proxy". Because the other side is a proxy server, `Proxy-Require` is needed in addition to `Require` (RFC 3329).

What these problems have in common: the spec says it, the code doesn't do it, and the error code only tells you "no", never what's missing.

### Kernel IPsec is a dead end

The Linux kernel can do IPsec on its own, which looks like exactly the right tool. In practice it doesn't work: the null encryption algorithm gets rendered as an empty key, which the kernel rejects outright; and after forcing it in anyway, the second registration request vanished without a trace.

Only after reading the implementation that did work did I understand that **the approach that actually interoperates with carriers doesn't use the kernel at all**: IPsec is done in user space, a user-space TCP/IP stack runs on top of it, and that is handed to the SIP library as an ordinary network connection.

All the time spent on "why didn't the kernel forward the second request" was wasted on the wrong architecture. At moments like this it pays to stop and ask: **how does everyone else do it?** rather than pushing harder down the road you picked.

### Two integration traps in the auth adapter

- At runtime it does an interface assertion on **the adapter type itself**; implementing the interface through an embedded field doesn't count, and the error you get is "config requires ISIM but provider does not support it".
- Authentication has to use the ISIM application on the card, not the default USIM. Both applications live on the same card, and if you pick the wrong one, everything it computes is wrong.

What I implemented on my side: open the ISIM on a logical channel, read the identities, run the authenticate command. On success the card returns tag `0xDB` with the result and keys; on a sync failure it returns `0xDC` with a resynchronization parameter.

### It always stopped on the same word

**Symptom**:

```text
IMS REGISTER failed: status=0 result=auth_phase_reached
```

**Cause**: this is a chained error, and a textbook one.

The card returned `0xDC`, asking for sequence-number resynchronization. That is a perfectly normal step in the protocol: the card and the network disagree on the count, so you redo it once. But the code treated it as a "normal event" and returned a **nil error**. The layer above decided "do we need to resync?" by checking the error type, and nil of course didn't match, so it was treated as "authentication succeeded but no keys came back". It then computed a digest from an empty result and finally died at the key check.

Two things made it worse: this error happened to match the library's rule for "sanitizing error messages", so the real cause was rewritten into a meaningless word; and **a unit test had locked the bug in place**, asserting that nil should be returned here. A test is not the truth; it just freezes the understanding someone had at one point in time.

**Fix**: on a sync failure, return a dedicated error type along with the parameter. After that the flow went smoothly: request resync → send → second challenge → authentication complete → install IPsec → 200 OK.

**Debugging lesson**: this library deliberately sanitizes registration failures. I wrapped the authenticate command in my own layer of logging (recording only the result type and data length, never any key material), and found the problem in one go. When registration fails, look at this layer first.

The full successful chain looks like this:

```text
initial_response 401 → auth_challenge → auth_success aka_complete
→ ipsec_install installed → protected_send → complete 200 ok
```

## SMS: only some arrive, and it gets worse after every restart

Once registered, texts arrive as SIP `MESSAGE` requests.

**Cause**: registration carries a device instance identifier, and the code generated a random one at every startup. The registrar tells devices apart by this identifier, so each restart didn't **replace** the old registration, it **added** a new one. Ten registrations piled up under the same number, and when the network delivered a text, the address it picked was most likely one left behind by some long-dead process.

**Fix**: following RFC 7255, generate a stable identifier from the device's IMEI. If the IMEI isn't available (with the radio parked in airplane mode the IMEI is empty, which is exactly the case here), generate a UUID from the IMSI, store it in the database, and use it from then on.

**Cleaning up old registrations takes some care too**: old entries can only expire on the registrar's own schedule, up to about an hour, and during that time **don't restart the service** (every restart changes the inner address and adds yet another entry). Some carriers refuse a wildcard deregistration that clears everything at once. To see the real list of registrations, query it with a subscription. The expiry echoed back in the successful registration response is the "granted duration", not the "time remaining"; it looks like there is still an hour left when in fact it's about to expire.

## Calls: the library has no voice at all

Only after reading the code did I find that the library handles SMS and USSD, but **voice is a 52-line empty shell**; calling dial returns "not yet implemented".

So I wrote the voice part myself, around 2,700 lines including tests:

| Module | Contents |
|---|---|
| SDP | Media capability negotiation, tolerant of the various extra attributes in carrier answers |
| RTP | Packing and parsing voice packets. Timestamps advance by **sample count** (160 per packet), not bytes and not milliseconds |
| Media | Shuttling between RTP and the internal audio bus, with its own 20 ms clock tick |
| SIP messages | Building and parsing; multi-value headers keep their order, and the length field is always recomputed |
| Dialog | The full call state machine: provisional responses, early media, ACK, CANCEL, BYE |

One piece of good news: the carrier I tested with accepts G.711, so AMR isn't needed. That means the whole project can stay pure Go with no C dependencies, and cross-compiles to the Raspberry Pi with a single command.

### The dial goes out, and nothing comes back

**Symptom**: outgoing calls sit at "dialing" forever, without even an error code. Meanwhile registration requests on the same channel work fine.

```text
INVITE sip:+1877xxxxxxx SIP/2.0
To: <sip:+1877xxxxxxx>
```

**Cause**: this address is invalid. A SIP address must have a host part (just as an email address needs the bit after the `@`), and a proxy simply drops an address without a host, **sending nothing back**. The spec requires either the `tel:` form or a full SIP address with the home domain.

**Fix**: write it as `sip:<number>@<home domain>;user=phone`, and the same for the To header. After the change, `100 Trying` came back immediately, and the call connected nine seconds later.

**There's a general debugging method here**: if the log shows only "sent" and never "received", the request was silently dropped by the network. In that case, suspect **a malformed message** first, before routing, subscription, or registration state. Network equipment usually answers an invalid message with silence, not an error.

### `603 Decline`, with the reason "user unknown"

It looks like a subscription problem. But the same SIM works perfectly with Wi-Fi Calling on a phone, so it isn't.

**Cause**: the card stores several public identities, and the code just took the first one. On this card the first one is an internal identity derived from the IMSI, and the billing system can't find a subscriber by that identity.

**Fix**: prefer the identity that is in the home domain and whose user part is not the IMSI, which is to say the one with the phone number.

### `408 Request Timeout`, when the other side had actually accepted

```text
SIP/2.0 183 Session Progress
Require: 100rel
RSeq: 2
```

**Cause**: `183` is a provisional response, and `Require: 100rel` marks it as a **reliable provisional response**, which per RFC 3262 must be acknowledged with `PRACK`. The code declared support for this feature in its request but never sent the acknowledgment. The network retransmitted a few times, gave up, and the whole request timed out.

Nowhere in the log was there any mention of "missing acknowledgment". Only by reading the spec line by line did I notice I had declared a capability I hadn't implemented: **the same class of mistake as "proposing an algorithm you can't implement" earlier.**

**Fix**: when a provisional response with a sequence number arrives, send the acknowledgment, and don't resend for retransmissions. Result: request → provisional response → acknowledgment → connected, in four seconds.

### A few protocol details that are easy to get wrong

- The upstream library's request function ends the transaction on the first response it gets. That's right for SMS and wrong for calls: `100 Trying` consumes the transaction, and the real `200 OK` that follows is discarded as unmatched. Calls need a version that survives provisional responses.
- The ACK for a success response is a separate transaction and needs a **new branch identifier**; the ACK for a failure response reuses the original one; and a CANCEL must repeat the original request's branch identifier and sequence number.
- Call requests also need to carry the access network info header. This one becomes very important in the next section.

### Dialing out and hearing a recording

The call was answered immediately by some network element that played a recording, with no ringing at all. At the time I suspected the emergency-call address hadn't been registered, and even went digging into the relevant module.

**In the end it turned out the test number had been dialed wrong.**

I'm writing this down because the mistake is a classic: until you've retested with a number known to work, don't draw any conclusions from a recording you can't understand.

### Half the audio goes missing

**Symptom**: three tests in a row, audio dropped about half its content in 20 ms chunks. It sounded like choppy, robotic speech.

**Cause**: the tunnel library's "get inner packets" function returned **the same channel** to every caller. During a call, two protocol stacks were reading it at once: the signaling stack and the media stack. A Go channel delivers each value to only one receiver, so each packet randomly landed in one of them, and the half that landed in the signaling stack was silently dropped because there was no matching receiving port there.

**Fix**: switch to a subscription model, where every consumer gets its own buffered channel and its own copy of the data, fanned out without blocking.

| | Packets received | Gaps concealed | Largest single-frame gap |
|---|---|---|---|
| Before fix | 521 | 531 | 395 |
| After fix | 1052 | 0 | 3 |

**Effort that got thrown away**: before this I'd tried adding a jitter buffer, decoupling playback, and switching to 40 ms frames. Every one of those hit the wrong layer, and none improved those three numbers.

**How the case was cracked**: put the packet count received at the tunnel layer side by side with the count received at the media layer. Packets that reached the tunnel but never reached media pinpointed exactly where the loss was. **Placing one counter at each of two different layers on the same data path is often faster than any amount of guessing.**

## Incoming calls: for a while I blamed the carrier

**Symptom**: texts arrived, outgoing calls went through, but **every incoming call went to voicemail**. No call request showed up anywhere in the protocol trace.

After ruling out a round of local causes, I wrote down this conclusion: "This is a device subscription or policy issue on the carrier side, not our protocol stack."

**That sentence was wrong.** Two local defects stacked together caused it.

**The first**: the registration request didn't carry the access network info header. The spec (GSMA IR.51) requires a terminal on Wi-Fi access to include this header, stating which Wi-Fi it's attached to. When a call comes in, the network relies on it for a decision called "terminating access domain selection": should this number be reached over cellular or over Wi-Fi right now? Without that header, the network doesn't consider the Wi-Fi path usable.

Outgoing calls don't go through that decision, and SMS has its own termination logic, **which neatly explains the odd combination of "outgoing works, SMS works, incoming doesn't".**

**The second**: the protected connection stored only one reply path, and cleared it after the first response was sent. That's fine for SMS (one question, one answer), but a call has to send a provisional response, ringing, and the answer one after another on the same connection, and that last answer couldn't be written, failing with "no source path". The network never got the answer, so it cancelled the call and sent it to voicemail. The fix was to key the reply paths by Call-ID and sequence number, keeping them across provisional responses and releasing them only on the final response.

**Lesson**: when the network withholds **just one** kind of service while everything else on the same registration works, compare your own registration message against the spec item by item instead of guessing about the subscription. The missing header was right there in the registration message captured long before; it had been on the screen the whole time.

One more thing: **"it works on an iPhone" only proves the line has a subscription, not that your own implementation is compliant.** People often mix those two up.

### The same problem, fixed twice

Later, when the whole thing was migrated onto a new backend foundation, the "stable device identifier" fix existed only in the old code, and nobody carried it over, so incoming calls once again went to voicemail.

**A patch with no test covering it is a patch that will get lost in a migration.** The check now is simple: place a call before and after a restart, and confirm the device identifier in the registration message hasn't changed.

## One problem still unsolved

**After the tunnel is rebuilt, outgoing calls fail, and only restarting the service recovers.**

```text
SWu outbound inner packet rejected {"error": "netstack dataplane closed", "packet_len": 220}
```

The network stack belonging to the old tunnel generation was never closed, and the voice path is still pinned to it. What makes it worse is that the status endpoint shows tunnel, registration, and ready all true (registration really has been rebuilt on the new tunnel), and the only clue is that the voice entry is empty.

The idea is to have the voice client rebind to the current tunnel session, or to tear down the old network stack together with the session when it closes.

It's actually from the same family as "half the audio goes missing": **a shared low-level resource held at the same time by several upper layers with different lifetimes.** This pattern shows up twice more in later posts.

## The traps in this post, sorted by protocol layer

| Protocol layer | Traps |
|---|---|
| Tunnel handshake | Proposed algorithms it didn't support |
| SIM authentication | Sequence-number resync treated as success |
| Encryption | The kernel approach doesn't work; it has to be done in user space |
| Registration | Empty authorization header, proxy requirement, access network info header, stable device identifier |
| Calls | Address missing a host, wrong identity chosen, acknowledgment never sent, only one reply path stored |
| Media | A shared channel with two protocol stacks fighting over packets |

Signaling works, and voice is now flowing through the Raspberry Pi as 8 kHz PCM. The next post tackles a more down-to-earth problem: how to get that sound to actually come out of a handset.

## The full series

1. [What Is It, Really](https://wuming.si/blog/4088)
2. [An SMS and eSIM Gateway on a Raspberry Pi](https://wuming.si/blog/4089)
3. [VoWiFi from Scratch](https://wuming.si/blog/4090)
4. [USB Handsets, Browser Calls and an ESP32](https://wuming.si/blog/4091)
5. [On a Mac](https://wuming.si/blog/4092)
6. [The iPhone Client](https://wuming.si/blog/4093)
7. [An Android Tablet Drives It Directly](https://wuming.si/blog/4094)

---

*This series is a personal record of learning and technical research. Please comply with local laws and regulations and with your carrier's terms of service.*
