github.com/pion/dtls/v2@v2.2.12/examples/util/util.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
     2  // SPDX-License-Identifier: MIT
     3  
     4  // Package util provides auxiliary utilities used in examples
     5  package util
     6  
     7  import (
     8  	"bufio"
     9  	"crypto/tls"
    10  	"encoding/pem"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"io/ioutil"
    15  	"net"
    16  	"os"
    17  	"path/filepath"
    18  	"strings"
    19  )
    20  
    21  const bufSize = 8192
    22  
    23  var (
    24  	errBlockIsNotCertificate = errors.New("block is not a certificate, unable to load certificates")
    25  	errNoCertificateFound    = errors.New("no certificate found, unable to load certificates")
    26  )
    27  
    28  // Chat simulates a simple text chat session over the connection
    29  func Chat(conn io.ReadWriter) {
    30  	go func() {
    31  		b := make([]byte, bufSize)
    32  
    33  		for {
    34  			n, err := conn.Read(b)
    35  			Check(err)
    36  			fmt.Printf("Got message: %s\n", string(b[:n]))
    37  		}
    38  	}()
    39  
    40  	reader := bufio.NewReader(os.Stdin)
    41  
    42  	for {
    43  		text, err := reader.ReadString('\n')
    44  		Check(err)
    45  
    46  		if strings.TrimSpace(text) == "exit" {
    47  			return
    48  		}
    49  
    50  		_, err = conn.Write([]byte(text))
    51  		Check(err)
    52  	}
    53  }
    54  
    55  // Check is a helper to throw errors in the examples
    56  func Check(err error) {
    57  	var netError net.Error
    58  	if errors.As(err, &netError) && netError.Temporary() { //nolint:staticcheck
    59  		fmt.Printf("Warning: %v\n", err)
    60  	} else if err != nil {
    61  		fmt.Printf("error: %v\n", err)
    62  		panic(err)
    63  	}
    64  }
    65  
    66  // LoadKeyAndCertificate reads certificates or key from file
    67  func LoadKeyAndCertificate(keyPath string, certificatePath string) (tls.Certificate, error) {
    68  	return tls.LoadX509KeyPair(certificatePath, keyPath)
    69  }
    70  
    71  // LoadCertificate Load/read certificate(s) from file
    72  func LoadCertificate(path string) (*tls.Certificate, error) {
    73  	rawData, err := ioutil.ReadFile(filepath.Clean(path))
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  
    78  	var certificate tls.Certificate
    79  
    80  	for {
    81  		block, rest := pem.Decode(rawData)
    82  		if block == nil {
    83  			break
    84  		}
    85  
    86  		if block.Type != "CERTIFICATE" {
    87  			return nil, errBlockIsNotCertificate
    88  		}
    89  
    90  		certificate.Certificate = append(certificate.Certificate, block.Bytes)
    91  		rawData = rest
    92  	}
    93  
    94  	if len(certificate.Certificate) == 0 {
    95  		return nil, errNoCertificateFound
    96  	}
    97  
    98  	return &certificate, nil
    99  }