text:
// Copyright 2015-2023 Bleemeo
//
// bleemeo.com an infrastructure monitoring solution in the Cloud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package containerd

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"glouton/facts"
	"os"
	"reflect"
	"syscall"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/api/services/tasks/v1"
	containerdTypes "github.com/containerd/containerd/api/types"
	"github.com/containerd/containerd/cio"
	"github.com/containerd/containerd/containers"
	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/events"
	"github.com/containerd/containerd/images"
	"github.com/containerd/containerd/namespaces"
	"github.com/containerd/containerd/oci"
	"github.com/containerd/containerd/platforms"
	"github.com/containerd/typeurl/v2"
	"github.com/google/go-cmp/cmp"
	"github.com/opencontainers/go-digest"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/opencontainers/runtime-spec/specs-go"
	"google.golang.org/protobuf/types/known/anypb"
)

var (
	// ErrMockNotImplemented is returned when a mock does not implement a method.
	ErrMockNotImplemented = errors.New("mock does not implement this method")
	// ErrWrongNamespace is returned when the namespace is mismatched.
	ErrWrongNamespace = errors.New("missmatch namespace")
	errIncorrectValue = errors.New("incorrect value")
	errNotImplemented = errors.New("not implemented")
)

// MockClient is a fake containerd client.
type MockClient struct {
	closed         bool
	Data           MockJSON
	EventChanMaker func() <-chan *events.Envelope
}

// MockJSON store all information that MockClient can provide.
type MockJSON struct {
	Namespaces []MockNamespace
	Version    containerd.Version
}

// MockNamespace contains namespaced information.
type MockNamespace struct {
	MockNamespace  string
	MockContainers []MockContainer
}

// MockContainer contains information about a container.
type MockContainer struct {
	MockInfo     ContainerOCISpec
	MockImageOCI ocispec.Descriptor
	MockTask     MockTask

	namespace string
}

// MockImage is an implementation of containerd.Image.
type MockImage struct {
	MockName   string
	MockTarget ocispec.Descriptor
}

// MockTask is an implementation of containerd.Task.
type MockTask struct {
	MockID     string
	MockPID    uint32
	MockStatus containerd.Status
	MockPids   []containerd.ProcessInfo

	namespace string
}

// DumpToJSON dump to a json all information required to build a MockClient.
// It will dump from all namespace: containers and their task + PIDs.
func DumpToJSON(ctx context.Context, address string) ([]byte, error) {
	client, err := containerd.New(address)
	if err != nil {
		return nil, err
	}

	defer client.Close()

	namespaces, err := client.NamespaceService().List(ctx)
	if err != nil {
		return nil, err
	}

	version, err := client.Version(ctx)
	if err != nil {
		return nil, err
	}

	result := MockJSON{
		Namespaces: make([]MockNamespace, len(namespaces)),
		Version:    version,
	}

	for i, ns := range namespaces {
		if ns == "moby" {
			// Skip Docker containers.
			continue
		}

		result.Namespaces[i].MockNamespace = ns

		if err := result.Namespaces[i].fill(ctx, client); err != nil {
			return nil, err
		}
	}

	// Set to nil all typeurl.Any fields.
	// These fields prevent unmarshalling from the JSON file.
	for i := 0; i < len(result.Namespaces); i++ {
		for j := 0; j < len(result.Namespaces[i].MockContainers); j++ {
			result.Namespaces[i].MockContainers[j].MockInfo.Container.Runtime.Options = nil
			result.Namespaces[i].MockContainers[j].MockInfo.Container.Extensions = nil
		}
	}

	return json.MarshalIndent(result, "", "  ")
}

func (j *MockNamespace) fill(ctx context.Context, client *containerd.Client) error {
	ctx = namespaces.WithNamespace(ctx, j.MockNamespace)

	containers, err := client.Containers(ctx)
	if err != nil {
		return err
	}

	for _, c := range containers {
		img, err := c.Image(ctx)
		if err != nil {
			return err
		}

		lbls, err := c.Labels(ctx)
		if err != nil {
			return err
		}

		spec, err := c.Spec(ctx)
		if err != nil {
			return err
		}

		mi := MockTask{}

		task, err := c.Task(ctx, nil)
		mi, err = getTaskInfo(ctx, err, task, mi)

		if err != nil {
			return err
		}

		info, err := c.Info(ctx)
		if err != nil {
			return err
		}

		// Ensure that information from Info() and other method match
		if c.ID() != info.ID {
			return fmt.Errorf("%w for ID() = %v, want %v", errIncorrectValue, c.ID(), info.ID)
		}

		if img.Name() != info.Image {
			return fmt.Errorf("%w img.Name() = %v, want %v", errIncorrectValue, img.Name(), info.Image)
		}

		if !reflect.DeepEqual(lbls, info.Labels) {
			return fmt.Errorf("%w, labels = %v, want %v", errIncorrectValue, lbls, info.Labels)
		}

		if info.Spec.GetTypeUrl() != expectedSpecType {
			return fmt.Errorf("%w, TypeUrl = %v, want %v", errIncorrectValue, info.Spec.GetTypeUrl(), expectedSpecType)
		}

		var infoSpec oci.Spec

		err = typeurl.UnmarshalTo(info.Spec, &infoSpec)
		if err != nil {
			return err
		}

		if diff := cmp.Diff(&infoSpec, spec); diff != "" {
			return fmt.Errorf("%w, spec don't match: %s", errIncorrectValue, diff)
		}

		mc := MockContainer{
			namespace: j.MockNamespace,
			MockInfo: ContainerOCISpec{
				Container: info,
				Spec:      &infoSpec,
			},
			MockImageOCI: img.Target(),
			MockTask:     mi,
		}

		j.MockContainers = append(j.MockContainers, mc)
	}

	return nil
}

func getTaskInfo(ctx context.Context, err error, task containerd.Task, mi MockTask) (MockTask, error) {
	if err == nil {
		status, err := task.Status(ctx)
		if err != nil {
			return mi, err
		}

		pids, err := task.Pids(ctx)
		if err != nil {
			return mi, err
		}

		mi.MockID = task.ID()
		mi.MockPID = task.Pid()
		mi.MockStatus = status
		mi.MockPids = pids
	}

	return mi, nil
}

// NewMockFromFile create a MockClient from JSON file. Use DumpToJSON to build such JSON.
func NewMockFromFile(filename string) (*MockClient, error) {
	result := &MockClient{}

	data, err := os.ReadFile(filename)
	if err == nil {
		err = json.Unmarshal(data, &result.Data)
		if err != nil {
			return result, err
		}
	}

	return result, err
}

// FakeContainerd return a Containerd runtime connector that use a mock client.
func FakeContainerd(client *MockClient, isContainerIgnored func(facts.Container) bool) *Containerd {
	return newWithOpenner(
		[]string{"unused"},
		nil,
		isContainerIgnored,
		func(_ context.Context, _ string) (cl containerdClient, err error) {
			return client, nil
		},
	)
}

// Containers do Containers.
func (m *MockClient) Containers(ctx context.Context) ([]containerd.Container, error) {
	if m.closed {
		panic("already closed")
	}

	namespace, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	for _, d := range m.Data.Namespaces {
		if d.MockNamespace == namespace {
			result := make([]containerd.Container, len(d.MockContainers))

			for i, c := range d.MockContainers {
				c.namespace = d.MockNamespace

				result[i] = c
			}

			return result, nil
		}
	}

	return nil, fmt.Errorf("namespace %w", errNotFound)
}

