// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build !windows && !plan9

package syslog

import (
	
	
	
	
	
	
	
	
)

// The Priority is a combination of the syslog facility and
// severity. For example, [LOG_ALERT] | [LOG_FTP] sends an alert severity
// message from the FTP facility. The default severity is [LOG_EMERG];
// the default facility is [LOG_KERN].
type Priority int

const severityMask = 0x07
const facilityMask = 0xf8

const (
	// Severity.

	// From /usr/include/sys/syslog.h.
	// These are the same on Linux, BSD, and OS X.
	LOG_EMERG Priority = iota
	LOG_ALERT
	LOG_CRIT
	LOG_ERR
	LOG_WARNING
	LOG_NOTICE
	LOG_INFO
	LOG_DEBUG
)

const (
	// Facility.

	// From /usr/include/sys/syslog.h.
	// These are the same up to LOG_FTP on Linux, BSD, and OS X.
	LOG_KERN Priority = iota << 3
	LOG_USER
	LOG_MAIL
	LOG_DAEMON
	LOG_AUTH
	LOG_SYSLOG
	LOG_LPR
	LOG_NEWS
	LOG_UUCP
	LOG_CRON
	LOG_AUTHPRIV
	LOG_FTP
	_ // unused
	_ // unused
	_ // unused
	_ // unused
	LOG_LOCAL0
	LOG_LOCAL1
	LOG_LOCAL2
	LOG_LOCAL3
	LOG_LOCAL4
	LOG_LOCAL5
	LOG_LOCAL6
	LOG_LOCAL7
)

// A Writer is a connection to a syslog server.
type Writer struct {
	priority Priority
	tag      string
	hostname string
	network  string
	raddr    string

	mu   sync.Mutex // guards conn
	conn serverConn
}

// This interface and the separate syslog_unix.go file exist for
// Solaris support as implemented by gccgo. On Solaris you cannot
// simply open a TCP connection to the syslog daemon. The gccgo
// sources have a syslog_solaris.go file that implements unixSyslog to
// return a type that satisfies this interface and simply calls the C
// library syslog function.
type serverConn interface {
	writeString(p Priority, hostname, tag, s, nl string) error
	close() error
}

type netConn struct {
	local bool
	conn  net.Conn
}

// New establishes a new connection to the system log daemon. Each
// write to the returned writer sends a log message with the given
// priority (a combination of the syslog facility and severity) and
// prefix tag. If tag is empty, the [os.Args][0] is used.
func ( Priority,  string) (*Writer, error) {
	return Dial("", "", , )
}

// Dial establishes a connection to a log daemon by connecting to
// address raddr on the specified network. Each write to the returned
// writer sends a log message with the facility and severity
// (from priority) and tag. If tag is empty, the [os.Args][0] is used.
// If network is empty, Dial will connect to the local syslog server.
// Otherwise, see the documentation for net.Dial for valid values
// of network and raddr.
func (,  string,  Priority,  string) (*Writer, error) {
	if  < 0 ||  > LOG_LOCAL7|LOG_DEBUG {
		return nil, errors.New("log/syslog: invalid priority")
	}

	if  == "" {
		 = os.Args[0]
	}
	,  := os.Hostname()

	 := &Writer{
		priority: ,
		tag:      ,
		hostname: ,
		network:  ,
		raddr:    ,
	}

	.mu.Lock()
	defer .mu.Unlock()

	 := .connect()
	if  != nil {
		return nil, 
	}
	return , 
}

// connect makes a connection to the syslog server.
// It must be called with w.mu held.
func ( *Writer) () ( error) {
	if .conn != nil {
		// ignore err from close, it makes sense to continue anyway
		.conn.close()
		.conn = nil
	}

	if .network == "" {
		.conn,  = unixSyslog()
		if .hostname == "" {
			.hostname = "localhost"
		}
	} else {
		var  net.Conn
		,  = net.Dial(.network, .raddr)
		if  == nil {
			.conn = &netConn{
				conn:  ,
				local: .network == "unixgram" || .network == "unix",
			}
			if .hostname == "" {
				.hostname = .LocalAddr().String()
			}
		}
	}
	return
}

// Write sends a log message to the syslog daemon.
func ( *Writer) ( []byte) (int, error) {
	return .writeAndRetry(.priority, string())
}

// Close closes a connection to the syslog daemon.
func ( *Writer) () error {
	.mu.Lock()
	defer .mu.Unlock()

	if .conn != nil {
		 := .conn.close()
		.conn = nil
		return 
	}
	return nil
}

// Emerg logs a message with severity [LOG_EMERG], ignoring the severity
// passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_EMERG, )
	return 
}

// Alert logs a message with severity [LOG_ALERT], ignoring the severity
// passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_ALERT, )
	return 
}

// Crit logs a message with severity [LOG_CRIT], ignoring the severity
// passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_CRIT, )
	return 
}

// Err logs a message with severity [LOG_ERR], ignoring the severity
// passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_ERR, )
	return 
}

// Warning logs a message with severity [LOG_WARNING], ignoring the
// severity passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_WARNING, )
	return 
}

// Notice logs a message with severity [LOG_NOTICE], ignoring the
// severity passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_NOTICE, )
	return 
}

// Info logs a message with severity [LOG_INFO], ignoring the severity
// passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_INFO, )
	return 
}

// Debug logs a message with severity [LOG_DEBUG], ignoring the severity
// passed to New.
func ( *Writer) ( string) error {
	,  := .writeAndRetry(LOG_DEBUG, )
	return 
}

func ( *Writer) ( Priority,  string) (int, error) {
	 := (.priority & facilityMask) | ( & severityMask)

	.mu.Lock()
	defer .mu.Unlock()

	if .conn != nil {
		if ,  := .write(, );  == nil {
			return , nil
		}
	}
	if  := .connect();  != nil {
		return 0, 
	}
	return .write(, )
}

// write generates and writes a syslog formatted string. The
// format is as follows: <PRI>TIMESTAMP HOSTNAME TAG[PID]: MSG
func ( *Writer) ( Priority,  string) (int, error) {
	// ensure it ends in a \n
	 := ""
	if !strings.HasSuffix(, "\n") {
		 = "\n"
	}

	 := .conn.writeString(, .hostname, .tag, , )
	if  != nil {
		return 0, 
	}
	// Note: return the length of the input, not the number of
	// bytes printed by Fprintf, because this must behave like
	// an io.Writer.
	return len(), nil
}

func ( *netConn) ( Priority, , , ,  string) error {
	if .local {
		// Compared to the network form below, the changes are:
		//	1. Use time.Stamp instead of time.RFC3339.
		//	2. Drop the hostname field from the Fprintf.
		 := time.Now().Format(time.Stamp)
		,  := fmt.Fprintf(.conn, "<%d>%s %s[%d]: %s%s",
			, ,
			, os.Getpid(), , )
		return 
	}
	 := time.Now().Format(time.RFC3339)
	,  := fmt.Fprintf(.conn, "<%d>%s %s %s[%d]: %s%s",
		, , ,
		, os.Getpid(), , )
	return 
}

func ( *netConn) () error {
	return .conn.Close()
}

// NewLogger creates a [log.Logger] whose output is written to the
// system log service with the specified priority, a combination of
// the syslog facility and severity. The logFlag argument is the flag
// set passed through to [log.New] to create the Logger.
func ( Priority,  int) (*log.Logger, error) {
	,  := New(, "")
	if  != nil {
		return nil, 
	}
	return log.New(, "", ), nil
}