Use global logger

This commit is contained in:
Elara 2021-06-19 00:36:48 -07:00
parent 8dc2ffff6f
commit 8099077c50
10 changed files with 21 additions and 64 deletions

View File

@ -18,25 +18,25 @@ package main
import ( import (
"errors" "errors"
"github.com/pelletier/go-toml"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"io/ioutil" "io/ioutil"
"os" "os"
"github.com/pelletier/go-toml"
"github.com/rs/zerolog/log"
) )
// Struct for unmarshaling of opensend TOML configs // Struct for unmarshaling of opensend TOML configs
type Config struct { type Config struct {
Receiver ReceiverConfig Receiver ReceiverConfig
Sender SenderConfig Sender SenderConfig
Targets map[string]Target Targets map[string]Target
} }
// Config section for receiver // Config section for receiver
type ReceiverConfig struct { type ReceiverConfig struct {
DestDir string `toml:"destinationDirectory"` DestDir string `toml:"destinationDirectory"`
SkipZeroconf bool SkipZeroconf bool
WorkDir string `toml:"workingDirectory"` WorkDir string `toml:"workingDirectory"`
} }
// Config section for sender // Config section for sender
@ -51,7 +51,6 @@ type Target struct {
// Attempt to find config path // Attempt to find config path
func GetConfigPath() string { func GetConfigPath() string {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Possible config locations // Possible config locations
configLocations := []string{"~/.config/opensend.toml", "/etc/opensend.toml"} configLocations := []string{"~/.config/opensend.toml", "/etc/opensend.toml"}
// For every possible location // For every possible location
@ -73,7 +72,6 @@ func GetConfigPath() string {
// Create new config object using values from given path // Create new config object using values from given path
func NewConfig(path string) *Config { func NewConfig(path string) *Config {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create new empty config struct // Create new empty config struct
newConfig := &Config{} newConfig := &Config{}
// Set config defaults // Set config defaults

View File

@ -18,17 +18,16 @@ package main
import ( import (
"context" "context"
"github.com/grandcat/zeroconf"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"os" "os"
"time" "time"
"github.com/grandcat/zeroconf"
"github.com/rs/zerolog/log"
) )
// Discover opensend receivers on the network // Discover opensend receivers on the network
func DiscoverReceivers() ([]string, []string) { func DiscoverReceivers() ([]string, []string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create zeroconf resolver // Create zeroconf resolver
resolver, err := zeroconf.NewResolver(nil) resolver, err := zeroconf.NewResolver(nil)
if err != nil { if err != nil {

View File

@ -17,16 +17,15 @@
package main package main
import ( import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/rs/zerolog/log"
) )
func ExpandPath(s string) string { func ExpandPath(s string) string {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Get user's home directory // Get user's home directory
homeDir, err := os.UserHomeDir() homeDir, err := os.UserHomeDir()
if err != nil { if err != nil {

View File

@ -29,7 +29,6 @@ import (
"strings" "strings"
"github.com/klauspost/compress/zstd" "github.com/klauspost/compress/zstd"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/chacha20poly1305"
) )
@ -37,7 +36,6 @@ import (
// Encrypt given file using the shared key // Encrypt given file using the shared key
func CompressAndEncryptFile(filePath string, newFilePath string, sharedKey string) { func CompressAndEncryptFile(filePath string, newFilePath string, sharedKey string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Read data from file // Read data from file
file, err := os.Open(filePath) file, err := os.Open(filePath)
if err != nil { if err != nil {
@ -100,7 +98,6 @@ func CompressAndEncryptFile(filePath string, newFilePath string, sharedKey strin
// Decrypt given file using the shared key // Decrypt given file using the shared key
func DecryptAndDecompressFile(filePath string, newFilePath string, sharedKey string) { func DecryptAndDecompressFile(filePath string, newFilePath string, sharedKey string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Read data from file // Read data from file
data, err := ioutil.ReadFile(filePath) data, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
@ -149,7 +146,6 @@ func DecryptAndDecompressFile(filePath string, newFilePath string, sharedKey str
// Encrypt files in given directory using shared key // Encrypt files in given directory using shared key
func EncryptFiles(dir string, sharedKey string) { func EncryptFiles(dir string, sharedKey string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Walk given directory // Walk given directory
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
// If error reading, return err // If error reading, return err
@ -177,7 +173,6 @@ func EncryptFiles(dir string, sharedKey string) {
// Decrypt files in given directory using shared key // Decrypt files in given directory using shared key
func DecryptFiles(dir string, sharedKey string) { func DecryptFiles(dir string, sharedKey string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Walk given directory // Walk given directory
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
// If error reading, return err // If error reading, return err

View File

@ -26,14 +26,12 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
// Save encrypted key to file // Save encrypted key to file
func SaveEncryptedKey(encryptedKey []byte, filePath string) { func SaveEncryptedKey(encryptedKey []byte, filePath string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create file at given file path // Create file at given file path
keyFile, err := os.Create(filePath) keyFile, err := os.Create(filePath)
if err != nil { if err != nil {
@ -53,7 +51,6 @@ func SaveEncryptedKey(encryptedKey []byte, filePath string) {
// Create HTTP server to transmit files // Create HTTP server to transmit files
func SendFiles(dir string) { func SendFiles(dir string) {
// Use ConsoleWriter logger with normal FatalHook // Use ConsoleWriter logger with normal FatalHook
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create TCP listener on port 9898 // Create TCP listener on port 9898
listener, err := net.Listen("tcp", ":9898") listener, err := net.Listen("tcp", ":9898")
if err != nil { if err != nil {
@ -138,7 +135,6 @@ func NewSender(senderAddr string) *Sender {
// Get files from sender // Get files from sender
func RecvFiles(sender *Sender) { func RecvFiles(sender *Sender) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
indexReader, code, err := sender.Get("/index") indexReader, code, err := sender.Get("/index")
if err != nil { if err != nil {
log.Fatal().Err(err).Msg("Error getting index") log.Fatal().Err(err).Msg("Error getting index")

View File

@ -22,16 +22,13 @@ import (
"crypto/sha256" "crypto/sha256"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
// Generate RSA keypair // Generate RSA keypair
func GenerateRSAKeypair() (*rsa.PrivateKey, *rsa.PublicKey) { func GenerateRSAKeypair() (*rsa.PrivateKey, *rsa.PublicKey) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Generate private/public RSA keypair // Generate private/public RSA keypair
privateKey, err := rsa.GenerateKey(rand.Reader, 2048) privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil { if err != nil {
@ -46,7 +43,6 @@ func GenerateRSAKeypair() (*rsa.PrivateKey, *rsa.PublicKey) {
// Get public key from sender // Get public key from sender
func GetKey(sender *Sender) []byte { func GetKey(sender *Sender) []byte {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Send key request to connection // Send key request to connection
keyReader, code, err := sender.Get("/key") keyReader, code, err := sender.Get("/key")
if err != nil { if err != nil {
@ -75,7 +71,6 @@ func GetKey(sender *Sender) []byte {
// Encrypt shared key with received public key // Encrypt shared key with received public key
func EncryptKey(sharedKey string, recvPubKey *rsa.PublicKey) []byte { func EncryptKey(sharedKey string, recvPubKey *rsa.PublicKey) []byte {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Encrypt shared key using RSA // Encrypt shared key using RSA
encryptedSharedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, recvPubKey, []byte(sharedKey), nil) encryptedSharedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, recvPubKey, []byte(sharedKey), nil)
if err != nil { if err != nil {

View File

@ -19,16 +19,14 @@ package main
import ( import (
"crypto/rsa" "crypto/rsa"
"encoding/gob" "encoding/gob"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"net" "net"
"os"
"github.com/rs/zerolog/log"
) )
// Exchange keys with sender // Exchange keys with sender
func ReceiverKeyExchange(key *rsa.PublicKey) string { func ReceiverKeyExchange(key *rsa.PublicKey) string {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create TCP listener on port 9797 // Create TCP listener on port 9797
listener, err := net.Listen("tcp", ":9797") listener, err := net.Listen("tcp", ":9797")
if err != nil { if err != nil {
@ -58,7 +56,6 @@ func ReceiverKeyExchange(key *rsa.PublicKey) string {
// Exchange keys with receiver // Exchange keys with receiver
func SenderKeyExchange(receiverIP string) *rsa.PublicKey { func SenderKeyExchange(receiverIP string) *rsa.PublicKey {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Connect to TCP socket on receiver IP port 9797 // Connect to TCP socket on receiver IP port 9797
connection, err := net.Dial("tcp", receiverIP+":9797") connection, err := net.Dial("tcp", receiverIP+":9797")
if err != nil { if err != nil {

View File

@ -17,12 +17,16 @@
package main package main
import ( import (
"fmt"
"github.com/rs/zerolog"
"net"
"os" "os"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
) )
func init() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
}
// Fatal hook to run in case of Fatal error // Fatal hook to run in case of Fatal error
type FatalHook struct{} type FatalHook struct{}
@ -34,22 +38,3 @@ func (hook FatalHook) Run(_ *zerolog.Event, level zerolog.Level, _ string) {
_ = os.RemoveAll(*workDir) _ = os.RemoveAll(*workDir)
} }
} }
// TCP Fatal hook to run in case of Fatal error with open TCP connection
type TCPFatalHook struct {
conn net.Conn
}
// Run function on trigger
func (hook TCPFatalHook) Run(_ *zerolog.Event, level zerolog.Level, _ string) {
// If log event is fatal
if level == zerolog.FatalLevel {
// Send error to connection
_, _ = fmt.Fprintln(hook.conn, "ERR;")
// Close connection
_ = hook.conn.Close()
// Attempt removal of opensend directory
_ = os.RemoveAll(*workDir)
}
}

View File

@ -29,7 +29,6 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
) )
@ -39,7 +38,6 @@ var destDir *string
func main() { func main() {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create --send-to flag to send to a specific IP // Create --send-to flag to send to a specific IP
sendTo := flag.String("send-to", "", "Use IP address of receiver instead of mDNS") sendTo := flag.String("send-to", "", "Use IP address of receiver instead of mDNS")

View File

@ -27,7 +27,6 @@ import (
"github.com/mholt/archiver/v3" "github.com/mholt/archiver/v3"
"github.com/pkg/browser" "github.com/pkg/browser"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/vmihailenco/msgpack/v5" "github.com/vmihailenco/msgpack/v5"
) )
@ -66,7 +65,6 @@ func (parameters *Parameters) Validate() {
// Create config file // Create config file
func (parameters *Parameters) CreateFile(dir string) { func (parameters *Parameters) CreateFile(dir string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Create parameters file at given directory // Create parameters file at given directory
configFile, err := os.Create(dir + "/parameters.msgpack") configFile, err := os.Create(dir + "/parameters.msgpack")
if err != nil { if err != nil {
@ -91,7 +89,6 @@ func (parameters *Parameters) CreateFile(dir string) {
// Collect all required files into given directory // Collect all required files into given directory
func (parameters *Parameters) CollectFiles(dir string) { func (parameters *Parameters) CollectFiles(dir string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// If action type is file // If action type is file
if parameters.ActionType == "file" { if parameters.ActionType == "file" {
// Open file path in parameters.ActionData // Open file path in parameters.ActionData
@ -128,7 +125,6 @@ func (parameters *Parameters) CollectFiles(dir string) {
// Read config file at given file path // Read config file at given file path
func (parameters *Parameters) ReadFile(filePath string) { func (parameters *Parameters) ReadFile(filePath string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Read file at filePath // Read file at filePath
fileData, err := ioutil.ReadFile(filePath) fileData, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
@ -144,7 +140,6 @@ func (parameters *Parameters) ReadFile(filePath string) {
// Execute action specified in config // Execute action specified in config
func (parameters *Parameters) ExecuteAction(srcDir string, destDir string) { func (parameters *Parameters) ExecuteAction(srcDir string, destDir string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// If action is file // If action is file
switch parameters.ActionType { switch parameters.ActionType {
case "file": case "file":