// LoadContainer do LoadContainer.
func (m *MockClient) LoadContainer(ctx context.Context, id string) (containerd.Container, error) {
	if m.closed {
		panic("already closed")
	}

	namespace, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	for _, d := range m.Data.Namespaces {
		if d.MockNamespace == namespace {
			for _, c := range d.MockContainers {
				if c.MockInfo.ID == id {
					c.namespace = d.MockNamespace

					return c, nil
				}
			}
		}
	}

	return nil, errNotFound
}

// Version do version.
func (m *MockClient) Version(context.Context) (containerd.Version, error) {
	if m.closed {
		panic("already closed")
	}

	return m.Data.Version, nil
}

// Metrics do metrics.
func (m *MockClient) Metrics(_ context.Context, filters []string) (*tasks.MetricsResponse, error) {
	_ = filters

	return nil, ErrMockNotImplemented
}

// Namespaces do namespaces.
func (m *MockClient) Namespaces(context.Context) ([]string, error) {
	if m.closed {
		panic("already closed")
	}

	namespaces := make([]string, len(m.Data.Namespaces))

	for i, d := range m.Data.Namespaces {
		namespaces[i] = d.MockNamespace
	}

	return namespaces, nil
}

// Events do events.
func (m *MockClient) Events(context.Context) (<-chan *events.Envelope, <-chan error) {
	if m.closed {
		panic("already closed")
	}

	if m.EventChanMaker != nil {
		return m.EventChanMaker(), nil
	}

	ch := make(chan error, 1)
	ch <- fmt.Errorf("ContainerTop %w", errNotImplemented)

	return nil, ch
}

// Close close.
func (m *MockClient) Close() error {
	if m.closed {
		panic("already closed")
	}

	m.closed = true

	return nil
}

// ID implement containerd.Container.
func (c MockContainer) ID() string {
	return c.MockInfo.ID
}

// Info implement containerd.Container.
func (c MockContainer) Info(ctx context.Context, _ ...containerd.InfoOpts) (containers.Container, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return containers.Container{}, err
	}

	if ns != c.namespace {
		return containers.Container{}, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, c.namespace)
	}

	buffer, err := json.Marshal(c.MockInfo.Spec)
	if err != nil {
		return containers.Container{}, err
	}

	info := c.MockInfo.Container
	info.Spec = &anypb.Any{
		TypeUrl: expectedSpecType,
		Value:   buffer,
	}

	return info, nil
}

// Delete implement containerd.Container.
func (c MockContainer) Delete(context.Context, ...containerd.DeleteOpts) error {
	return ErrMockNotImplemented
}

// NewTask implement containerd.Container.
func (c MockContainer) NewTask(context.Context, cio.Creator, ...containerd.NewTaskOpts) (containerd.Task, error) {
	return nil, ErrMockNotImplemented
}

// Spec implement containerd.Container.
func (c MockContainer) Spec(ctx context.Context) (*oci.Spec, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	if ns != c.namespace {
		return nil, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, c.namespace)
	}

	return c.MockInfo.Spec, nil
}

// Task implement containerd.Container.
func (c MockContainer) Task(ctx context.Context, _ cio.Attach) (containerd.Task, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	if ns != c.namespace {
		return nil, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, c.namespace)
	}

	c.MockTask.namespace = c.namespace

	if c.MockTask.MockID == "" {
		return nil, errNotFound
	}

	return c.MockTask, nil
}

// Image implement containerd.Container.
func (c MockContainer) Image(ctx context.Context) (containerd.Image, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	if ns != c.namespace {
		return nil, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, c.namespace)
	}

	return MockImage{MockName: c.MockInfo.Image, MockTarget: c.MockImageOCI}, nil
}

// Labels implement containerd.Container.
func (c MockContainer) Labels(ctx context.Context) (map[string]string, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	if ns != c.namespace {
		return nil, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, c.namespace)
	}

	return c.MockInfo.Labels, nil
}

// SetLabels implement containerd.Container.
func (c MockContainer) SetLabels(context.Context, map[string]string) (map[string]string, error) {
	return nil, ErrMockNotImplemented
}

// Extensions implement containerd.Container.
func (c MockContainer) Extensions(context.Context) (map[string]typeurl.Any, error) {
	return nil, ErrMockNotImplemented
}

// Update implement containerd.Container.
func (c MockContainer) Update(context.Context, ...containerd.UpdateContainerOpts) error {
	return ErrMockNotImplemented
}

// Checkpoint implement containerd.Container.
func (c MockContainer) Checkpoint(context.Context, string, ...containerd.CheckpointOpts) (containerd.Image, error) {
	return nil, ErrMockNotImplemented
}

// Name implement containerd.Image.
func (i MockImage) Name() string {
	return i.MockName
}

// Target implement containerd.Image.
func (i MockImage) Target() ocispec.Descriptor {
	return i.MockTarget
}

// Labels implement containerd.Image.
func (i MockImage) Labels() map[string]string {
	panic(ErrMockNotImplemented)
}

// Unpack implement containerd.Image.
func (i MockImage) Unpack(context.Context, string, ...containerd.UnpackOpt) error {
	return ErrMockNotImplemented
}

// RootFS implement containerd.Image.
func (i MockImage) RootFS(_ context.Context) ([]digest.Digest, error) {
	return nil, ErrMockNotImplemented
}

// Size implement containerd.Image.
func (i MockImage) Size(_ context.Context) (int64, error) {
	return 0, ErrMockNotImplemented
}

// Spec implement containerd.Image.
func (i MockImage) Spec(_ context.Context) (ocispec.Image, error) {
	return ocispec.Image{}, ErrMockNotImplemented
}

// Usage implement containerd.Image.
func (i MockImage) Usage(context.Context, ...containerd.UsageOpt) (int64, error) {
	return 0, ErrMockNotImplemented
}

// Config implement containerd.Image.
func (i MockImage) Config(_ context.Context) (ocispec.Descriptor, error) {
	return ocispec.Descriptor{}, ErrMockNotImplemented
}

// IsUnpacked implement containerd.Image.
func (i MockImage) IsUnpacked(context.Context, string) (bool, error) {
	return false, ErrMockNotImplemented
}

// ContentStore implement containerd.Image.
func (i MockImage) ContentStore() content.Store {
	return nil
}

// Metadata implement containerd.Image.
func (i MockImage) Metadata() images.Image {
	panic(ErrMockNotImplemented)
}

// Platform implement containerd.Image.
func (i MockImage) Platform() platforms.MatchComparer {
	panic(ErrMockNotImplemented)
}

// ID implements containerd.Task.
func (t MockTask) ID() string {
	return t.MockID
}

// Pid implements containerd.Task.
func (t MockTask) Pid() uint32 {
	return t.MockPID
}

// Start implements containerd.Task.
func (t MockTask) Start(context.Context) error {
	return ErrMockNotImplemented
}

// Delete implements containerd.Task.
func (t MockTask) Delete(context.Context, ...containerd.ProcessDeleteOpts) (*containerd.ExitStatus, error) {
	return nil, ErrMockNotImplemented
}

// Kill implements containerd.Task.
func (t MockTask) Kill(context.Context, syscall.Signal, ...containerd.KillOpts) error {
	return ErrMockNotImplemented
}

// Wait implements containerd.Task.
func (t MockTask) Wait(context.Context) (<-chan containerd.ExitStatus, error) {
	return nil, ErrMockNotImplemented
}

