Example #1
0
func Example() {
	var (
		g           = cflag.NewGroup(nil, "Program Options")
		bindFlag    = cflag.String(g, "bind", ":80", "Address to bind server to (e.g. :80)")
		fooFlag     = cflag.String(g, "foo", "", "Some flag")
		barFlag     = cflag.Int(g, "bar", 42, "Some other flag")
		doStuffFlag = cflag.Bool(g, "doStuff", false, "Do stuff?")
	)

	adaptflag.Adapt()
	flag.Parse()

	fmt.Printf("Bind: %s\n", bindFlag.Value())
	fmt.Printf("Foo:  %s\n", fooFlag.Value())
	fmt.Printf("Bar:  %d\n", barFlag.Value())
	fmt.Printf("Do Stuff: %v\n", doStuffFlag.Value())
}
Example #2
0
// Package session provides session storage facilities.
package session

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gorilla/context"
	"github.com/hlandau/degoutils/web/origin"
	"github.com/hlandau/degoutils/web/session/storage"
	"gopkg.in/hlandau/easyconfig.v1/cflag"
)

var cookieNameFlag = cflag.String(nil, "sessioncookiename", "s", "Session cookie name")

// Session system configuration.
type Config struct {
	// The session store to use. Required.
	Store storage.Store

	// The name to be used for the session cookie. Defaults to configurable
	// "sessioncookiename", which itself defaults to "s".
	CookieName string

	// Secret key used to generate the HMAC signatures for session cookies.
	//
	// If not specified, a temporary random key will be generated automatically.
	SecretKey []byte
}
Example #3
0
import "bytes"
import "time"
import "github.com/hlandau/degoutils/log"
import "github.com/hlandau/degoutils/sendemail"
import "gopkg.in/hlandau/easyconfig.v1/cflag"
import "gopkg.in/hlandau/svcutils.v1/exepath"
import "fmt"
import "github.com/hlandau/degoutils/web/opts"
import "github.com/hlandau/degoutils/web/servicenexus"
import "net/url"
import "strings"
import "gopkg.in/hlandau/easymetric.v1/cexp"

var cErrorResponsesIssued = cexp.NewCounter("web.errorResponsesIssued")

var panicsToFlag = cflag.String(nil, "panicsto", "", "E. mail address to send panics to")
var webmasterAddressFlag = cflag.String(nil, "webmasteraddress", "", "Webmaster e. mail address (shown on panic)")

// The error handling HTTP handler, wrapping an inner handler for which panics
// are handled.
func Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				const size = 4096
				stack := make([]byte, size)
				stack = stack[:runtime.Stack(stack, false)]

				renderError(rw, req, err, stack)
			}
		}()
Example #4
0
import (
	"fmt"
	"github.com/btcsuite/winsvc/mgr"
	"github.com/btcsuite/winsvc/svc"
	"gopkg.in/hlandau/easyconfig.v1/cflag"
	"gopkg.in/hlandau/svcutils.v1/exepath"
	"os"
	"time"
)

// This is always empty on Windows, as Windows does not support chrooting.
// It is present to allow code relying upon it to compile upon all platforms.
var EmptyChrootPath = ""

var (
	serviceFlag = cflag.String(fg, "do", "", "service command (one of: start, stop, install, remove)")
)

var errNotSupported = fmt.Errorf("not supported")

func systemdUpdateStatus(status string) error {
	return errNotSupported
}

func setproctitle(status string) error {
	return errNotSupported
}

