rlimit_unix.mx raw

   1  // Copyright 2023 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  //go:build unix || wasip1
   6  
   7  package net
   8  
   9  import "syscall"
  10  
  11  // concurrentThreadsLimit returns the number of threads we permit to
  12  // run concurrently doing DNS lookups via cgo. A DNS lookup may use a
  13  // file descriptor so we limit this to less than the number of
  14  // permitted open files. On some systems, notably Darwin, if
  15  // getaddrinfo is unable to open a file descriptor it simply returns
  16  // EAI_NONAME rather than a useful error. Limiting the number of
  17  // concurrent getaddrinfo calls to less than the permitted number of
  18  // file descriptors makes that error less likely. We don't bother to
  19  // apply the same limit to DNS lookups run directly from Go, because
  20  // there we will return a meaningful "too many open files" error.
  21  func concurrentThreadsLimit() int {
  22  	var rlim syscall.Rlimit
  23  	if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim); err != nil {
  24  		return 500
  25  	}
  26  	r := rlim.Cur
  27  	if r > 500 {
  28  		r = 500
  29  	} else if r > 30 {
  30  		r -= 30
  31  	}
  32  	return int(r)
  33  }
  34