• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1package grpc_hello_fuzz
2
3import (
4	"context"
5	"log"
6	"net"
7	"time"
8
9	"google.golang.org/grpc"
10	pb "google.golang.org/grpc/examples/helloworld/helloworld"
11)
12
13var initialized = 0
14
15type server struct {
16	pb.UnimplementedGreeterServer
17}
18
19// SayHello implements helloworld.GreeterServer
20func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
21	log.Printf("Received: %v", in.GetName())
22	return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
23}
24
25func FuzzHelloServer(data []byte) int {
26	if initialized == 0 {
27		lis, err := net.Listen("tcp", ":50051")
28		if err != nil {
29			log.Printf("failed to listen: %v\n", err)
30			return 0
31		}
32		s := grpc.NewServer()
33		pb.RegisterGreeterServer(s, &server{})
34		// start server as a separate goroutine
35		go func() {
36			if err := s.Serve(lis); err != nil {
37				log.Printf("failed to serve: %v\n", err)
38			}
39		}()
40		initialized = 1
41	}
42
43	conn, err := net.Dial("tcp", "localhost:50051")
44	if err != nil {
45		log.Printf("failed to dial: %v\n", err)
46		return 0
47	}
48	conn.Write(data)
49	response := make([]byte, 1+len(data))
50	n, err := conn.Read(response)
51	conn.Close()
52	if err != nil || n == 0 {
53		return 0
54	}
55	return 1
56}
57
58var fuzzdata []byte
59
60func FuzzHelloClient(data []byte) int {
61	if len(data) == 0 {
62		return 0
63	}
64	if initialized == 0 {
65		lis, err := net.Listen("tcp", ":50051")
66		if err != nil {
67			log.Printf("failed to listen: %v\n", err)
68			return 0
69		}
70		go func() {
71			for {
72				conn, err := lis.Accept()
73				if err != nil {
74					log.Printf("did not accept: %v", err)
75					break
76				}
77				conn.SetDeadline(time.Now().Add(time.Millisecond * 100))
78				request := make([]byte, 24)
79				n, err := conn.Read(request)
80				if err != nil || n == 0 {
81					log.Printf("did not read: %v", err)
82					conn.Close()
83					break
84				}
85				n, err = conn.Write(fuzzdata)
86				if err != nil || n == 0 {
87					log.Printf("did not write: %v", err)
88				}
89				conn.Close()
90			}
91		}()
92		initialized = 1
93	}
94
95	fuzzdata = data
96	// Set up a connection to the server.
97	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10)
98	defer cancel()
99	conn, err := grpc.DialContext(ctx, "localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
100	if err != nil {
101		return 0
102	}
103	defer conn.Close()
104	c := pb.NewGreeterClient(conn)
105
106	// Contact the server and print out its response.
107	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "world"})
108	if err != nil {
109		return 0
110	}
111	r.GetMessage()
112	return 1
113}
114