<commit_before>package network

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"

	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/device/nictype"
	"github.com/lxc/lxd/lxd/dnsmasq"
	"github.com/lxc/lxd/lxd/dnsmasq/dhcpalloc"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/network/openvswitch"
	"github.com/lxc/lxd/lxd/project"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
)

// validInterfaceName validates a real network interface name.
func validInterfaceName(value string) error {
	// Validate the length.
	if len(value) < 2 {
		return fmt.Errorf("Network interface is too short (minimum 2 characters)")
	}

	if len(value) > 15 {
		return fmt.Errorf("Network interface is too long (maximum 15 characters)")
	}

	// Validate the character set.
	match, _ := regexp.MatchString("^[-_a-zA-Z0-9.]*$", value)
	if !match {
		return fmt.Errorf("Network interface contains invalid characters")
	}

	return nil
}

func networkValidPort(value string) error {
	if value == "" {
		return nil
	}

	valueInt, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		return fmt.Errorf("Invalid value for an integer: %s", value)
	}

	if valueInt < 1 || valueInt > 65536 {
		return fmt.Errorf("Invalid port number: %s", value)
	}

	return nil
}

// RandomDevName returns a random device name with prefix.
// If the random string combined with the prefix exceeds 13 characters then empty string is returned.
// This is to ensure we support buggy dhclient applications: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858580
func RandomDevName(prefix string) string {
	// Return a new random veth device name.
	randBytes := make([]byte, 4)
	rand.Read(randBytes)
	iface := prefix + hex.EncodeToString(randBytes)
	if len(iface) > 13 {
		return ""
	}

	return iface
}

// IsInUseByInstance indicates if network is referenced by an instance's NIC devices.
// Checks if the device's parent or network properties match the network name.
func IsInUseByInstance(s *state.State, inst instance.Instance, networkProjectName string, networkName string) (bool, error) {
	// Get the translated network project name from the instance's project.
	instNetworkProjectName, err := project.NetworkProject(s.Cluster, inst.Project())
	if err != nil {
		return false, err
	}

	// Skip instances who's translated network project doesn't match the requested network's project.
	// Because its devices can't be using this network.
	if networkProjectName != instNetworkProjectName {
		return false, nil
	}

	return isInUseByDevices(s, networkProjectName, networkName, inst.ExpandedDevices())
}

// IsInUseByProfile indicates if network is referenced by a profile's NIC devices.
// Checks if the device's parent or network properties match the network name.
func IsInUseByProfile(s *state.State, profile api.Profile, networkName string) (bool, error) {
	return isInUseByDevices(s, deviceConfig.NewDevices(profile.Devices), networkName)
}

func isInUseByDevices(s *state.State, devices deviceConfig.Devices, networkName string) (bool, error) {
	for _, d := range devices {
		if d["type"] != "nic" {
			continue
		}

		nicType, err := nictype.NICType(s, d)
		if err != nil {<commit_msg>lxd/network/network/utils: Updates isInUseByDevices to support projects<commit_after>package network

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"

	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/device/nictype"
	"github.com/lxc/lxd/lxd/dnsmasq"
	"github.com/lxc/lxd/lxd/dnsmasq/dhcpalloc"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/network/openvswitch"
	"github.com/lxc/lxd/lxd/project"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
)

// validInterfaceName validates a real network interface name.
func validInterfaceName(value string) error {
	// Validate the length.
	if len(value) < 2 {
		return fmt.Errorf("Network interface is too short (minimum 2 characters)")
	}

	if len(value) > 15 {
		return fmt.Errorf("Network interface is too long (maximum 15 characters)")
	}

	// Validate the character set.
	match, _ := regexp.MatchString("^[-_a-zA-Z0-9.]*$", value)
	if !match {
		return fmt.Errorf("Network interface contains invalid characters")
	}

	return nil
}

func networkValidPort(value string) error {
	if value == "" {
		return nil
	}

	valueInt, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		return fmt.Errorf("Invalid value for an integer: %s", value)
	}

	if valueInt < 1 || valueInt > 65536 {
		return fmt.Errorf("Invalid port number: %s", value)
	}

	return nil
}

// RandomDevName returns a random device name with prefix.
// If the random string combined with the prefix exceeds 13 characters then empty string is returned.
// This is to ensure we support buggy dhclient applications: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858580
func RandomDevName(prefix string) string {
	// Return a new random veth device name.
	randBytes := make([]byte, 4)
	rand.Read(randBytes)
	iface := prefix + hex.EncodeToString(randBytes)
	if len(iface) > 13 {
		return ""
	}

	return iface
}

// IsInUseByInstance indicates if network is referenced by an instance's NIC devices.
// Checks if the device's parent or network properties match the network name.
func IsInUseByInstance(s *state.State, inst instance.Instance, networkProjectName string, networkName string) (bool, error) {
	// Get the translated network project name from the instance's project.
	instNetworkProjectName, err := project.NetworkProject(s.Cluster, inst.Project())
	if err != nil {
		return false, err
	}

	// Skip instances who's translated network project doesn't match the requested network's project.
	// Because its devices can't be using this network.
	if networkProjectName != instNetworkProjectName {
		return false, nil
	}

	return isInUseByDevices(s, networkProjectName, networkName, inst.ExpandedDevices())
}

// IsInUseByProfile indicates if network is referenced by a profile's NIC devices.
// Checks if the device's parent or network properties match the network name.
func IsInUseByProfile(s *state.State, profile api.Profile, networkName string) (bool, error) {
	return isInUseByDevices(s, deviceConfig.NewDevices(profile.Devices), networkName)
}

func isInUseByDevices(s *state.State, networkProjectName string, networkName string, devices deviceConfig.Devices) (bool, error) {
	for _, d := range devices {
		if d["type"] != "nic" {
			continue
		}

		nicType, err := nictype.NICType(s, networkProjectName, d)
		if err != nil {
{'fraction_non_alphanumeric': 0.11913305583464906, 'fraction_numerical': 0.008324960528204393, 'mean_word_length': 4.286798179059181, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1526720', 'n_tokens_mistral': 2469, 'n_tokens_neox': 2330, 'n_words': 658}