// CloseIO implements containerd.Task.
func (t MockTask) CloseIO(context.Context, ...containerd.IOCloserOpts) error {
	return ErrMockNotImplemented
}

// Resize implements containerd.Task.
func (t MockTask) Resize(_ context.Context, _, _ uint32) error {
	return ErrMockNotImplemented
}

// IO implements containerd.Task.
func (t MockTask) IO() cio.IO {
	return nil
}

// Status implements containerd.Task.
func (t MockTask) Status(ctx context.Context) (containerd.Status, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return containerd.Status{}, err
	}

	if ns != t.namespace {
		return containerd.Status{}, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, t.namespace)
	}

	return t.MockStatus, nil
}

// Pause implements containerd.Task.
func (t MockTask) Pause(context.Context) error {
	return ErrMockNotImplemented
}

// Resume implements containerd.Task.
func (t MockTask) Resume(context.Context) error {
	return ErrMockNotImplemented
}

// Exec implements containerd.Task.
func (t MockTask) Exec(context.Context, string, *specs.Process, cio.Creator) (containerd.Process, error) {
	return nil, ErrMockNotImplemented
}

// Pids implements containerd.Task.
func (t MockTask) Pids(ctx context.Context) ([]containerd.ProcessInfo, error) {
	ns, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, err
	}

	if ns != t.namespace {
		return nil, fmt.Errorf("%w: %s != %s", ErrWrongNamespace, ns, t.namespace)
	}

	return t.MockPids, nil
}

// Checkpoint implements containerd.Task.
func (t MockTask) Checkpoint(context.Context, ...containerd.CheckpointTaskOpts) (containerd.Image, error) {
	return nil, ErrMockNotImplemented
}

// Update implements containerd.Task.
func (t MockTask) Update(context.Context, ...containerd.UpdateTaskOpts) error {
	return ErrMockNotImplemented
}

// LoadProcess implements containerd.Task.
func (t MockTask) LoadProcess(context.Context, string, cio.Attach) (containerd.Process, error) {
	return nil, ErrMockNotImplemented
}

// Metrics implements containerd.Task.
func (t MockTask) Metrics(context.Context) (*containerdTypes.Metric, error) {
	return nil, ErrMockNotImplemented
}

// Spec implements containerd.Task.
func (t MockTask) Spec(context.Context) (*oci.Spec, error) {
	return nil, ErrMockNotImplemented
}

repository: bleemeo/glouton

repo_name: bleemeo/glouton

gha_language: Go

extension: go


text:
SRC_URI = "${SOURCEFORGE_MIRROR}/atmelwlandriver/atmelwlandriver-${PV}.tar.bz2 \
	file://dotconfig \
	file://pcmf502rd.conf \
	file://makefile.patch"
S = "${WORKDIR}/atmelwlandriver"
LICENSE = "GPL"

inherit module
SECTION = "base"

do_configure() {
	install ${WORKDIR}/dotconfig .config
}

CFLAGS = "-DLINUX_OS -D__KERNEL__ -DMODULE -I${S}/src/includes -I${S}/src/includes/pcmcia -I${STAGING_KERNEL_DIR}/include"

do_compile() {
	export INC="${S}/src/includes"
	export OBJDIR="${D}${base_libdir}/modules/${KERNEL_VERSION}/drivers/net/wireless/atmel/"
	export KERNEL_PATH="${STAGING_KERNEL_DIR}"
	export KERNEL_SRC="${STAGING_KERNEL_DIR}"
	export CC="${KERNEL_CC}"
	export LD="${KERNEL_LD}"
	export KERNEL_VERSION="${KERNEL_VERSION}"
	export TOPDIR="${S}"
	unset CFLAGS CPPFLAGS CXXFLAGS LDFLAGS
	install -d ${OBJDIR}
	#oe_runmake -C src/Pcmcia_Pci final CFLAGS:='${CFLAGS} -DATMEL_WLAN -DRFMD -DINT_ROAM' MODULE:='pcmf502r' LIB:=-RFMD-
	oe_runmake -C src/Pcmcia_Pci final CFLAGS:='${CFLAGS} -DATMEL_WLAN -DRFMD -DINT_ROAM -DREV_D' MODULE:='pcmf502rd' LIB:=-REVD-
	#oe_runmake -C src/Pcmcia_Pci final CFLAGS:='${CFLAGS} -DATMEL_WLAN -DRFMD -DINT_ROAM -DREV_E' MODULE:='pcmf502re' LIB:=-REVE-
}

