parse cloudinit yaml files and set windows hostname
This commit is contained in:
commit
03b298e8cc
14 changed files with 1386 additions and 0 deletions
43
cloudinit/cloudinit.go
Normal file
43
cloudinit/cloudinit.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package cloudinit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"jonasled.dev/jonasled/cloud-init-windows/filesystem"
|
||||
)
|
||||
|
||||
type CloudInit struct {
|
||||
UserData UserData
|
||||
NetworkConfig NetworkConfig
|
||||
}
|
||||
|
||||
func (c *CloudInit) Load() error {
|
||||
cloudInitDrive, err := getCloudInitMountpoint()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = c.UserData.Load(cloudInitDrive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = c.NetworkConfig.Load(cloudInitDrive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getCloudInitMountpoint() (string, error) {
|
||||
mounts, _, err := filesystem.Mounts()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for _, mount := range mounts {
|
||||
if mount.Device == "cidata" {
|
||||
return mount.Mountpoint, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("no Cloud-Init Mountpoint found")
|
||||
|
||||
}
|
||||
51
cloudinit/networkconfig.go
Normal file
51
cloudinit/networkconfig.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
package cloudinit
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type NetworkConfig struct {
|
||||
Version int `yaml:"version"`
|
||||
Config []ConfigEntry `yaml:"config"`
|
||||
}
|
||||
|
||||
type ConfigEntry struct {
|
||||
Type string `yaml:"type"`
|
||||
Name string `yaml:"name,omitempty"`
|
||||
MacAddress string `yaml:"mac_address,omitempty"`
|
||||
Subnets []Subnet `yaml:"subnets,omitempty"`
|
||||
Address []string `yaml:"address,omitempty"`
|
||||
Search []string `yaml:"search,omitempty"`
|
||||
}
|
||||
|
||||
type Subnet struct {
|
||||
Type string `yaml:"type"`
|
||||
Address string `yaml:"address"`
|
||||
Netmask string `yaml:"netmask"`
|
||||
Gateway string `yaml:"gateway"`
|
||||
}
|
||||
|
||||
func (c *NetworkConfig) Load(cloudInitDrive string) error {
|
||||
data, err := os.ReadFile(cloudInitDrive + "NETWORK_CONFIG")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Unmarshal the YAML data into the Config struct
|
||||
err = yaml.Unmarshal(data, &c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *NetworkConfig) GetNameservers() []string {
|
||||
for _, config := range c.Config {
|
||||
if config.Type == "nameserver" {
|
||||
return config.Address
|
||||
}
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
35
cloudinit/userdata.go
Normal file
35
cloudinit/userdata.go
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package cloudinit
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type UserData struct {
|
||||
Hostname string `yaml:"hostname"`
|
||||
ManageEtcHosts bool `yaml:"manage_etc_hosts"`
|
||||
FQDN string `yaml:"fqdn"`
|
||||
User string `yaml:"user"`
|
||||
Password string `yaml:"password"`
|
||||
Chpasswd Chpasswd `yaml:"chpasswd"`
|
||||
Users []string `yaml:"users"`
|
||||
PackageUpgrade bool `yaml:"package_upgrade"`
|
||||
}
|
||||
type Chpasswd struct {
|
||||
Expire bool `yaml:"expire"`
|
||||
}
|
||||
|
||||
func (u *UserData) Load(cloudInitDrive string) error {
|
||||
data, err := os.ReadFile(cloudInitDrive + "USER_DATA")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Unmarshal the YAML data into the Config struct
|
||||
err = yaml.Unmarshal(data, &u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
68
filesystem/filesystem.go
Normal file
68
filesystem/filesystem.go
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
package filesystem
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func findMounts(mounts []Mount, path string) ([]Mount, error) {
|
||||
var err error
|
||||
path, err = filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
path, err = filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var m []Mount
|
||||
for _, v := range mounts {
|
||||
if path == v.Device {
|
||||
return []Mount{v}, nil
|
||||
}
|
||||
|
||||
if strings.HasPrefix(path, v.Mountpoint) {
|
||||
var nm []Mount
|
||||
|
||||
// keep all entries that are as close or closer to the target
|
||||
for _, mv := range m {
|
||||
if len(mv.Mountpoint) >= len(v.Mountpoint) {
|
||||
nm = append(nm, mv)
|
||||
}
|
||||
}
|
||||
m = nm
|
||||
|
||||
// add entry only if we didn't already find something closer
|
||||
if len(nm) == 0 || len(v.Mountpoint) >= len(nm[0].Mountpoint) {
|
||||
m = append(m, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func deviceType(m Mount) string {
|
||||
if isNetworkFs(m) {
|
||||
return networkDevice
|
||||
}
|
||||
if isSpecialFs(m) {
|
||||
return specialDevice
|
||||
}
|
||||
if isFuseFs(m) {
|
||||
return fuseDevice
|
||||
}
|
||||
|
||||
return localDevice
|
||||
}
|
||||
|
||||
// remote: [ "nfs", "smbfs", "cifs", "ncpfs", "afs", "coda", "ftpfs", "mfs", "sshfs", "fuse.sshfs", "nfs4" ]
|
||||
// special: [ "tmpfs", "devpts", "devtmpfs", "proc", "sysfs", "usbfs", "devfs", "fdescfs", "linprocfs" ]
|
||||
301
filesystem/filesystem_linux.go
Normal file
301
filesystem/filesystem_linux.go
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package filesystem
|
||||
|
||||
import "strings"
|
||||
|
||||
//nolint:revive,deadcode
|
||||
const (
|
||||
// man statfs
|
||||
ADFS_SUPER_MAGIC = 0xadf5
|
||||
AFFS_SUPER_MAGIC = 0xADFF
|
||||
AUTOFS_SUPER_MAGIC = 0x0187
|
||||
BDEVFS_MAGIC = 0x62646576
|
||||
BEFS_SUPER_MAGIC = 0x42465331
|
||||
BFS_MAGIC = 0x1BADFACE
|
||||
BINFMTFS_MAGIC = 0x42494e4d
|
||||
BPF_FS_MAGIC = 0xcafe4a11
|
||||
BTRFS_SUPER_MAGIC = 0x9123683E
|
||||
CGROUP_SUPER_MAGIC = 0x27e0eb
|
||||
CGROUP2_SUPER_MAGIC = 0x63677270
|
||||
CIFS_MAGIC_NUMBER = 0xFF534D42
|
||||
CODA_SUPER_MAGIC = 0x73757245
|
||||
COH_SUPER_MAGIC = 0x012FF7B7
|
||||
CONFIGFS_MAGIC = 0x62656570
|
||||
CRAMFS_MAGIC = 0x28cd3d45
|
||||
DEBUGFS_MAGIC = 0x64626720
|
||||
DEVFS_SUPER_MAGIC = 0x1373
|
||||
DEVPTS_SUPER_MAGIC = 0x1cd1
|
||||
EFIVARFS_MAGIC = 0xde5e81e4
|
||||
EFS_SUPER_MAGIC = 0x00414A53
|
||||
EXT_SUPER_MAGIC = 0x137D
|
||||
EXT2_OLD_SUPER_MAGIC = 0xEF51
|
||||
EXT2_SUPER_MAGIC = 0xEF53
|
||||
EXT3_SUPER_MAGIC = 0xEF53
|
||||
EXT4_SUPER_MAGIC = 0xEF53
|
||||
FUSE_SUPER_MAGIC = 0x65735546
|
||||
FUTEXFS_SUPER_MAGIC = 0xBAD1DEA
|
||||
HFS_SUPER_MAGIC = 0x4244
|
||||
HFSPLUS_SUPER_MAGIC = 0x482b
|
||||
HOSTFS_SUPER_MAGIC = 0x00c0ffee
|
||||
HPFS_SUPER_MAGIC = 0xF995E849
|
||||
HUGETLBFS_MAGIC = 0x958458f6
|
||||
ISOFS_SUPER_MAGIC = 0x9660
|
||||
JFFS2_SUPER_MAGIC = 0x72b6
|
||||
JFS_SUPER_MAGIC = 0x3153464a
|
||||
MINIX_SUPER_MAGIC = 0x137F /* orig. minix */
|
||||
MINIX_SUPER_MAGIC2 = 0x138F /* 30 char minix */
|
||||
MINIX2_SUPER_MAGIC = 0x2468 /* minix V2 */
|
||||
MINIX2_SUPER_MAGIC2 = 0x2478 /* minix V2, 30 char names */
|
||||
MINIX3_SUPER_MAGIC = 0x4d5a /* minix V3 fs, 60 char names */
|
||||
MQUEUE_MAGIC = 0x19800202
|
||||
MSDOS_SUPER_MAGIC = 0x4d44
|
||||
NCP_SUPER_MAGIC = 0x564c
|
||||
NFS_SUPER_MAGIC = 0x6969
|
||||
NILFS_SUPER_MAGIC = 0x3434
|
||||
NTFS_SB_MAGIC = 0x5346544e
|
||||
OCFS2_SUPER_MAGIC = 0x7461636f
|
||||
OPENPROM_SUPER_MAGIC = 0x9fa1
|
||||
PIPEFS_MAGIC = 0x50495045
|
||||
PROC_SUPER_MAGIC = 0x9fa0
|
||||
PSTOREFS_MAGIC = 0x6165676C
|
||||
QNX4_SUPER_MAGIC = 0x002f
|
||||
QNX6_SUPER_MAGIC = 0x68191122
|
||||
RAMFS_MAGIC = 0x858458f6
|
||||
REISERFS_SUPER_MAGIC = 0x52654973
|
||||
ROMFS_MAGIC = 0x7275
|
||||
SELINUX_MAGIC = 0xf97cff8c
|
||||
SMACK_MAGIC = 0x43415d53
|
||||
SMB_SUPER_MAGIC = 0x517B
|
||||
SMB2_MAGIC_NUMBER = 0xfe534d42
|
||||
SOCKFS_MAGIC = 0x534F434B
|
||||
SQUASHFS_MAGIC = 0x73717368
|
||||
SYSFS_MAGIC = 0x62656572
|
||||
SYSV2_SUPER_MAGIC = 0x012FF7B6
|
||||
SYSV4_SUPER_MAGIC = 0x012FF7B5
|
||||
TMPFS_MAGIC = 0x01021994
|
||||
TRACEFS_MAGIC = 0x74726163
|
||||
UDF_SUPER_MAGIC = 0x15013346
|
||||
UFS_MAGIC = 0x00011954
|
||||
USBDEVICE_SUPER_MAGIC = 0x9fa2
|
||||
V9FS_MAGIC = 0x01021997
|
||||
VXFS_SUPER_MAGIC = 0xa501FCF5
|
||||
XENFS_SUPER_MAGIC = 0xabba1974
|
||||
XENIX_SUPER_MAGIC = 0x012FF7B4
|
||||
XFS_SUPER_MAGIC = 0x58465342
|
||||
_XIAFS_SUPER_MAGIC = 0x012FD16D
|
||||
|
||||
AFS_SUPER_MAGIC = 0x5346414F
|
||||
AUFS_SUPER_MAGIC = 0x61756673
|
||||
ANON_INODE_FS_SUPER_MAGIC = 0x09041934
|
||||
CEPH_SUPER_MAGIC = 0x00C36400
|
||||
ECRYPTFS_SUPER_MAGIC = 0xF15F
|
||||
FAT_SUPER_MAGIC = 0x4006
|
||||
FHGFS_SUPER_MAGIC = 0x19830326
|
||||
FUSEBLK_SUPER_MAGIC = 0x65735546
|
||||
FUSECTL_SUPER_MAGIC = 0x65735543
|
||||
GFS_SUPER_MAGIC = 0x1161970
|
||||
GPFS_SUPER_MAGIC = 0x47504653
|
||||
MTD_INODE_FS_SUPER_MAGIC = 0x11307854
|
||||
INOTIFYFS_SUPER_MAGIC = 0x2BAD1DEA
|
||||
ISOFS_R_WIN_SUPER_MAGIC = 0x4004
|
||||
ISOFS_WIN_SUPER_MAGIC = 0x4000
|
||||
JFFS_SUPER_MAGIC = 0x07C0
|
||||
KAFS_SUPER_MAGIC = 0x6B414653
|
||||
LUSTRE_SUPER_MAGIC = 0x0BD00BD0
|
||||
NFSD_SUPER_MAGIC = 0x6E667364
|
||||
PANFS_SUPER_MAGIC = 0xAAD7AAEA
|
||||
RPC_PIPEFS_SUPER_MAGIC = 0x67596969
|
||||
SECURITYFS_SUPER_MAGIC = 0x73636673
|
||||
UFS_BYTESWAPPED_SUPER_MAGIC = 0x54190100
|
||||
VMHGFS_SUPER_MAGIC = 0xBACBACBC
|
||||
VZFS_SUPER_MAGIC = 0x565A4653
|
||||
ZFS_SUPER_MAGIC = 0x2FC12FC1
|
||||
)
|
||||
|
||||
// coreutils/src/stat.c
|
||||
var fsTypeMap = map[int64]string{
|
||||
ADFS_SUPER_MAGIC: "adfs", /* 0xADF5 local */
|
||||
AFFS_SUPER_MAGIC: "affs", /* 0xADFF local */
|
||||
AFS_SUPER_MAGIC: "afs", /* 0x5346414F remote */
|
||||
ANON_INODE_FS_SUPER_MAGIC: "anon-inode FS", /* 0x09041934 local */
|
||||
AUFS_SUPER_MAGIC: "aufs", /* 0x61756673 remote */
|
||||
AUTOFS_SUPER_MAGIC: "autofs", /* 0x0187 local */
|
||||
BEFS_SUPER_MAGIC: "befs", /* 0x42465331 local */
|
||||
BDEVFS_MAGIC: "bdevfs", /* 0x62646576 local */
|
||||
BFS_MAGIC: "bfs", /* 0x1BADFACE local */
|
||||
BINFMTFS_MAGIC: "binfmt_misc", /* 0x42494E4D local */
|
||||
BTRFS_SUPER_MAGIC: "btrfs", /* 0x9123683E local */
|
||||
CEPH_SUPER_MAGIC: "ceph", /* 0x00C36400 remote */
|
||||
CGROUP_SUPER_MAGIC: "cgroupfs", /* 0x0027E0EB local */
|
||||
CIFS_MAGIC_NUMBER: "cifs", /* 0xFF534D42 remote */
|
||||
CODA_SUPER_MAGIC: "coda", /* 0x73757245 remote */
|
||||
COH_SUPER_MAGIC: "coh", /* 0x012FF7B7 local */
|
||||
CRAMFS_MAGIC: "cramfs", /* 0x28CD3D45 local */
|
||||
DEBUGFS_MAGIC: "debugfs", /* 0x64626720 local */
|
||||
DEVFS_SUPER_MAGIC: "devfs", /* 0x1373 local */
|
||||
DEVPTS_SUPER_MAGIC: "devpts", /* 0x1CD1 local */
|
||||
ECRYPTFS_SUPER_MAGIC: "ecryptfs", /* 0xF15F local */
|
||||
EFS_SUPER_MAGIC: "efs", /* 0x00414A53 local */
|
||||
EXT_SUPER_MAGIC: "ext", /* 0x137D local */
|
||||
EXT2_SUPER_MAGIC: "ext2/ext3", /* 0xEF53 local */
|
||||
EXT2_OLD_SUPER_MAGIC: "ext2", /* 0xEF51 local */
|
||||
FAT_SUPER_MAGIC: "fat", /* 0x4006 local */
|
||||
FHGFS_SUPER_MAGIC: "fhgfs", /* 0x19830326 remote */
|
||||
FUSEBLK_SUPER_MAGIC: "fuseblk", /* 0x65735546 remote */
|
||||
FUSECTL_SUPER_MAGIC: "fusectl", /* 0x65735543 remote */
|
||||
FUTEXFS_SUPER_MAGIC: "futexfs", /* 0x0BAD1DEA local */
|
||||
GFS_SUPER_MAGIC: "gfs/gfs2", /* 0x1161970 remote */
|
||||
GPFS_SUPER_MAGIC: "gpfs", /* 0x47504653 remote */
|
||||
HFS_SUPER_MAGIC: "hfs", /* 0x4244 local */
|
||||
HFSPLUS_SUPER_MAGIC: "hfsplus", /* 0x482b local */
|
||||
HPFS_SUPER_MAGIC: "hpfs", /* 0xF995E849 local */
|
||||
HUGETLBFS_MAGIC: "hugetlbfs", /* 0x958458F6 local */
|
||||
MTD_INODE_FS_SUPER_MAGIC: "inodefs", /* 0x11307854 local */
|
||||
INOTIFYFS_SUPER_MAGIC: "inotifyfs", /* 0x2BAD1DEA local */
|
||||
ISOFS_SUPER_MAGIC: "isofs", /* 0x9660 local */
|
||||
ISOFS_R_WIN_SUPER_MAGIC: "isofs", /* 0x4004 local */
|
||||
ISOFS_WIN_SUPER_MAGIC: "isofs", /* 0x4000 local */
|
||||
JFFS_SUPER_MAGIC: "jffs", /* 0x07C0 local */
|
||||
JFFS2_SUPER_MAGIC: "jffs2", /* 0x72B6 local */
|
||||
JFS_SUPER_MAGIC: "jfs", /* 0x3153464A local */
|
||||
KAFS_SUPER_MAGIC: "k-afs", /* 0x6B414653 remote */
|
||||
LUSTRE_SUPER_MAGIC: "lustre", /* 0x0BD00BD0 remote */
|
||||
MINIX_SUPER_MAGIC: "minix", /* 0x137F local */
|
||||
MINIX_SUPER_MAGIC2: "minix (30 char.)", /* 0x138F local */
|
||||
MINIX2_SUPER_MAGIC: "minix v2", /* 0x2468 local */
|
||||
MINIX2_SUPER_MAGIC2: "minix v2 (30 char.)", /* 0x2478 local */
|
||||
MINIX3_SUPER_MAGIC: "minix3", /* 0x4D5A local */
|
||||
MQUEUE_MAGIC: "mqueue", /* 0x19800202 local */
|
||||
MSDOS_SUPER_MAGIC: "msdos", /* 0x4D44 local */
|
||||
NCP_SUPER_MAGIC: "novell", /* 0x564C remote */
|
||||
NFS_SUPER_MAGIC: "nfs", /* 0x6969 remote */
|
||||
NFSD_SUPER_MAGIC: "nfsd", /* 0x6E667364 remote */
|
||||
NILFS_SUPER_MAGIC: "nilfs", /* 0x3434 local */
|
||||
NTFS_SB_MAGIC: "ntfs", /* 0x5346544E local */
|
||||
OPENPROM_SUPER_MAGIC: "openprom", /* 0x9FA1 local */
|
||||
OCFS2_SUPER_MAGIC: "ocfs2", /* 0x7461636f remote */
|
||||
PANFS_SUPER_MAGIC: "panfs", /* 0xAAD7AAEA remote */
|
||||
PIPEFS_MAGIC: "pipefs", /* 0x50495045 remote */
|
||||
PROC_SUPER_MAGIC: "proc", /* 0x9FA0 local */
|
||||
PSTOREFS_MAGIC: "pstorefs", /* 0x6165676C local */
|
||||
QNX4_SUPER_MAGIC: "qnx4", /* 0x002F local */
|
||||
QNX6_SUPER_MAGIC: "qnx6", /* 0x68191122 local */
|
||||
RAMFS_MAGIC: "ramfs", /* 0x858458F6 local */
|
||||
REISERFS_SUPER_MAGIC: "reiserfs", /* 0x52654973 local */
|
||||
ROMFS_MAGIC: "romfs", /* 0x7275 local */
|
||||
RPC_PIPEFS_SUPER_MAGIC: "rpc_pipefs", /* 0x67596969 local */
|
||||
SECURITYFS_SUPER_MAGIC: "securityfs", /* 0x73636673 local */
|
||||
SELINUX_MAGIC: "selinux", /* 0xF97CFF8C local */
|
||||
SMB_SUPER_MAGIC: "smb", /* 0x517B remote */
|
||||
SMB2_MAGIC_NUMBER: "smb2", /* 0xfe534d42 remote */
|
||||
SOCKFS_MAGIC: "sockfs", /* 0x534F434B local */
|
||||
SQUASHFS_MAGIC: "squashfs", /* 0x73717368 local */
|
||||
SYSFS_MAGIC: "sysfs", /* 0x62656572 local */
|
||||
SYSV2_SUPER_MAGIC: "sysv2", /* 0x012FF7B6 local */
|
||||
SYSV4_SUPER_MAGIC: "sysv4", /* 0x012FF7B5 local */
|
||||
TMPFS_MAGIC: "tmpfs", /* 0x01021994 local */
|
||||
UDF_SUPER_MAGIC: "udf", /* 0x15013346 local */
|
||||
UFS_MAGIC: "ufs", /* 0x00011954 local */
|
||||
UFS_BYTESWAPPED_SUPER_MAGIC: "ufs", /* 0x54190100 local */
|
||||
USBDEVICE_SUPER_MAGIC: "usbdevfs", /* 0x9FA2 local */
|
||||
V9FS_MAGIC: "v9fs", /* 0x01021997 local */
|
||||
VMHGFS_SUPER_MAGIC: "vmhgfs", /* 0xBACBACBC remote */
|
||||
VXFS_SUPER_MAGIC: "vxfs", /* 0xA501FCF5 local */
|
||||
VZFS_SUPER_MAGIC: "vzfs", /* 0x565A4653 local */
|
||||
XENFS_SUPER_MAGIC: "xenfs", /* 0xABBA1974 local */
|
||||
XENIX_SUPER_MAGIC: "xenix", /* 0x012FF7B4 local */
|
||||
XFS_SUPER_MAGIC: "xfs", /* 0x58465342 local */
|
||||
_XIAFS_SUPER_MAGIC: "xia", /* 0x012FD16D local */
|
||||
ZFS_SUPER_MAGIC: "zfs", /* 0x2FC12FC1 local */
|
||||
}
|
||||
|
||||
/*
|
||||
var localMap = map[int64]bool{
|
||||
AFS_SUPER_MAGIC: true,
|
||||
BTRFS_SUPER_MAGIC: true,
|
||||
EXT_SUPER_MAGIC: true,
|
||||
EXT2_OLD_SUPER_MAGIC: true,
|
||||
EXT2_SUPER_MAGIC: true,
|
||||
FAT_SUPER_MAGIC: true,
|
||||
HPFS_SUPER_MAGIC: true,
|
||||
MSDOS_SUPER_MAGIC: true,
|
||||
NTFS_SB_MAGIC: true,
|
||||
REISERFS_SUPER_MAGIC: true,
|
||||
UDF_SUPER_MAGIC: true,
|
||||
XFS_SUPER_MAGIC: true,
|
||||
ZFS_SUPER_MAGIC: true,
|
||||
}
|
||||
*/
|
||||
|
||||
var networkMap = map[int64]bool{
|
||||
CIFS_MAGIC_NUMBER: true,
|
||||
NFS_SUPER_MAGIC: true,
|
||||
SMB_SUPER_MAGIC: true,
|
||||
SMB2_MAGIC_NUMBER: true,
|
||||
}
|
||||
|
||||
var specialMap = map[int64]bool{
|
||||
AUTOFS_SUPER_MAGIC: true,
|
||||
BINFMTFS_MAGIC: true,
|
||||
BPF_FS_MAGIC: true,
|
||||
CGROUP_SUPER_MAGIC: true,
|
||||
CGROUP2_SUPER_MAGIC: true,
|
||||
CONFIGFS_MAGIC: true,
|
||||
DEBUGFS_MAGIC: true,
|
||||
DEVPTS_SUPER_MAGIC: true,
|
||||
EFIVARFS_MAGIC: true,
|
||||
FUSECTL_SUPER_MAGIC: true,
|
||||
HUGETLBFS_MAGIC: true,
|
||||
MQUEUE_MAGIC: true,
|
||||
PROC_SUPER_MAGIC: true,
|
||||
PSTOREFS_MAGIC: true,
|
||||
SECURITYFS_SUPER_MAGIC: true,
|
||||
SYSFS_MAGIC: true,
|
||||
TMPFS_MAGIC: true,
|
||||
TRACEFS_MAGIC: true,
|
||||
}
|
||||
|
||||
/*
|
||||
func isLocalFs(m Mount) bool {
|
||||
return localMap[int64(m.Stat().Type)] //nolint:unconvert
|
||||
}
|
||||
*/
|
||||
|
||||
func isFuseFs(m Mount) bool {
|
||||
return m.Stat().Type == FUSEBLK_SUPER_MAGIC ||
|
||||
m.Stat().Type == FUSE_SUPER_MAGIC
|
||||
}
|
||||
|
||||
func isNetworkFs(m Mount) bool {
|
||||
return networkMap[int64(m.Stat().Type)] //nolint:unconvert
|
||||
}
|
||||
|
||||
func isSpecialFs(m Mount) bool {
|
||||
if m.Device == "nsfs" {
|
||||
return true
|
||||
}
|
||||
|
||||
return specialMap[int64(m.Stat().Type)] //nolint:unconvert
|
||||
}
|
||||
|
||||
func isHiddenFs(m Mount) bool {
|
||||
switch m.Device {
|
||||
case "shm":
|
||||
return true
|
||||
case "overlay":
|
||||
return true
|
||||
}
|
||||
|
||||
switch m.Fstype {
|
||||
case "autofs":
|
||||
return true
|
||||
case "squashfs":
|
||||
if strings.HasPrefix(m.Mountpoint, "/snap") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
56
filesystem/filesystem_windows.go
Normal file
56
filesystem/filesystem_windows.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
const (
|
||||
WindowsSandboxMountPointRegistryPath = `Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\CPC\LocalMOF`
|
||||
)
|
||||
|
||||
var windowsSandboxMountPoints = loadRegisteredWindowsSandboxMountPoints()
|
||||
|
||||
func loadRegisteredWindowsSandboxMountPoints() (ret map[string]struct{}) {
|
||||
ret = make(map[string]struct{})
|
||||
key, err := registry.OpenKey(registry.CURRENT_USER, WindowsSandboxMountPointRegistryPath, registry.READ)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
keyInfo, err := key.Stat()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
mountPoints, err := key.ReadValueNames(int(keyInfo.ValueCount))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, val := range mountPoints {
|
||||
ret[val] = struct{}{}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func isFuseFs(m Mount) bool {
|
||||
//FIXME: implement
|
||||
return false
|
||||
}
|
||||
|
||||
func isNetworkFs(m Mount) bool {
|
||||
_, ok := m.Metadata.(*NetResource)
|
||||
return ok
|
||||
}
|
||||
|
||||
func isSpecialFs(m Mount) bool {
|
||||
_, ok := windowsSandboxMountPoints[m.Mountpoint]
|
||||
return ok
|
||||
}
|
||||
|
||||
func isHiddenFs(m Mount) bool {
|
||||
return false
|
||||
}
|
||||
101
filesystem/mounts.go
Normal file
101
filesystem/mounts.go
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
package filesystem
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
localDevice = "local"
|
||||
networkDevice = "network"
|
||||
fuseDevice = "fuse"
|
||||
specialDevice = "special"
|
||||
loopsDevice = "loops"
|
||||
bindsMount = "binds"
|
||||
)
|
||||
|
||||
// Mount contains all metadata for a single filesystem mount.
|
||||
type Mount struct {
|
||||
Device string `json:"device"`
|
||||
DeviceType string `json:"device_type"`
|
||||
Mountpoint string `json:"mount_point"`
|
||||
Fstype string `json:"fs_type"`
|
||||
Type string `json:"type"`
|
||||
Opts string `json:"opts"`
|
||||
Total uint64 `json:"total"`
|
||||
Free uint64 `json:"free"`
|
||||
Used uint64 `json:"used"`
|
||||
Inodes uint64 `json:"inodes"`
|
||||
InodesFree uint64 `json:"inodes_free"`
|
||||
InodesUsed uint64 `json:"inodes_used"`
|
||||
Blocks uint64 `json:"blocks"`
|
||||
BlockSize uint64 `json:"block_size"`
|
||||
Metadata interface{} `json:"-"`
|
||||
}
|
||||
|
||||
func readLines(filename string) ([]string, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close() //nolint:errcheck // ignore error
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
var s []string
|
||||
for scanner.Scan() {
|
||||
s = append(s, scanner.Text())
|
||||
}
|
||||
|
||||
return s, scanner.Err()
|
||||
}
|
||||
|
||||
func unescapeFstab(path string) string {
|
||||
escaped, err := strconv.Unquote(`"` + path + `"`)
|
||||
if err != nil {
|
||||
return path
|
||||
}
|
||||
return escaped
|
||||
}
|
||||
|
||||
//nolint:deadcode,unused // used on BSD
|
||||
func byteToString(orig []byte) string {
|
||||
n := -1
|
||||
l := -1
|
||||
for i, b := range orig {
|
||||
// skip left side null
|
||||
if l == -1 && b == 0 {
|
||||
continue
|
||||
}
|
||||
if l == -1 {
|
||||
l = i
|
||||
}
|
||||
|
||||
if b == 0 {
|
||||
break
|
||||
}
|
||||
n = i + 1
|
||||
}
|
||||
if n == -1 {
|
||||
return string(orig)
|
||||
}
|
||||
return string(orig[l:n])
|
||||
}
|
||||
|
||||
//nolint:deadcode,unused // used on OpenBSD
|
||||
func intToString(orig []int8) string {
|
||||
ret := make([]byte, len(orig))
|
||||
size := -1
|
||||
for i, o := range orig {
|
||||
if o == 0 {
|
||||
size = i
|
||||
break
|
||||
}
|
||||
ret[i] = byte(o)
|
||||
}
|
||||
if size == -1 {
|
||||
size = len(orig)
|
||||
}
|
||||
|
||||
return string(ret[0:size])
|
||||
}
|
||||
172
filesystem/mounts_linux.go
Normal file
172
filesystem/mounts_linux.go
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const (
|
||||
// A line of self/mountinfo has the following structure:
|
||||
// 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
|
||||
// (0) (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)
|
||||
//
|
||||
// (0) mount ID: unique identifier of the mount (may be reused after umount).
|
||||
//mountinfoMountID = 0
|
||||
// (1) parent ID: ID of parent (or of self for the top of the mount tree).
|
||||
//mountinfoParentID = 1
|
||||
// (2) major:minor: value of st_dev for files on filesystem.
|
||||
//mountinfoMajorMinor = 2
|
||||
// (3) root: root of the mount within the filesystem.
|
||||
//mountinfoRoot = 3
|
||||
// (4) mount point: mount point relative to the process's root.
|
||||
mountinfoMountPoint = 4
|
||||
// (5) mount options: per mount options.
|
||||
mountinfoMountOpts = 5
|
||||
// (6) optional fields: zero or more fields terminated by "-".
|
||||
mountinfoOptionalFields = 6
|
||||
// (7) separator between optional fields.
|
||||
//mountinfoSeparator = 7
|
||||
// (8) filesystem type: name of filesystem of the form.
|
||||
mountinfoFsType = 8
|
||||
// (9) mount source: filesystem specific information or "none".
|
||||
mountinfoMountSource = 9
|
||||
// (10) super options: per super block options.
|
||||
//mountinfoSuperOptions = 10
|
||||
)
|
||||
|
||||
// Stat returns the mountpoint's stat information.
|
||||
func (m *Mount) Stat() unix.Statfs_t {
|
||||
return m.Metadata.(unix.Statfs_t)
|
||||
}
|
||||
|
||||
func Mounts() ([]Mount, []string, error) {
|
||||
var warnings []string
|
||||
|
||||
filename := "/proc/self/mountinfo"
|
||||
lines, err := readLines(filename)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
ret := make([]Mount, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
nb, fields := parseMountInfoLine(line)
|
||||
if nb == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// if the number of fields does not match the structure of mountinfo,
|
||||
// emit a warning and ignore the line.
|
||||
if nb < 10 || nb > 11 {
|
||||
warnings = append(warnings, fmt.Sprintf("found invalid mountinfo line: %s", line))
|
||||
continue
|
||||
}
|
||||
|
||||
// blockDeviceID := fields[mountinfoMountID]
|
||||
mountPoint := fields[mountinfoMountPoint]
|
||||
mountOpts := fields[mountinfoMountOpts]
|
||||
fstype := fields[mountinfoFsType]
|
||||
device := fields[mountinfoMountSource]
|
||||
|
||||
var stat unix.Statfs_t
|
||||
err := unix.Statfs(mountPoint, &stat)
|
||||
if err != nil {
|
||||
if err != os.ErrPermission {
|
||||
warnings = append(warnings, fmt.Sprintf("%s: %s", mountPoint, err))
|
||||
continue
|
||||
}
|
||||
|
||||
stat = unix.Statfs_t{}
|
||||
}
|
||||
|
||||
d := Mount{
|
||||
Device: device,
|
||||
Mountpoint: mountPoint,
|
||||
Fstype: fstype,
|
||||
Type: fsTypeMap[int64(stat.Type)], //nolint:unconvert
|
||||
Opts: mountOpts,
|
||||
Metadata: stat,
|
||||
Total: (uint64(stat.Blocks) * uint64(stat.Bsize)), //nolint:unconvert
|
||||
Free: (uint64(stat.Bavail) * uint64(stat.Bsize)), //nolint:unconvert
|
||||
Used: (uint64(stat.Blocks) - uint64(stat.Bfree)) * uint64(stat.Bsize), //nolint:unconvert
|
||||
Inodes: stat.Files,
|
||||
InodesFree: stat.Ffree,
|
||||
InodesUsed: stat.Files - stat.Ffree,
|
||||
Blocks: uint64(stat.Blocks), //nolint:unconvert
|
||||
BlockSize: uint64(stat.Bsize),
|
||||
}
|
||||
d.DeviceType = deviceType(d)
|
||||
|
||||
// resolve /dev/mapper/* device names
|
||||
if strings.HasPrefix(d.Device, "/dev/mapper/") {
|
||||
re := regexp.MustCompile(`^\/dev\/mapper\/(.*)-(.*)`)
|
||||
match := re.FindAllStringSubmatch(d.Device, -1)
|
||||
if len(match) > 0 && len(match[0]) == 3 {
|
||||
d.Device = filepath.Join("/dev", match[0][1], match[0][2])
|
||||
}
|
||||
}
|
||||
|
||||
ret = append(ret, d)
|
||||
}
|
||||
|
||||
return ret, warnings, nil
|
||||
}
|
||||
|
||||
// parseMountInfoLine parses a line of /proc/self/mountinfo and returns the
|
||||
// amount of parsed fields and their values.
|
||||
func parseMountInfoLine(line string) (int, [11]string) {
|
||||
var fields [11]string
|
||||
|
||||
if len(line) == 0 || line[0] == '#' {
|
||||
// ignore comments and empty lines
|
||||
return 0, fields
|
||||
}
|
||||
|
||||
var i int
|
||||
for _, f := range strings.Fields(line) {
|
||||
// when parsing the optional fields, loop until we find the separator
|
||||
if i == mountinfoOptionalFields {
|
||||
// (6) optional fields: zero or more fields of the form
|
||||
// "tag[:value]"; see below.
|
||||
// (7) separator: the end of the optional fields is marked
|
||||
// by a single hyphen.
|
||||
if f != "-" {
|
||||
if fields[i] == "" {
|
||||
fields[i] += f
|
||||
} else {
|
||||
fields[i] += " " + f
|
||||
}
|
||||
|
||||
// keep reading until we reach the separator
|
||||
continue
|
||||
}
|
||||
|
||||
// separator found, continue parsing
|
||||
i++
|
||||
}
|
||||
|
||||
switch i {
|
||||
case mountinfoMountPoint:
|
||||
fallthrough
|
||||
case mountinfoMountSource:
|
||||
fallthrough
|
||||
case mountinfoFsType:
|
||||
fields[i] = unescapeFstab(f)
|
||||
|
||||
default:
|
||||
fields[i] = f
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
return i, fields
|
||||
}
|
||||
378
filesystem/mounts_windows.go
Normal file
378
filesystem/mounts_windows.go
Normal file
|
|
@ -0,0 +1,378 @@
|
|||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// Local devices
|
||||
const (
|
||||
guidBufLen = windows.MAX_PATH + 1
|
||||
volumeNameBufLen = windows.MAX_PATH + 1
|
||||
rootPathBufLen = windows.MAX_PATH + 1
|
||||
fileSystemBufLen = windows.MAX_PATH + 1
|
||||
)
|
||||
|
||||
func getMountPoint(guidBuf []uint16) (mountPoint string, err error) {
|
||||
var rootPathLen uint32
|
||||
rootPathBuf := make([]uint16, rootPathBufLen)
|
||||
|
||||
err = windows.GetVolumePathNamesForVolumeName(&guidBuf[0], &rootPathBuf[0], rootPathBufLen*2, &rootPathLen)
|
||||
if err != nil && err.(windows.Errno) == windows.ERROR_MORE_DATA {
|
||||
// Retry if buffer size is too small
|
||||
rootPathBuf = make([]uint16, (rootPathLen+1)/2)
|
||||
err = windows.GetVolumePathNamesForVolumeName(
|
||||
&guidBuf[0], &rootPathBuf[0], rootPathLen, &rootPathLen)
|
||||
}
|
||||
return windows.UTF16ToString(rootPathBuf), err
|
||||
}
|
||||
|
||||
func getVolumeInfo(guidOrMountPointBuf []uint16) (volumeName string, fsType string, err error) {
|
||||
volumeNameBuf := make([]uint16, volumeNameBufLen)
|
||||
fsTypeBuf := make([]uint16, fileSystemBufLen)
|
||||
|
||||
err = windows.GetVolumeInformation(&guidOrMountPointBuf[0], &volumeNameBuf[0], volumeNameBufLen*2,
|
||||
nil, nil, nil,
|
||||
&fsTypeBuf[0], fileSystemBufLen*2)
|
||||
|
||||
return windows.UTF16ToString(volumeNameBuf), windows.UTF16ToString(fsTypeBuf), err
|
||||
}
|
||||
|
||||
func getSpaceInfo(guidOrMountPointBuf []uint16) (totalBytes uint64, freeBytes uint64, err error) {
|
||||
err = windows.GetDiskFreeSpaceEx(&guidOrMountPointBuf[0], nil, &totalBytes, &freeBytes)
|
||||
return
|
||||
}
|
||||
|
||||
func getClusterInfo(guidOrMountPointBuf []uint16) (totalClusters uint32, clusterSize uint32, err error) {
|
||||
var sectorsPerCluster uint32
|
||||
var bytesPerSector uint32
|
||||
err = GetDiskFreeSpace(&guidOrMountPointBuf[0], §orsPerCluster, &bytesPerSector, nil, &totalClusters)
|
||||
clusterSize = bytesPerSector * sectorsPerCluster
|
||||
return
|
||||
}
|
||||
|
||||
func getMount(guidOrMountPointBuf []uint16, isGUID bool) (m Mount, skip bool, warnings []string) {
|
||||
var err error
|
||||
guidOrMountPoint := windows.UTF16ToString(guidOrMountPointBuf)
|
||||
|
||||
mountPoint := guidOrMountPoint
|
||||
if isGUID {
|
||||
mountPoint, err = getMountPoint(guidOrMountPointBuf)
|
||||
if err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("%s: %s", guidOrMountPoint, err))
|
||||
}
|
||||
// Skip unmounted volumes
|
||||
if len(mountPoint) == 0 {
|
||||
skip = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Get volume name & filesystem type
|
||||
volumeName, fsType, err := getVolumeInfo(guidOrMountPointBuf)
|
||||
if err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("%s: %s", guidOrMountPoint, err))
|
||||
}
|
||||
|
||||
// Get space info
|
||||
totalBytes, freeBytes, err := getSpaceInfo(guidOrMountPointBuf)
|
||||
if err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("%s: %s", guidOrMountPoint, err))
|
||||
}
|
||||
|
||||
// Get cluster info
|
||||
totalClusters, clusterSize, err := getClusterInfo(guidOrMountPointBuf)
|
||||
if err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("%s: %s", guidOrMountPoint, err))
|
||||
}
|
||||
|
||||
m = Mount{
|
||||
Device: volumeName,
|
||||
Mountpoint: mountPoint,
|
||||
Fstype: fsType,
|
||||
Type: fsType,
|
||||
Opts: "",
|
||||
Total: totalBytes,
|
||||
Free: freeBytes,
|
||||
Used: totalBytes - freeBytes,
|
||||
Blocks: uint64(totalClusters),
|
||||
BlockSize: uint64(clusterSize),
|
||||
}
|
||||
m.DeviceType = deviceType(m)
|
||||
return
|
||||
}
|
||||
|
||||
func getMountFromGUID(guidBuf []uint16) (m Mount, skip bool, warnings []string) {
|
||||
m, skip, warnings = getMount(guidBuf, true)
|
||||
|
||||
// Use GUID as volume name if no label was set
|
||||
if len(m.Device) == 0 {
|
||||
m.Device = windows.UTF16ToString(guidBuf)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func getMountFromMountPoint(mountPointBuf []uint16) (m Mount, warnings []string) {
|
||||
m, _, warnings = getMount(mountPointBuf, false)
|
||||
|
||||
// Use mount point as volume name if no label was set
|
||||
if len(m.Device) == 0 {
|
||||
m.Device = windows.UTF16ToString(mountPointBuf)
|
||||
}
|
||||
|
||||
return m, warnings
|
||||
}
|
||||
|
||||
func appendLocalMounts(mounts []Mount, warnings []string) ([]Mount, []string, error) {
|
||||
guidBuf := make([]uint16, guidBufLen)
|
||||
|
||||
hFindVolume, err := windows.FindFirstVolume(&guidBuf[0], guidBufLen*2)
|
||||
if err != nil {
|
||||
return mounts, warnings, err
|
||||
}
|
||||
|
||||
VolumeLoop:
|
||||
for ; ; err = windows.FindNextVolume(hFindVolume, &guidBuf[0], guidBufLen*2) {
|
||||
if err != nil {
|
||||
switch err.(windows.Errno) {
|
||||
case windows.ERROR_NO_MORE_FILES:
|
||||
break VolumeLoop
|
||||
default:
|
||||
warnings = append(warnings, fmt.Sprintf("%s: %s", windows.UTF16ToString(guidBuf), err))
|
||||
continue VolumeLoop
|
||||
}
|
||||
}
|
||||
|
||||
if m, skip, w := getMountFromGUID(guidBuf); !skip {
|
||||
mounts = append(mounts, m)
|
||||
warnings = append(warnings, w...)
|
||||
}
|
||||
}
|
||||
|
||||
if err = windows.FindVolumeClose(hFindVolume); err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("%s", err))
|
||||
}
|
||||
return mounts, warnings, nil
|
||||
}
|
||||
|
||||
// Network devices
|
||||
func getMountFromNetResource(netResource NetResource) (m Mount, warnings []string) {
|
||||
mountPoint := windows.UTF16PtrToString(netResource.LocalName)
|
||||
if !strings.HasSuffix(mountPoint, string(filepath.Separator)) {
|
||||
mountPoint += string(filepath.Separator)
|
||||
}
|
||||
mountPointBuf := windows.StringToUTF16(mountPoint)
|
||||
|
||||
m, _, warnings = getMount(mountPointBuf, false)
|
||||
|
||||
// Use remote name as volume name if no label was set
|
||||
if len(m.Device) == 0 {
|
||||
m.Device = windows.UTF16PtrToString(netResource.RemoteName)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func appendNetworkMounts(mounts []Mount, warnings []string) ([]Mount, []string, error) {
|
||||
hEnumResource, err := WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_DISK, RESOURCEUSAGE_CONNECTABLE, nil)
|
||||
if err != nil {
|
||||
return mounts, warnings, err
|
||||
}
|
||||
|
||||
EnumLoop:
|
||||
for {
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/wnet/enumerating-network-resources
|
||||
var nrBuf [16384]byte
|
||||
count := uint32(math.MaxUint32)
|
||||
size := uint32(len(nrBuf))
|
||||
if err := WNetEnumResource(hEnumResource, &count, &nrBuf[0], &size); err != nil {
|
||||
switch err.(windows.Errno) {
|
||||
case windows.ERROR_NO_MORE_ITEMS:
|
||||
break EnumLoop
|
||||
default:
|
||||
warnings = append(warnings, err.Error())
|
||||
break EnumLoop
|
||||
}
|
||||
}
|
||||
|
||||
for i := uint32(0); i < count; i++ {
|
||||
nr := (*NetResource)(unsafe.Pointer(&nrBuf[uintptr(i)*NetResourceSize]))
|
||||
m, w := getMountFromNetResource(*nr)
|
||||
mounts = append(mounts, m)
|
||||
warnings = append(warnings, w...)
|
||||
}
|
||||
}
|
||||
|
||||
if err = WNetCloseEnum(hEnumResource); err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("%s", err))
|
||||
}
|
||||
return mounts, warnings, nil
|
||||
}
|
||||
|
||||
func mountPointAlreadyPresent(mounts []Mount, mountPoint string) bool {
|
||||
for _, m := range mounts {
|
||||
if m.Mountpoint == mountPoint {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func appendLogicalDrives(mounts []Mount, warnings []string) ([]Mount, []string) {
|
||||
driveBitmap, err := windows.GetLogicalDrives()
|
||||
if err != nil {
|
||||
warnings = append(warnings, fmt.Sprintf("GetLogicalDrives(): %s", err))
|
||||
return mounts, warnings
|
||||
}
|
||||
|
||||
for drive := 'A'; drive <= 'Z'; drive, driveBitmap = drive+1, driveBitmap>>1 {
|
||||
if driveBitmap&0x1 == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
mountPoint := fmt.Sprintf("%c:\\", drive)
|
||||
if mountPointAlreadyPresent(mounts, mountPoint) {
|
||||
continue
|
||||
}
|
||||
|
||||
mountPointBuf := windows.StringToUTF16(mountPoint)
|
||||
m, w := getMountFromMountPoint(mountPointBuf)
|
||||
mounts = append(mounts, m)
|
||||
warnings = append(warnings, w...)
|
||||
}
|
||||
|
||||
return mounts, warnings
|
||||
}
|
||||
|
||||
func Mounts() (ret []Mount, warnings []string, err error) {
|
||||
ret = make([]Mount, 0)
|
||||
|
||||
// Local devices
|
||||
if ret, warnings, err = appendLocalMounts(ret, warnings); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Network devices
|
||||
if ret, warnings, err = appendNetworkMounts(ret, warnings); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Logical devices (from GetLogicalDrives bitflag)
|
||||
// Check any possible logical drives, in case of some special virtual devices, such as RAM disk
|
||||
ret, warnings = appendLogicalDrives(ret, warnings)
|
||||
|
||||
return ret, warnings, nil
|
||||
}
|
||||
|
||||
// Windows API
|
||||
const (
|
||||
// Windows Networking const
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetopenenumw
|
||||
RESOURCE_CONNECTED = 0x00000001
|
||||
RESOURCE_GLOBALNET = 0x00000002
|
||||
RESOURCE_REMEMBERED = 0x00000003
|
||||
RESOURCE_RECENT = 0x00000004
|
||||
RESOURCE_CONTEXT = 0x00000005
|
||||
|
||||
RESOURCETYPE_ANY = 0x00000000
|
||||
RESOURCETYPE_DISK = 0x00000001
|
||||
RESOURCETYPE_PRINT = 0x00000002
|
||||
RESOURCETYPE_RESERVED = 0x00000008
|
||||
RESOURCETYPE_UNKNOWN = 0xFFFFFFFF
|
||||
|
||||
RESOURCEUSAGE_CONNECTABLE = 0x00000001
|
||||
RESOURCEUSAGE_CONTAINER = 0x00000002
|
||||
RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004
|
||||
RESOURCEUSAGE_SIBLING = 0x00000008
|
||||
RESOURCEUSAGE_ATTACHED = 0x00000010
|
||||
RESOURCEUSAGE_ALL = RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED
|
||||
RESOURCEUSAGE_RESERVED = 0x80000000
|
||||
)
|
||||
|
||||
var (
|
||||
// Windows syscall
|
||||
modmpr = windows.NewLazySystemDLL("mpr.dll")
|
||||
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
|
||||
|
||||
procWNetOpenEnumW = modmpr.NewProc("WNetOpenEnumW")
|
||||
procWNetCloseEnum = modmpr.NewProc("WNetCloseEnum")
|
||||
procWNetEnumResourceW = modmpr.NewProc("WNetEnumResourceW")
|
||||
procGetDiskFreeSpaceW = modkernel32.NewProc("GetDiskFreeSpaceW")
|
||||
|
||||
NetResourceSize = unsafe.Sizeof(NetResource{})
|
||||
)
|
||||
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/ns-winnetwk-netresourcew
|
||||
type NetResource struct {
|
||||
Scope uint32
|
||||
Type uint32
|
||||
DisplayType uint32
|
||||
Usage uint32
|
||||
LocalName *uint16
|
||||
RemoteName *uint16
|
||||
Comment *uint16
|
||||
Provider *uint16
|
||||
}
|
||||
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetopenenumw
|
||||
func WNetOpenEnum(scope uint32, resourceType uint32, usage uint32, resource *NetResource) (handle windows.Handle, err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procWNetOpenEnumW.Addr(), 5, uintptr(scope), uintptr(resourceType), uintptr(usage), uintptr(unsafe.Pointer(resource)), uintptr(unsafe.Pointer(&handle)), 0)
|
||||
if r1 != windows.NO_ERROR {
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetenumresourcew
|
||||
func WNetEnumResource(enumResource windows.Handle, count *uint32, buffer *byte, bufferSize *uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procWNetEnumResourceW.Addr(), 4, uintptr(enumResource), uintptr(unsafe.Pointer(count)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(bufferSize)), 0, 0)
|
||||
if r1 != windows.NO_ERROR {
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetcloseenum
|
||||
func WNetCloseEnum(enumResource windows.Handle) (err error) {
|
||||
r1, _, e1 := syscall.Syscall(procWNetCloseEnum.Addr(), 1, uintptr(enumResource), 0, 0)
|
||||
if r1 != windows.NO_ERROR {
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Reference: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespacew
|
||||
func GetDiskFreeSpace(directoryName *uint16, sectorsPerCluster *uint32, bytesPerSector *uint32, numberOfFreeClusters *uint32, totalNumberOfClusters *uint32) (err error) {
|
||||
r1, _, e1 := syscall.Syscall6(procGetDiskFreeSpaceW.Addr(), 5, uintptr(unsafe.Pointer(directoryName)), uintptr(unsafe.Pointer(sectorsPerCluster)), uintptr(unsafe.Pointer(bytesPerSector)), uintptr(unsafe.Pointer(numberOfFreeClusters)), uintptr(unsafe.Pointer(totalNumberOfClusters)), 0)
|
||||
if r1 == 0 {
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
} else {
|
||||
err = syscall.EINVAL
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
8
go.mod
Normal file
8
go.mod
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
module jonasled.dev/jonasled/cloud-init-windows
|
||||
|
||||
go 1.22.3
|
||||
|
||||
require (
|
||||
golang.org/x/sys v0.12.0
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
)
|
||||
6
go.sum
Normal file
6
go.sum
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
36
main.go
Normal file
36
main.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"jonasled.dev/jonasled/cloud-init-windows/cloudinit"
|
||||
"jonasled.dev/jonasled/cloud-init-windows/windows"
|
||||
)
|
||||
|
||||
func main() {
|
||||
rebootRequired := false
|
||||
|
||||
var cloudInitConfig cloudinit.CloudInit
|
||||
err := cloudInitConfig.Load()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if windows.GetHostname() != cloudInitConfig.UserData.Hostname {
|
||||
fmt.Println("Setting hostname to " + cloudInitConfig.UserData.Hostname)
|
||||
windows.SetHostname(cloudInitConfig.UserData.Hostname)
|
||||
rebootRequired = true
|
||||
}
|
||||
|
||||
for _, networkconfig := range cloudInitConfig.NetworkConfig.Config {
|
||||
networkInterface, err := windows.GetNetworkInterfaceByMac(networkconfig.MacAddress)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println("Setting IP address for Interface " + networkInterface)
|
||||
}
|
||||
|
||||
if rebootRequired {
|
||||
fmt.Println("Reboot is required")
|
||||
}
|
||||
}
|
||||
41
windows/hostname.go
Normal file
41
windows/hostname.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
ComputerNamePhysicalDnsHostname = 5
|
||||
)
|
||||
|
||||
// SetHostname sets the computer's hostname
|
||||
func SetHostname(hostname string) error {
|
||||
// Convert the hostname to UTF-16
|
||||
hostnameUTF16, err := syscall.UTF16PtrFromString(hostname)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert hostname to UTF-16: %v", err)
|
||||
}
|
||||
|
||||
// Load kernel32.dll and get the address of SetComputerNameExW
|
||||
mod := syscall.NewLazyDLL("kernel32.dll")
|
||||
proc := mod.NewProc("SetComputerNameExW")
|
||||
|
||||
// Call SetComputerNameExW
|
||||
r1, _, err := proc.Call(
|
||||
uintptr(ComputerNamePhysicalDnsHostname),
|
||||
uintptr(unsafe.Pointer(hostnameUTF16)),
|
||||
)
|
||||
if r1 == 0 {
|
||||
return fmt.Errorf("SetComputerNameExW failed: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetHostname() string {
|
||||
hostname, _ := os.Hostname()
|
||||
return hostname
|
||||
}
|
||||
90
windows/netowrking.go
Normal file
90
windows/netowrking.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
type IP_ADAPTER_INFO struct {
|
||||
Next *IP_ADAPTER_INFO
|
||||
ComboIndex uint32
|
||||
AdapterName [260]byte
|
||||
Description [132]byte
|
||||
AddressLength uint32
|
||||
Address [8]byte
|
||||
Index uint32
|
||||
Type uint32
|
||||
DhcpEnabled uint32
|
||||
CurrentIpAddress *IP_ADDR_STRING
|
||||
IpAddressList IP_ADDR_STRING
|
||||
GatewayList IP_ADDR_STRING
|
||||
DhcpServer IP_ADDR_STRING
|
||||
HaveWins uint32
|
||||
PrimaryWinsServer IP_ADDR_STRING
|
||||
SecondaryWinsServer IP_ADDR_STRING
|
||||
LeaseObtained uint32
|
||||
LeaseExpires uint32
|
||||
}
|
||||
|
||||
type IP_ADDR_STRING struct {
|
||||
Next *IP_ADDR_STRING
|
||||
IpAddress [16]byte
|
||||
IpMask [16]byte
|
||||
Context uint32
|
||||
}
|
||||
|
||||
func GetNetworkInterfaceByMac(macAddress string) (string, error) {
|
||||
iphlpapi := windows.NewLazySystemDLL("iphlpapi.dll")
|
||||
getAdaptersInfo := iphlpapi.NewProc("GetAdaptersInfo")
|
||||
|
||||
var buflen uint32
|
||||
r1, _, err := getAdaptersInfo.Call(uintptr(unsafe.Pointer(&buflen)), 0)
|
||||
if r1 != uintptr(windows.ERROR_BUFFER_OVERFLOW) {
|
||||
return "", fmt.Errorf("error getting buffer size: %v", err)
|
||||
}
|
||||
|
||||
buf := make([]byte, buflen)
|
||||
r1, _, err = getAdaptersInfo.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&buflen)))
|
||||
if r1 != 0 {
|
||||
return "", fmt.Errorf("error getting adapter info: %v", err)
|
||||
}
|
||||
|
||||
var adapters []IP_ADAPTER_INFO
|
||||
var adapter *IP_ADAPTER_INFO = (*IP_ADAPTER_INFO)(unsafe.Pointer(&buf[0]))
|
||||
|
||||
for adapter != nil {
|
||||
adapters = append(adapters, *adapter)
|
||||
adapter = adapter.Next
|
||||
}
|
||||
|
||||
for _, adapter := range adapters {
|
||||
mac := fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
|
||||
adapter.Address[0],
|
||||
adapter.Address[1],
|
||||
adapter.Address[2],
|
||||
adapter.Address[3],
|
||||
adapter.Address[4],
|
||||
adapter.Address[5])
|
||||
fmt.Println(mac)
|
||||
if mac == strings.ToLower(macAddress) {
|
||||
fmt.Println(adapter.AdapterName)
|
||||
return "windows.UTF16ToString(adapter.AdapterName[:])", nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("interface with MAC address %s not found", macAddress)
|
||||
}
|
||||
|
||||
func setIPAddress(interfaceName string, ipAddress string, subnetMask string, gateway string) error {
|
||||
cmd := exec.Command("netsh", "interface", "ip", "set", "address", fmt.Sprintf("name=%s", interfaceName), "source=static", fmt.Sprintf("addr=%s", ipAddress), fmt.Sprintf("mask=%s", subnetMask), fmt.Sprintf("gateway=%s", gateway))
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set IP address: %v, output: %s", err, output)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue