go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/logdog/client/butler/streamserver/namedPipe_windows.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package streamserver
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"os"
    21  	"sync/atomic"
    22  
    23  	"go.chromium.org/luci/common/errors"
    24  	"go.chromium.org/luci/common/logging"
    25  	log "go.chromium.org/luci/common/logging"
    26  	"go.chromium.org/luci/logdog/client/butlerlib/streamproto"
    27  
    28  	"github.com/Microsoft/go-winio"
    29  )
    30  
    31  // maxWindowsNamedPipeLength is the maximum length of a Windows named pipe.
    32  const maxWindowsNamedPipeLength = 256
    33  
    34  var winpipeCounter uint64
    35  
    36  const defaultWinPipePrefix = "logdog_butler"
    37  
    38  // newStreamServer instantiates a new Windows named pipe server instance.
    39  func newStreamServer(ctx context.Context, prefix string) (*StreamServer, error) {
    40  	if prefix == "" {
    41  		prefix = defaultWinPipePrefix
    42  	}
    43  
    44  	path := fmt.Sprintf("%s.%d.%d", prefix, os.Getpid(), atomic.AddUint64(&winpipeCounter, 1))
    45  	realPath := streamproto.LocalNamedPipePath(path)
    46  
    47  	if len(realPath) > maxWindowsNamedPipeLength {
    48  		return nil, errors.Reason("path exceeds maximum length %d", maxWindowsNamedPipeLength).Err()
    49  	}
    50  
    51  	ctx = log.SetField(ctx, "path", path)
    52  	return &StreamServer{
    53  		log:     logging.Get(ctx),
    54  		address: "net.pipe:" + path,
    55  		gen: func() (listener, error) {
    56  			log.Infof(ctx, "Creating Windows server socket Listener.")
    57  
    58  			l, err := winio.ListenPipe(realPath, &winio.PipeConfig{
    59  				InputBufferSize:  1024 * 1024,
    60  				OutputBufferSize: 1024 * 1024,
    61  			})
    62  			if err != nil {
    63  				return nil, errors.Annotate(err, "failed to listen on named pipe").Err()
    64  			}
    65  			return mkListener(l), nil
    66  		},
    67  	}, nil
    68  }