do_install() {
	install -d ${D}${sysconfdir}/pcmcia
	install -m 0644 ${WORKDIR}/pcmf502rd.conf ${D}${sysconfdir}/pcmcia/

	# remove any maps that were installed
	rm -f ${D}${base_libdir}/modules/${KERNEL_VERSION}/drivers/net/wireless/atmel/*.map
}

SRC_URI[md5sum] = "dd9a11d175ba0fbb62cf7fec5426f5de"
SRC_URI[sha256sum] = "d80b88753725e2ce83add9f80d120c022112527adbf4425368387da1936345f2"

license: MIT

repository: overo/overo-oe-natty

license_type: permissive

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
DESCRIPTION = "rce run supervisor"
SECTION = "console/utils"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${RESIN_COREBASE}/COPYING.Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

PR = "r1.6"

SRC_URI = "file://rce-run-supervisor"
S = "${WORKDIR}"

FILES_${PN} = "${bindir}/*"
RDEPENDS_${PN} = "bash rce"

do_install() {
    install -d ${D}${bindir}
    install -m 0775 ${WORKDIR}/rce-run-supervisor ${D}${bindir}/rce-run-supervisor
}

pkg_postinst_${PN} () {
#!/bin/sh -e
# Commands to carry out
# Remove networking
}

repository: gmacario/meta-resin

repo_name: gmacario/meta-resin

branch_name: refs/heads/master


text:
require recipes-core/images/core-image-minimal.bb

IMAGE_INSTALL += "libstdc++ startup"
IMAGE_INSTALL += "openssh openssl openssh-sftp-server"
IMAGE_INSTALL += "gdb gdbserver"
IMAGE_INSTALL += "procps mtd-utils"
IMAGE_INSTALL += "unzip cifs-utils"

IMAGE_FEATURES += " \
    dev-pkgs \
    tools-sdk \
"

EXTRA_IMAGE_FEATURES += " \
    tools-debug \
    tools-profile \
    debug-tweaks \
"

repository: adps/meta-adlnx

repo_name: adps/meta-adlnx


text:
/*
Copyright 2020 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package metrics

import (
	"fmt"
	"net/http"
	"os"
	"strconv"

	"google.golang.org/grpc/codes"
	"k8s.io/component-base/metrics"
	"k8s.io/klog/v2"
	"sigs.k8s.io/gcp-compute-persistent-disk-csi-driver/pkg/common"
	gce "sigs.k8s.io/gcp-compute-persistent-disk-csi-driver/pkg/gce-cloud-provider/compute"
)

const (
	// envGKEPDCSIVersion is an environment variable set in the PDCSI controller manifest
	// with the current version of the GKE component.
	envGKEPDCSIVersion               = "GKE_PDCSI_VERSION"
	pdcsiDriverName                  = "pd.csi.storage.gke.io"
	DefaultDiskTypeForMetric         = "unknownDiskType"
	DefaultEnableConfidentialCompute = "unknownConfidentialMode"
)

var (
	// This metric is exposed only from the controller driver component when GKE_PDCSI_VERSION env variable is set.
	gkeComponentVersion = metrics.NewGaugeVec(&metrics.GaugeOpts{
		Name: "component_version",
		Help: "Metric to expose the version of the PDCSI GKE component.",
	}, []string{"component_version"})

	pdcsiOperationErrorsMetric = metrics.NewCounterVec(
		&metrics.CounterOpts{
			Subsystem:      "csidriver",
			Name:           "operation_errors",
			Help:           "CSI server side error metrics",
			StabilityLevel: metrics.ALPHA,
		},
		[]string{"driver_name", "method_name", "grpc_status_code", "disk_type", "enable_confidential_storage"})
)

type MetricsManager struct {
	registry metrics.KubeRegistry
}

func NewMetricsManager() MetricsManager {
	mm := MetricsManager{
		registry: metrics.NewKubeRegistry(),
	}
	return mm
}

func (mm *MetricsManager) GetRegistry() metrics.KubeRegistry {
	return mm.registry
}

func (mm *MetricsManager) registerComponentVersionMetric() {
	mm.registry.MustRegister(gkeComponentVersion)
}

func (mm *MetricsManager) RegisterPDCSIMetric() {
	mm.registry.MustRegister(pdcsiOperationErrorsMetric)
}

func (mm *MetricsManager) recordComponentVersionMetric() error {
	v := getEnvVar(envGKEPDCSIVersion)
	if v == "" {
		klog.V(2).Info("Skip emitting component version metric")
		return fmt.Errorf("Failed to register GKE component version metric, env variable %v not defined", envGKEPDCSIVersion)
	}

	gkeComponentVersion.WithLabelValues(v).Set(1.0)
	klog.Infof("Recorded GKE component version : %v", v)
	return nil
}

func (mm *MetricsManager) RecordOperationErrorMetrics(
	operationName string,
	operationErr error,
	diskType string,
	enableConfidentialStorage string) {
	err := codes.OK.String()
	if operationErr != nil {
		err = common.CodeForError(operationErr).String()
	}
	pdcsiOperationErrorsMetric.WithLabelValues(pdcsiDriverName, "/csi.v1.Controller/"+operationName, err, diskType, enableConfidentialStorage).Inc()
}

func (mm *MetricsManager) EmitGKEComponentVersion() error {
	mm.registerComponentVersionMetric()
	if err := mm.recordComponentVersionMetric(); err != nil {
		return err
	}

	return nil
}

// Server represents any type that could serve HTTP requests for the metrics
// endpoint.
type Server interface {
	Handle(pattern string, handler http.Handler)
}

// RegisterToServer registers an HTTP handler for this metrics manager to the
// given server at the specified address/path.
func (mm *MetricsManager) registerToServer(s Server, metricsPath string) {
	s.Handle(metricsPath, metrics.HandlerFor(
		mm.GetRegistry(),
		metrics.HandlerOpts{
			ErrorHandling: metrics.ContinueOnError}))
}

// InitializeHttpHandler sets up a server and creates a handler for metrics.
func (mm *MetricsManager) InitializeHttpHandler(address, path string) {
	mux := http.NewServeMux()
	mm.registerToServer(mux, path)
	go func() {
		klog.Infof("Metric server listening at %q", address)
		if err := http.ListenAndServe(address, mux); err != nil {
			klog.Fatalf("Failed to start metric server at specified address (%q) and path (%q): %v", address, path, err.Error())
		}
	}()
}

func getEnvVar(envVarName string) string {
	v, ok := os.LookupEnv(envVarName)
	if !ok {
		klog.Warningf("%q env not set", envVarName)
		return ""
	}

	return v
}

func IsGKEComponentVersionAvailable() bool {
	if getEnvVar(envGKEPDCSIVersion) == "" {
		return false
	}

	return true
}

func GetMetricParameters(disk *gce.CloudDisk) (string, string) {
	diskType := DefaultDiskTypeForMetric
	enableConfidentialStorage := DefaultEnableConfidentialCompute
	if disk != nil {
		diskType = disk.GetPDType()
		enableConfidentialStorage = strconv.FormatBool(disk.GetEnableConfidentialCompute())
	}
	return diskType, enableConfidentialStorage
}


text:
@INPROCEEDINGS{baruah18airavat,
author={T. {Baruah} and Y. {Sun} and S. {Dong} and D. {Kaeli} and N. {Rubin}},
booktitle={2018 Design, Automation Test in Europe Conference Exhibition (DATE)},
title={Airavat: Improving energy efficiency of heterogeneous applications},
year={2018},
volume={},
number={},
pages={731-736},
keywords={energy conservation;graphics processing units;learning (artificial intelligence);low-power electronics;microprocessor chips;CPU;GPU;Energy Delay Product;memory frequencies;power management framework;energy management;energy efficiency;Airavat;Graphics processing units;Energy efficiency;Power system management;Collaboration;Benchmark testing;Memory management;Power demand},
doi={10.23919/DATE.2018.8342104},
ISSN={1558-1101},
month={March},}

gha_language: HTML

extension: bib


text:
package roomPkg

import "main/protocol"

type RoomConfig struct {
	StartRoomNumber int32
	MaxRoomCount int32
	MaxUserCount int32

	RoomCountByGoroutine          int32
	ChanPacketBufferCount         int32
	InternalPacketChanBufferCount int32
}

type roomUser struct {
	netSessionIndex     int32
	netSessionUniqueId  uint64

	// <<< 다른 유저에게 알려줘야 하는 정보
	RoomUniqueId uint64
	IDLen int8
	ID [protocol.MAX_USER_ID_BYTE_LENGTH]byte
	// >>> 다른 유저에게 알려줘야 하는 정보

	packetDataSize int16
}

func (user *roomUser) init(userID []byte, uniqueId uint64) {
	idlen := len(userID)

	user.IDLen = int8(idlen)
	copy(user.ID[:], userID)

	user.RoomUniqueId = uniqueId
}

func (user *roomUser) SetNetworkInfo(sessionIndex int32, sessionUniqueId uint64) {
	user.netSessionIndex = sessionIndex
	user.netSessionUniqueId = sessionUniqueId
}

func (user *roomUser) PacketDataSize() int16 {
	return int16(1) + int16(user.IDLen) + 8
}

type RoomMemberPacket struct {
	RoomIndex int

	UserID    []byte
	SessionIndex    int32
	SessionUniqueId uint64
}

type userNetworkInfo struct {
	sessionIndex    int32
	sessionUniqueId uint64
}

type addRoomUserInfo struct {
	userID []byte

	netSessionIndex     int32
	netSessionUniqueId  uint64
}

gha_license_id: MIT


text:
file(REMOVE_RECURSE
  "CMakeFiles/UltrasonicACC.dir/home/aadc/AADC/include/tinyxml2.cpp.o"
  "CMakeFiles/UltrasonicACC.dir/UltrasonicACC.cpp.o"
  "UltrasonicACC.pdb"
  "UltrasonicACC.adtfplugin"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/UltrasonicACC.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

extension: cmake


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
//
//   Copyright (c) 2014 Microsoft Corporation.  All Rights Reserved.
//
//   Module Name:
//      Framework_WFPSampler.cpp
//
//   Abstract:
//      This module contains functions which form the entry point to our client program
//         WFPSampler.Exe.
//
//   Naming Convention:
//
//      <Scope><Object><Action><Modifier>
//
//      i.e.
//
//       <Scope>
//          {
//                        - Function is likely visible to other modules.
//            Prv         - Function is private to this module.
//          }
//       <Object>
//          {
//            FlowControl - Function pertains to how the program execution should behave.
//            Scenario    - Function pertains to scenarios.
//       <Action>
//          {
//            Dispatch    - Function selects and invokes necessary code paths for given data.
//            Get         - Function parses strings for requested value.
//            Log         - Function writes to the console.
//          }
//       <Modifier>
//          {
//            Usage       - Function provides generic application usage information.
//          }
//
//   Private Functions:
//      PrvFlowControlGet(),
//      PrvLogUsage(),
//      PrvScenarioDispatch(),
//      PrvScenarioGet(),
//      wmain(),

//   Public Functions:
//
//   Author:
//      Dusty Harper      (DHarper)
//
//   Revision History:
//
//      [ Month ][Day] [Year] - [Revision]-[ Comments ]
//      May       01,   2010  -     1.0   -  Creation
//      December  13,   2013  -     1.1   -  Add ADVANCED_PACKET_INJECTION, FLOW_ASSOCIATION, and
//                                              PEND_ENDPOINT_CLOSURE scenarios
//
////////////////////////////////////////////////////////////////////////////////////////////////////

#include "Framework_WFPSampler.h"         /// .
#include "Framework_RPCClientInterface.h" /// .

/// Module's Local Enumerations

typedef enum WFPSAMPLER_FLOW_CONTROL_
{
   FLOW_CONTROL_NORMAL = 0,
   FLOW_CONTROL_HELP   = 1,
   FLOW_CONTROL_CLEAN  = 2,
}WFPSAMPLER_FLOW_CONTROL;

///

/**
 @private_function="PrvFlowControlGet"

   Purpose:  Parse the command line parameters for any flow control commands such as:

                help (-?) (?) (-help)

   Notes:

   MSDN_Ref:

*/
WFPSAMPLER_FLOW_CONTROL PrvFlowControlGet(_In_reads_(stringCount) PCWSTR* ppCLPStrings,
                                          _In_ UINT32 stringCount)
{
   ASSERT(ppCLPStrings);
   ASSERT(stringCount);

   WFPSAMPLER_FLOW_CONTROL flowControl = FLOW_CONTROL_NORMAL;

   for(UINT32 stringIndex = 0;
       stringIndex < stringCount;
       stringIndex++)
   {
      if(HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"-?") ||
         HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"/?") ||
         HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"?") ||
         HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"-help") ||
         HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"/help"))
      {
         flowControl = FLOW_CONTROL_HELP;

         break;
      }
      /// This is used for testing purposes only.  Generally we should not be touching any other
      /// provider's WFP objects, and is grounds for failure in the Hardware Certification Kit.
      else if(HlprStringsAreEqual(ppCLPStrings[stringIndex],
                                  L"-clean") ||
              HlprStringsAreEqual(ppCLPStrings[stringIndex],
                                  L"/clean"))
      {
         flowControl = FLOW_CONTROL_CLEAN;

         break;
      }
   }

   return flowControl;
}

