text:
/*
Copyright 2016 Gravitational, Inc.

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 client

import (
	"bufio"
	"encoding/pem"
	"fmt"
	"io"
	osfs "io/fs"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"golang.org/x/crypto/ssh"

	"github.com/gravitational/teleport"
	"github.com/gravitational/teleport/api/constants"
	"github.com/gravitational/teleport/api/profile"
	"github.com/gravitational/teleport/api/utils/keypaths"
	"github.com/gravitational/teleport/lib/auth"
	"github.com/gravitational/teleport/lib/sshutils"
	"github.com/gravitational/teleport/lib/utils"

	"github.com/sirupsen/logrus"

	"github.com/gravitational/trace"
)

const (

	// profileDirPerms is the default permissions applied to the profile
	// directory (usually ~/.tsh)
	profileDirPerms os.FileMode = 0700

	// keyFilePerms is the default permissions applied to key files (.cert, .key, pub)
	// under ~/.tsh
	keyFilePerms os.FileMode = 0600

	// tshConfigFileName is the name of the directory containing the
	// tsh config file.
	tshConfigFileName = "config"
)

// LocalKeyStore interface allows for different storage backends for tsh to
// load/save its keys.
//
// The _only_ filesystem-based implementation of LocalKeyStore is declared
// below (FSLocalKeyStore)
type LocalKeyStore interface {
	// AddKey adds the given key to the store.
	AddKey(key *Key) error

	// GetKey returns the user's key including the specified certs.
	GetKey(idx KeyIndex, opts ...CertOption) (*Key, error)

	// DeleteKey deletes the user's key with all its certs.
	DeleteKey(idx KeyIndex) error

	// DeleteUserCerts deletes only the specified certs of the user's key,
	// keeping the private key intact.
	DeleteUserCerts(idx KeyIndex, opts ...CertOption) error

	// DeleteKeys removes all session keys.
	DeleteKeys() error

	// AddKnownHostKeys adds the public key to the list of known hosts for
	// a hostname.
	AddKnownHostKeys(hostname, proxyHost string, keys []ssh.PublicKey) error

	// GetKnownHostKeys returns all public keys for a hostname.
	GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error)

	// SaveTrustedCerts saves trusted TLS certificates of certificate authorities.
	SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) error

	// GetTrustedCertsPEM gets trusted TLS certificates of certificate authorities.
	// Each returned byte slice contains an individual PEM block.
	GetTrustedCertsPEM(proxyHost string) ([][]byte, error)
}

// FSLocalKeyStore implements LocalKeyStore interface using the filesystem.
//
// The FS store uses the file layout outlined in `api/utils/keypaths.go`.
type FSLocalKeyStore struct {
	fsLocalNonSessionKeyStore
}

// NewFSLocalKeyStore creates a new filesystem-based local keystore object
// and initializes it.
//
// If dirPath is empty, sets it to ~/.tsh.
func NewFSLocalKeyStore(dirPath string) (s *FSLocalKeyStore, err error) {
	dirPath, err = initKeysDir(dirPath)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &FSLocalKeyStore{
		fsLocalNonSessionKeyStore: fsLocalNonSessionKeyStore{
			log:    logrus.WithField(trace.Component, teleport.ComponentKeyStore),
			KeyDir: dirPath,
		},
	}, nil
}

// initKeysDir initializes the keystore root directory, usually `~/.tsh`.
func initKeysDir(dirPath string) (string, error) {
	dirPath = profile.FullProfilePath(dirPath)
	if err := os.MkdirAll(dirPath, os.ModeDir|profileDirPerms); err != nil {
		return "", trace.ConvertSystemError(err)
	}
	return dirPath, nil
}

// AddKey adds the given key to the store.
func (fs *FSLocalKeyStore) AddKey(key *Key) error {
	if err := key.KeyIndex.Check(); err != nil {
		return trace.Wrap(err)
	}
	// Store core key data.
	if err := fs.writeBytes(key.Priv, fs.UserKeyPath(key.KeyIndex)); err != nil {
		return trace.Wrap(err)
	}
	if err := fs.writeBytes(key.Pub, fs.sshCAsPath(key.KeyIndex)); err != nil {
		return trace.Wrap(err)
	}
	if err := fs.writeBytes(key.TLSCert, fs.tlsCertPath(key.KeyIndex)); err != nil {
		return trace.Wrap(err)
	}
	if runtime.GOOS == constants.WindowsOS {
		if err := fs.writeBytes(key.PPK, fs.PPKFilePath(key.KeyIndex)); err != nil {
			return trace.Wrap(err)
		}
	}

	// Store per-cluster key data.
	if len(key.Cert) > 0 {
		if err := fs.writeBytes(key.Cert, fs.sshCertPath(key.KeyIndex)); err != nil {
			return trace.Wrap(err)
		}
	}

	// TODO(awly): unit test this.
	for kubeCluster, cert := range key.KubeTLSCerts {
		// Prevent directory traversal via a crafted kubernetes cluster name.
		//
		// This will confuse cluster cert loading (GetKey will return
		// kubernetes cluster names different from the ones stored here), but I
		// don't expect any well-meaning user to create bad names.
		kubeCluster = filepath.Clean(kubeCluster)

		path := fs.kubeCertPath(key.KeyIndex, kubeCluster)
		if err := fs.writeBytes(cert, path); err != nil {
			return trace.Wrap(err)
		}
	}
	for db, cert := range key.DBTLSCerts {
		path := fs.databaseCertPath(key.KeyIndex, filepath.Clean(db))
		if err := fs.writeBytes(cert, path); err != nil {
			return trace.Wrap(err)
		}
	}
	for app, cert := range key.AppTLSCerts {
		path := fs.appCertPath(key.KeyIndex, filepath.Clean(app))
		if err := fs.writeBytes(cert, path); err != nil {
			return trace.Wrap(err)
		}
	}

	return nil
}

func (fs *FSLocalKeyStore) writeBytes(bytes []byte, fp string) error {
	if err := os.MkdirAll(filepath.Dir(fp), os.ModeDir|profileDirPerms); err != nil {
		fs.log.Error(err)
		return trace.ConvertSystemError(err)
	}
	err := os.WriteFile(fp, bytes, keyFilePerms)
	if err != nil {
		fs.log.Error(err)
	}
	return trace.ConvertSystemError(err)
}

// DeleteKey deletes the user's key with all its certs.
func (fs *FSLocalKeyStore) DeleteKey(idx KeyIndex) error {
	files := []string{
		fs.UserKeyPath(idx),
		fs.sshCAsPath(idx),
		fs.tlsCertPath(idx),
	}
	for _, fn := range files {
		if err := os.Remove(fn); err != nil {
			return trace.ConvertSystemError(err)
		}
	}
	// we also need to delete the extra PuTTY-formatted .ppk file when running on Windows,
	// but it may not exist when upgrading from v9 -> v10 and logging into an existing cluster.
	// as such, deletion should be best-effort and not generate an error if it fails.
	if runtime.GOOS == constants.WindowsOS {
		os.Remove(fs.PPKFilePath(idx))
	}

	// Clear ClusterName to delete the user certs stored for all clusters.
	idx.ClusterName = ""
	return fs.DeleteUserCerts(idx, WithAllCerts...)
}

// DeleteUserCerts deletes only the specified certs of the user's key,
// keeping the private key intact.
// Empty clusterName indicates to delete the certs for all clusters.
//
// Useful when needing to log out of a specific service, like a particular
// database proxy.
func (fs *FSLocalKeyStore) DeleteUserCerts(idx KeyIndex, opts ...CertOption) error {
	for _, o := range opts {
		certPath := o.certPath(fs.KeyDir, idx)
		if err := os.RemoveAll(certPath); err != nil {
			return trace.ConvertSystemError(err)
		}
	}
	return nil
}

// DeleteKeys removes all session keys.
func (fs *FSLocalKeyStore) DeleteKeys() error {

	files, err := os.ReadDir(fs.KeyDir)
	if err != nil {
		return trace.ConvertSystemError(err)
	}
	for _, file := range files {
		if file.IsDir() && file.Name() == tshConfigFileName {
			continue
		}
		if file.IsDir() {
			err := os.RemoveAll(filepath.Join(fs.KeyDir, file.Name()))
			if err != nil {
				return trace.ConvertSystemError(err)
			}
			continue
		}
		err := os.Remove(filepath.Join(fs.KeyDir, file.Name()))
		if err != nil {
			return trace.ConvertSystemError(err)
		}
	}
	return nil
}

// GetKey returns the user's key including the specified certs.
// If the key is not found, returns trace.NotFound error.
func (fs *FSLocalKeyStore) GetKey(idx KeyIndex, opts ...CertOption) (*Key, error) {
	if len(opts) > 0 {
		if err := idx.Check(); err != nil {
			return nil, trace.Wrap(err, "GetKey with CertOptions requires a fully specified KeyIndex")
		}
	}

	if _, err := os.ReadDir(fs.KeyDir); err != nil && trace.IsNotFound(err) {
		return nil, trace.Wrap(err, "no session keys for %+v", idx)
	}

	priv, err := os.ReadFile(fs.UserKeyPath(idx))
	if err != nil {
		fs.log.Error(err)
		return nil, trace.ConvertSystemError(err)
	}
	pub, err := os.ReadFile(fs.sshCAsPath(idx))
	if err != nil {
		fs.log.Error(err)
		return nil, trace.ConvertSystemError(err)
	}
	tlsCertFile := fs.tlsCertPath(idx)
	tlsCert, err := os.ReadFile(tlsCertFile)
	if err != nil {
		fs.log.Error(err)
		return nil, trace.ConvertSystemError(err)
	}
	tlsCA, err := fs.GetTrustedCertsPEM(idx.ProxyHost)
	if err != nil {
		fs.log.Error(err)
		return nil, trace.ConvertSystemError(err)
	}

	key := &Key{
		KeyIndex: idx,
		Pub:      pub,
		Priv:     priv,
		TLSCert:  tlsCert,
		TrustedCA: []auth.TrustedCerts{{
			TLSCertificates: tlsCA,
		}},
		KubeTLSCerts:        make(map[string][]byte),
		DBTLSCerts:          make(map[string][]byte),
		AppTLSCerts:         make(map[string][]byte),
		WindowsDesktopCerts: make(map[string][]byte),
	}

	tlsCertExpiration, err := key.TeleportTLSCertValidBefore()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	fs.log.Debugf("Returning Teleport TLS certificate %q valid until %q.", tlsCertFile, tlsCertExpiration)

	for _, o := range opts {
		if err := fs.updateKeyWithCerts(o, key); err != nil && !trace.IsNotFound(err) {
			fs.log.Error(err)
			return nil, trace.Wrap(err)
		}
	}

	// Note, we may be returning expired certificates here, that is okay. If a
	// certificate is expired, it's the responsibility of the TeleportClient to
	// perform cleanup of the certificates and the profile.

	return key, nil
}

func (fs *FSLocalKeyStore) updateKeyWithCerts(o CertOption, key *Key) error {
	certPath := o.certPath(fs.KeyDir, key.KeyIndex)
	info, err := os.Stat(certPath)
	if err != nil {
		return trace.ConvertSystemError(err)
	}

	fs.log.Debugf("Reading certificates from path %q.", certPath)

	if info.IsDir() {
		certDataMap := map[string][]byte{}
		certFiles, err := os.ReadDir(certPath)
		if err != nil {
			return trace.ConvertSystemError(err)
		}
		for _, certFile := range certFiles {
			name := keypaths.TrimCertPathSuffix(certFile.Name())
			if isCert := name != certFile.Name(); isCert {
				data, err := os.ReadFile(filepath.Join(certPath, certFile.Name()))
				if err != nil {
					return trace.ConvertSystemError(err)
				}
				certDataMap[name] = data
			}
		}
		return o.updateKeyWithMap(key, certDataMap)
	}

	certBytes, err := os.ReadFile(certPath)
	if err != nil {
		return trace.ConvertSystemError(err)
	}
	return o.updateKeyWithBytes(key, certBytes)
}

// CertOption is an additional step to run when loading/deleting user certificates.
type CertOption interface {
	// certPath returns a path to the cert (or to a dir holding the certs)
	// within the given key dir. For use with FSLocalKeyStore.
	certPath(keyDir string, idx KeyIndex) string
	// updateKeyWithBytes adds the cert bytes to the key and performs related checks.
	updateKeyWithBytes(key *Key, certBytes []byte) error
	// updateKeyWithMap adds the cert data map to the key and performs related checks.
	updateKeyWithMap(key *Key, certMap map[string][]byte) error
	// deleteFromKey deletes the cert data from the key.
	deleteFromKey(key *Key)
}

// WithAllCerts lists all known CertOptions.
var WithAllCerts = []CertOption{WithSSHCerts{}, WithKubeCerts{}, WithDBCerts{}, WithAppCerts{}}

// WithSSHCerts is a CertOption for handling SSH certificates.
type WithSSHCerts struct{}

func (o WithSSHCerts) certPath(keyDir string, idx KeyIndex) string {
	if idx.ClusterName == "" {
		return keypaths.SSHDir(keyDir, idx.ProxyHost, idx.Username)
	}
	return keypaths.SSHCertPath(keyDir, idx.ProxyHost, idx.Username, idx.ClusterName)
}

func (o WithSSHCerts) updateKeyWithBytes(key *Key, certBytes []byte) error {
	key.Cert = certBytes

	// Validate the SSH certificate.
	if err := key.CheckCert(); err != nil {
		if !utils.IsCertExpiredError(err) {
			return trace.Wrap(err)
		}
	}
	return nil
}

func (o WithSSHCerts) updateKeyWithMap(key *Key, certMap map[string][]byte) error {
	return trace.NotImplemented("WithSSHCerts does not implement updateKeyWithMap")
}

func (o WithSSHCerts) deleteFromKey(key *Key) {
	key.Cert = nil
}

// WithKubeCerts is a CertOption for handling kubernetes certificates.
type WithKubeCerts struct{}

func (o WithKubeCerts) certPath(keyDir string, idx KeyIndex) string {
	if idx.ClusterName == "" {
		return keypaths.KubeDir(keyDir, idx.ProxyHost, idx.Username)
	}
	return keypaths.KubeCertDir(keyDir, idx.ProxyHost, idx.Username, idx.ClusterName)
}

func (o WithKubeCerts) updateKeyWithBytes(key *Key, certBytes []byte) error {
	return trace.NotImplemented("WithKubeCerts does not implement updateKeyWithBytes")
}

func (o WithKubeCerts) updateKeyWithMap(key *Key, certMap map[string][]byte) error {
	key.KubeTLSCerts = certMap
	return nil
}

func (o WithKubeCerts) deleteFromKey(key *Key) {
	key.KubeTLSCerts = nil
}

// WithDBCerts is a CertOption for handling database access certificates.
type WithDBCerts struct {
	dbName string
}

func (o WithDBCerts) certPath(keyDir string, idx KeyIndex) string {
	if idx.ClusterName == "" {
		return keypaths.DatabaseDir(keyDir, idx.ProxyHost, idx.Username)
	}
	if o.dbName == "" {
		return keypaths.DatabaseCertDir(keyDir, idx.ProxyHost, idx.Username, idx.ClusterName)
	}
	return keypaths.DatabaseCertPath(keyDir, idx.ProxyHost, idx.Username, idx.ClusterName, o.dbName)
}

func (o WithDBCerts) updateKeyWithBytes(key *Key, certBytes []byte) error {
	return trace.NotImplemented("WithDBCerts does not implement updateKeyWithBytes")
}

func (o WithDBCerts) updateKeyWithMap(key *Key, certMap map[string][]byte) error {
	key.DBTLSCerts = certMap
	return nil
}

func (o WithDBCerts) deleteFromKey(key *Key) {
	key.DBTLSCerts = nil
}

// WithAppCerts is a CertOption for handling application access certificates.
type WithAppCerts struct {
	appName string
}

func (o WithAppCerts) certPath(keyDir string, idx KeyIndex) string {
	if idx.ClusterName == "" {
		return keypaths.AppDir(keyDir, idx.ProxyHost, idx.Username)
	}
	if o.appName == "" {
		return keypaths.AppCertDir(keyDir, idx.ProxyHost, idx.Username, idx.ClusterName)
	}
	return keypaths.AppCertPath(keyDir, idx.ProxyHost, idx.Username, idx.ClusterName, o.appName)
}

func (o WithAppCerts) updateKeyWithBytes(key *Key, certBytes []byte) error {
	return trace.NotImplemented("WithAppCerts does not implement updateKeyWithBytes")
}

func (o WithAppCerts) updateKeyWithMap(key *Key, certMap map[string][]byte) error {
	key.AppTLSCerts = certMap
	return nil
}

func (o WithAppCerts) deleteFromKey(key *Key) {
	key.AppTLSCerts = nil
}

// fsLocalNonSessionKeyStore is a FS-based store implementing methods
// for CA certificates and known host fingerprints. It is embedded
// in both FSLocalKeyStore and MemLocalKeyStore.
type fsLocalNonSessionKeyStore struct {
	// log holds the structured logger.
	log logrus.FieldLogger

	// KeyDir is the directory where all keys are stored.
	KeyDir string
}

// proxyKeyDir returns the keystore's keys directory for the given proxy.
func (fs *fsLocalNonSessionKeyStore) proxyKeyDir(proxy string) string {
	return keypaths.ProxyKeyDir(fs.KeyDir, proxy)
}

// casDir returns path to trusted clusters certificates directory.
func (fs *fsLocalNonSessionKeyStore) casDir(proxy string) string {
	return keypaths.CAsDir(fs.KeyDir, proxy)
}

// clusterCAPath returns path to cluster certificate.
func (fs *fsLocalNonSessionKeyStore) clusterCAPath(proxy, clusterName string) string {
	return keypaths.TLSCAsPathCluster(fs.KeyDir, proxy, clusterName)
}

// knownHostsPath returns the keystore's known hosts file path.
func (fs *fsLocalNonSessionKeyStore) knownHostsPath() string {
	return keypaths.KnownHostsPath(fs.KeyDir)
}

// UserKeyPath returns the private key path for the given KeyIndex.
func (fs *fsLocalNonSessionKeyStore) UserKeyPath(idx KeyIndex) string {
	return keypaths.UserKeyPath(fs.KeyDir, idx.ProxyHost, idx.Username)
}

// tlsCertPath returns the TLS certificate path given KeyIndex.
func (fs *fsLocalNonSessionKeyStore) tlsCertPath(idx KeyIndex) string {
	return keypaths.TLSCertPath(fs.KeyDir, idx.ProxyHost, idx.Username)
}

// tlsCAsPath returns the TLS CA certificates path for the given KeyIndex.
func (fs *fsLocalNonSessionKeyStore) tlsCAsPath(proxy string) string {
	return keypaths.TLSCAsPath(fs.KeyDir, proxy)
}

// sshCertPath returns the SSH certificate path for the given KeyIndex.
func (fs *fsLocalNonSessionKeyStore) sshCertPath(idx KeyIndex) string {
	return keypaths.SSHCertPath(fs.KeyDir, idx.ProxyHost, idx.Username, idx.ClusterName)
}

// PPKFilePath returns the PPK (PuTTY-formatted) keypair path for the given KeyIndex.
func (fs *fsLocalNonSessionKeyStore) PPKFilePath(idx KeyIndex) string {
	return keypaths.PPKFilePath(fs.KeyDir, idx.ProxyHost, idx.Username)
}

// sshCAsPath returns the SSH CA certificates path for the given KeyIndex.
func (fs *fsLocalNonSessionKeyStore) sshCAsPath(idx KeyIndex) string {
	return keypaths.SSHCAsPath(fs.KeyDir, idx.ProxyHost, idx.Username)
}

//  appCertPath returns the TLS certificate path for the given KeyIndex and app name.
func (fs *fsLocalNonSessionKeyStore) appCertPath(idx KeyIndex, appname string) string {
	return keypaths.AppCertPath(fs.KeyDir, idx.ProxyHost, idx.Username, idx.ClusterName, appname)
}

// databaseCertPath returns the TLS certificate path for the given KeyIndex and database name.
func (fs *fsLocalNonSessionKeyStore) databaseCertPath(idx KeyIndex, dbname string) string {
	return keypaths.DatabaseCertPath(fs.KeyDir, idx.ProxyHost, idx.Username, idx.ClusterName, dbname)
}

// kubeCertPath returns the TLS certificate path for the given KeyIndex and kube cluster name.
func (fs *fsLocalNonSessionKeyStore) kubeCertPath(idx KeyIndex, kubename string) string {
	return keypaths.KubeCertPath(fs.KeyDir, idx.ProxyHost, idx.Username, idx.ClusterName, kubename)
}

// AddKnownHostKeys adds a new entry to `known_hosts` file.
func (fs *fsLocalNonSessionKeyStore) AddKnownHostKeys(hostname, proxyHost string, hostKeys []ssh.PublicKey) (retErr error) {
	fp, err := os.OpenFile(fs.knownHostsPath(), os.O_CREATE|os.O_RDWR, 0640)
	if err != nil {
		return trace.ConvertSystemError(err)
	}
	defer utils.StoreErrorOf(fp.Close, &retErr)
	// read all existing entries into a map (this removes any pre-existing dupes)
	entries := make(map[string]int)
	output := make([]string, 0)
	scanner := bufio.NewScanner(fp)
	for scanner.Scan() {
		line := scanner.Text()
		if _, exists := entries[line]; !exists {
			output = append(output, line)
			entries[line] = 1
		}
	}
	// check if the scanner ran into an error
	if err := scanner.Err(); err != nil {
		return trace.Wrap(err)
	}
	// add every host key to the list of entries
	for i := range hostKeys {
		fs.log.Debugf("Adding known host %s with proxy %s and key: %v", hostname, proxyHost, sshutils.Fingerprint(hostKeys[i]))
		bytes := ssh.MarshalAuthorizedKey(hostKeys[i])

		// Write keys in an OpenSSH-compatible format. A previous format was not
		// quite OpenSSH-compatible, so we may write a duplicate entry here. Any
		// duplicates will be pruned below.
		// We include both the proxy server and original hostname as well as the
		// root domain wildcard. OpenSSH clients match against both the proxy
		// host and nodes (via the wildcard). Teleport itself occasionally uses
		// the root cluster name.
		line := fmt.Sprintf(
			"@cert-authority %s,%s,*.%s %s type=host",
			proxyHost, hostname, hostname, strings.TrimSpace(string(bytes)),
		)
		if _, exists := entries[line]; !exists {
			output = append(output, line)
		}
	}
	// Prune any duplicate host entries for migrated hosts. Note that only
	// duplicates matching the current hostname/proxyHost will be pruned; others
	// will be cleaned up at subsequent logins.
	output = pruneOldHostKeys(output)
	// re-create the file:
	_, err = fp.Seek(0, 0)
	if err != nil {
		return trace.Wrap(err)
	}
	if err = fp.Truncate(0); err != nil {
		return trace.Wrap(err)
	}
	for _, line := range output {
		fmt.Fprintf(fp, "%s\n", line)
	}
	return fp.Sync()
}

// matchesWildcard ensures the given `hostname` matches the given `pattern`.
// The `pattern` may be prefixed with `*.` which will match exactly one domain
// segment, meaning `*.example.com` will match `foo.example.com` but not
// `foo.bar.example.com`.
func matchesWildcard(hostname, pattern string) bool {
	// Trim any trailing "." in case of an absolute domain.
	hostname = strings.TrimSuffix(hostname, ".")

	// Don't allow non-wildcard patterns.
	if !strings.HasPrefix(pattern, "*.") {
		return false
	}

	// Never match a top-level hostname.
	if !strings.Contains(hostname, ".") {
		return false
	}

	// Don't allow empty matches.
	pattern = pattern[2:]
	if strings.TrimSpace(pattern) == "" {
		return false
	}

	hostnameParts := strings.Split(hostname, ".")
	hostnameRoot := strings.Join(hostnameParts[1:], ".")

	return hostnameRoot == pattern
}

// GetKnownHostKeys returns all known public keys from `known_hosts`.
func (fs *fsLocalNonSessionKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error) {
	bytes, err := os.ReadFile(fs.knownHostsPath())
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, trace.Wrap(err)
	}
	var (
		pubKey    ssh.PublicKey
		retval    []ssh.PublicKey = make([]ssh.PublicKey, 0)
		hosts     []string
		hostMatch bool
	)
	for err == nil {
		_, hosts, pubKey, _, bytes, err = ssh.ParseKnownHosts(bytes)
		if err == nil {
			hostMatch = (hostname == "")
			if !hostMatch {
				for i := range hosts {
					if hosts[i] == hostname || matchesWildcard(hostname, hosts[i]) {
						hostMatch = true
						break
					}
				}
			}
			if hostMatch {
				retval = append(retval, pubKey)
			}
		}
	}
	if err != io.EOF {
		return nil, trace.Wrap(err)
	}
	return retval, nil
}

// SaveTrustedCerts saves trusted TLS certificates of certificate authorities.
func (fs *fsLocalNonSessionKeyStore) SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) (retErr error) {
	if err := os.MkdirAll(fs.proxyKeyDir(proxyHost), os.ModeDir|profileDirPerms); err != nil {
		fs.log.Error(err)
		return trace.ConvertSystemError(err)
	}

	// Save trusted clusters certs in CAS directory.
	if err := fs.saveTrustedCertsInCASDir(proxyHost, cas); err != nil {
		return trace.Wrap(err)
	}

	// For backward compatibility save trusted in legacy certs.pem file.
	if err := fs.saveTrustedCertsInLegacyCAFile(proxyHost, cas); err != nil {
		return trace.Wrap(err)
	}

	return nil
}

func (fs *fsLocalNonSessionKeyStore) saveTrustedCertsInCASDir(proxyHost string, cas []auth.TrustedCerts) error {
	casDirPath := filepath.Join(fs.casDir(proxyHost))
	if err := os.MkdirAll(casDirPath, os.ModeDir|profileDirPerms); err != nil {
		fs.log.Error(err)
		return trace.ConvertSystemError(err)
	}

	for _, ca := range cas {
		if !isSafeClusterName(ca.ClusterName) {
			fs.log.Warnf("Skipped unsafe cluster name: %q", ca.ClusterName)
			continue
		}
		// Create CA files in cas dir for each cluster.
		caFile, err := os.OpenFile(fs.clusterCAPath(proxyHost, ca.ClusterName), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640)
		if err != nil {
			return trace.ConvertSystemError(err)
		}

		if err := writeClusterCertificates(caFile, ca.TLSCertificates); err != nil {
			return trace.Wrap(err)
		}
	}
	return nil
}

func (fs *fsLocalNonSessionKeyStore) saveTrustedCertsInLegacyCAFile(proxyHost string, cas []auth.TrustedCerts) (retErr error) {
	certsFile := fs.tlsCAsPath(proxyHost)
	fp, err := os.OpenFile(certsFile, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640)
	if err != nil {
		return trace.ConvertSystemError(err)
	}
	defer utils.StoreErrorOf(fp.Close, &retErr)
	for _, ca := range cas {
		for _, cert := range ca.TLSCertificates {
			if _, err := fp.Write(cert); err != nil {
				return trace.ConvertSystemError(err)
			}
			if _, err := fmt.Fprintln(fp); err != nil {
				return trace.ConvertSystemError(err)
			}
		}
	}
	return fp.Sync()
}

// isSafeClusterName check if cluster name is safe and doesn't contain miscellaneous characters.
func isSafeClusterName(name string) bool {
	return !strings.Contains(name, "..")
}

func writeClusterCertificates(f *os.File, tlsCertificates [][]byte) error {
	defer f.Close()
	for _, cert := range tlsCertificates {
		if _, err := f.Write(cert); err != nil {
			return trace.ConvertSystemError(err)
		}
	}
	if err := f.Sync(); err != nil {
		return trace.ConvertSystemError(err)
	}
	return nil
}

// GetTrustedCertsPEM returns trusted TLS certificates of certificate authorities PEM
// blocks.
func (fs *fsLocalNonSessionKeyStore) GetTrustedCertsPEM(proxyHost string) ([][]byte, error) {
	dir := fs.casDir(proxyHost)

	if _, err := os.Stat(dir); err != nil {
		if os.IsNotExist(err) {
			return nil, trace.NotFound("please relogin, tsh user profile doesn't contain CAS directory: %s", dir)
		}
		return nil, trace.ConvertSystemError(err)
	}

	var blocks [][]byte
	err := filepath.Walk(dir, func(path string, info osfs.FileInfo, err error) error {
		if err != nil {
			return nil
		}
		if info.IsDir() {
			return nil
		}

		data, err := os.ReadFile(path)
		for len(data) > 0 {
			if err != nil {
				return trace.Wrap(err)
			}
			block, rest := pem.Decode(data)
			if block == nil {
				break
			}
			if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
				fs.log.Debugf("Skipping PEM block type=%v headers=%v.", block.Type, block.Headers)
				data = rest
				continue
			}
			// rest contains the remainder of data after reading a block.
			// Therefore, the block length is len(data) - len(rest).
			// Use that length to slice the block from the start of data.
			blocks = append(blocks, data[:len(data)-len(rest)])
			data = rest
		}
		return nil
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return blocks, nil
}

// noLocalKeyStore is a LocalKeyStore representing the absence of a keystore.
// All methods return errors. This exists to avoid nil checking everywhere in
// LocalKeyAgent and prevent nil pointer panics.
type noLocalKeyStore struct{}

var errNoLocalKeyStore = trace.NotFound("there is no local keystore")

func (noLocalKeyStore) AddKey(key *Key) error {
	return errNoLocalKeyStore
}
func (noLocalKeyStore) GetKey(idx KeyIndex, opts ...CertOption) (*Key, error) {
	return nil, errNoLocalKeyStore
}
func (noLocalKeyStore) DeleteKey(idx KeyIndex) error {
	return errNoLocalKeyStore
}
func (noLocalKeyStore) DeleteUserCerts(idx KeyIndex, opts ...CertOption) error {
	return errNoLocalKeyStore
}
func (noLocalKeyStore) DeleteKeys() error { return errNoLocalKeyStore }
func (noLocalKeyStore) AddKnownHostKeys(hostname, proxyHost string, keys []ssh.PublicKey) error {
	return errNoLocalKeyStore
}
func (noLocalKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error) {
	return nil, errNoLocalKeyStore
}
func (noLocalKeyStore) SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) error {
	return errNoLocalKeyStore
}
func (noLocalKeyStore) GetTrustedCertsPEM(proxyHost string) ([][]byte, error) {
	return nil, errNoLocalKeyStore
}

// MemLocalKeyStore is an in-memory session keystore implementation.
type MemLocalKeyStore struct {
	fsLocalNonSessionKeyStore
	inMem memLocalKeyStoreMap
}

// memLocalKeyStoreMap is a three-dimensional map indexed by [proxyHost][username][clusterName]
type memLocalKeyStoreMap = map[string]map[string]map[string]*Key

// NewMemLocalKeyStore initializes a MemLocalKeyStore.
// The key directory here is only used for storing CA certificates and known
// host fingerprints.
func NewMemLocalKeyStore(dirPath string) (*MemLocalKeyStore, error) {
	dirPath, err := initKeysDir(dirPath)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &MemLocalKeyStore{
		fsLocalNonSessionKeyStore{
			log:    logrus.WithField(trace.Component, teleport.ComponentKeyStore),
			KeyDir: dirPath,
		},
		memLocalKeyStoreMap{},
	}, nil
}

// AddKey writes a key to the underlying key store.
func (s *MemLocalKeyStore) AddKey(key *Key) error {
	if err := key.KeyIndex.Check(); err != nil {
		return trace.Wrap(err)
	}
	_, ok := s.inMem[key.ProxyHost]
	if !ok {
		s.inMem[key.ProxyHost] = map[string]map[string]*Key{}
	}
	_, ok = s.inMem[key.ProxyHost][key.Username]
	if !ok {
		s.inMem[key.ProxyHost][key.Username] = map[string]*Key{}
	}
	s.inMem[key.ProxyHost][key.Username][key.ClusterName] = key
	return nil
}

// GetKey returns the user's key including the specified certs.
func (s *MemLocalKeyStore) GetKey(idx KeyIndex, opts ...CertOption) (*Key, error) {
	var key *Key
	if idx.ClusterName == "" {
		// If clusterName is not specified then the cluster-dependent fields
		// are not considered relevant and we may simply return any key
		// associated with any cluster name whatsoever.
		for _, found := range s.inMem[idx.ProxyHost][idx.Username] {
			key = found
			break
		}
	} else {
		key = s.inMem[idx.ProxyHost][idx.Username][idx.ClusterName]
	}
	if key == nil {
		return nil, trace.NotFound("key for %+v not found", idx)
	}

	// It is not necessary to handle opts because all the optional certs are
	// already part of the Key struct as stored in memory.

	tlsCertExpiration, err := key.TeleportTLSCertValidBefore()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	s.log.Debugf("Returning Teleport TLS certificate from memory, valid until %q.", tlsCertExpiration)

	// Validate the SSH certificate.
	if err := key.CheckCert(); err != nil {
		if !utils.IsCertExpiredError(err) {
			return nil, trace.Wrap(err)
		}
	}

	return key, nil
}

// DeleteKey deletes the user's key with all its certs.
func (s *MemLocalKeyStore) DeleteKey(idx KeyIndex) error {
	delete(s.inMem[idx.ProxyHost], idx.Username)
	return nil
}

// DeleteKeys removes all session keys.
func (s *MemLocalKeyStore) DeleteKeys() error {
	s.inMem = memLocalKeyStoreMap{}
	return nil
}

// DeleteUserCerts deletes only the specified certs of the user's key,
// keeping the private key intact.
// Empty clusterName indicates to delete the certs for all clusters.
//
// Useful when needing to log out of a specific service, like a particular
// database proxy.
func (s *MemLocalKeyStore) DeleteUserCerts(idx KeyIndex, opts ...CertOption) error {
	var keys []*Key
	if idx.ClusterName != "" {
		key, ok := s.inMem[idx.ProxyHost][idx.Username][idx.ClusterName]
		if !ok {
			return nil
		}
		keys = []*Key{key}
	} else {
		keys = make([]*Key, 0, len(s.inMem[idx.ProxyHost][idx.Username]))
		for _, key := range s.inMem[idx.ProxyHost][idx.Username] {
			keys = append(keys, key)
		}
	}

	for _, key := range keys {
		for _, o := range opts {
			o.deleteFromKey(key)
		}
	}
	return nil
}

repository: dolfly/teleport

repo_name: dolfly/teleport

gha_language: Go

extension: go


text:
package sparse

import "net"
import "github.com/kp6/alphorn/log"
import "os"
import "encoding/gob"
import "strconv"
import "time"

// Server daemon
func Server(addr TCPEndPoint, timeout int) {
	server(addr, true /*serve single connection for now*/, timeout)
}

