package tls

import (
	
	
	

	
)

var ErrEmptyPsk = errors.New("tls: empty psk detected; remove the psk extension for this connection or set OmitEmptyPsk to true to conceal it in utls")

type PreSharedKeyCommon struct {
	Identities  []PskIdentity
	Binders     [][]byte
	BinderKey   []byte // this will be used to compute the binder when hello message is ready
	EarlySecret []byte
	Session     *SessionState
}

// The lifecycle of a PreSharedKeyExtension:
//
// Creation Phase:
//   - The extension is created.
//
// Write Phase:
//
//   - [writeToUConn() called]:
//
//     > - During this phase, it is important to note that implementations should not write any session data to the UConn (Underlying Connection) as the session is not yet loaded. The session context is not active at this point.
//
// Initialization Phase:
//
//   - [IsInitialized() called]:
//
//     If IsInitialized() returns true
//
//     > - GetPreSharedKeyCommon() will be called subsequently and the PSK states in handshake/clientHello will be fully initialized.
//
//     If IsInitialized() returns false:
//
//     > - [conn.loadSession() called]:
//
//     >> - Once the session is available:
//
//     >>> - [InitializeByUtls() called]:
//
//     >>>> - The InitializeByUtls() method is invoked to initialize the extension based on the loaded session data.
//
//     >>>> - This step prepares the extension for further processing.
//
// Marshal Phase:
//
//   - [Len() called], [Read() called]:
//
//     > - Implementations should marshal the extension into bytes, using placeholder binders to maintain the correct length.
//
// Binders Preparation Phase:
//
//   - [PatchBuiltHello(hello) called]:
//
//     > - The client hello is already marshaled in the "hello.Raw" format.
//
//     > - Implementations are expected to update the binders within the marshaled client hello.
//
//   - [GetPreSharedKeyCommon() called]:
//
//     > - Implementations should gather and provide the final pre-shared key (PSK) related data.
//
//     > - This data will be incorporated into both the clientHello and HandshakeState, ensuring that the PSK-related information is properly set and ready for the handshake process.
type PreSharedKeyExtension interface {
	// TLSExtension must be implemented by all PreSharedKeyExtension implementations.
	TLSExtension

	// If false is returned, utls will invoke `InitializeByUtls()` for the necessary initialization.
	Initializable

	SetOmitEmptyPsk(val bool)

	// InitializeByUtls is invoked when IsInitialized() returns false.
	// It initializes the extension using a real and valid TLS 1.3 session.
	InitializeByUtls(session *SessionState, earlySecret []byte, binderKey []byte, identities []PskIdentity)

	// GetPreSharedKeyCommon retrieves the final PreSharedKey-related states as defined in PreSharedKeyCommon.
	GetPreSharedKeyCommon() PreSharedKeyCommon

	// PatchBuiltHello is called once the hello message is fully applied and marshaled.
	// Its purpose is to update the binders of PSK (Pre-Shared Key) identities.
	PatchBuiltHello(hello *PubClientHelloMsg) error

	mustEmbedUnimplementedPreSharedKeyExtension() // this works like a type guard
}

type UnimplementedPreSharedKeyExtension struct{}

func (UnimplementedPreSharedKeyExtension) () {}