/**
 @private_function="PrvScenarioDispatcher"

   Purpose:  Route the provider scenario to the appropriate Scenario implementation.

   Notes:

   MSDN_Ref:

*/
UINT32 PrvScenarioDispatcher(_In_ WFPSAMPLER_SCENARIO scenario,
                             _In_reads_(stringCount) PCWSTR* ppCLPStrings,
                             _In_ UINT32 stringCount)
{
   ASSERT(scenario < SCENARIO_MAX);
   ASSERT(ppCLPStrings);
   ASSERT(stringCount);

   UINT32 status = NO_ERROR;

   switch(scenario)
   {

      case SCENARIO_ADVANCED_PACKET_INJECTION:
      {
         status = AdvancedPacketInjectionScenarioExecute(ppCLPStrings,
                                                         stringCount);

         break;
      }

#if(NTDDI_VERSION >= NTDDI_WIN8)

      case SCENARIO_APP_CONTAINER:
      {
         status = AppContainerScenarioExecute(ppCLPStrings,
                                              stringCount);

         break;
      }

#endif /// (NTDDI_VERSION >= NTDDI_WIN8)

      case SCENARIO_BASIC_ACTION_BLOCK:
      {
         status = BasicActionBlockScenarioExecute(ppCLPStrings,
                                                  stringCount);

         break;
      }
      case SCENARIO_BASIC_ACTION_CONTINUE:
      {
         status = BasicActionContinueScenarioExecute(ppCLPStrings,
                                                     stringCount);

         break;
      }
      case SCENARIO_BASIC_ACTION_PERMIT:
      {
         status = BasicActionPermitScenarioExecute(ppCLPStrings,
                                                   stringCount);

         break;
      }
      case SCENARIO_BASIC_ACTION_RANDOM:
      {
         status = BasicActionRandomScenarioExecute(ppCLPStrings,
                                                   stringCount);

         break;
      }
      case SCENARIO_BASIC_PACKET_EXAMINATION:
      {
         status = BasicPacketExaminationScenarioExecute(ppCLPStrings,
                                                        stringCount);

         break;
      }
      case SCENARIO_BASIC_PACKET_INJECTION:
      {
         status = BasicPacketInjectionScenarioExecute(ppCLPStrings,
                                                      stringCount);

         break;
      }
      case SCENARIO_BASIC_PACKET_MODIFICATION:
      {
         status = BasicPacketModificationScenarioExecute(ppCLPStrings,
                                                         stringCount);

         break;
      }
      case SCENARIO_BASIC_STREAM_INJECTION:
      {
         status = BasicStreamInjectionScenarioExecute(ppCLPStrings,
                                                      stringCount);

         break;
      }
      case SCENARIO_FAST_PACKET_INJECTION:
      {
         status = FastPacketInjectionScenarioExecute(ppCLPStrings,
                                                     stringCount);

         break;
      }
      case SCENARIO_FAST_STREAM_INJECTION:
      {
         status = FastStreamInjectionScenarioExecute(ppCLPStrings,
                                                     stringCount);

         break;
      }
      case SCENARIO_FLOW_ASSOCIATION:
      {
         status = FlowAssociationScenarioExecute(ppCLPStrings,
                                                 stringCount);

         break;
      }
      case SCENARIO_PEND_AUTHORIZATION:
      {
         status = PendAuthorizationScenarioExecute(ppCLPStrings,
                                                   stringCount);

         break;
      }

#if(NTDDI_VERSION >= NTDDI_WIN7)

      case SCENARIO_PEND_ENDPOINT_CLOSURE:
      {
         status = PendEndpointClosureScenarioExecute(ppCLPStrings,
                                                     stringCount);

         break;
      }

#endif /// (NTDDI_VERSION >= NTDDI_WIN7)

      case SCENARIO_PROXY:
      {
         status = ProxyScenarioExecute(ppCLPStrings,
                                       stringCount);

         break;
      }
      default:
      {
         status = ERROR_NOT_SUPPORTED;

         break;
      }
   }

   return status;
}

/**
 @private_function="PrvScenarioGet"

   Purpose:  Parse the command line parameters for the scenario (-s ).

   Notes:

   MSDN_Ref: N/A

*/
WFPSAMPLER_SCENARIO PrvScenarioGet(_In_reads_(stringCount) PCWSTR* ppCLPStrings,
                                   _In_ UINT32 stringCount,
                                   _In_ WFPSAMPLER_FLOW_CONTROL flowControl)
{
   ASSERT(ppCLPStrings);
   ASSERT(stringCount);

   WFPSAMPLER_SCENARIO scenario = SCENARIO_UNDEFINED;

   for(UINT32 stringIndex = 0;
       (stringIndex + 1) < stringCount;
       stringIndex++)
   {
      if(HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"-s") ||
         HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"/s"))
      {
         PCWSTR pScenarioString = ppCLPStrings[stringIndex + 1];

         if(pScenarioString)
         {
            if(HlprStringsAreEqual(pScenarioString,
                                   L"ADVANCED_PACKET_INJECTION"))
               scenario = SCENARIO_ADVANCED_PACKET_INJECTION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"APP_CONTAINER"))
               scenario = SCENARIO_APP_CONTAINER;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_ACTION_BLOCK"))
               scenario = SCENARIO_BASIC_ACTION_BLOCK;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_ACTION_CONTINUE"))
               scenario = SCENARIO_BASIC_ACTION_CONTINUE;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_ACTION_PERMIT"))
               scenario = SCENARIO_BASIC_ACTION_PERMIT;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_ACTION_RANDOM"))
               scenario = SCENARIO_BASIC_ACTION_RANDOM;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_PACKET_EXAMINATION"))
               scenario = SCENARIO_BASIC_PACKET_EXAMINATION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_PACKET_INJECTION"))
               scenario = SCENARIO_BASIC_PACKET_INJECTION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_PACKET_MODIFICATION"))
               scenario = SCENARIO_BASIC_PACKET_MODIFICATION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"BASIC_STREAM_INJECTION"))
               scenario = SCENARIO_BASIC_STREAM_INJECTION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"FAST_PACKET_INJECTION"))
               scenario = SCENARIO_FAST_PACKET_INJECTION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"FAST_STREAM_INJECTION"))
               scenario = SCENARIO_FAST_STREAM_INJECTION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"FLOW_ASSOCIATION"))
               scenario = SCENARIO_FLOW_ASSOCIATION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"PEND_AUTHORIZATION"))
               scenario = SCENARIO_PEND_AUTHORIZATION;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"PEND_ENDPOINT_CLOSURE"))
               scenario = SCENARIO_PEND_ENDPOINT_CLOSURE;
            else if(HlprStringsAreEqual(pScenarioString,
                                        L"PROXY"))
               scenario = SCENARIO_PROXY;
         }

         if(scenario != SCENARIO_UNDEFINED)
            break;
      }
   }

   if(scenario == SCENARIO_UNDEFINED &&
      flowControl == FLOW_CONTROL_NORMAL)
      HlprLogError(L"Invalid Scenario defined");

   return scenario;
}