// TestServer daemon serves only one connection for each test then exits
func TestServer(addr TCPEndPoint, timeout int) {
	server(addr, true, timeout)
}

func server(addr TCPEndPoint, serveOnce /*test flag*/ bool, timeout int) {
    serverConnectionTimeout := time.Duration(timeout) * time.Second
	// listen on all interfaces
	EndPoint := addr.Host + ":" + strconv.Itoa(int(addr.Port))
	laddr, err := net.ResolveTCPAddr("tcp", EndPoint)
	if err != nil {
		log.Fatal("Connection listener address resolution error:", err)
	}
	ln, err := net.ListenTCP("tcp", laddr)
	if err != nil {
		log.Fatal("Connection listener error:", err)
	}
	defer ln.Close()
	ln.SetDeadline(time.Now().Add(serverConnectionTimeout))
	log.Info("Sync server is up...")

	for {
		conn, err := ln.AcceptTCP()
		if err != nil {
			log.Fatal("Connection accept error:", err)
		}

		if serveOnce {
			// This is to avoid server listening port conflicts while running tests
			// exit after single connection request
            serveConnection(conn)
			break
		}

		go serveConnection(conn)
	}
	log.Info("Sync server exit.")
}

type requestCode int

const (
	requestMagic    requestCode = 31415926
	syncRequestCode requestCode = 1
)

