func (d *UDPClient) sendAnnouncement(remote net.Addr, conn *net.UDPConn) bool { if debug { l.Debugf("discover %s: broadcast: Sending self announcement to %v", d.url, remote) } ann := d.announcer.Announcement() pkt, err := ann.MarshalXDR() if err != nil { return false } myID := protocol.DeviceIDFromBytes(ann.This.ID) _, err = conn.WriteTo(pkt, remote) if err != nil { if debug { l.Debugf("discover %s: broadcast: Failed to send self announcement: %s", d.url, err) } return false } // Verify that the announce server responds positively for our device ID time.Sleep(1 * time.Second) ann, err = d.Lookup(myID) if err != nil && debug { l.Debugf("discover %s: broadcast: Self-lookup failed: %v", d.url, err) } else if debug { l.Debugf("discover %s: broadcast: Self-lookup returned: %v", d.url, ann.This.Addresses) } return len(ann.This.Addresses) > 0 }
func (d *Discoverer) recvAnnouncements(b beacon.Interface) { for { buf, addr := b.Recv() var pkt Announce err := pkt.UnmarshalXDR(buf) if err != nil && err != io.EOF { if debug { l.Debugf("discover: Failed to unmarshal local announcement from %s:\n%s", addr, hex.Dump(buf)) } continue } if debug { l.Debugf("discover: Received local announcement from %s for %s", addr, protocol.DeviceIDFromBytes(pkt.This.ID)) } var newDevice bool if bytes.Compare(pkt.This.ID, d.myID[:]) != 0 { newDevice = d.registerDevice(addr, pkt.This) } if newDevice { select { case d.forcedBcastTick <- time.Now(): } } } }
func (d *UDPClient) Start(uri *url.URL, pkt *Announce) error { d.url = uri d.id = protocol.DeviceIDFromBytes(pkt.This.ID) d.stop = make(chan struct{}) params := uri.Query() // The address must not have a port, as otherwise both announce and lookup // sockets would try to bind to the same port. addr, err := net.ResolveUDPAddr(d.url.Scheme, params.Get("listenaddress")+":0") if err != nil { return err } d.listenAddress = addr broadcastSeconds, err := strconv.ParseUint(params.Get("broadcast"), 0, 0) if err != nil { d.globalBroadcastInterval = DefaultGlobalBroadcastInterval } else { d.globalBroadcastInterval = time.Duration(broadcastSeconds) * time.Second } retrySeconds, err := strconv.ParseUint(params.Get("retry"), 0, 0) if err != nil { d.errorRetryInterval = DefaultErrorRetryInternval } else { d.errorRetryInterval = time.Duration(retrySeconds) * time.Second } d.wg.Add(1) go d.broadcast(pkt.MustMarshalXDR()) return nil }
func ldbAvailability(db *leveldb.DB, folder, file []byte) []protocol.DeviceID { k := globalKey(folder, file) bs, err := db.Get(k, nil) if err == leveldb.ErrNotFound { return nil } if err != nil { panic(err) } var vl versionList err = vl.UnmarshalXDR(bs) if err != nil { panic(err) } var devices []protocol.DeviceID for _, v := range vl.versions { if v.version != vl.versions[0].version { break } n := protocol.DeviceIDFromBytes(v.device) devices = append(devices, n) } return devices }
func ldbReplaceWithDelete(db *leveldb.DB, folder, device []byte, fs []protocol.FileInfo) int64 { return ldbGenericReplace(db, folder, device, fs, func(db dbReader, batch dbWriter, folder, device, name []byte, dbi iterator.Iterator) int64 { var tf FileInfoTruncated err := tf.UnmarshalXDR(dbi.Value()) if err != nil { panic(err) } if !tf.IsDeleted() { if debugDB { l.Debugf("mark deleted; folder=%q device=%v name=%q", folder, protocol.DeviceIDFromBytes(device), name) } ts := clock(tf.LocalVersion) f := protocol.FileInfo{ Name: tf.Name, Version: lamport.Default.Tick(tf.Version), LocalVersion: ts, Flags: tf.Flags | protocol.FlagDeleted, Modified: tf.Modified, } bs, _ := f.MarshalXDR() if debugDB { l.Debugf("batch.Put %p %x", batch, dbi.Key()) } batch.Put(dbi.Key(), bs) ldbUpdateGlobal(db, batch, folder, device, deviceKeyName(dbi.Key()), f.Version) return ts } return 0 }) }
// ldbUpdateGlobal adds this device+version to the version list for the given // file. If the device is already present in the list, the version is updated. // If the file does not have an entry in the global list, it is created. func ldbUpdateGlobal(db dbReader, batch dbWriter, folder, device, file []byte, version protocol.Vector) bool { if debugDB { l.Debugf("update global; folder=%q device=%v file=%q version=%d", folder, protocol.DeviceIDFromBytes(device), file, version) } gk := globalKey(folder, file) svl, err := db.Get(gk, nil) if err != nil && err != leveldb.ErrNotFound { panic(err) } var fl versionList // Remove the device from the current version list if svl != nil { err = fl.UnmarshalXDR(svl) if err != nil { panic(err) } for i := range fl.versions { if bytes.Compare(fl.versions[i].device, device) == 0 { if fl.versions[i].version.Equal(version) { // No need to do anything return false } fl.versions = append(fl.versions[:i], fl.versions[i+1:]...) break } } } nv := fileVersion{ device: device, version: version, } for i := range fl.versions { // We compare against ConcurrentLesser as well here because we need // to enforce a consistent ordering of versions even in the case of // conflicts. if comp := fl.versions[i].version.Compare(version); comp == protocol.Equal || comp == protocol.Lesser || comp == protocol.ConcurrentLesser { t := append(fl.versions, fileVersion{}) copy(t[i+1:], t[i:]) t[i] = nv fl.versions = t goto done } } fl.versions = append(fl.versions, nv) done: if debugDB { l.Debugf("batch.Put %p %x", batch, gk) l.Debugf("new global after update: %v", fl) } batch.Put(gk, fl.MustMarshalXDR()) return true }
// ldbUpdateGlobal adds this device+version to the version list for the given // file. If the device is already present in the list, the version is updated. // If the file does not have an entry in the global list, it is created. func ldbUpdateGlobal(db dbReader, batch dbWriter, folder, device, file []byte, version int64) bool { if debugDB { l.Debugf("update global; folder=%q device=%v file=%q version=%d", folder, protocol.DeviceIDFromBytes(device), file, version) } gk := globalKey(folder, file) svl, err := db.Get(gk, nil) if err != nil && err != leveldb.ErrNotFound { panic(err) } var fl versionList nv := fileVersion{ device: device, version: version, } if svl != nil { err = fl.UnmarshalXDR(svl) if err != nil { panic(err) } for i := range fl.versions { if bytes.Compare(fl.versions[i].device, device) == 0 { if fl.versions[i].version == version { // No need to do anything return false } fl.versions = append(fl.versions[:i], fl.versions[i+1:]...) break } } } for i := range fl.versions { if fl.versions[i].version <= version { t := append(fl.versions, fileVersion{}) copy(t[i+1:], t[i:]) t[i] = nv fl.versions = t goto done } } fl.versions = append(fl.versions, nv) done: if debugDB { l.Debugf("batch.Put %p %x", batch, gk) l.Debugf("new global after update: %v", fl) } batch.Put(gk, fl.MustMarshalXDR()) return true }
func ldbReplace(db *leveldb.DB, folder, device []byte, fs []protocol.FileInfo) int64 { // TODO: Return the remaining maxLocalVer? return ldbGenericReplace(db, folder, device, fs, func(db dbReader, batch dbWriter, folder, device, name []byte, dbi iterator.Iterator) int64 { // Database has a file that we are missing. Remove it. if debugDB { l.Debugf("delete; folder=%q device=%v name=%q", folder, protocol.DeviceIDFromBytes(device), name) } ldbRemoveFromGlobal(db, batch, folder, device, name) if debugDB { l.Debugf("batch.Delete %p %x", batch, dbi.Key()) } batch.Delete(dbi.Key()) return 0 }) }
func ldbInsert(batch dbWriter, folder, device []byte, file protocol.FileInfo) int64 { if debugDB { l.Debugf("insert; folder=%q device=%v %v", folder, protocol.DeviceIDFromBytes(device), file) } if file.LocalVersion == 0 { file.LocalVersion = clock(0) } name := []byte(file.Name) nk := deviceKey(folder, device, name) if debugDB { l.Debugf("batch.Put %p %x", batch, nk) } batch.Put(nk, file.MustMarshalXDR()) return file.LocalVersion }
// ldbRemoveFromGlobal removes the device from the global version list for the // given file. If the version list is empty after this, the file entry is // removed entirely. func ldbRemoveFromGlobal(db dbReader, batch dbWriter, folder, device, file []byte) { if debugDB { l.Debugf("remove from global; folder=%q device=%v file=%q", folder, protocol.DeviceIDFromBytes(device), file) } gk := globalKey(folder, file) svl, err := db.Get(gk, nil) if err != nil { // We might be called to "remove" a global version that doesn't exist // if the first update for the file is already marked invalid. return } var fl versionList err = fl.UnmarshalXDR(svl) if err != nil { panic(err) } for i := range fl.versions { if bytes.Compare(fl.versions[i].device, device) == 0 { fl.versions = append(fl.versions[:i], fl.versions[i+1:]...) break } } if len(fl.versions) == 0 { if debugDB { l.Debugf("batch.Delete %p %x", batch, gk) } batch.Delete(gk) } else { if debugDB { l.Debugf("batch.Put %p %x", batch, gk) l.Debugf("new global after remove: %v", fl) } batch.Put(gk, fl.MustMarshalXDR()) } }
func (d *UDPClient) broadcast() { defer d.wg.Done() conn, err := net.ListenUDP(d.url.Scheme, d.listenAddress) for err != nil { if debug { l.Debugf("discover %s: broadcast listen: %v; trying again in %v", d.url, err, d.errorRetryInterval) } select { case <-d.stop: return case <-time.After(d.errorRetryInterval): } conn, err = net.ListenUDP(d.url.Scheme, d.listenAddress) } defer conn.Close() remote, err := net.ResolveUDPAddr(d.url.Scheme, d.url.Host) for err != nil { if debug { l.Debugf("discover %s: broadcast resolve: %v; trying again in %v", d.url, err, d.errorRetryInterval) } select { case <-d.stop: return case <-time.After(d.errorRetryInterval): } remote, err = net.ResolveUDPAddr(d.url.Scheme, d.url.Host) } timer := time.NewTimer(0) for { select { case <-d.stop: return case <-timer.C: var ok bool if debug { l.Debugf("discover %s: broadcast: Sending self announcement to %v", d.url, remote) } ann := d.announcer.Announcement() pkt, err := ann.MarshalXDR() if err != nil { timer.Reset(d.errorRetryInterval) continue } _, err = conn.WriteTo(pkt, remote) if err != nil { if debug { l.Debugf("discover %s: broadcast: Failed to send self announcement: %s", d.url, err) } ok = false } else { // Verify that the announce server responds positively for our device ID time.Sleep(1 * time.Second) pkt, err := d.Lookup(protocol.DeviceIDFromBytes(ann.This.ID)) if err != nil && debug { l.Debugf("discover %s: broadcast: Self-lookup failed: %v", d.url, err) } else if debug { l.Debugf("discover %s: broadcast: Self-lookup returned: %v", d.url, pkt.This.Addresses) } ok = len(pkt.This.Addresses) > 0 } d.mut.Lock() d.status = ok d.mut.Unlock() if ok { timer.Reset(d.globalBroadcastInterval) } else { timer.Reset(d.errorRetryInterval) } } } }
func (i SessionInvitation) String() string { return fmt.Sprintf("%s@%s", syncthingprotocol.DeviceIDFromBytes(i.From), i.AddressString()) }
func ldbWithNeed(db *leveldb.DB, folder, device []byte, truncate bool, fn Iterator) { runtime.GC() start := globalKey(folder, nil) limit := globalKey(folder, []byte{0xff, 0xff, 0xff, 0xff}) snap, err := db.GetSnapshot() if err != nil { panic(err) } if debugDB { l.Debugf("created snapshot %p", snap) } defer func() { if debugDB { l.Debugf("close snapshot %p", snap) } snap.Release() }() dbi := snap.NewIterator(&util.Range{Start: start, Limit: limit}, nil) defer dbi.Release() outer: for dbi.Next() { var vl versionList err := vl.UnmarshalXDR(dbi.Value()) if err != nil { panic(err) } if len(vl.versions) == 0 { l.Debugln(dbi.Key()) panic("no versions?") } have := false // If we have the file, any version need := false // If we have a lower version of the file var haveVersion int64 for _, v := range vl.versions { if bytes.Compare(v.device, device) == 0 { have = true haveVersion = v.version need = v.version < vl.versions[0].version break } } if need || !have { name := globalKeyName(dbi.Key()) needVersion := vl.versions[0].version inner: for i := range vl.versions { if vl.versions[i].version != needVersion { // We haven't found a valid copy of the file with the needed version. continue outer } fk := deviceKey(folder, vl.versions[i].device, name) if debugDB { l.Debugf("snap.Get %p %x", snap, fk) } bs, err := snap.Get(fk, nil) if err != nil { var id protocol.DeviceID copy(id[:], device) l.Debugf("device: %v", id) l.Debugf("need: %v, have: %v", need, have) l.Debugf("key: %q (%x)", dbi.Key(), dbi.Key()) l.Debugf("vl: %v", vl) l.Debugf("i: %v", i) l.Debugf("fk: %q (%x)", fk, fk) l.Debugf("name: %q (%x)", name, name) panic(err) } gf, err := unmarshalTrunc(bs, truncate) if err != nil { panic(err) } if gf.IsInvalid() { // The file is marked invalid for whatever reason, don't use it. continue inner } if gf.IsDeleted() && !have { // We don't need deleted files that we don't have continue outer } if debugDB { l.Debugf("need folder=%q device=%v name=%q need=%v have=%v haveV=%d globalV=%d", folder, protocol.DeviceIDFromBytes(device), name, need, have, haveVersion, vl.versions[0].version) } if cont := fn(gf); !cont { return } // This file is handled, no need to look further in the version list continue outer } } } }
func ldbGenericReplace(db *leveldb.DB, folder, device []byte, fs []protocol.FileInfo, deleteFn deletionHandler) int64 { runtime.GC() sort.Sort(fileList(fs)) // sort list on name, same as in the database start := deviceKey(folder, device, nil) // before all folder/device files limit := deviceKey(folder, device, []byte{0xff, 0xff, 0xff, 0xff}) // after all folder/device files batch := new(leveldb.Batch) if debugDB { l.Debugf("new batch %p", batch) } snap, err := db.GetSnapshot() if err != nil { panic(err) } if debugDB { l.Debugf("created snapshot %p", snap) } defer func() { if debugDB { l.Debugf("close snapshot %p", snap) } snap.Release() }() dbi := snap.NewIterator(&util.Range{Start: start, Limit: limit}, nil) defer dbi.Release() moreDb := dbi.Next() fsi := 0 var maxLocalVer int64 for { var newName, oldName []byte moreFs := fsi < len(fs) if !moreDb && !moreFs { break } if moreFs { newName = []byte(fs[fsi].Name) } if moreDb { oldName = deviceKeyName(dbi.Key()) } cmp := bytes.Compare(newName, oldName) if debugDB { l.Debugf("generic replace; folder=%q device=%v moreFs=%v moreDb=%v cmp=%d newName=%q oldName=%q", folder, protocol.DeviceIDFromBytes(device), moreFs, moreDb, cmp, newName, oldName) } switch { case moreFs && (!moreDb || cmp == -1): if debugDB { l.Debugln("generic replace; missing - insert") } // Database is missing this file. Insert it. if lv := ldbInsert(batch, folder, device, fs[fsi]); lv > maxLocalVer { maxLocalVer = lv } if fs[fsi].IsInvalid() { ldbRemoveFromGlobal(snap, batch, folder, device, newName) } else { ldbUpdateGlobal(snap, batch, folder, device, newName, fs[fsi].Version) } fsi++ case moreFs && moreDb && cmp == 0: // File exists on both sides - compare versions. We might get an // update with the same version and different flags if a device has // marked a file as invalid, so handle that too. if debugDB { l.Debugln("generic replace; exists - compare") } var ef FileInfoTruncated ef.UnmarshalXDR(dbi.Value()) if fs[fsi].Version > ef.Version || (fs[fsi].Version == ef.Version && fs[fsi].Flags != ef.Flags) { if debugDB { l.Debugln("generic replace; differs - insert") } if lv := ldbInsert(batch, folder, device, fs[fsi]); lv > maxLocalVer { maxLocalVer = lv } if fs[fsi].IsInvalid() { ldbRemoveFromGlobal(snap, batch, folder, device, newName) } else { ldbUpdateGlobal(snap, batch, folder, device, newName, fs[fsi].Version) } } else if debugDB { l.Debugln("generic replace; equal - ignore") } fsi++ moreDb = dbi.Next() case moreDb && (!moreFs || cmp == 1): if debugDB { l.Debugln("generic replace; exists - remove") } if lv := deleteFn(snap, batch, folder, device, oldName, dbi); lv > maxLocalVer { maxLocalVer = lv } moreDb = dbi.Next() } } if debugDB { l.Debugf("db.Write %p", batch) } err = db.Write(batch, nil) if err != nil { panic(err) } return maxLocalVer }
// ldbUpdateGlobal adds this device+version to the version list for the given // file. If the device is already present in the list, the version is updated. // If the file does not have an entry in the global list, it is created. func ldbUpdateGlobal(db dbReader, batch dbWriter, folder, device []byte, file protocol.FileInfo) bool { if debugDB { l.Debugf("update global; folder=%q device=%v file=%q version=%d", folder, protocol.DeviceIDFromBytes(device), file.Name, file.Version) } name := []byte(file.Name) gk := globalKey(folder, name) svl, err := db.Get(gk, nil) if err != nil && err != leveldb.ErrNotFound { panic(err) } var fl versionList // Remove the device from the current version list if svl != nil { err = fl.UnmarshalXDR(svl) if err != nil { panic(err) } for i := range fl.versions { if bytes.Compare(fl.versions[i].device, device) == 0 { if fl.versions[i].version.Equal(file.Version) { // No need to do anything return false } fl.versions = append(fl.versions[:i], fl.versions[i+1:]...) break } } } nv := fileVersion{ device: device, version: file.Version, } // Find a position in the list to insert this file. The file at the front // of the list is the newer, the "global". for i := range fl.versions { switch fl.versions[i].version.Compare(file.Version) { case protocol.Equal, protocol.Lesser: // The version at this point in the list is equal to or lesser // ("older") than us. We insert ourselves in front of it. fl.versions = insertVersion(fl.versions, i, nv) goto done case protocol.ConcurrentLesser, protocol.ConcurrentGreater: // The version at this point is in conflict with us. We must pull // the actual file metadata to determine who wins. If we win, we // insert ourselves in front of the loser here. (The "Lesser" and // "Greater" in the condition above is just based on the device // IDs in the version vector, which is not the only thing we use // to determine the winner.) of, ok := ldbGet(db, folder, fl.versions[i].device, name) if !ok { panic("file referenced in version list does not exist") } if file.WinsConflict(of) { fl.versions = insertVersion(fl.versions, i, nv) goto done } } } // We didn't find a position for an insert above, so append to the end. fl.versions = append(fl.versions, nv) done: if debugDB { l.Debugf("batch.Put %p %x", batch, gk) l.Debugf("new global after update: %v", fl) } batch.Put(gk, fl.MustMarshalXDR()) return true }
func protocolConnectionHandler(tcpConn net.Conn, config *tls.Config) { conn := tls.Server(tcpConn, config) err := conn.Handshake() if err != nil { if debug { log.Println("Protocol connection TLS handshake:", conn.RemoteAddr(), err) } conn.Close() return } state := conn.ConnectionState() if (!state.NegotiatedProtocolIsMutual || state.NegotiatedProtocol != protocol.ProtocolName) && debug { log.Println("Protocol negotiation error") } certs := state.PeerCertificates if len(certs) != 1 { if debug { log.Println("Certificate list error") } conn.Close() return } id := syncthingprotocol.NewDeviceID(certs[0].Raw) messages := make(chan interface{}) errors := make(chan error, 1) outbox := make(chan interface{}) // Read messages from the connection and send them on the messages // channel. When there is an error, send it on the error channel and // return. Applies also when the connection gets closed, so the pattern // below is to close the connection on error, then wait for the error // signal from messageReader to exit. go messageReader(conn, messages, errors) pingTicker := time.NewTicker(pingInterval) timeoutTicker := time.NewTimer(networkTimeout) joined := false for { select { case message := <-messages: timeoutTicker.Reset(networkTimeout) if debug { log.Printf("Message %T from %s", message, id) } switch msg := message.(type) { case protocol.JoinRelayRequest: outboxesMut.RLock() _, ok := outboxes[id] outboxesMut.RUnlock() if ok { protocol.WriteMessage(conn, protocol.ResponseAlreadyConnected) if debug { log.Println("Already have a peer with the same ID", id, conn.RemoteAddr()) } conn.Close() continue } outboxesMut.Lock() outboxes[id] = outbox outboxesMut.Unlock() joined = true protocol.WriteMessage(conn, protocol.ResponseSuccess) case protocol.ConnectRequest: requestedPeer := syncthingprotocol.DeviceIDFromBytes(msg.ID) outboxesMut.RLock() peerOutbox, ok := outboxes[requestedPeer] outboxesMut.RUnlock() if !ok { if debug { log.Println(id, "is looking for", requestedPeer, "which does not exist") } protocol.WriteMessage(conn, protocol.ResponseNotFound) conn.Close() continue } ses := newSession(sessionLimiter, globalLimiter) go ses.Serve() clientInvitation := ses.GetClientInvitationMessage(requestedPeer) serverInvitation := ses.GetServerInvitationMessage(id) if err := protocol.WriteMessage(conn, clientInvitation); err != nil { if debug { log.Printf("Error sending invitation from %s to client: %s", id, err) } conn.Close() continue } peerOutbox <- serverInvitation if debug { log.Println("Sent invitation from", id, "to", requestedPeer) } conn.Close() case protocol.Pong: // Nothing default: if debug { log.Printf("Unknown message %s: %T", id, message) } protocol.WriteMessage(conn, protocol.ResponseUnexpectedMessage) conn.Close() } case err := <-errors: if debug { log.Printf("Closing connection %s: %s", id, err) } close(outbox) // Potentially closing a second time. conn.Close() // Only delete the outbox if the client is joined, as it might be // a lookup request coming from the same client. if joined { outboxesMut.Lock() delete(outboxes, id) outboxesMut.Unlock() } return case <-pingTicker.C: if !joined { if debug { log.Println(id, "didn't join within", pingInterval) } conn.Close() continue } if err := protocol.WriteMessage(conn, protocol.Ping{}); err != nil { if debug { log.Println(id, err) } conn.Close() } case <-timeoutTicker.C: // We should receive a error from the reader loop, which will cause // us to quit this loop. if debug { log.Printf("%s timed out", id) } conn.Close() case msg := <-outbox: if debug { log.Printf("Sending message %T to %s", msg, id) } if err := protocol.WriteMessage(conn, msg); err != nil { if debug { log.Println(id, err) } conn.Close() } } } }