/**
 @private_function="PrvCleanPolicy"

   Purpose:  Remove all WFP objects based on the passed in scope.

               default   -   cleanup all WFPSampler objects except WFPSAMPLER_SUBLAYER and
                                WFPSAMPLER_PROVIDER.

               firewall  -   cleanup all WFP objects from the non-usermode layers except those
                                that are built-in, the WFPSAMPLER_SUBLAYER, and the
                                WFPSAMPLER_PROVIDER.

               all       -   cleanup all WFP objects except those that are built-in, the
                                WFPSAMPLER_SUBLAYER, and the WFPSAMPLER_PROVIDER.

   Notes:    All and firewall are meant for testing purposes only.  Doing this in a commercial
             product is grounds for failure in the Microsoft Hardware Certification Kit.

   MSDN_Ref:

*/
UINT32 PrvCleanPolicy(_In_reads_(stringCount) PCWSTR* ppCLPStrings,
                      _In_ UINT32 stringCount)
{
   ASSERT(ppCLPStrings);
   ASSERT(stringCount);

   UINT32                               status                        = NO_ERROR;
   BOOLEAN                              cleanFirewallOnly             = FALSE;
   BOOLEAN                              cleanWFPSamplersOnly          = FALSE;
   HANDLE                               engineHandle                  = 0;
   HANDLE                               enumHandle                    = 0;
   UINT32                               numEntries                    = 0;
   FWPM_CALLOUT**                       ppCallouts                    = 0;
   FWPM_FILTER**                        ppFilters                     = 0;
   FWPM_PROVIDER**                      ppProviders                   = 0;
   FWPM_PROVIDER_CONTEXT**              ppProviderContexts            = 0;
   FWPM_SUBLAYER**                      ppSubLayers                   = 0;
   FWPM_FILTER_ENUM_TEMPLATE*           pFilterEnumTemplate           = 0;
   FWPM_CALLOUT_ENUM_TEMPLATE*          pCalloutEnumTemplate          = 0;
   FWPM_PROVIDER_CONTEXT_ENUM_TEMPLATE* pProviderContextEnumTemplate  = 0;

   for(UINT32 stringIndex = 0;
       stringIndex < stringCount;
       stringIndex++)
   {
      if(HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"-clean") ||
         HlprStringsAreEqual(ppCLPStrings[stringIndex],
                             L"/clean"))
      {
         PCWSTR pString = 0;

         if((stringIndex + 1) < stringCount)
            pString = ppCLPStrings[++stringIndex];
         {
            if(HlprStringsAreEqual(pString,
                                   L"all"))
              break;
            else if(HlprStringsAreEqual(pString,
                                        L"firewall"))
               cleanFirewallOnly = TRUE;
            else
               cleanWFPSamplersOnly = TRUE;
         }

         break;
      }
   }

   status = HlprFwpmEngineOpen(&engineHandle);
   HLPR_BAIL_ON_FAILURE(status);

   if(cleanWFPSamplersOnly)
   {
      HLPR_NEW(pFilterEnumTemplate,
               FWPM_FILTER_ENUM_TEMPLATE);
      HLPR_BAIL_ON_ALLOC_FAILURE(pFilterEnumTemplate,
                                 status);

      HLPR_NEW(pCalloutEnumTemplate,
               FWPM_CALLOUT_ENUM_TEMPLATE);
      HLPR_BAIL_ON_ALLOC_FAILURE(pCalloutEnumTemplate,
                                 status);

      HLPR_NEW(pProviderContextEnumTemplate,
               FWPM_PROVIDER_CONTEXT_ENUM_TEMPLATE);
      HLPR_BAIL_ON_ALLOC_FAILURE(pProviderContextEnumTemplate,
                                 status);

      pFilterEnumTemplate->providerKey = (GUID*)&WFPSAMPLER_PROVIDER;
      pFilterEnumTemplate->enumType    = FWP_FILTER_ENUM_FULLY_CONTAINED;
      pFilterEnumTemplate->flags       = FWP_FILTER_ENUM_FLAG_INCLUDE_BOOTTIME |
                                         FWP_FILTER_ENUM_FLAG_INCLUDE_DISABLED;
      pFilterEnumTemplate->actionMask  = 0xFFFFFFFF;

      pCalloutEnumTemplate->providerKey = (GUID*)&WFPSAMPLER_PROVIDER;

      pProviderContextEnumTemplate->providerKey         = (GUID*)&WFPSAMPLER_PROVIDER;
      pProviderContextEnumTemplate->providerContextType = FWPM_GENERAL_CONTEXT;

      /// enumerate and flush filters
      for(UINT32 layerIndex = 0;
          layerIndex < RTL_NUMBER_OF(ppLayerKeyArray);
          layerIndex++)
      {
         pFilterEnumTemplate->layerKey = *(ppLayerKeyArray[layerIndex]);

         status = HlprFwpmFilterCreateEnumHandle(engineHandle,
                                                 pFilterEnumTemplate,
                                                 &enumHandle);
         HLPR_BAIL_ON_FAILURE_2(status);

         status = HlprFwpmFilterEnum(engineHandle,
                                     enumHandle,
                                     0xFFFFFFFF,
                                     &ppFilters,
                                     &numEntries);
         if(status == NO_ERROR &&
            ppFilters &&
            numEntries)
         {
            for(UINT32 filterIndex = 0;
                filterIndex < numEntries;
                filterIndex++)
            {
               if(cleanFirewallOnly &&
                  HlprFwpmLayerIsUserMode(&(ppFilters[filterIndex]->layerKey)))
                  continue;

               HlprFwpmFilterDeleteByKey(engineHandle,
                                         &(ppFilters[filterIndex]->filterKey));
            }

            numEntries = 0;
         }

         HLPR_BAIL_LABEL_2:

         HlprFwpmFilterDestroyEnumHandle(engineHandle,
                                         &enumHandle);
      }
   }
   else
   {
      status = HlprFwpmFilterCreateEnumHandle(engineHandle,
                                              pFilterEnumTemplate,
                                              &enumHandle);
      HLPR_BAIL_ON_FAILURE(status);

      status = HlprFwpmFilterEnum(engineHandle,
                                  enumHandle,
                                  0xFFFFFFFF,
                                  &ppFilters,
                                  &numEntries);
      if(status == NO_ERROR &&
         ppFilters &&
         numEntries)
      {
         for(UINT32 filterIndex = 0;
             filterIndex < numEntries;
             filterIndex++)
         {
            if(cleanFirewallOnly &&
               HlprFwpmLayerIsUserMode(&(ppFilters[filterIndex]->layerKey)))
               continue;

            HlprFwpmFilterDeleteByKey(engineHandle,
                                      &(ppFilters[filterIndex]->filterKey));
         }

         numEntries = 0;
      }

      HlprFwpmFilterDestroyEnumHandle(engineHandle,
                                      &enumHandle);
   }

   /// Enumerate and flush all Callouts
   status = HlprFwpmCalloutCreateEnumHandle(engineHandle,
                                            pCalloutEnumTemplate,
                                            &enumHandle);
   HLPR_BAIL_ON_FAILURE(status);

   status = HlprFwpmCalloutEnum(engineHandle,
                                enumHandle,
                                0xFFFFFFFF,
                                &ppCallouts,
                                &numEntries);
   if(status == NO_ERROR &&
      ppCallouts &&
      numEntries)
   {
      for(UINT32 calloutIndex = 0;
          calloutIndex < numEntries;
          calloutIndex++)
      {
         if(cleanFirewallOnly &&
            HlprFwpmLayerIsUserMode(&(ppCallouts[calloutIndex]->applicableLayer)))
            continue;

         HlprFwpmCalloutDeleteByKey(engineHandle,
                                    &(ppCallouts[calloutIndex]->calloutKey));
      }

      numEntries = 0;
   }

   HlprFwpmCalloutDestroyEnumHandle(engineHandle,
                                    &enumHandle);

   if(!cleanFirewallOnly)
   {
      /// Enumerate and flush all provider contexts
      status = HlprFwpmProviderContextCreateEnumHandle(engineHandle,
                                                       pProviderContextEnumTemplate,
                                                       &enumHandle);
      HLPR_BAIL_ON_FAILURE(status);

      status = HlprFwpmProviderContextEnum(engineHandle,
                                           enumHandle,
                                           0xFFFFFFFF,
                                           &ppProviderContexts,
                                           &numEntries);
      if(status == NO_ERROR &&
         ppProviderContexts &&
         numEntries)
      {
         for(UINT32 providerContextIndex = 0;
             providerContextIndex < numEntries;
             providerContextIndex++)
         {
            HlprFwpmProviderContextDeleteByKey(engineHandle,
                                               &(ppProviderContexts[providerContextIndex]->providerContextKey));
         }

         numEntries = 0;
      }

      HlprFwpmProviderContextDestroyEnumHandle(engineHandle,
                                               &enumHandle);
   }

   if(!cleanWFPSamplersOnly)
   {
      /// Enumerate and flush all sublayers not owned by WFPSampler
      status = HlprFwpmSubLayerCreateEnumHandle(engineHandle,
                                                0,
                                                &enumHandle);
      HLPR_BAIL_ON_FAILURE(status);

      status = HlprFwpmSubLayerEnum(engineHandle,
                                    enumHandle,
                                    0xFFFFFFFF,
                                    &ppSubLayers,
                                    &numEntries);
      if(status == NO_ERROR &&
         ppSubLayers &&
         numEntries)
      {
         for(UINT32 subLayerIndex = 0;
             subLayerIndex < numEntries;
             subLayerIndex++)
         {
            if(!HlprGUIDsAreEqual(ppSubLayers[subLayerIndex]->providerKey,
                                  &WFPSAMPLER_PROVIDER))
               HlprFwpmSubLayerDeleteByKey(engineHandle,
                                           &(ppSubLayers[subLayerIndex]->subLayerKey));
         }

         numEntries = 0;
      }

      HlprFwpmSubLayerDestroyEnumHandle(engineHandle,
                                        &enumHandle);

      /// Enumerate and flush all providers not owned by WFPSampler
      status = HlprFwpmProviderCreateEnumHandle(engineHandle,
                                                0,
                                                &enumHandle);
      HLPR_BAIL_ON_FAILURE(status);

      status = HlprFwpmProviderEnum(engineHandle,
                                    enumHandle,
                                    0xFFFFFFFF,
                                    &ppProviders,
                                    &numEntries);
      if(status == NO_ERROR &&
         ppProviders &&
         numEntries)
      {
         for(UINT32 providerIndex = 0;
             providerIndex < numEntries;
             providerIndex++)
         {
            if(!HlprGUIDsAreEqual(&(ppProviders[providerIndex]->providerKey),
                                  &WFPSAMPLER_PROVIDER))
               HlprFwpmProviderDeleteByKey(engineHandle,
                                           &(ppProviders[providerIndex]->providerKey));
         }

         numEntries = 0;
      }

      HlprFwpmProviderDestroyEnumHandle(engineHandle,
                                        &enumHandle);
   }

   HLPR_BAIL_LABEL:

   if(engineHandle)
      HlprFwpmEngineClose(&engineHandle);

   HLPR_DELETE(pProviderContextEnumTemplate);

   HLPR_DELETE(pCalloutEnumTemplate);

   HLPR_DELETE(pFilterEnumTemplate);

   return status;
}