type requestHeader struct {
	Magic requestCode
	Code  requestCode
}

func serveConnection(conn net.Conn) {
	defer conn.Close()

	decoder := gob.NewDecoder(conn)
	var request requestHeader
	err := decoder.Decode(&request)
	if err != nil {
		log.Error("Protocol decoder error:", err)
		return
	}
	if requestMagic != request.Magic {
		log.Error("Bad request")
		return
	}

	switch request.Code {
	case syncRequestCode:
		var path string
		err := decoder.Decode(&path)
		if err != nil {
			log.Error("Protocol decoder error:", err)
			return
		}
		var size int64
		err = decoder.Decode(&size)
		if err != nil {
			log.Error("Protocol decoder error:", err)
			return
		}
		encoder := gob.NewEncoder(conn)
		serveSyncRequest(encoder, decoder, path, size)
	}
}

func serveSyncRequest(encoder *gob.Encoder, decoder *gob.Decoder, path string, size int64) {

	// Open destination file
	file, err := os.OpenFile(path, os.O_RDWR, 0)
	if err != nil {
		file, err = os.Create(path)
		if err != nil {
			log.Error("Failed to create file:", string(path), err)
			encoder.Encode(false) // NACK request
			return
		}
	}
	defer file.Close()

	// Resize the file
	if err = file.Truncate(size); err != nil {
		log.Error("Failed to resize file:", string(path), err)
		encoder.Encode(false) // NACK request
		return
	}

	// load
	layout, err := loadFile(file)
	if err != nil {
		encoder.Encode(false) // NACK request
		return
	}
	encoder.Encode(true) // ACK request

	// send layout back
	items := len(layout)
	log.Info("Sending layout, item count=", items)
	err = encoder.Encode(layout)
	if err != nil {
		log.Error("Protocol encoder error:", err)
		return
	}

	// receive & process data diff
	status := true
	for status {
		var delta FileInterval
		err := decoder.Decode(&delta)
		if err != nil {
			log.Error("Protocol decoder error:", err)
			status = false
			break
		}
		log.Debug("receiving delta [", delta, "]")
		if 0 == delta.Len() {
			log.Debug("received end of transimission marker")
			break // end of diff
		}
		switch delta.Kind {
		case SparseData:
			var data []byte
			err = decoder.Decode(&data)
			if err != nil {
				log.Error("Protocol data decoder error:", err)
				status = false
				break
			}
			if int64(len(data)) != delta.Len() {
				log.Error("Failed to receive data")
				status = false
				break
			}
			log.Debug("writing data...")
			_, err = file.WriteAt(data, delta.Begin)
			if err != nil {
				log.Error("Failed to write file")
				status = false
				break
			}
		case SparseHole:
			log.Debug("trimming...")
			err := PunchHole(file, delta.Interval)
			if err != nil {
				log.Error("Failed to trim file")
				status = false
				break
			}
		}
	}

	file.Sync() //TODO: switch to O_DIRECT and compare performance

	// reply to client with status
	log.Info("Sync remote status=", status)
	err = encoder.Encode(status)
	if err != nil {
		log.Error("Protocol encoder error:", err)
		return
	}
}

