Forráskód Böngészése

Added MAc addr broadcast in mDNS

Toby Chui 3 éve
szülő
commit
7119d39608

+ 16 - 185
mod/network/mdns/common.go

@@ -1,196 +1,27 @@
 package mdns
 
-import (
-	"os"
-    "log"
-	"net/http"
-	"strconv"
-	"strings"
-	"errors"
-	"encoding/base64"
-	"bufio"
-	"io/ioutil"
-	"time"
-)
-
-/*
-	SYSTEM COMMON FUNCTIONS
-
-	This is a system function that put those we usually use function but not belongs to
-	any module / system.
-
-	E.g. fileExists / IsDir etc
-
-*/
-
-/*
-	Basic Response Functions
-
-	Send response with ease
-*/
-//Send text response with given w and message as string
-func sendTextResponse(w http.ResponseWriter, msg string) {
-	w.Write([]byte(msg))
-}
-
-//Send JSON response, with an extra json header
-func sendJSONResponse(w http.ResponseWriter, json string) {
-	w.Header().Set("Content-Type", "application/json")
-	w.Write([]byte(json))
-}
-
-func sendErrorResponse(w http.ResponseWriter, errMsg string) {
-	w.Header().Set("Content-Type", "application/json")
-	w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
-}
-
-func sendOK(w http.ResponseWriter) {
-	w.Header().Set("Content-Type", "application/json")
-	w.Write([]byte("\"OK\""))
-}
-/*
-	The paramter move function (mv)
-
-	You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
-	r (HTTP Request Object)
-	getParamter (string, aka $_GET['This string])
-
-	Will return
-	Paramter string (if any)
-	Error (if error)
-
-*/
-func mv(r *http.Request, getParamter string, postMode bool) (string, error) {
-	if postMode == false {
-		//Access the paramter via GET
-		keys, ok := r.URL.Query()[getParamter]
-
-		if !ok || len(keys[0]) < 1 {
-			//log.Println("Url Param " + getParamter +" is missing")
-			return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
-		}
-
-		// Query()["key"] will return an array of items,
-		// we only want the single item.
-		key := keys[0]
-		return string(key), nil
-	} else {
-		//Access the parameter via POST
-		r.ParseForm()
-		x := r.Form.Get(getParamter)
-		if len(x) == 0 || x == "" {
-			return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
-		}
-		return string(x), nil
-	}
-
-}
+import "net"
 
 func stringInSlice(a string, list []string) bool {
-    for _, b := range list {
-        if b == a {
-            return true
-        }
-    }
-    return false
-}
-
-
-func fileExists(filename string) bool {
-    _, err := os.Stat(filename)
-    if os.IsNotExist(err) {
-        return false
-    }
-    return true
-}
-
-
-func IsDir(path string) bool{
-	if (fileExists(path) == false){
-		return false
-	}
-	fi, err := os.Stat(path)
-    if err != nil {
-        log.Fatal(err)
-        return false
-    }
-    switch mode := fi.Mode(); {
-    case mode.IsDir():
-        return true
-    case mode.IsRegular():
-        return false
+	for _, b := range list {
+		if b == a {
+			return true
+		}
 	}
 	return false
 }
 
-func inArray(arr []string, str string) bool {
-	for _, a := range arr {
-	   if a == str {
-		  return true
-	   }
-	}
-	return false
- }
-
- func timeToString(targetTime time.Time) string{
-	 return targetTime.Format("2006-01-02 15:04:05")
- }
-
- func IntToString(number int) string{
-	return strconv.Itoa(number)
- }
-
- func StringToInt(number string) (int, error){
-	return strconv.Atoi(number)
- }
-
- func StringToInt64(number string) (int64, error){
-	i, err := strconv.ParseInt(number, 10, 64)
+func getMacAddr() ([]string, error) {
+	ifas, err := net.Interfaces()
 	if err != nil {
-		return -1, err
+		return nil, err
 	}
-	return i, nil
- }
-
- func Int64ToString(number int64) string{
-	convedNumber:=strconv.FormatInt(number,10)
-	return convedNumber
- }
-
- func GetUnixTime() int64{
-	return time.Now().Unix()
- }
-
- func LoadImageAsBase64(filepath string) (string, error){
-	if !fileExists(filepath){
-		return "", errors.New("File not exists")
+	var as []string
+	for _, ifa := range ifas {
+		a := ifa.HardwareAddr.String()
+		if a != "" {
+			as = append(as, a)
+		}
 	}
-	f, _ := os.Open(filepath)
-    reader := bufio.NewReader(f)
-    content, _ := ioutil.ReadAll(reader)
-	encoded := base64.StdEncoding.EncodeToString(content)
-	return string(encoded), nil
- }
-
- //Get the IP address of the current authentication user
-func getUserIPAddr(w http.ResponseWriter, r *http.Request) {
-    requestPort,_ :=  mv(r, "port", false)
-    showPort := false;
-    if (requestPort == "true"){
-        //Show port as well
-        showPort = true;
-    }
-    IPAddress := r.Header.Get("X-Real-Ip")
-    if IPAddress == "" {
-        IPAddress = r.Header.Get("X-Forwarded-For")
-    }
-    if IPAddress == "" {
-        IPAddress = r.RemoteAddr
-    }
-    if (!showPort){
-        IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
-
-    }
-    w.Write([]byte(IPAddress))
-    return;
-}
+	return as, nil
+}

+ 28 - 1
mod/network/mdns/mdns.go

@@ -25,12 +25,19 @@ type NetworkHost struct {
 	Vendor       string
 	BuildVersion string
 	MinorVersion string
+	MacAddr      []string
 }
 
 func NewMDNS(config NetworkHost) (*MDNSHost, error) {
+	//Get host MAC Address
+	macAddress, err := getMacAddr()
+	macAddressBoardcast := ""
+	if err == nil {
+		macAddressBoardcast = strings.Join(macAddress, ",")
+	}
 	//Register the mds services
 	//server, err := zeroconf.Register("ArOZ", "_http._tcp", "local.", *listen_port, []string{"version_build=" + build_version, "version_minor=" + internal_version, "vendor=" + deviceVendor, "model=" + deviceModel, "uuid=" + deviceUUID, "domain=aroz.online"}, nil)
-	server, err := zeroconf.Register(config.HostName, "_http._tcp", "local.", config.Port, []string{"version_build=" + config.BuildVersion, "version_minor=" + config.MinorVersion, "vendor=" + config.Vendor, "model=" + config.Model, "uuid=" + config.UUID, "domain=" + config.Domain}, nil)
+	server, err := zeroconf.Register(config.HostName, "_http._tcp", "local.", config.Port, []string{"version_build=" + config.BuildVersion, "version_minor=" + config.MinorVersion, "vendor=" + config.Vendor, "model=" + config.Model, "uuid=" + config.UUID, "domain=" + config.Domain, "mac_addr=" + macAddressBoardcast}, nil)
 	if err != nil {
 		return &MDNSHost{}, err
 	}
@@ -76,6 +83,15 @@ func (m *MDNSHost) Scan(timeout int, domainFilter string) []*NetworkHost {
 					}
 				}
 
+				var macAddrs []string
+				val, ok := properties["mac_addr"]
+				if !ok || val == "" {
+					//No MacAddr found. Target node version too old
+					macAddrs = []string{}
+				} else {
+					macAddrs = strings.Split(properties["mac_addr"], ",")
+				}
+
 				//log.Println(properties)
 				discoveredHost = append(discoveredHost, &NetworkHost{
 					HostName:     entry.HostName,
@@ -87,6 +103,7 @@ func (m *MDNSHost) Scan(timeout int, domainFilter string) []*NetworkHost {
 					Vendor:       properties["vendor"],
 					BuildVersion: properties["version_build"],
 					MinorVersion: properties["version_minor"],
+					MacAddr:      macAddrs,
 				})
 
 			} else {
@@ -102,6 +119,15 @@ func (m *MDNSHost) Scan(timeout int, domainFilter string) []*NetworkHost {
 						}
 					}
 
+					var macAddrs []string
+					val, ok := properties["mac_addr"]
+					if !ok || val == "" {
+						//No MacAddr found. Target node version too old
+						macAddrs = []string{}
+					} else {
+						macAddrs = strings.Split(properties["mac_addr"], ",")
+					}
+
 					//log.Println(properties)
 					discoveredHost = append(discoveredHost, &NetworkHost{
 						HostName:     entry.HostName,
@@ -113,6 +139,7 @@ func (m *MDNSHost) Scan(timeout int, domainFilter string) []*NetworkHost {
 						Vendor:       properties["vendor"],
 						BuildVersion: properties["version_build"],
 						MinorVersion: properties["version_minor"],
+						MacAddr:      macAddrs,
 					})
 
 				}

BIN
web/Memo/img/logo.psd


+ 70 - 41
web/SystemAO/cluster/neighbour.html

@@ -74,25 +74,31 @@
                                     <div class="item">
                                         <i class="disk icon"></i>
                                         <div class="content">
-                                            ${host.Model} (${host.Vendor})
+                                            <b>MODEL:</b> ${host.Model} (${host.Vendor})
                                         </div>
                                     </div>
                                     <div class="item">
                                         <i class="paperclip icon"></i>
                                         <div class="content">
-                                        ${host.MinorVersion} (${host.BuildVersion})
+                                            <b>VER:</b> ${host.MinorVersion} (${host.BuildVersion})
                                         </div>
                                     </div>
                                     <div class="item">
                                         <i class="marker icon"></i>
                                         <div class="content">
-                                            ${host.IPv4.join(" / ")}
+                                            <b>IP:</b> ${host.IPv4.join(" / ")}
                                         </div>
                                     </div>
                                     <div class="item">
                                         <i class="tag icon"></i>
                                         <div class="content">
-                                            ${host.UUID}
+                                            <b>UUID:</b> ${host.UUID}
+                                        </div>
+                                    </div>
+                                    <div class="item">
+                                        <i class="server icon"></i>
+                                        <div class="content">
+                                            <b>MAC:</b> ${host.MacAddr.join(" / ")}
                                         </div>
                                     </div>
                                 </div>
@@ -102,47 +108,70 @@
 
                     //Render remote host info
                     $("#nearybylist").html("");
-                    data.NearbyHosts.forEach(host => {
-                        var iplinks = [];
-                        host.IPv4.forEach(ip => {
-                            iplinks.push(`<a href="//${ip}:${host.Port}" target="_blank">${ip}</a>`);
-                        }) 
-                        var ipDOM = iplinks.join(" / ");
-                        $("#nearybylist").append(`<div class="ui icon teal message">
-                        <i class="server icon"></i>
-                        <div class="content">
-                            <div class="header">
-                                <a href="//${host.HostName}:${host.Port}" target="_blank">${host.HostName}</a>
-                            </div>
-                            <div class="ui list">
-                                <div class="item">
-                                    <i class="disk icon"></i>
-                                    <div class="content">
-                                        ${host.Model} (${host.Vendor})
-                                    </div>
-                                </div>
-                                <div class="item">
-                                    <i class="paperclip icon"></i>
-                                    <div class="content">
-                                    ${host.MinorVersion} (${host.BuildVersion})
-                                    </div>
+                    if (data.NearbyHosts == null){
+                        $("#nearybylist").append(`<div class="ui icon message">
+                                <i class="question icon"></i>
+                                <div class="content">
+                                    No nearby hosts discovered
                                 </div>
-                                <div class="item">
-                                    <i class="marker icon"></i>
-                                    <div class="content">
-                                        ${ipDOM}
+                            `);
+                    }else{
+                        data.NearbyHosts.forEach(host => {
+                            var iplinks = [];
+                            host.IPv4.forEach(ip => {
+                                iplinks.push(`<a href="//${ip}:${host.Port}" target="_blank">${ip}</a>`);
+                            }) 
+                            var ipDOM = iplinks.join(" / ");
+                            var macDOM = host.MacAddr.join(" / ");
+                            console.log(host.MacAddr);
+                            if (host.MacAddr.length == 0){
+                                //Old version of ArozOS, do not support MAC addr broadcast
+                                macDOM = "Version Not Supported";
+                            }
+                            $("#nearybylist").append(`<div class="ui icon teal message">
+                                <i class="server icon"></i>
+                                <div class="content">
+                                    <div class="header">
+                                        <a href="//${host.HostName}:${host.Port}" target="_blank">${host.HostName}</a>
                                     </div>
-                                </div>
-                                <div class="item">
-                                    <i class="tag icon"></i>
-                                    <div class="content">
-                                        ${host.UUID}
+                                    <div class="ui list">
+                                        <div class="item">
+                                            <i class="disk icon"></i>
+                                            <div class="content">
+                                                <b>MODEL:</b> ${host.Model} (${host.Vendor})
+                                            </div>
+                                        </div>
+                                        <div class="item">
+                                            <i class="paperclip icon"></i>
+                                            <div class="content">
+                                                <b>VER:</b> ${host.MinorVersion} (${host.BuildVersion})
+                                            </div>
+                                        </div>
+                                        <div class="item">
+                                            <i class="marker icon"></i>
+                                            <div class="content">
+                                                <b>IP:</b> ${ipDOM}
+                                            </div>
+                                        </div>
+                                        <div class="item">
+                                            <i class="tag icon"></i>
+                                            <div class="content">
+                                                <b>UUID:</b> ${host.UUID}
+                                            </div>
+                                        </div>
+                                        <div class="item">
+                                            <i class="server icon"></i>
+                                            <div class="content">
+                                                <b>MAC:</b> ${macDOM}
+                                            </div>
+                                        </div>
                                     </div>
                                 </div>
-                            </div>
-                        </div>
-                    </div>`);
-                    });
+                            </div>`);
+                            });
+                    }
+
+                   
 
                     //Update the update time
                     $("#lastUpdateTime").text(Math.floor(Date.now() / 1000) - data.LastUpdate);