/**
 @private_function="PrvLogUsage"

   Purpose:  Log usage information to the console.

   Notes:

   MSDN_Ref:

*/
VOID PrvLogUsage(_In_ UINT32 scenario)
{
   wprintf(L"\n\t WFPSampler.Exe \n");
   wprintf(L"\n\t The syntax of this command is: \n\n");

   if(scenario != SCENARIO_UNDEFINED &&
      scenario < SCENARIO_MAX)
   {
      switch(scenario)
      {
         case SCENARIO_ADVANCED_PACKET_INJECTION:
         {
            AdvancedPacketInjectionScenarioLogHelp();

            break;
         }
         case SCENARIO_APP_CONTAINER:
         {

#if(NTDDI_VERSION >= NTDDI_WIN8)

            AppContainerScenarioLogHelp();

#else

            wprintf(L"\n\t\t\t APP_CONTAINER scenario is not supported on this version of Windows \n");

#endif /// (NTDDI_VERSION >= NTDDI_WIN8)

            break;
         }
         case SCENARIO_BASIC_ACTION_BLOCK:
         case SCENARIO_BASIC_ACTION_CONTINUE:
         case SCENARIO_BASIC_ACTION_PERMIT:
         case SCENARIO_BASIC_ACTION_RANDOM:
         {
            BasicActionScenarioLogHelp(scenario);

            break;
         }
         case SCENARIO_BASIC_PACKET_EXAMINATION:
         {
            BasicPacketExaminationScenarioLogHelp();

            break;
         }
         case SCENARIO_BASIC_PACKET_INJECTION:
         {
            BasicPacketInjectionScenarioLogHelp();

            break;
         }
         case SCENARIO_BASIC_PACKET_MODIFICATION:
         {
            BasicPacketModificationScenarioLogHelp();

            break;
         }
         case SCENARIO_BASIC_STREAM_INJECTION:
         {
            BasicStreamInjectionScenarioLogHelp();

            break;
         }
         case SCENARIO_FAST_PACKET_INJECTION:
         {
            FastPacketInjectionScenarioLogHelp();

            break;
         }
         case SCENARIO_FAST_STREAM_INJECTION:
         {
            FastStreamInjectionScenarioLogHelp();

            break;
         }
         case SCENARIO_FLOW_ASSOCIATION:
         {
            FlowAssociationScenarioLogHelp();

            break;
         }
         case SCENARIO_PEND_AUTHORIZATION:
         {
            PendAuthorizationScenarioLogHelp();

            break;
         }
         case SCENARIO_PEND_ENDPOINT_CLOSURE:
         {

#if(NTDDI_VERSION >= NTDDI_WIN7)

            PendEndpointClosureScenarioLogHelp();

#else

            wprintf(L"\n\t\t\t PEND_ENDPOINT_CLOSURE scenario is not supported on this version of Windows \n");

#endif /// (NTDDI_VERSION >= NTDDI_WIN7)

            break;
         }
         case SCENARIO_PROXY:
         {
            ProxyScenarioLogHelp();

            break;
         }
      }
   }
   else
   {
      wprintf(L"\n\t\t -?     \t Receive usage information.");
      wprintf(L"\n\t\t -clean \t Remove groups of WFP objects.");
      wprintf(L"\n\t\t        \t    default  \t Removes all of WFPSampler's objects except its Provider and SubLayer. 3rd party policy is preserved. [Optional]");
      wprintf(L"\n\t\t        \t    firewall \t Removes all of WFP's kernel-mode objects except built-in and WFPSampler's Provider and SubLayer. IPsec Policy will be preserved. [Optional]");
      wprintf(L"\n\t\t        \t    all      \t Removes all WFP objects except built-in and WFPSampler's Provider and SubLayer. No policy is preserved. [Optional]");
      wprintf(L"\n\t\t -s     \t Specify one of the following scenarios.");
      wprintf(L"\n\t\t\t\t ADVANCED_PACKET_INJECTION");

#if(NTDDI_VERSION >= NTDDI_WIN8)

      wprintf(L"\n\t\t\t\t APP_CONTAINER");

#endif /// (NTDDI_VERSION >= NTDDI_WIN8)

      wprintf(L"\n\t\t\t\t BASIC_ACTION_BLOCK");
      wprintf(L"\n\t\t\t\t BASIC_ACTION_CONTINUE");
      wprintf(L"\n\t\t\t\t BASIC_ACTION_PERMIT");
      wprintf(L"\n\t\t\t\t BASIC_ACTION_RANDOM");
      wprintf(L"\n\t\t\t\t BASIC_PACKET_EXAMINATION");
      wprintf(L"\n\t\t\t\t BASIC_PACKET_INJECTION");
      wprintf(L"\n\t\t\t\t BASIC_PACKET_MODIFICATION");
      wprintf(L"\n\t\t\t\t BASIC_STREAM_INJECTION");
      wprintf(L"\n\t\t\t\t FAST_PACKET_INJECTION");
      wprintf(L"\n\t\t\t\t FAST_STREAM_INJECTION");
      wprintf(L"\n\t\t\t\t FLOW_ASSOCIATION");
      wprintf(L"\n\t\t\t\t PEND_AUTHORIZATION");
      wprintf(L"\n\t\t\t\t PEND_ENDPOINT_CLOSURE");
      wprintf(L"\n\t\t\t\t PROXY");
      wprintf(L"\n");
      wprintf(L"\n\t Add -? for a scenario's context sensitive help");
      wprintf(L"\n");
      wprintf(L"\n\t\t  i.e.");
      wprintf(L"\n\t\t\t WFPSampler.exe -s BASIC_ACTION_BLOCK -?");
      wprintf(L"\n");
   }

   return;
}

/**
 @framework_function="wmain"

   Purpose:  Entry point for WFPSampler.Exe.  Accepts multiple parameters which are parsed and
             dispatched to the rest of the program.

   Notes:

   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/AA299386.aspx

*/
int __cdecl wmain(_In_ const int argumentCount,
                  _In_reads_(argumentCount) PCWSTR pArguments[])
{
   ASSERT(argumentCount);
   ASSERT(pArguments);

   UINT32 status = NO_ERROR;

   /// First argument is the executable's name, WFPSampler.exe,
   /// so start with next argument
   if(argumentCount > 1)
   {
      PCWSTR*                 ppCommandLineParameterStrings = (PCWSTR*)&(pArguments[1]);
      UINT32                  stringCount                   = argumentCount - 1;
      WFPSAMPLER_FLOW_CONTROL flowControl                   = PrvFlowControlGet(ppCommandLineParameterStrings,
                                                                                stringCount);
      WFPSAMPLER_SCENARIO     scenario                      = PrvScenarioGet(ppCommandLineParameterStrings,
                                                                             stringCount,
                                                                             flowControl);

      if(flowControl == FLOW_CONTROL_CLEAN)
      {
         PrvCleanPolicy(ppCommandLineParameterStrings,
                        stringCount);

         if(scenario == SCENARIO_UNDEFINED)
            HLPR_BAIL;
         else
            flowControl = FLOW_CONTROL_NORMAL;
      }

      if(flowControl == FLOW_CONTROL_NORMAL)
      {
         if(scenario == SCENARIO_UNDEFINED ||
            scenario > SCENARIO_MAX)
         {
            status = ERROR_NOT_FOUND;

            HlprLogError(L"wmain : PrvScenarioGet() [status: %#x][scenario: %d]",
                         status,
                         scenario);

            HLPR_BAIL;
         }
      }
      else if(flowControl == FLOW_CONTROL_HELP)
      {
         PrvLogUsage(scenario);

         HLPR_BAIL;
      }

      status = HlprServiceStart(g_pServiceName);
      HLPR_BAIL_ON_FAILURE(status);

      status = RPCClientInterfaceInitialize();
      HLPR_BAIL_ON_FAILURE(status);

      status = PrvScenarioDispatcher(scenario,
                                     ppCommandLineParameterStrings,
                                     stringCount);
      HLPR_BAIL_ON_FAILURE(status);
   }
   else
   {
      status = ERROR_INVALID_PARAMETER;

      HlprLogError(L"wmain() [status: %#x]",
                   status);
   }

   HLPR_BAIL_LABEL:

   RPCClientInterfaceTerminate();

   return (int)status;
}

license: MS-PL

repository: microkatz/Windows-driver-samples

repo_name: microkatz/Windows-driver-samples

gha_license_id: MS-PL

gha_language: C

extension: cpp