2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
26 common "github.com/iotbzh/xds-common/golib"
27 uuid "github.com/satori/go.uuid"
28 "github.com/syncthing/syncthing/lib/sync"
31 // xmlServerData contains persistent data stored/loaded by server
32 type xmlServerData struct {
33 XMLName xml.Name `xml:"XDS-Server"`
34 Version string `xml:"version,attr"`
35 Data ServerData `xml:"server-data"`
38 type ServerData struct {
42 var sdMutex = sync.NewMutex()
45 func ServerIDGet() (string, error) {
50 if f, err = ServerDataFilenameGet(); err != nil {
53 if err = serverDataRead(f, &d); err != nil || d.ID == "" {
54 // Create a new uuid when not found
55 d.ID = uuid.NewV1().String()
56 if err := serverDataWrite(f, d); err != nil {
63 // serverDataRead reads data saved on disk
64 func serverDataRead(file string, data *ServerData) error {
65 if !common.Exists(file) {
66 return fmt.Errorf("No folder config file found (%s)", file)
70 defer sdMutex.Unlock()
72 fd, err := os.Open(file)
78 xsd := xmlServerData{}
79 err = xml.NewDecoder(fd).Decode(&xsd)
86 // serverDataWrite writes persistant data to disk
87 func serverDataWrite(file string, data ServerData) error {
89 defer sdMutex.Unlock()
91 dir := filepath.Dir(file)
92 if !common.Exists(dir) {
93 if err := os.MkdirAll(dir, 0755); err != nil {
94 return fmt.Errorf("Cannot create server data directory: %s", dir)
98 fd, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
104 xsd := &xmlServerData{
109 enc := xml.NewEncoder(fd)
111 return enc.Encode(xsd)