ref: f436d228d5b6ad5a048a04a8c2401d5328d99270
server/grpc/yats-grpc-server.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
/** * Yats - yats * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Paolo Lulli <kevwe.com> * @copyright Paolo Lulli 2024 */ package grpc import ( "crypto/tls" "crypto/x509" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "log" "net" "os" "yats-server/config" "yats-server/proto" ) type server struct { proto.UnimplementedYatsGrpcServiceServer } func RunUnsecureYatsGrpcServer(address string) { lis, err := net.Listen("tcp", address) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() proto.RegisterYatsGrpcServiceServer(s, &server{}) log.Printf("Server is running on port %s\n", address) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } func NOCARunSecureYatsGrpcServer(conf config.Configuration) { cert, err := tls.LoadX509KeyPair(conf.TlsCertificate, conf.TlsKeyFile) if err != nil { log.Fatal(err) } opts := []grpc.ServerOption{ grpc.Creds(credentials.NewServerTLSFromCert(&cert)), } lis, err := net.Listen("tcp", conf.GrpcAddress) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer(opts...) proto.RegisterYatsGrpcServiceServer(s, &server{}) log.Printf("Server is running on port %s\n", conf.GrpcAddress) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } func RunSecureYatsGrpcServer(conf config.Configuration) { caPem, err := os.ReadFile(conf.TlsCA) if err != nil { log.Fatal(err) } certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(caPem) { log.Fatal(err) } serverCert, err := tls.LoadX509KeyPair(conf.TlsCertificate, conf.TlsKeyFile) if err != nil { log.Fatal(err) } tlsconf := &tls.Config{ Certificates: []tls.Certificate{serverCert}, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: certPool, } lis, err := net.Listen("tcp", conf.GrpcAddress) if err != nil { log.Fatalf("failed to listen: %v", err) } tlsCredentials := credentials.NewTLS(tlsconf) s := grpc.NewServer(grpc.Creds(tlsCredentials)) proto.RegisterYatsGrpcServiceServer(s, &server{}) log.Printf("Server is running on port %s\n", conf.GrpcAddress) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } |