Prevent adding a gateway twice

Prevent adding an existing gateway.

The first three commits belong to #695 and #697, and should disappear once they get merged.

Fixes #692.