func loadFile(file *os.File) ([]FileInterval, error) {
	size, err := file.Seek(0, os.SEEK_END)
	if err != nil {
		return make([]FileInterval, 0), err
	}

	return RetrieveLayout(file, Interval{0, size})
}

repository: ibuildthecloud/sparse-tools

license_type: permissive

repo_name: ibuildthecloud/sparse-tools

branch_name: refs/heads/master


text:
require python-inflection.inc
inherit setuptools3
SRC_URI[md5sum] = "7941165e9f148e0520023941c0886b40"
SRC_URI[sha256sum] = "18ea7fb7a7d152853386523def08736aa8c32636b047ade55f7578c4edeb16ca"

license: MIT

repository: NGenetzky/meta-ngenetzky

repo_name: NGenetzky/meta-ngenetzky

extension: bb


text:
// This program generates version.go.
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"text/template"
	"time"
)

var tpl = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
// THIS FILE IS AUTOGENERATED BY THE MAKEFILE. DO NOT EDIT.
package version

import "fmt"

var (
	version = "{{ .Version }}"
	buildDate = "{{ .BuildDate }}"
	commitHash = "{{ .CommitHash }}"
	author = "{{ .Author }}"
)

// PrintVersion returns the current version information
func PrintVersion() {
	fmt.Printf("Version %s, Date: %s (Commit: %s), Author: %s\n", version, buildDate, commitHash, author)
}
`))

func main() {

	version, err := ioutil.ReadFile("../VERSION.txt") // just pass the file name
	if err != nil {
		fmt.Print(err)
	}

	cmd, err := exec.Run("git rev-parse --verify HEAD", nil, nil, exec.DevNull, exec.Pipe, exec.MergeWithStdout)

	cmdOutput, _ := ioutil.ReadAll(cmd.Stdout)

	f, err := os.Create("version/version_new.go")
	die(err)
	defer f.Close()

	tpl.Execute(f, struct {
		Version    string
		BuildDate  string
		CommitHash string
		Author     string
	}{
		Version:    string(version),
		BuildDate:  time.Now().Format(time.RFC850),
		CommitHash: string(cmdOutput),
		Author:     "Alain Lefebvre",
	})
}

func die(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

repository: hartfordfive/kafka-topic-tailer

repo_name: hartfordfive/kafka-topic-tailer

gha_license_id: MIT


text:
// Package main as wedit entry point
// Part of `wedit` project (https://wedit.io) (https://github.com/sofmon/wedit)
// Use of this source code is governed by MIT license that can be found in the LICENSE file.
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"github.com/sofmon/wedit/builder"
	"github.com/sofmon/wedit/service"
)

const version = "1"

func init() {
	log.SetFlags(0)
	log.SetOutput(os.Stdout)
}

// Action requested when running wedit
type Action string

const (
	actionHelp    Action = "help"
	actionVersion Action = "version"
	actionInit    Action = "init"
	actionEdit    Action = "edit"
	actionBuild   Action = "build"
	actionClean   Action = "clean"
)

const initPage = `

<title>wedit init page</title>

This is editable text