// handler is used when running as a service.
// Otherwise we use the generic ihandler.
type handler struct {
Example #5
0
// Package adaptconf adapts registered configurables to configuration file
// formats.
package adaptconf

import "os"
import "fmt"
import "strings"
import "path/filepath"
import "gopkg.in/hlandau/configurable.v1"
import "gopkg.in/hlandau/easyconfig.v1/cflag"
import "gopkg.in/hlandau/svcutils.v1/exepath"
import "github.com/BurntSushi/toml"

var confFlag = cflag.String(nil, "conf", "", "Configuration file path")
var lastConfPath string

func LastConfPath() string {
	return lastConfPath
}

func LoadPath(confFilePath string) error {
	var m map[string]interface{}
	_, err := toml.DecodeFile(confFilePath, &m)
	if err != nil {
		return err
	}

	lastConfPath = confFilePath

	configurable.Visit(func(c configurable.Configurable) error {
		applyChild(c, m)
Example #6
0
	"gopkg.in/hlandau/easyconfig.v1/cflag"
	"gopkg.in/hlandau/easymetric.v1/cexp"
	"gopkg.in/tylerb/graceful.v1"
	"net"
	"net/http"
	"net/url"
	"path/filepath"
	"strings"
	"time"
)

var log, Log = xlog.New("web")

var cRequestsHandled = cexp.NewCounter("web.requestsHandled")

var bindFlag = cflag.String(nil, "bind", ":3400", "HTTP binding address")
var redisAddressFlag = cflag.String(nil, "redisaddress", "localhost:6379", "Redis address")
var redisPasswordFlag = cflag.String(nil, "redispassword", "", "Redis password")
var redisPrefixFlag = cflag.String(nil, "redisprefix", "", "Redis prefix")
var captchaFontPathFlag = cflag.String(nil, "captchafontpath", "", "Path to CAPTCHA font directory")
var reportURI = cflag.String(nil, "reporturi", "/.csp-report", "CSP/PKP report URI")

var Router *mux.Router

func init() {
	Router = mux.NewRouter()
	Router.KeepContext = true
	Router.NotFoundHandler = http.HandlerFunc(NotFound)
}

func NotFound(rw http.ResponseWriter, req *http.Request) {
Example #7
0
package examplelib

import "gopkg.in/hlandau/easyconfig.v1/cflag"

var g = cflag.NewGroup(nil, "Server Options")
var bindFlag = cflag.String(g, "bind", ":53", "Address to bind to (e.g. 0.0.0.0:53)")
var publicKeyFlag = cflag.String(g, "publicKey", "", "Path to the DNSKEY KSK public key file")
var privateKeyFlag = cflag.String(g, "privateKey", "", "Path to the KSK's corresponding private key file")
var zonePublicKeyFlag = cflag.String(g, "zonePublicKey", "", "Path to the DNSKEY ZSK public key file; if one is not specified, a temporary one is generated on startup and used only for the duration of that process")
var zonePrivateKeyFlag = cflag.String(g, "zonePrivateKey", "", "Path to the ZSK's corresponding private key file")
var namecoinRPCUsernameFlag = cflag.String(g, "namecoinRPCUsername", "", "Namecoin RPC username")
var namecoinRPCPasswordFlag = cflag.String(g, "namecoinRPCPassword", "", "Namecoin RPC password")
var namecoinRPCAddressFlag = cflag.String(g, "namecoinRPCAddress", "localhost:8336", "Namecoin RPC server address")
var cacheMaxEntriesFlag = cflag.Int(g, "cacheMaxEntries", 100, "Maximum name cache entries")
var selfNameFlag = cflag.String(g, "selfName", "", "The FQDN of this nameserver; if empty, a psuedo-hostname is generated")
var selfIPFlag = cflag.String(g, "selfIP", "127.127.127.127", "The canonical IP address for this service")
var httpListenAddrFlag = cflag.String(g, "httpListenAddr", "", "Address for the webserver to listen at (default: disabled)")
var canonicalSuffixFlag = cflag.String(g, "canonicalSuffix", "bit", "Suffix to advertise via HTTP")
var canonicalNameserversFlag = cflag.String(g, "canonicalNameservers", "", "Comma-separated list of nameservers to use for NS records; if blank, selfName (or autogenerated psuedo-hostname) is used")
var hostmasterFlag = cflag.String(g, "hostmaster", "", "Hostmaster e. mail address")
var vanityIPs = cflag.String(g, "vanityIPs", "", "Comma separated list of IP addresses to place in A/AAAA records at the zone apex (default: don't add any records)")
var doStuff = cflag.Bool(g, "doStuff", false, "Do stuff")
Example #8
0
	"io"
	"net/http"
	_ "net/http/pprof" // register pprof handler for debug server
	"os"
	"os/signal"
	"runtime/pprof"
	"sync"
	"syscall"
	"time"
)

// Flags

var (
	fg                  = cflag.NewGroup(nil, "service")
	cpuProfileFlag      = cflag.String(fg, "cpuprofile", "", "Write CPU profile to file")
	debugServerAddrFlag = cflag.String(fg, "debugserveraddr", "", "Address for debug server to listen on (do not specify a public address) (default: disabled)")
)

type nullWriter struct{}

func (nw nullWriter) Write(p []byte) (n int, err error) {
	return len(p), nil
}

func init() {
	expvar.NewString("service.startTime").Set(time.Now().String())
}

// This function should typically be called directly from func main(). It takes
// care of all housekeeping for running services and handles service lifecycle.
Example #9
0
	"gopkg.in/hlandau/service.v2/passwd"
	"gopkg.in/hlandau/service.v2/sdnotify"
	"os"
	"strconv"
)

// This will always point to a path which the platform guarantees is an empty
// directory. You can use it as your default chroot path if your service doesn't
// access the filesystem after it's started.
//
// On Linux, the FHS provides that "/var/empty" is an empty directory, so it
// points to that.
var EmptyChrootPath = daemon.EmptyChrootPath

var (
	uidFlag       = cflag.String(fg, "uid", "", "UID to run as (default: don't drop privileges)")
	gidFlag       = cflag.String(fg, "gid", "", "GID to run as (default: don't drop privileges)")
	daemonizeFlag = cflag.Bool(fg, "daemon", false, "Run as daemon? (doesn't fork)")
	chrootFlag    = cflag.String(fg, "chroot", "", "Chroot to a directory (must set UID, GID) (\"/\" disables)")
	pidfileFlag   = cflag.String(fg, "pidfile", "", "Write PID to file with given filename and hold a write lock")
	forkFlag      = cflag.Bool(fg, "fork", false, "Fork? (implies -daemon)")
)

func systemdUpdateStatus(status string) error {
	return sdnotify.Send(status)
}

func setproctitle(status string) error {
	gspt.SetProcTitle(status)
	return nil
}
Example #10
0
import "gopkg.in/hlandau/easyconfig.v1/cflag"
import "path/filepath"
import "github.com/hlandau/xlog"
import "sync"
import "io"
import "gopkg.in/alexcesaro/quotedprintable.v3"
import "mime/multipart"
import "net/textproto"

var cEmailsSent = cexp.NewCounter("sendemail.emailsSent")

var log, Log = xlog.New("sendemail")

var (
	fg               = cflag.NewGroup(nil, "sendemail")
	smtpAddressFlag  = cflag.String(fg, "smtpaddress", "", "SMTP address (hostname[:port])")
	smtpUsernameFlag = cflag.String(fg, "smtpusername", "", "SMTP username")
	smtpPasswordFlag = cflag.String(fg, "smtppassword", "", "SMTP password")
	sendmailPathFlag = cflag.String(fg, "sendmailpath", "", "path to /usr/sbin/sendmail")
	numSendersFlag   = cflag.Int(fg, "numsenders", 2, "number of asynchronous e. mail senders")
	fromFlag         = cflag.String(fg, "from", "nobody@localhost", "Default from address")
)

var sendChan = make(chan *Email, 32)
var startOnce sync.Once

func sendLoop() {
	for e := range sendChan {
		err := Send(e)
		log.Errore(err, "cannot send e. mail")
	}
Example #11
0
	if secretKey != nil {
		return secretKey
	}

	var err error
	s := secretKeyFlag.Value()
	if s == "" {
		secretKey = make([]byte, 32)
		_, err = rand.Read(secretKey)
		log.Panice(err)
	} else if len(s) == 64 {
		secretKey, err = hex.DecodeString(s)
		log.Fatale(err, "Cannot decode secret key string (must be hex)")
	} else {
		log.Fatale(err, "Secret key must be 64 hex characters")
	}

	return secretKey
}

// Gets a 32-byte variant secret key, derived using the given name.
func VariantSecretKey(name string) []byte {
	h := hmac.New(sha256.New, SecretKey())
	h.Write([]byte(name))
	return h.Sum(nil)
}

var secretKey []byte

var secretKeyFlag = cflag.String(nil, "secretkey", "", "Secret key (64 hex characters)")