CyCoreSystems / ari

Golang Asterisk REST Interface (ARI) library
Apache License 2.0
180 stars 74 forks source link

Dial event is dispatched to all active channels #129

Open rashikzaman opened 2 years ago

rashikzaman commented 2 years ago

Problem:
When asterisk fires a dial event, all active channels that have subscribed to this event receive this event, regardless of whether this event is intended for them.

Reason: When a dial event is dispatched by asterisk, it provides three IDs, Caller ID, Peer ID and Forwarded ID. Among them, Caller ID and Forwarded ID are optional.

At events.go file, for dial events, these three ids are added to the Keys array. Here, Caller ID and Forwarded ID can be empty.

// Keys returns the list of keys associated with this event
func (evt *Dial) Keys() (sx Keys) {
    sx = append(sx, evt.Key(ChannelKey, evt.Caller.ID))
    sx = append(sx, evt.Key(ChannelKey, evt.Peer.ID))
    sx = append(sx, evt.Key(ChannelKey, evt.Forwarded.ID))

    return
}

Now at stdbus/bus.go, Send method sends all events to their appropriate subscribers. This is done by matching subscriber key with event keys. But this Match method returns true even if event key is empty. So for dial event, as two of three keys can be empty, s.key.Match(k) provides true and as a result, regardless of the subscriber, this dial event is dispatched to all subscribers.

// Send sends the message to the bus
func (b *bus) Send(e ari.Event) {
    var matched bool

    b.rwMux.RLock()

    // Disseminate the message to the subscribers
    for _, s := range b.subs {
        matched = false
        for _, k := range e.Keys() {
            if matched {
                break
            }

            if s.key.Match(k) {
                matched = true
                for _, topic := range s.events {
                    if topic == e.GetType() || topic == ari.Events.All {
                        select {
                        case s.C <- e:
                        default: // never block
                        }
                    }
                }
            }
        }
    }

    b.rwMux.RUnlock()
}

Possible Solution: Prevent adding empty IDs to event keys, as of for Dial event, don't add Caller ID and Forwarded ID if they are empty.

Ulexus commented 2 years ago

Interesting. I haven't run into problems with this before (just hasn't mattered, not that it hasn't ocurred), but I can certainly see the issue.

It seems like the most obvious solution would be empty checks for those IDs before they are added to the event. Feel free to PR if you are up for it.