2023-05-10 03:24:05 -04:00
|
|
|
package hscontrol
|
2022-08-14 17:12:18 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"tailscale.com/tailcfg"
|
|
|
|
"tailscale.com/types/key"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NoisePollNetMapHandler takes care of /machine/:id/map using the Noise protocol
|
|
|
|
//
|
|
|
|
// This is the busiest endpoint, as it keeps the HTTP long poll that updates
|
|
|
|
// the clients when something in the network changes.
|
|
|
|
//
|
|
|
|
// The clients POST stuff like HostInfo and their Endpoints here, but
|
|
|
|
// only after their first request (marked with the ReadOnly field).
|
|
|
|
//
|
|
|
|
// At this moment the updates are sent in a quite horrendous way, but they kinda work.
|
2023-05-02 02:15:33 -04:00
|
|
|
func (ns *noiseServer) NoisePollNetMapHandler(
|
2022-08-14 17:12:18 -04:00
|
|
|
writer http.ResponseWriter,
|
|
|
|
req *http.Request,
|
|
|
|
) {
|
|
|
|
log.Trace().
|
|
|
|
Str("handler", "NoisePollNetMap").
|
|
|
|
Msg("PollNetMapHandler called")
|
2023-05-02 02:15:33 -04:00
|
|
|
|
|
|
|
log.Trace().
|
|
|
|
Any("headers", req.Header).
|
|
|
|
Msg("Headers")
|
|
|
|
|
2022-08-14 17:12:18 -04:00
|
|
|
body, _ := io.ReadAll(req.Body)
|
|
|
|
|
|
|
|
mapRequest := tailcfg.MapRequest{}
|
|
|
|
if err := json.Unmarshal(body, &mapRequest); err != nil {
|
|
|
|
log.Error().
|
|
|
|
Caller().
|
|
|
|
Err(err).
|
|
|
|
Msg("Cannot parse MapRequest")
|
|
|
|
http.Error(writer, "Internal error", http.StatusInternalServerError)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-02 02:15:33 -04:00
|
|
|
ns.nodeKey = mapRequest.NodeKey
|
|
|
|
|
2023-05-11 03:09:18 -04:00
|
|
|
machine, err := ns.headscale.db.GetMachineByAnyKey(
|
|
|
|
ns.conn.Peer(),
|
|
|
|
mapRequest.NodeKey,
|
|
|
|
key.NodePublic{},
|
|
|
|
)
|
2022-08-14 17:12:18 -04:00
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
|
|
log.Warn().
|
|
|
|
Str("handler", "NoisePollNetMap").
|
|
|
|
Msgf("Ignoring request, cannot find machine with key %s", mapRequest.NodeKey.String())
|
|
|
|
http.Error(writer, "Internal error", http.StatusNotFound)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Error().
|
|
|
|
Str("handler", "NoisePollNetMap").
|
|
|
|
Msgf("Failed to fetch machine from the database with node key: %s", mapRequest.NodeKey.String())
|
|
|
|
http.Error(writer, "Internal error", http.StatusInternalServerError)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Debug().
|
|
|
|
Str("handler", "NoisePollNetMap").
|
|
|
|
Str("machine", machine.Hostname).
|
2022-08-15 04:44:22 -04:00
|
|
|
Msg("A machine is entering polling via the Noise protocol")
|
2022-08-14 17:12:18 -04:00
|
|
|
|
2023-06-06 11:14:56 -04:00
|
|
|
ns.headscale.handlePoll(writer, req.Context(), machine, mapRequest, true)
|
2022-08-14 17:12:18 -04:00
|
|
|
}
|