file_windows.mx raw

   1  // Copyright 2011 The Go Authors. All rights reserved.
   2  // Use of this source code is governed by a BSD-style
   3  // license that can be found in the LICENSE file.
   4  
   5  package net
   6  
   7  import (
   8  	"internal/syscall/windows"
   9  	"os"
  10  	"syscall"
  11  )
  12  
  13  const _SO_TYPE = windows.SO_TYPE
  14  
  15  func dupSocket(h syscall.Handle) (syscall.Handle, error) {
  16  	var info syscall.WSAProtocolInfo
  17  	err := windows.WSADuplicateSocket(h, uint32(syscall.Getpid()), &info)
  18  	if err != nil {
  19  		return 0, err
  20  	}
  21  	return windows.WSASocket(-1, -1, -1, &info, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
  22  }
  23  
  24  func dupFileSocket(f *os.File) (syscall.Handle, error) {
  25  	// Call Fd to disassociate the IOCP from the handle,
  26  	// it is not safe to share a duplicated handle
  27  	// that is associated with IOCP.
  28  	// Don't use the returned fd, as it might be closed
  29  	// if f happens to be the last reference to the file.
  30  	f.Fd()
  31  
  32  	sc, err := f.SyscallConn()
  33  	if err != nil {
  34  		return 0, err
  35  	}
  36  
  37  	var h syscall.Handle
  38  	var syserr error
  39  	err = sc.Control(func(fd uintptr) {
  40  		h, syserr = dupSocket(syscall.Handle(fd))
  41  	})
  42  	if err != nil {
  43  		err = syserr
  44  	}
  45  	if err != nil {
  46  		return 0, err
  47  	}
  48  	return h, nil
  49  }
  50