func (*UnimplementedPreSharedKeyExtension) () bool {
	panic("tls: IsInitialized is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) ( *SessionState,  []byte,  []byte,  []PskIdentity) {
	panic("tls: Initialize is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) (*UConn) error {
	panic("tls: writeToUConn is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) () int {
	panic("tls: Len is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) ([]byte) (int, error) {
	panic("tls: Read is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) () PreSharedKeyCommon {
	panic("tls: GetPreSharedKeyCommon is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) ( *PubClientHelloMsg) error {
	panic("tls: ReadWithRawHello is not implemented for the PreSharedKeyExtension")
}

func (*UnimplementedPreSharedKeyExtension) ( bool) {
	panic("tls: SetOmitEmptyPsk is not implemented for the PreSharedKeyExtension")
}

// UtlsPreSharedKeyExtension is an extension used to set the PSK extension in the
// ClientHello.
type UtlsPreSharedKeyExtension struct {
	UnimplementedPreSharedKeyExtension
	PreSharedKeyCommon
	cipherSuite  *cipherSuiteTLS13
	cachedLength *int
	// Deprecated: Set OmitEmptyPsk in Config instead.
	OmitEmptyPsk bool
}

func ( *UtlsPreSharedKeyExtension) () bool {
	return .Session != nil
}

func ( *UtlsPreSharedKeyExtension) ( *SessionState,  []byte,  []byte,  []PskIdentity) {
	.Session = 
	.EarlySecret = 
	.BinderKey = 
	.cipherSuite = cipherSuiteTLS13ByID(.Session.cipherSuite)
	.Identities = 
	.Binders = make([][]byte, 0, len(.Identities))
	for  := 0;  < len(.Identities); ++ {
		.Binders = append(.Binders, make([]byte, .cipherSuite.hash.Size()))
	}
}

func ( *UtlsPreSharedKeyExtension) ( *UConn) error {
	.HandshakeState.Hello.TicketSupported = true // This doesn't matter though, as utls doesn't care about this field. We write this for consistency.
	return nil
}

func ( *UtlsPreSharedKeyExtension) () PreSharedKeyCommon {
	return .PreSharedKeyCommon
}

func ( []PskIdentity,  [][]byte) int {
	if len() == 0 || len() == 0 {
		// If there isn't psk identities, we don't write this ticket to the client hello, and therefore the length should be 0.
		return 0
	}
	 := 4 // extension type + extension length
	 += 2 // identities length
	for ,  := range  {
		 += 2 + len(.Label) + 4 // identity length + identity + obfuscated ticket age
	}
	 += 2 // binders length
	for ,  := range  {
		 += len() + 1
	}
	return 
}

func ( *UtlsPreSharedKeyExtension) () int {
	if .Session == nil {
		return 0
	}
	if .cachedLength != nil {
		return *.cachedLength
	}
	 := pskExtLen(.Identities, .Binders)
	.cachedLength = &
	return 
}

func ( []byte,  []PskIdentity,  [][]byte) (int, error) {
	 := pskExtLen(, )
	if  == 0 {
		return 0, io.EOF
	}
	if len() <  {
		return 0, io.ErrShortBuffer
	}

	[0] = byte(extensionPreSharedKey >> 8)
	[1] = byte(extensionPreSharedKey)
	[2] = byte(( - 4) >> 8)
	[3] = byte( - 4)

	// identities length
	 := 0
	for ,  := range  {
		 += 2 + len(.Label) + 4 // identity length + identity + obfuscated ticket age
	}
	[4] = byte( >> 8)
	[5] = byte()

	// identities
	 := 6
	for ,  := range  {
		[] = byte(len(.Label) >> 8)
		[+1] = byte(len(.Label))
		 += 2
		copy([:], .Label)
		 += len(.Label)
		[] = byte(.ObfuscatedTicketAge >> 24)
		[+1] = byte(.ObfuscatedTicketAge >> 16)
		[+2] = byte(.ObfuscatedTicketAge >> 8)
		[+3] = byte(.ObfuscatedTicketAge)
		 += 4
	}

	// binders length
	 := 0
	for ,  := range  {
		// check if binder size is valid
		 += len() + 1 // binder length + binder
	}
	[] = byte( >> 8)
	[+1] = byte()
	 += 2

	// binders
	for ,  := range  {
		[] = byte(len())
		++
		copy([:], )
		 += len()
	}

	return , io.EOF
}

func ( *UtlsPreSharedKeyExtension) ( bool) {
	.OmitEmptyPsk = 
}

func ( *UtlsPreSharedKeyExtension) ( []byte) (int, error) {
	if !.OmitEmptyPsk && .Len() == 0 {
		return 0, ErrEmptyPsk
	}
	return readPskIntoBytes(, .Identities, .Binders)
}

func ( *UtlsPreSharedKeyExtension) ( *PubClientHelloMsg) error {
	if .Len() == 0 {
		return nil
	}
	 := .getCachedPrivatePtr()
	if  == nil {
		 = .getPrivatePtr()
	}
	.original = .Raw
	.pskBinders = .Binders // set the placeholder to the private Hello

	//--- mirror loadSession() begin ---//
	 := .cipherSuite.hash.New()
	,  := .marshalWithoutBinders() // no marshal() will be actually called, as we have set the field `raw`
	if  != nil {
		return 
	}
	.Write()
	 := [][]byte{.cipherSuite.finishedHash(.BinderKey, )}

	if  := .updateBinders();  != nil {
		return 
	}

	// copied from handshake_messages.go in 1.22
	 := len()
	 := cryptobyte.NewFixedBuilder(.original[:])
	.AddUint16LengthPrefixed(func( *cryptobyte.Builder) {
		for ,  := range .pskBinders {
			.AddUint8LengthPrefixed(func( *cryptobyte.Builder) {
				.AddBytes()
			})
		}
	})
	if ,  := .Bytes();  != nil || len() != len(.original) {
		return errors.New("tls: internal error: failed to update binders")
	}

	//--- mirror loadSession() end ---//
	.Binders = 

	// no need to care about other PSK related fields, they will be handled separately

	return io.EOF
}

func ( *UtlsPreSharedKeyExtension) ( []byte) (int, error) {
	return len(), nil // ignore the data
}

func ( *UtlsPreSharedKeyExtension) ( []byte) error {
	return nil // ignore the data
}

// FakePreSharedKeyExtension is an extension used to set the PSK extension in the
// ClientHello.
//
// It does not compute binders based on ClientHello, but uses the binders specified instead.
// We still need to learn more of the safety
// of hardcoding both Identities and Binders without recalculating the latter.
type FakePreSharedKeyExtension struct {
	UnimplementedPreSharedKeyExtension

	Identities []PskIdentity `json:"identities"`
	Binders    [][]byte      `json:"binders"`
	// Deprecated: Set OmitEmptyPsk in Config instead.
	OmitEmptyPsk bool
}

func ( *FakePreSharedKeyExtension) () bool {
	return .Identities != nil && .Binders != nil
}

func ( *FakePreSharedKeyExtension) ( *SessionState,  []byte,  []byte,  []PskIdentity) {
	panic("InitializeByUtls failed: don't let utls initialize FakePreSharedKeyExtension; provide your own identities and binders or use UtlsPreSharedKeyExtension")
}

func ( *FakePreSharedKeyExtension) ( *UConn) error {
	if .config.ClientSessionCache == nil {
		return nil // don't write the extension if there is no session cache
	}
	if ,  := .config.ClientSessionCache.Get(.clientSessionCacheKey()); ! ||  == nil {
		return nil // don't write the extension if there is no session cache available for this session
	}
	.HandshakeState.Hello.PskIdentities = .Identities
	.HandshakeState.Hello.PskBinders = .Binders
	return nil
}

func ( *FakePreSharedKeyExtension) () int {
	return pskExtLen(.Identities, .Binders)
}

func ( *FakePreSharedKeyExtension) ( bool) {
	.OmitEmptyPsk = 
}

func ( *FakePreSharedKeyExtension) ( []byte) (int, error) {
	if !.OmitEmptyPsk && .Len() == 0 {
		return 0, ErrEmptyPsk
	}
	for ,  := range .Binders {
		if !(anyTrue(validHashLen, func( int,  *int) bool {
			return len() == *
		})) {
			return 0, errors.New("tls: FakePreSharedKeyExtension.Read failed: invalid binder size")
		}
	}

	return readPskIntoBytes(, .Identities, .Binders)
}

func ( *FakePreSharedKeyExtension) () PreSharedKeyCommon {
	return PreSharedKeyCommon{
		Identities: .Identities,
		Binders:    .Binders,
	}
}

var validHashLen = mapSlice(cipherSuitesTLS13, func( *cipherSuiteTLS13) int {
	return .hash.Size()
})

func (*FakePreSharedKeyExtension) (*PubClientHelloMsg) error {
	return nil // no need to patch the hello since we don't need to update binders
}

func ( *FakePreSharedKeyExtension) ( []byte) ( int,  error) {
	 := len()
	 := cryptobyte.String()

	var  uint16
	if !.ReadUint16(&) {
		return 0, errors.New("tls: invalid PSK extension")
	}

	// identities
	for  > 0 {
		var  uint16
		if !.ReadUint16(&) {
			return 0, errors.New("tls: invalid PSK extension")
		}
		 -= 2

		if  >  {
			return 0, errors.New("tls: invalid PSK extension")
		}

		var  []byte
		if !.ReadBytes(&, int()) {
			return 0, errors.New("tls: invalid PSK extension")
		}

		 -=  // identity

		var  uint32
		if !.ReadUint32(&) {
			return 0, errors.New("tls: invalid PSK extension")
		}

		.Identities = append(.Identities, PskIdentity{
			Label:               ,
			ObfuscatedTicketAge: ,
		})

		 -= 4 // obfuscated ticket age
	}

	var  uint16
	if !.ReadUint16(&) {
		return 0, errors.New("tls: invalid PSK extension")
	}

	// binders
	for  > 0 {
		var  uint8
		if !.ReadUint8(&) {
			return 0, errors.New("tls: invalid PSK extension")
		}
		 -= 1

		if uint16() >  {
			return 0, errors.New("tls: invalid PSK extension")
		}

		var  []byte
		if !.ReadBytes(&, int()) {
			return 0, errors.New("tls: invalid PSK extension")
		}

		.Binders = append(.Binders, )

		 -= uint16()
	}

	return , nil
}

func ( *FakePreSharedKeyExtension) ( []byte) error {
	var  struct {
		 []PskIdentity `json:"identities"`
		    [][]byte      `json:"binders"`
	}

	if  := json.Unmarshal(, &);  != nil {
		return 
	}

	.Identities = .
	.Binders = .
	return nil
}

// type guard
var (
	_ PreSharedKeyExtension = (*UtlsPreSharedKeyExtension)(nil)
	_ TLSExtensionJSON      = (*UtlsPreSharedKeyExtension)(nil)
	_ PreSharedKeyExtension = (*FakePreSharedKeyExtension)(nil)
	_ TLSExtensionJSON      = (*FakePreSharedKeyExtension)(nil)
	_ TLSExtensionWriter    = (*FakePreSharedKeyExtension)(nil)
)

// type ExternalPreSharedKeyExtension struct{} // TODO: wait for whoever cares about external PSK to implement it