RFC 3261 defines the To header field to contain the logical recipient of a request, which of course does not have any representation to that of the target of a given branch.
To make this more clear, the To and From header fields are end to end header fields populated by the originating UA, and not modified by the network. A UA is free to place whatever it likes in this field, as it is not used in any routing or targeting decisions.
As an example, if alice (A) was to call bob (B) via a proxy, alice may form a request (i'll only show the relivant fields) like the following one:
INVITE sip:bob@voip.co.uk SIP/2.0 From: Alice <sip:alice@voip.co.uk> To: Bob <sip:bob@voip.co.uk>
alice's UA would then send this request to proxy.voip.co.uk.
bob has configured proxy.voip.co.uk to unconditionally forward all calls for his uri (sip:bob@voip.co.uk) to another URI, sip:voispeed@voip.co.uk.
So when proxy.voip.co.uk gets alices INVITE, it performs resolution on the AOR for sip:voispeed@voip.co.uk, and replaces the Request-URI with the URI that was contained within the Contact header of the REGISTER when the voispeed software registered.
So, the request that proxy.voip.co.uk will forward now looks like this:
INVITE sip:056854@87.127.89.138:5060 SIP/2.0 From: Alice <sip:alice@voip.co.uk> To: Bob <sip:bob@voip.co.uk>
Note that the From and To headers have NOT been modified by the proxy, as RFC 3261 (the SIP standard) makes clear on page 162/163 in “Table 2: Summary of header fields”:
Header field where proxy ACK BYE CAN INV OPT REG
___________________________________________________________
From c r m m m m m m
To c(1) r m m m m m m
The "proxy" column describes the operations a proxy may perform on a
header field:
r: A proxy must be able to read the header field, and thus this
header field cannot be encrypted.
So, as you can see, a SIP proxy is NOT allowed to modify the To or From headers, only read them.
So your software would receive the request alice originally sent to bob but got redirected to voispeed as follows:
INVITE sip:056854@87.127.89.138:5060 SIP/2.0 From: Alice <sip:alice@voip.co.uk> To: Bob <sip:bob@voip.co.uk>
however, your software matches on the To header field for the incoming call, and thus sees 'bob' instead of the expected '056854', and rejects the call with a 404.
In short, you can not use the To header for matching, and doign so is totally incorrect.
There is currently work going on in the IETF to provide a mechanism to work out what (logical) address a request was initially targeted to, as there is no “correct” way to pass this information yet (although we try and send with P-Called-Party-ID where possible). Current ideas include a new 'Target' header or using loose routing and not modifying the R-URI at all.