`

func determineAction() Action {

	if len(os.Args) < 2 {
		return actionEdit
	}

	return Action(strings.ToLower(os.Args[1]))
}

func main() {

	action := determineAction()

	switch action {

	case actionInit:
		initialize()

	case actionEdit:
		edit()

	case actionBuild:
		build()

	case actionClean:
		clean()

	case actionVersion:
		log.Printf("★ wedit version: %s\n", version)

	case actionHelp:
		printHelp()

	default:
		log.Printf("✘ unknown action '%s' ... printing 'help' text\n", action)
		printHelp()
		os.Exit(1)
	}

	os.Exit(0)
}

func initialize() {

	_, err := os.Stat("wedit.json")
	if err == nil {
		log.Fatalf("✘ file 'wedit.json' already exists")
	}
	if !os.IsNotExist(err) {
		log.Fatalf("✘ unable to verify 'wedit.json' file due to an error: %v\n", err)
	}

	cfg := struct {
		TemplateFolder      string   `json:"templateFolder"`
		ContentFolder       string   `json:"contentFolder"`
		PublicFolder        string   `json:"publicFolder"`
		VariationFolderName string   `json:"variationFolderName"`
		RootJSONFile        string   `json:"rootJsonFile"`
		RootKeyPrefix       string   `json:"rootKeyPrefix"`
		EditAttr            string   `json:"editAttribute"`
		RepeatAttr          string   `json:"repeatAttribute"`
		IncludeAttr         string   `json:"includeAttribute"`
		KeepWeditAttrs      bool     `json:"keepAttributes"`
		DefaultPage         string   `json:"defaultPage"`
		AllowedPageExt      []string `json:"allowedPageExt"`
		Host                string   `json:"host"`
		Port                int      `json:"port"`
		OpenBrowser         bool     `json:"openBrowser"`
		DarkMode            bool     `json:"darkMode"`
	}{
		TemplateFolder:      "template",
		ContentFolder:       "content",
		PublicFolder:        "public",
		VariationFolderName: "-",
		RootJSONFile:        "root.json",
		RootKeyPrefix:       "!",
		EditAttr:            "wedit",
		RepeatAttr:          "wedit-repeat",
		IncludeAttr:         "wedit-include",
		KeepWeditAttrs:      false,
		DefaultPage:         "index.html",
		AllowedPageExt:      []string{".html"},
		Host:                "localhost",
		Port:                5000,
		OpenBrowser:         true,
		DarkMode:            false,
	}

	if _, err := os.Stat(cfg.TemplateFolder); os.IsNotExist(err) {
		err = os.MkdirAll(cfg.TemplateFolder, 0755)
		if err != nil {
			log.Fatalf("✘ unable to create template folder '%s' due to an error: %v\n", cfg.TemplateFolder, err)
		}
	}

	if _, err := os.Stat(cfg.ContentFolder); os.IsNotExist(err) {
		err = os.MkdirAll(cfg.ContentFolder, 0755)
		if err != nil {
			log.Fatalf("✘ unable to create content folder '%s' due to an error: %v\n", cfg.ContentFolder, err)
		}
	}

	if _, err := os.Stat(cfg.PublicFolder); os.IsNotExist(err) {
		err = os.MkdirAll(cfg.PublicFolder, 0755)
		if err != nil {
			log.Fatalf("✘ unable to create public folder '%s' due to an error: %v\n", cfg.PublicFolder, err)
		}
	}

	cfgBytes, err := json.Marshal(cfg)
	if err != nil {
		panic(err)
	}

	err = ioutil.WriteFile("wedit.json", cfgBytes, 0777)
	if err != nil {
		log.Fatalf("✘ unable to save 'wedit.json' file due to an error: %v\n", err)
	}

	if _, err := os.Stat(cfg.TemplateFolder + "/" + cfg.DefaultPage); os.IsNotExist(err) {
		err = ioutil.WriteFile(cfg.TemplateFolder+"/"+cfg.DefaultPage, []byte(initPage), 0777)
		if err != nil {
			log.Fatalf("✘ unable to save 'index.html' file due to an error: %v\n", err)
		}
	}

	log.Println("✔ folder ready, run 'wedit' to start editing")
}

func edit() {

	err := LoadConfig()
	if err != nil {
		log.Fatalf("✘ unable to read config file. Did you forget `wedit init`? Error: %v\n", err)
	}
	err = builder.LoadConfig("wedit.json")
	if err != nil {
		log.Fatalf("✘ unable to read config file. Did you forget `wedit init`? Error: %v\n", err)
	}
	err = service.LoadConfig("wedit.json")
	if err != nil {
		log.Fatalf("✘ unable to read config file. Did you forget `wedit init`? Error: %v\n", err)
	}

	done := make(chan error)

	go func() {
		done <- service.ListenAndServe()
	}()

	if cfg.OpenBrowser {
		time.Sleep(1 * time.Second) // wait 1s for web server to start
		openBrowser(fmt.Sprintf("http://%s:%d/", cfg.Host, cfg.Port))
	}

	log.Printf("✔ running local http server on http://%s:%d/\n", cfg.Host, cfg.Port)

	err = <-done
	if err != nil {
		log.Fatalf("✘ error in serving wedit http requests doe to an error: %v\n", err)
	}
}

func build() {

	err := builder.LoadConfig("wedit.json")
	if err != nil {
		log.Fatalf("✘ unable to read config file. Did you forget `wedit init`? Error: %v\n", err)
	}

	err = builder.RebuildAll()
	if err != nil {
		log.Fatalf("✘ error in building public folder doe to an error: %v\n", err)
	}
}

func clean() {

	err := builder.LoadConfig("wedit.json")
	if err != nil {
		log.Fatalf("✘ unable to read config file. Did you forget `wedit init`? Error: %v\n", err)
	}

	err = builder.CleanUp()
	if err != nil {
		log.Fatalf("✘ error in cleaning public and content folders doe to an error: %v\n", err)
	}
}

func openBrowser(url string) {
	var cmd *exec.Cmd

	switch runtime.GOOS {

	case "darwin":
		cmd = exec.Command("open", url)
	case "windows":
		cmd = exec.Command(
			filepath.Join(os.Getenv("SYSTEMROOT"), "System32", "rundll32.exe"),
			"url.dll,FileProtocolHandler",
			url,
		)
	case "linux":
		cmd = exec.Command("xdg-open", url)
	}

	if cmd != nil {
		err := cmd.Start()
		if err != nil {
			log.Fatalf("✘ unable to start browser due to an error: %v\n", err)
		}
	}
}

func printHelp() {
	log.Print(
		"\n┊ web edit tool from https://wedit.io/\n┊\n" +
			"┊ usage: wedit [action]\n┊\n" +
			"┊ actions:\n" +
			"┊   edit    - edit current website using the default web browser (default action)\n" +
			"┊   init    - prepare the current folder as a wedit project\n" +
			"┊   build   - [re]generate the static website, for example after template change\n" +
			"┊   clean   - clean up content and public folder from items not matching template folder\n" +
			"┊   version - prints wedit version\n" +
			"┊   coffee  - support wedit maintainers by donating through PayPal\n" +
			"┊   help    - prints this message\n\n",
	)
}

repository: sofmon/wedit

repo_name: sofmon/wedit


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// updateable_storage.h
//
// Identification: src/include/codegen/updateable_storage.h
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include "codegen/codegen.h"
#include "codegen/compact_storage.h"
#include "codegen/value.h"

namespace peloton {
namespace codegen {

//===----------------------------------------------------------------------===//
// A storage area where slots can be updated.
//===----------------------------------------------------------------------===//
class UpdateableStorage {
 public:
  // Constructor
  UpdateableStorage() : storage_size_(0), storage_type_(nullptr) {}

  // Add the given type to the storage format. We return the index that this
  // value can be found it (i.e., the index to pass into Get() to get the value)
  uint32_t AddType(type::Type::TypeId type);

  // Construct the final LLVM type given all the types that'll be stored
  llvm::Type *Finalize(CodeGen &codegen);

  // Get the value at a specific index into the storage area
  codegen::Value GetValueAt(CodeGen &codegen, llvm::Value *area_start,
                            uint64_t index) const;

  // Get the value at a specific index into the storage area
  void SetValueAt(CodeGen &codegen, llvm::Value *area_start, uint64_t index,
                  const codegen::Value &value) const;

  // Return the format of the storage area
  llvm::Type *GetStorageType() const { return storage_type_; }

  // Return the total bytes required by this storage format
  uint32_t GetStorageSize() const { return storage_size_; }

  // Return the number of elements this format is configured to handle
  uint32_t GetNumElements() const {
    return static_cast<uint32_t>(types_.size());
  }

 private:
  // The types we store in the storage area
  std::vector<type::Type::TypeId> types_;

  // The physical storage format
  std::vector<CompactStorage::EntryInfo> storage_format_;

  // The total number of bytes needed for this format
  uint32_t storage_size_;

  // The finalized LLVM type that represents this storage area
  llvm::Type *storage_type_;
};

}  // namespace codegen
}  // namespace peloton

extension: h


text:
SUMMARY = "ZDoom"
# TODO: Change this
LICENSE = "CLOSED"
SECTION = "games"

INHIBIT_DEFAULT_DEPS = "1"

SRC_URI = "file://zdoom.service"

inherit systemd

do_install() {
    install -d ${D}${systemd_system_unitdir}
    install -m 644 ${WORKDIR}/zdoom.service ${D}${systemd_system_unitdir}/
}

#FILES_${PN} = "${systemd_system_unitdir}"
RDEPENDS_${PN} = "weston-init zdoom"
SYSTEMD_SERVICE_${PN} = "zdoom.service"

repository: JPEWdev/yocto-doom-demo

repo_name: JPEWdev/yocto-doom-demo

branch_name: refs/heads/main

gha_language: Python


text:
// Code generated by entc, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"

	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/karashiiro/gacha/ent/drop"
	"github.com/karashiiro/gacha/ent/series"
)

// DropCreate is the builder for creating a Drop entity.
type DropCreate struct {
	config
	mutation *DropMutation
	hooks    []Hook
}

// SetObjectID sets the "object_id" field.
func (dc *DropCreate) SetObjectID(u uint32) *DropCreate {
	dc.mutation.SetObjectID(u)
	return dc
}

// SetRate sets the "rate" field.
func (dc *DropCreate) SetRate(f float32) *DropCreate {
	dc.mutation.SetRate(f)
	return dc
}

// SetSeriesID sets the "series_id" field.
func (dc *DropCreate) SetSeriesID(u uint32) *DropCreate {
	dc.mutation.SetSeriesID(u)
	return dc
}

// SetID sets the "id" field.
func (dc *DropCreate) SetID(u uint32) *DropCreate {
	dc.mutation.SetID(u)
	return dc
}

// SetSeries sets the "series" edge to the Series entity.
func (dc *DropCreate) SetSeries(s *Series) *DropCreate {
	return dc.SetSeriesID(s.ID)
}

// Mutation returns the DropMutation object of the builder.
func (dc *DropCreate) Mutation() *DropMutation {
	return dc.mutation
}

// Save creates the Drop in the database.
func (dc *DropCreate) Save(ctx context.Context) (*Drop, error) {
	var (
		err  error
		node *Drop
	)
	if len(dc.hooks) == 0 {
		if err = dc.check(); err != nil {
			return nil, err
		}
		node, err = dc.sqlSave(ctx)
	} else {
		var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
			mutation, ok := m.(*DropMutation)
			if !ok {
				return nil, fmt.Errorf("unexpected mutation type %T", m)
			}
			if err = dc.check(); err != nil {
				return nil, err
			}
			dc.mutation = mutation
			node, err = dc.sqlSave(ctx)
			mutation.done = true
			return node, err
		})
		for i := len(dc.hooks) - 1; i >= 0; i-- {
			mut = dc.hooks[i](mut)
		}
		if _, err := mut.Mutate(ctx, dc.mutation); err != nil {
			return nil, err
		}
	}
	return node, err
}

// SaveX calls Save and panics if Save returns an error.
func (dc *DropCreate) SaveX(ctx context.Context) *Drop {
	v, err := dc.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// check runs all checks and user-defined validators on the builder.
func (dc *DropCreate) check() error {
	if _, ok := dc.mutation.ObjectID(); !ok {
		return &ValidationError{Name: "object_id", err: errors.New("ent: missing required field \"object_id\"")}
	}
	if _, ok := dc.mutation.Rate(); !ok {
		return &ValidationError{Name: "rate", err: errors.New("ent: missing required field \"rate\"")}
	}
	if _, ok := dc.mutation.SeriesID(); !ok {
		return &ValidationError{Name: "series_id", err: errors.New("ent: missing required field \"series_id\"")}
	}
	if _, ok := dc.mutation.SeriesID(); !ok {
		return &ValidationError{Name: "series", err: errors.New("ent: missing required edge \"series\"")}
	}
	return nil
}

func (dc *DropCreate) sqlSave(ctx context.Context) (*Drop, error) {
	_node, _spec := dc.createSpec()
	if err := sqlgraph.CreateNode(ctx, dc.driver, _spec); err != nil {
		if cerr, ok := isSQLConstraintError(err); ok {
			err = cerr
		}
		return nil, err
	}
	if _node.ID == 0 {
		id := _spec.ID.Value.(int64)
		_node.ID = uint32(id)
	}
	return _node, nil
}

func (dc *DropCreate) createSpec() (*Drop, *sqlgraph.CreateSpec) {
	var (
		_node = &Drop{config: dc.config}
		_spec = &sqlgraph.CreateSpec{
			Table: drop.Table,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeUint32,
				Column: drop.FieldID,
			},
		}
	)
	if id, ok := dc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = id
	}
	if value, ok := dc.mutation.ObjectID(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeUint32,
			Value:  value,
			Column: drop.FieldObjectID,
		})
		_node.ObjectID = value
	}
	if value, ok := dc.mutation.Rate(); ok {
		_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
			Type:   field.TypeFloat32,
			Value:  value,
			Column: drop.FieldRate,
		})
		_node.Rate = value
	}
	if nodes := dc.mutation.SeriesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   drop.SeriesTable,
			Columns: []string{drop.SeriesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: &sqlgraph.FieldSpec{
					Type:   field.TypeUint32,
					Column: series.FieldID,
				},
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.SeriesID = nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// DropCreateBulk is the builder for creating many Drop entities in bulk.
type DropCreateBulk struct {
	config
	builders []*DropCreate
}

// Save creates the Drop entities in the database.
func (dcb *DropCreateBulk) Save(ctx context.Context) ([]*Drop, error) {
	specs := make([]*sqlgraph.CreateSpec, len(dcb.builders))
	nodes := make([]*Drop, len(dcb.builders))
	mutators := make([]Mutator, len(dcb.builders))
	for i := range dcb.builders {
		func(i int, root context.Context) {
			builder := dcb.builders[i]
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*DropMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				nodes[i], specs[i] = builder.createSpec()
				var err error
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, dcb.builders[i+1].mutation)
				} else {
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, dcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
						if cerr, ok := isSQLConstraintError(err); ok {
							err = cerr
						}
					}
				}
				mutation.done = true
				if err != nil {
					return nil, err
				}
				if nodes[i].ID == 0 {
					id := specs[i].ID.Value.(int64)
					nodes[i].ID = uint32(id)
				}
				return nodes[i], nil
			})
			for i := len(builder.hooks) - 1; i >= 0; i-- {
				mut = builder.hooks[i](mut)
			}
			mutators[i] = mut
		}(i, ctx)
	}
	if len(mutators) > 0 {
		if _, err := mutators[0].Mutate(ctx, dcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

// SaveX is like Save, but panics if an error occurs.
func (dcb *DropCreateBulk) SaveX(ctx context.Context) []*Drop {
	v, err := dcb.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

license: Unlicense

repository: karashiiro/gacha

repo_name: karashiiro/gacha


text:
SECTION = "devel/chicken"
DESCRIPTION = "Serialize SXML to XML and HTML"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://sxml-serializer.meta;md5=21608bfc133fd7611a075bba40eae49d"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/sxml-serializer/sxml-serializer-${PV}.tar.gz"

SRC_URI[md5sum] = "912165b1ee4102accedfd133afa5f713"
SRC_URI[sha256sum] = "2a99e8e964792a437702f95e79f548e405c205a19c23e0b8b0b26e52cc2d9c8e"

S = "${WORKDIR}/sxml-serializer-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
package main

import (
	"net/http"
	_ "net/http/pprof"

	conf "github.com/pion/ion/pkg/conf/biz"
	"github.com/pion/ion/pkg/discovery"
	"github.com/pion/ion/pkg/log"
	"github.com/pion/ion/pkg/node/biz"
	"github.com/pion/ion/pkg/signal"
)

func init() {
	log.Init(conf.Log.Level)
	signal.Init(conf.Signal.Host, conf.Signal.Port, conf.Signal.Cert, conf.Signal.Key, biz.Entry)
}

func close() {
	biz.Close()
}

func main() {
	log.Infof("--- Starting Biz Node ---")

	if conf.Global.Pprof != "" {
		go func() {
			log.Infof("Start pprof on %s", conf.Global.Pprof)
			http.ListenAndServe(conf.Global.Pprof, nil)
		}()
	}

	serviceNode := discovery.NewServiceNode(conf.Etcd.Addrs, conf.Global.Dc)
	serviceNode.RegisterNode("biz", "node-biz", "biz-channel-id")

	rpcID := serviceNode.GetRPCChannel()
	eventID := serviceNode.GetEventChannel()
	biz.Init(conf.Global.Dc, serviceNode.NodeInfo().ID, rpcID, eventID, conf.Nats.URL)

	serviceWatcher := discovery.NewServiceWatcher(conf.Etcd.Addrs, conf.Global.Dc)
	serviceWatcher.WatchServiceNode("islb", biz.WatchServiceNodes)

	defer close()
	select {}
}

repository: zyberzero/secure-videoconference

repo_name: zyberzero/secure-videoconference

gha_language: C


text:
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///
/// @file contiguous_iterator.hpp
///

#ifndef BSL_CONTIGUOUS_ITERATOR_HPP
#define BSL_CONTIGUOUS_ITERATOR_HPP

#include "bsl/ensures.hpp"
#include "bsl/expects.hpp"
#include "bsl/safe_idx.hpp"
#include "bsl/safe_integral.hpp"
#include "bsl/unlikely.hpp"

namespace bsl
{
    /// @class bsl::contiguous_iterator
    ///
    /// <!-- description -->
    ///   @brief Provides a contiguous iterator as defined by the C++
    ///     specification, with the follwing differences:
    ///     - The difference type that we use is unsigned instead of a
    ///       signed type, which causes a lot of problems with AUTOSAR
    ///       compliance as signed/unsigned conversions and overflow are a
    ///       huge problem with the standard library. This iterator type is
    ///       used by all of the "view" type containers including the
    ///       bsl::span, bsl::array and bsl::string_view
    ///     - We do not provide any of the *, -> or [] accessors as none of
    ///       these accessors are compliant with AUTOSAR. Instead, we provide
    ///       a get_if() function, which returns a pointer to the element
    ///       being accessed by the iterator, or a nullptr if the iterator is
    ///       invalid or is the same as end(). As a result, ranged based for
    ///       loops are not supported, and instead, use a view's for_each
    ///       function which will perform the same action, with less overhead,
    ///       and better safety.
    ///     - The iterator is always inbounds, equal to end() or is invalid.
    ///       Traditional iterators can be anything, they can overrun,
    ///       underrun, and everyting in between. If this iterator is valid,
    ///       the index is always bounded by the size of the array it is
    ///       pointing to, or is equal to end(). Wrapping, overruns, and
    ///       underruns are not possible.
    ///     - We don't implement all of the iterator functions that make up
    ///       a contiguous iterator as defined by the C++ spec. Some of these
    ///       can be added in future upon request.
    ///   @include example_contiguous_iterator_overview.hpp
    ///
    /// <!-- template parameters -->
    ///   @tparam T the type of element being iterated.
    ///
    template<typename T>
    class contiguous_iterator final
    {
    public:
        /// @brief alias for: T
        using value_type = T;
        /// @brief alias for: safe_umx
        using size_type = safe_umx;
        /// @brief alias for: safe_umx
        using difference_type = safe_umx;
        /// @brief alias for: safe_idx
        using index_type = safe_idx;
        /// @brief alias for: T &
        using reference_type = T &;
        /// @brief alias for: T const &
        using const_reference_type = T const &;
        /// @brief alias for: T *
        using pointer_type = T *;
        /// @brief alias for: T const *
        using const_pointer_type = T const *;

        /// <!-- description -->
        ///   @brief Creates a contiguous iterator given a ptr to an array
        ///     and the total number of elements in the array. Note that you
        ///     should not use this directly but instead, should use the
        ///     container's begin() function.
        ///
        /// <!-- inputs/outputs -->
        ///   @param pudm_ptr a pointer to the array being iterated
        ///   @param count the number of elements in the array being iterated
        ///   @param i the initial index of the iterator
        ///
        constexpr contiguous_iterator(      // --
            pointer_type const pudm_ptr,    // --
            size_type const &count,         // --
            index_type const &i) noexcept
            : m_ptr{pudm_ptr}, m_count{count}, m_i{i}
        {
            if (unlikely(nullptr == pudm_ptr)) {
                m_count = {};
                m_i = {};
                return;
            }

            expects(count.is_valid_and_checked());
            expects(i.is_valid());
            expects(i <= count);
        }

        /// <!-- description -->
        ///   @brief Destroyes a previously created bsl::contiguous_iterator
        ///
        constexpr ~contiguous_iterator() noexcept = default;

        /// <!-- description -->
        ///   @brief copy constructor
        ///
        /// <!-- inputs/outputs -->
        ///   @param o the object being copied
        ///
        constexpr contiguous_iterator(contiguous_iterator const &o) noexcept = default;

        /// <!-- description -->
        ///   @brief move constructor
        ///
        /// <!-- inputs/outputs -->
        ///   @param mut_o the object being moved
        ///
        constexpr contiguous_iterator(contiguous_iterator &&mut_o) noexcept = default;

        /// <!-- description -->
        ///   @brief copy assignment
        ///
        /// <!-- inputs/outputs -->
        ///   @param o the object being copied
        ///   @return a reference to *this
        ///
        [[maybe_unused]] constexpr auto operator=(contiguous_iterator const &o) &noexcept
            -> contiguous_iterator & = default;

        /// <!-- description -->
        ///   @brief move assignment
        ///
        /// <!-- inputs/outputs -->
        ///   @param mut_o the object being moved
        ///   @return a reference to *this
        ///
        [[maybe_unused]] constexpr auto operator=(contiguous_iterator &&mut_o) &noexcept
            -> contiguous_iterator & = default;

        /// <!-- description -->
        ///   @brief Returns a pointer to the array being iterated
        ///   @include contiguous_iterator/example_contiguous_iterator_data.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns a pointer to the array being iterated
        ///
        [[nodiscard]] constexpr auto
        data() noexcept -> pointer_type
        {
            return m_ptr;
        }

        /// <!-- description -->
        ///   @brief Returns a pointer to the array being iterated
        ///   @include contiguous_iterator/example_contiguous_iterator_data.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns a pointer to the array being iterated
        ///
        [[nodiscard]] constexpr auto
        data() const noexcept -> const_pointer_type
        {
            return m_ptr;
        }

        /// <!-- description -->
        ///   @brief Returns the number of elements in the array being iterated
        ///   @include contiguous_iterator/example_contiguous_iterator_size.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns the number of elements in the array being iterated
        ///
        [[nodiscard]] constexpr auto
        size() const noexcept -> size_type const &
        {
            ensures(m_count.is_valid_and_checked());
            return m_count;
        }

        /// <!-- description -->
        ///   @brief Returns the iterator's current index. If the iterator is
        ///     at the end, this function returns size().
        ///   @include contiguous_iterator/example_contiguous_iterator_index.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns the iterator's current index
        ///
        [[nodiscard]] constexpr auto
        // NOLINTNEXTLINE(bsl-using-ident-unique-namespace)
        index() const noexcept -> index_type const &
        {
            ensures(m_i.is_valid());
            ensures(m_i <= m_count);
            ensures(m_i >= index_type::magic_0());

            return m_i;
        }

        /// <!-- description -->
        ///   @brief Returns nullptr == data()
        ///   @include contiguous_iterator/example_contiguous_iterator_empty.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns nullptr == data()
        ///
        [[nodiscard]] constexpr auto
        empty() const noexcept -> bool
        {
            return m_count.is_zero();
        }

        /// <!-- description -->
        ///   @brief Returns data() == nullptr;
        ///   @include contiguous_iterator/example_contiguous_iterator_is_invalid.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns data() == nullptr;
        ///
        [[nodiscard]] constexpr auto
        is_invalid() const noexcept -> bool
        {
            return this->data() == nullptr;
        }

        /// <!-- description -->
        ///   @brief Returns data() != nullptr
        ///   @include contiguous_iterator/example_contiguous_iterator_is_valid.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns data() != nullptr
        ///
        [[nodiscard]] constexpr auto
        is_valid() const noexcept -> bool
        {
            return this->data() != nullptr;
        }

        /// <!-- description -->
        ///   @brief Returns index() == size()
        ///   @include contiguous_iterator/example_contiguous_iterator_is_end.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns index() == size()
        ///
        [[nodiscard]] constexpr auto
        is_end() const noexcept -> bool
        {
            return this->index() == this->size();
        }

        /// <!-- description -->
        ///   @brief Returns a pointer to the instance of T stored at the
        ///     iterator's current index. If the index is out of bounds,
        ///     or the iterator is invalid, this function returns a nullptr.
        ///   @include contiguous_iterator/example_contiguous_iterator_get_if.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns a pointer to the instance of T stored at the
        ///     iterator's current index. If the index is out of bounds,
        ///     or the iterator is invalid, this function returns a nullptr.
        ///
        [[nodiscard]] constexpr auto
        get_if() noexcept -> pointer_type
        {
            if (unlikely(nullptr == m_ptr)) {
                return nullptr;
            }

            if (unlikely(m_i >= m_count)) {
                return nullptr;
            }

            return &m_ptr[m_i.get()];
        }

        /// <!-- description -->
        ///   @brief Returns a pointer to the instance of T stored at the
        ///     iterator's current index. If the index is out of bounds,
        ///     or the iterator is invalid, this function returns a nullptr.
        ///   @include contiguous_iterator/example_contiguous_iterator_get_if.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns a pointer to the instance of T stored at the
        ///     iterator's current index. If the index is out of bounds,
        ///     or the iterator is invalid, this function returns a nullptr.
        ///
        [[nodiscard]] constexpr auto
        get_if() const noexcept -> const_pointer_type
        {
            if (unlikely(nullptr == m_ptr)) {
                return nullptr;
            }

            if (unlikely(m_i >= m_count)) {
                return nullptr;
            }

            return &m_ptr[m_i.get()];
        }

        /// <!-- description -->
        ///   @brief Returns *this
        ///   @include contiguous_iterator/example_contiguous_iterator_operator_star.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns *this
        ///
        [[nodiscard]] constexpr auto
        operator*() noexcept -> value_type &
        {
            return m_ptr[m_i.get()];
        }

        /// <!-- description -->
        ///   @brief Returns *this
        ///   @include contiguous_iterator/example_contiguous_iterator_operator_star.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return Returns *this
        ///
        [[nodiscard]] constexpr auto
        operator*() const noexcept -> value_type const &
        {
            return m_ptr[m_i.get()];
        }

        /// <!-- description -->
        ///   @brief Increments the iterator
        ///   @include contiguous_iterator/example_contiguous_iterator_increment.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return returns *this
        ///
        [[maybe_unused]] constexpr auto
        operator++() noexcept -> contiguous_iterator &
        {
            if (unlikely(m_i >= m_count)) {
                return *this;
            }

            ++m_i;

            ensures(m_i.is_valid());
            ensures(m_i <= m_count);
            return *this;
        }

        /// <!-- description -->
        ///   @brief Decrements the iterator
        ///   @include contiguous_iterator/example_contiguous_iterator_decrement.hpp
        ///
        /// <!-- inputs/outputs -->
        ///   @return returns *this
        ///
        [[maybe_unused]] constexpr auto
        operator--() noexcept -> contiguous_iterator &
        {
            if (unlikely(m_i.is_zero())) {
                return *this;
            }

            --m_i;

            ensures(m_i.is_valid());
            ensures(m_i >= index_type::magic_0());
            return *this;
        }

    private:
        /// @brief stores a pointer to the array being iterated
        pointer_type m_ptr;
        /// @brief stores the number of elements in the array being iterated
        size_type m_count;
        /// @brief stores the current index in the array being iterated
        index_type m_i;
    };

    /// <!-- description -->
    ///   @brief Returns true if the provided contiguous iterators point to
    ///     the same array and the same index.
    ///   @include contiguous_iterator/example_contiguous_iterator_equals.hpp
    ///   @related bsl::contiguous_iterator
    ///
    /// <!-- inputs/outputs -->
    ///   @tparam T the type of element being iterated.
    ///   @param lhs the left hand side of the operation
    ///   @param rhs the rhs hand side of the operation
    ///   @return Returns true if the provided contiguous iterators point to
    ///     the same array and the same index.
    ///
    template<typename T>
    [[nodiscard]] constexpr auto
    operator==(contiguous_iterator<T> const &lhs, contiguous_iterator<T> const &rhs) noexcept
        -> bool
    {
        return lhs.index() == rhs.index();
    }

    /// <!-- description -->
    ///   @brief Returns true if the provided contiguous iterators do not point
    ///     to the same array or the same index.
    ///   @include contiguous_iterator/example_contiguous_iterator_not_equals.hpp
    ///   @related bsl::contiguous_iterator
    ///
    /// <!-- inputs/outputs -->
    ///   @tparam T the type of element being iterated.
    ///   @param lhs the left hand side of the operation
    ///   @param rhs the rhs hand side of the operation
    ///   @return Returns true if the provided contiguous iterators do not point
    ///     to the same array or the same index.
    ///
    template<typename T>
    [[nodiscard]] constexpr auto
    operator!=(contiguous_iterator<T> const &lhs, contiguous_iterator<T> const &rhs) noexcept
        -> bool
    {
        return !(lhs == rhs);
    }

    /// <!-- description -->
    ///   @brief Returns lhs.index() < rhs.index()
    ///   @include contiguous_iterator/example_contiguous_iterator_lt.hpp
    ///   @related bsl::contiguous_iterator
    ///
    /// <!-- inputs/outputs -->
    ///   @tparam T the type of element being iterated.
    ///   @param lhs the left hand side of the operation
    ///   @param rhs the rhs hand side of the operation
    ///   @return Returns lhs.index() < rhs.index()
    ///
    template<typename T>
    [[nodiscard]] constexpr auto
    operator<(contiguous_iterator<T> const &lhs, contiguous_iterator<T> const &rhs) noexcept -> bool
    {
        return lhs.index() < rhs.index();
    }

    /// <!-- description -->
    ///   @brief Returns lhs.index() > rhs.index()
    ///   @include contiguous_iterator/example_contiguous_iterator_gt.hpp
    ///   @related bsl::contiguous_iterator
    ///
    /// <!-- inputs/outputs -->
    ///   @tparam T the type of element being iterated.
    ///   @param lhs the left hand side of the operation
    ///   @param rhs the rhs hand side of the operation
    ///   @return Returns lhs.index() > rhs.index()
    ///
    template<typename T>
    [[nodiscard]] constexpr auto
    operator>(contiguous_iterator<T> const &lhs, contiguous_iterator<T> const &rhs) noexcept -> bool
    {
        return lhs.index() > rhs.index();
    }
}

#endif

repository: Bareflank/bsl

repo_name: Bareflank/bsl

gha_license_id: NOASSERTION

extension: hpp


text:
// This file is copied from https://github.com/influxdata/telegraf

package system

import (
	"os"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/net"
)

// PS XXX
type PS interface {
	CPUTimes(perCPU, totalCPU bool) ([]cpu.TimesStat, error)
	DiskUsage(mountPointFilter []string, fstypeExclude []string) ([]*disk.UsageStat, error)
	NetIO() ([]net.IOCountersStat, error)
	NetProto() ([]net.ProtoCountersStat, error)
	DiskIO() (map[string]disk.IOCountersStat, error)
	VMStat() (*mem.VirtualMemoryStat, error)
	SwapStat() (*mem.SwapMemoryStat, error)
	NetConnections() ([]net.ConnectionStat, error)
}

type systemPS struct{}

func (s *systemPS) CPUTimes(perCPU, totalCPU bool) ([]cpu.TimesStat, error) {
	var cpuTimes []cpu.TimesStat
	if perCPU {
		if perCPUTimes, err := cpu.Times(true); err == nil {
			cpuTimes = append(cpuTimes, perCPUTimes...)
		} else {
			return nil, err
		}
	}
	if totalCPU {
		if totalCPUTimes, err := cpu.Times(false); err == nil {
			cpuTimes = append(cpuTimes, totalCPUTimes...)
		} else {
			return nil, err
		}
	}
	return cpuTimes, nil
}

func (s *systemPS) DiskUsage(
	mountPointFilter []string,
	fstypeExclude []string,
) ([]*disk.UsageStat, error) {
	parts, err := disk.Partitions(true)
	if err != nil {
		return nil, err
	}

	// Make a "set" out of the filter slice
	mountPointFilterSet := make(map[string]bool)
	for _, filter := range mountPointFilter {
		mountPointFilterSet[filter] = true
	}
	fstypeExcludeSet := make(map[string]bool)
	for _, filter := range fstypeExclude {
		fstypeExcludeSet[filter] = true
	}

	var usage []*disk.UsageStat

	for _, p := range parts {
		if len(mountPointFilter) > 0 {
			// If the mount point is not a member of the filter set,
			// don't gather info on it.
			_, ok := mountPointFilterSet[p.Mountpoint]
			if !ok {
				continue
			}
		}
		mountpoint := os.Getenv("HOST_MOUNT_PREFIX") + p.Mountpoint
		if _, err := os.Stat(mountpoint); err == nil {
			du, err := disk.Usage(mountpoint)
			if err != nil {
				return nil, err
			}
			du.Path = p.Mountpoint
			// If the mount point is a member of the exclude set,
			// don't gather info on it.
			_, ok := fstypeExcludeSet[p.Fstype]
			if ok {
				continue
			}
			du.Fstype = p.Fstype
			usage = append(usage, du)
		}
	}

	return usage, nil
}

func (s *systemPS) NetProto() ([]net.ProtoCountersStat, error) {
	return net.ProtoCounters(nil)
}

func (s *systemPS) NetIO() ([]net.IOCountersStat, error) {
	return net.IOCounters(true)
}

func (s *systemPS) NetConnections() ([]net.ConnectionStat, error) {
	return net.Connections("all")
}

func (s *systemPS) DiskIO() (map[string]disk.IOCountersStat, error) {
	return disk.IOCounters()
}

func (s *systemPS) VMStat() (*mem.VirtualMemoryStat, error) {
	return mem.VirtualMemory()
}

func (s *systemPS) SwapStat() (*mem.SwapMemoryStat, error) {
	return mem.SwapMemory()
}


text:
package hashed_index

import (
	"github.com/eosspark/eos-go/libraries/container"
	"github.com/eosspark/eos-go/libraries/interprocess/allocator"
	. "github.com/eosspark/eos-go/libraries/interprocess/offsetptr"
	"github.com/eosspark/eos-go/libraries/multiindex"
	"unsafe"
)

// template type HashedIndex(FinalIndex,FinalNode,SuperIndex,SuperNode,Value,Key,KeyFunc,Hasher,Allocator)
type Key = int
type Value = int

var Allocator allocator.MemoryManager = nil
var KeyFunc = func(Value) Key { return 0 }
var Hasher = func(h Key) uintptr { return container.Hash(h) }

//TODO nonunique_hashtable const Multiply = false

type HashedIndex struct {
	super Pointer `*SuperIndex` // index on the HashedUniqueIndex, IndexBase is the last super index
	final Pointer `*FinalIndex` // index under the HashedUniqueIndex, MultiIndex is the final index
	b     Pointer `*Buckets`
	l     uintptr
}

func (h *HashedIndex) init(final *FinalIndex) {
	h.final.Set(unsafe.Pointer(final))
	h.super.Set(unsafe.Pointer(NewSuperIndex()))
	h.b.Set(unsafe.Pointer(NewBuckets(0)))
	//h.b.NewBuckets(0)
	h.l = 0
	(*SuperIndex)(h.super.Get()).init(final)
}

func (h *HashedIndex) free() {
	(*SuperIndex)(h.super.Get()).free()
	Allocator.DeAllocate(unsafe.Pointer(h))
}

/*generic class*/
type SuperIndex struct {
	init    func(*FinalIndex)
	free    func()
	clear   func()
	insert  func(Value, *FinalNode) (*SuperNode, bool)
	erase   func(*SuperNode) bool
	erase_  func(multiindex.IteratorType)
	modify  func(*SuperNode) (*SuperNode, bool)
	modify_ func(multiindex.IteratorType, func(*Value)) bool
}

func NewSuperIndex() *SuperIndex {
	return (*SuperIndex)(Allocator.Allocate(unsafe.Sizeof(SuperIndex{})))
}

/*generic class*/
type FinalIndex struct {
	insert func(Value) (*FinalNode, bool)
	erase  func(*FinalNode)
	modify func(func(*Value), *FinalNode) (*FinalNode, bool)
}

type Buckets struct {
	array Pointer `Pointer<*HashedIndexNode>`
	len   uintptr
}

const _SizeofBuckets = unsafe.Sizeof(Buckets{})
const _SizeofBucket = unsafe.Sizeof(&HashedIndexNode{})

func NewBuckets(size uintptr) *Buckets {
	b := (*Buckets)(Allocator.Allocate(_SizeofBuckets))
	if size == 0 {
		size++
	}
	b.array.Set(Allocator.Allocate(_SizeofBucket * size))
	//b.array = (**HashedIndexNode)(Allocator.Allocate(_SizeofBucket * size))
	allocator.Memset(b.array.Get(), 0, _SizeofBucket*size)
	//allocator.Memset(unsafe.Pointer(b.array), 0, _SizeofBucket*size)
	b.len = size
	return b
}

func (b *Buckets) Put(i uintptr, e *HashedIndexNode) {
	(*Pointer)(unsafe.Pointer(uintptr(b.array.Get()) + _SizeofBucket*i)).Set(unsafe.Pointer(e))
	//*(**HashedIndexNode)(unsafe.Pointer(uintptr(b.array.Get()) + _SizeofBucket*i)) = e
	//*(**HashedIndexNode)(unsafe.Pointer(uintptr(unsafe.Pointer(b.array)) + _SizeofBucket*i)) = e
}

func (b *Buckets) At(i uintptr) *HashedIndexNode {
	p := (*Pointer)(unsafe.Pointer(uintptr(b.array.Get()) + _SizeofBucket*i))
	if p.IsSelf() {
		p.Set(nil)
	}

	return (*HashedIndexNode)(p.Get())
	//return *(**HashedIndexNode)(unsafe.Pointer(uintptr(b.array.Get()) + _SizeofBucket*i))
	//return *(**HashedIndexNode)(unsafe.Pointer(uintptr(unsafe.Pointer(b.array)) + _SizeofBucket*i))
}

type HashedIndexNode struct {
	super  Pointer `*SuperNode` // index-node on the HashedUniqueIndexNode, IndexBaseNode is the last super node
	final  Pointer `*FinalNode` // index-node under the HashedUniqueIndexNode, MultiIndexNode is the final index
	bucket uintptr              // buckets position
	key    Key                  // k of hashtable
	next   Pointer `*HashedIndexNode`
}

func NewHashedIndexNode(bucket uintptr, key Key) *HashedIndexNode {
	n := (*HashedIndexNode)(Allocator.Allocate(unsafe.Sizeof(HashedIndexNode{})))
	n.key = key
	n.bucket = bucket
	n.super.Set(nil)
	n.final.Set(nil)
	n.next.Set(nil)
	//n.next = nil
	return n
}

func (n *HashedIndexNode) free() {
	if n != nil {
		Allocator.DeAllocate(unsafe.Pointer(n))
	}
}

/*generic class*/
type SuperNode struct {
	value func() *Value
}

/*generic class*/
type FinalNode struct {
	GetSuperNode func() interface{}
	GetFinalNode func() interface{}
}

func (h *HashedIndex) GetSuperIndex() interface{} { return h.super }
func (h *HashedIndex) GetFinalIndex() interface{} { return h.final }

func (n *HashedIndexNode) GetSuperNode() interface{} { return n.super }
func (n *HashedIndexNode) GetFinalNode() interface{} { return n.final }

func (n *HashedIndexNode) value() *Value {
	return (*SuperNode)(n.super.Get()).value()
}

func (n *HashedIndexNode) Get(key Key) *HashedIndexNode {
	for node := n; node != nil; node = (*HashedIndexNode)(node.next.Get()) {
		//for node := n; node != nil; node = node.next {
		if node.key == key {
			return node
		}
	}
	return nil
}

func (h *HashedIndex) Size() int {
	return int(h.l)
}

func (h *HashedIndex) Empty() bool {
	return h.l == 0
}

func (h *HashedIndex) clear() {
	//h.inner = map[Hash]*HashedIndexNode{}
	(*SuperIndex)(h.super.Get()).clear()
}

func (h *HashedIndex) Insert(v Value) (Iterator, bool) {
	fn, res := (*FinalIndex)(h.final.Get()).insert(v)
	if res {
		return h.makeIterator(fn), true
	}
	return h.End(), false
}

func (h *HashedIndex) insert(v Value, fn *FinalNode) (*HashedIndexNode, bool) {
	key := KeyFunc(v)
	b := (*Buckets)(h.b.Get())
	bucket := Hasher(key) % b.len
	//bucket := Hasher(key) % h.b.len
	node := NewHashedIndexNode(bucket, key)

	if !h.link(bucket, key, node) {
		container.Logger.Warn("#hash index insert failed")
		node.free()
		return nil, false
	}

	if h.l > b.len {
		//if h.l > h.b.len {
		h.resize()
	}

	sn, res := (*SuperIndex)(h.super.Get()).insert(v, fn)
	if res {
		node.final.Set(unsafe.Pointer(fn))
		node.super.Set(unsafe.Pointer(sn))
		return node, true
	}

	//rollback for failed insert of SuperIndex
	h.unlink(node) //should never failed
	return nil, false
}

func (h *HashedIndex) Find(k Key) Iterator {
	b := (*Buckets)(h.b.Get())
	return Iterator{h, b.At(Hasher(k) % b.len).Get(k)}
	//return Iterator{h, h.b.At(Hasher(k) % h.b.len).Get(k)}
}

func (h *HashedIndex) Erase(iter Iterator) {
	(*FinalIndex)(h.final.Get()).erase((*FinalNode)(iter.node.final.Get()))
}

func (h *HashedIndex) erase(n *HashedIndexNode) {
	h.unlink(n) //should never failed
	(*SuperIndex)(h.super.Get()).erase((*SuperNode)(n.super.Get()))
	n.free()
}

func (h *HashedIndex) erase_(iter multiindex.IteratorType) {
	if itr, ok := iter.(Iterator); ok {
		h.Erase(itr)
	} else {
		(*SuperIndex)(h.super.Get()).erase_(iter)
	}
}

func (h *HashedIndex) Modify(iter Iterator, mod func(*Value)) bool {
	if _, b := (*FinalIndex)(h.final.Get()).modify(mod, (*FinalNode)(iter.node.final.Get())); b {
		return true
	}
	return false
}

func (h *HashedIndex) modify(n *HashedIndexNode) (*HashedIndexNode, bool) {
	key := KeyFunc(*n.value())
	bucket := Hasher(key) % (*Buckets)(h.b.Get()).len
	//bucket := Hasher(key) % h.b.len

	if !h.inPlace(bucket, key, n) {
		h.unlink(n)
		if !h.link(bucket, key, n) {
			container.Logger.Warn("#hash index modify failed")
			(*SuperIndex)(h.super.Get()).erase((*SuperNode)(n.super.Get()))
			n.free()
			return nil, false
		}
	}

	if sn, res := (*SuperIndex)(h.super.Get()).modify((*SuperNode)(n.super.Get())); !res {
		h.unlink(n)
		n.free()
		return nil, false
	} else {
		n.super.Set(unsafe.Pointer(sn))
	}

	return n, true
}

func (h *HashedIndex) modify_(iter multiindex.IteratorType, mod func(*Value)) bool {
	if itr, ok := iter.(Iterator); ok {
		return h.Modify(itr, mod)
	} else {
		return (*SuperIndex)(h.super.Get()).modify_(iter, mod)
	}
}

func (h *HashedIndex) Values() []Value {
	vs := make([]Value, 0, h.Size())
	for it := h.Begin(); it.HasNext(); it.Next() {
		vs = append(vs, it.Value())
	}
	return vs
}

func (h *HashedIndex) resize() {
	b := (*Buckets)(h.b.Get())
	n := b.len * 2
	//n := h.b.len * 2
	tmp := NewBuckets(n)
	for bucket := uintptr(0); bucket < b.len; bucket++ {
		//for bucket := uintptr(0); bucket < h.b.len; bucket++ {
		first := b.At(bucket)
		//first := h.b.At(bucket)
		for first != nil {
			newBucket := Hasher(first.key) % n
			b.Put(bucket, (*HashedIndexNode)(first.next.Get()))
			//h.b.Put(bucket, first.next)

			first.bucket = newBucket
			first.next.Set(unsafe.Pointer(tmp.At(newBucket)))
			//first.next = tmp.At(newBucket)

			tmp.Put(newBucket, first)
			first = b.At(bucket)
			//first = h.b.At(bucket)
		}
	}

	Allocator.DeAllocate(unsafe.Pointer(b))
	//Allocator.DeAllocate(unsafe.Pointer(h.b))
	h.b.Set(unsafe.Pointer(tmp))
	//h.b = tmp
}

func (h *HashedIndex) inPlace(buc uintptr, k Key, x *HashedIndexNode) bool {
	b := (*Buckets)(h.b.Get())
	found := false
	for y := b.At(buc); y != nil; y = (*HashedIndexNode)(y.next.Get()) {
		//for y := h.b.At(buc); y != nil; y = y.next {
		if x == y {
			found = true
		} else if k == y.key {
			found = false
		}
	}
	return found
}

func (h *HashedIndex) unlink(n *HashedIndexNode) {
	b := (*Buckets)(h.b.Get())
	var node, prev *HashedIndexNode

	found := false
	for node = b.At(n.bucket); node != nil; node = (*HashedIndexNode)(node.next.Get()) {
		//for node = h.b.At(n.bucket); node != nil; node = node.next {
		if node == n {
			break
		}
		prev = node
	}

	if !found {
		container.Logger.Warn("unlink node not found")
	}

	if prev != nil {
		prev.next.Forward(&node.next)
	} else {
		b.Put(n.bucket, (*HashedIndexNode)(node.next.Get()))
		//h.b.Put(n.bucket, node.next)
	}

	h.l--
}

func (h *HashedIndex) link(buc uintptr, k Key, n *HashedIndexNode) bool {
	b := (*Buckets)(h.b.Get())
	var prev *HashedIndexNode
	for node := b.At(buc); node != nil; node = (*HashedIndexNode)(node.next.Get()) {
		//for node := h.b.At(buc); node != nil; node = node.next {
		if node.key == k {
			return false
		}
		prev = node
	}

	if prev != nil {
		prev.next.Set(unsafe.Pointer(n))
		//prev.next = n
	} else {
		b.Put(buc, n)
		//h.b.Put(buc, n)
	}

	n.key = k
	n.next.Set(nil)
	//n.next = nil
	h.l++

	return true
}

type Iterator struct {
	index *HashedIndex
	node  *HashedIndexNode
}

func (h *HashedIndex) Begin() Iterator {
	if h.l == 0 {
		return h.End()
	}

	b := (*Buckets)(h.b.Get())
	for i := uintptr(0); i < b.len; i++ {
		//for i := uintptr(0); i < h.b.len; i++ {
		if e := b.At(i); e != nil {
			//if e := h.b.At(i); e != nil {
			return Iterator{h, e}
		}
	}

	panic(container.ErrFatalAddress)
}

func (h *HashedIndex) makeIterator(fn *FinalNode) Iterator {
	node := fn.GetSuperNode()
	for {
		if node == nil {
			panic("Wrong index node type!")

		} else if n, ok := node.(*HashedIndexNode); ok {
			return Iterator{h, n}
		} else {
			node = node.(multiindex.NodeType).GetSuperNode()
		}
	}
}

func (h *HashedIndex) End() Iterator {
	return Iterator{h, nil}
}

func (iter Iterator) Value() (v Value) {
	return *iter.node.value()
}

func (iter *Iterator) Next() bool {
	b := (*Buckets)(iter.index.b.Get())

	if !iter.node.next.IsNil() {
		//if iter.node.next != nil {
		iter.node = (*HashedIndexNode)(iter.node.next.Get())
		//iter.node = iter.node.next
		return true
	}

	for bucket := (Hasher(iter.node.key) % b.len) + 1; bucket < b.len; bucket++ {
		//for bucket := (Hasher(iter.node.key) % iter.index.b.len) + 1; bucket < iter.index.b.len; bucket++ {
		if entry := b.At(bucket); entry != nil {
			//if entry := iter.index.b.At(bucket); entry != nil {
			iter.node = entry
			return true
		}
	}

	iter.node = nil
	return false
}

func (iter Iterator) HasNext() bool {
	return iter.node != nil
}

func (iter Iterator) IsEnd() bool {
	return iter.node == nil
}

repository: eosspark/geos

repo_name: eosspark/geos


text:
//          Copyright Adam Lach 2013
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP

#include "asciidoc_output/document_element.hpp"
#include "model/class.hpp"

namespace asciidoc_output {

class Functions : public DocumentElement {
public:
    Functions(const model::Class* aClass) : cls(aClass) {}

private:
    void print(std::ostream& stream) const {
        stream << "Functions" << std::endl;
        stream << "~~~~~~~~~" << std::endl;
        stream << std::endl;
        for(auto&& function : cls->methods) {
            stream << CODE_DELIMETER << std::endl;
            stream << function.signature << std::endl;
            stream << CODE_DELIMETER << std::endl;
            stream << std::endl;
            stream << Description(&function);
            stream << "*Requires:* "       << function.description.precondition  << " +" << std::endl;
			stream << "*Effects:* "        << function.description.effects       << " +" << std::endl;
            stream << "*Postconditions:* " << function.description.postcondition << " +" << std::endl;
            stream << "*Returns:* "        << function.description.returns       << " +" << std::endl;
            stream << "*Throws:* "         << function.description.throws        << " +" << std::endl;
			stream << "*Complexity:* "     << function.description.complexity    << " +" << std::endl;
            stream << "*Note:* "           << function.description.note          << " +" << std::endl;
            stream << "*Danger:* "         << function.description.danger        << " +" << std::endl;
			stream << "*Rationale:* "      << function.description.rationale     << " +" << std::endl;
            stream << std::endl;
        }
    }

    struct Description : public DocumentElement {
        Description(const model::Method* aMethod) : method(aMethod) {}

        void print(std::ostream& stream) const {
            if(!method->description.brief.empty()) {
                stream << method->description.brief << std::endl;
                stream << std::endl;
            }
            if(!method->description.detailed.empty()) {
                stream << method->description.detailed << std::endl;
                stream << std::endl;
            }
        }

        const model::Method* method;
    };

    const model::Class* cls;
};

} // namespace asciidoc_output

#endif // FUNCTIONS_HPP

repository: lachem/d-injection

repo_name: lachem/d-injection


text:
#include "vertex/GLAbstractVarying.h"

#include "utils/GLDebug.h"

void GLAbstractVarying::print()
{
    for (int i=0; i<mData.size(); ++i)
    {
        float* p = mData[i];
        for (int j=0; j<mUnit; ++j)
        {
            printf("%f ", p[j]);
        }
        printf("\n");
    }
}

extension: cpp


text:
package types

import (
	"github.com/cosmos/cosmos-sdk/codec"
	cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
)

// SubModuleCdc defines the IBC tendermint client codec.
var SubModuleCdc *codec.Codec

func init() {
	SubModuleCdc = codec.New()
	cryptocodec.RegisterCrypto(SubModuleCdc)
	RegisterCodec(SubModuleCdc)
}

// RegisterCodec registers the Tendermint types
func RegisterCodec(cdc *codec.Codec) {
	cdc.RegisterConcrete(ClientState{}, "ibc/client/tendermint/ClientState", nil)
	cdc.RegisterConcrete(ConsensusState{}, "ibc/client/tendermint/ConsensusState", nil)
	cdc.RegisterConcrete(Header{}, "ibc/client/tendermint/Header", nil)
	cdc.RegisterConcrete(Evidence{}, "ibc/client/tendermint/Evidence", nil)
	cdc.RegisterConcrete(&MsgCreateClient{}, "ibc/client/tendermint/MsgCreateClient", nil)
	cdc.RegisterConcrete(&MsgUpdateClient{}, "ibc/client/tendermint/MsgUpdateClient", nil)
	cdc.RegisterConcrete(&MsgSubmitClientMisbehaviour{}, "ibc/client/tendermint/MsgSubmitClientMisbehaviour", nil)
}

repository: irisnet/cosmos-sdk

repo_name: irisnet/cosmos-sdk