Problem with double redirection

Hello everyone, and thanks for your help in advance.

I’m having some trouble with redirecting an already redirected call on Asterisk 15.7.4

In a part of our dialplan, I’ve setup a redirection of inbound calls to a certain number XXX to be redirected to YYY as follows. Note 1234567 is a real DID acquired from a provider, I just haven’t listed it:

exten => direct,n,Gotoif($["${ARG1}" = “XXX”]?emergency)
exten => direct,n(emergency),NoOp()
exten => direct,n,Set(CALLERID(all)=“1234567” <1234567>)
exten => direct,n,Dial(SIP/provider/YYY/213.226.61.66)
exten => direct,n,Hangup()

This part of the dialplan works without any problems. The problem arises when we try to redirect calls from a physical device, a GSM (ZZZ) to the XXX number. What we’re trying to achieve is basically someone calls ZZZ - call is redirected to XXX - XXX redirects to YYY. On their own - ZZZ to XXX and XXX to YYY calls are getting redirected as intended, however when all three numbers are configured to redirect in order, the call to YYY fails.

In the logs I observe the following response:

== Using SIP RTP CoS mark 5
– Called SIP/provider/YYY/213.226.61.66
[2021-09-28 08:34:40.812] WARNING[8932][C-000002b5]: chan_sip.c:24133 handle_response_invite: Received response: “Forbidden” from ‘“1234567” sip:1234567@10.252.42.254;tag=as7bc974b4’

Any help would be appreciated.

Can you explain why you are using the unusual form of the dial string, with the IP address?

Setting the account name in the dialplan, rather that with fromuser is strange, but you say it works for a direct call to XXX.

When you say ZZZ is forwarding, do you mean it is doing a network unconditional call forward? (Your Asterisk call forward is really a relay operation, not a forwarding one.)

Is there any way that the provider can associate the incoming and outgoing Asterisk legs, as, to a first approximation, the outgoing leg should be independent of the incoming one.

Please provide sip set debug on output for both the working case and the failing case.