[
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n\n  build:\n    name: Console CI\n    runs-on: ubuntu-22.04\n    timeout-minutes: 5\n    steps:\n\n    - name: Set up Go\n      uses: actions/setup-go@v3\n      with:\n        go-version: 1.19.x\n      id: go\n\n    - name: Setup Go binary path\n      shell: bash\n      run: |\n        echo \"GOPATH=${{ github.workspace }}\" >> $GITHUB_ENV\n        echo \"${{ github.workspace }}/bin\" >> $GITHUB_PATH\n\n    - name: Check out code\n      uses: actions/checkout@v3\n      with:\n        path: src/github.com/containerd/console\n        fetch-depth: 25\n\n    - name: Install dependencies\n      run: |\n        go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1\n\n    - name: Project Checks\n      uses: containerd/project-checks@v1.2.2\n      with:\n        working-directory: src/github.com/containerd/console\n\n    - name: Go Linting\n      run: GOGC=75 golangci-lint run\n      working-directory: src/github.com/containerd/console\n\n    - name: Build & Test\n      working-directory: src/github.com/containerd/console\n      run: |\n        go test -race\n        GOOS=openbsd go build\n        GOOS=windows go build\n"
  },
  {
    "path": ".golangci.yml",
    "content": "linters:\n  enable:\n    - gofmt\n    - goimports\n    - ineffassign\n    - misspell\n    - revive\n    - staticcheck\n    - structcheck\n    - unconvert\n    - unused\n    - varcheck\n    - vet\n  disable:\n    - errcheck\n\nrun:\n  timeout: 3m\n  skip-dirs:\n    - vendor\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        https://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   Copyright The containerd Authors\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       https://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# console\n\n[![PkgGoDev](https://pkg.go.dev/badge/github.com/containerd/console)](https://pkg.go.dev/github.com/containerd/console)\n[![Build Status](https://github.com/containerd/console/workflows/CI/badge.svg)](https://github.com/containerd/console/actions?query=workflow%3ACI)\n[![Go Report Card](https://goreportcard.com/badge/github.com/containerd/console)](https://goreportcard.com/report/github.com/containerd/console)\n\nGolang package for dealing with consoles.  Light on deps and a simple API.\n\n## Modifying the current process\n\n```go\ncurrent := console.Current()\ndefer current.Reset()\n\nif err := current.SetRaw(); err != nil {\n}\nws, err := current.Size()\ncurrent.Resize(ws)\n```\n\n## Project details\n\nconsole is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE).\nAs a containerd sub-project, you will find the:\n * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md),\n * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS),\n * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md)\n\ninformation in our [`containerd/project`](https://github.com/containerd/project) repository.\n"
  },
  {
    "path": "console.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n)\n\nvar (\n\tErrNotAConsole    = errors.New(\"provided file is not a console\")\n\tErrNotImplemented = errors.New(\"not implemented\")\n)\n\ntype File interface {\n\tio.ReadWriteCloser\n\n\t// Fd returns its file descriptor\n\tFd() uintptr\n\t// Name returns its file name\n\tName() string\n}\n\ntype Console interface {\n\tFile\n\n\t// Resize resizes the console to the provided window size\n\tResize(WinSize) error\n\t// ResizeFrom resizes the calling console to the size of the\n\t// provided console\n\tResizeFrom(Console) error\n\t// SetRaw sets the console in raw mode\n\tSetRaw() error\n\t// DisableEcho disables echo on the console\n\tDisableEcho() error\n\t// Reset restores the console to its original state\n\tReset() error\n\t// Size returns the window size of the console\n\tSize() (WinSize, error)\n}\n\n// WinSize specifies the window size of the console\ntype WinSize struct {\n\t// Height of the console\n\tHeight uint16\n\t// Width of the console\n\tWidth uint16\n\tx     uint16\n\ty     uint16\n}\n\n// Current returns the current process' console\nfunc Current() (c Console) {\n\tvar err error\n\t// Usually all three streams (stdin, stdout, and stderr)\n\t// are open to the same console, but some might be redirected,\n\t// so try all three.\n\tfor _, s := range []*os.File{os.Stderr, os.Stdout, os.Stdin} {\n\t\tif c, err = ConsoleFromFile(s); err == nil {\n\t\t\treturn c\n\t\t}\n\t}\n\t// One of the std streams should always be a console\n\t// for the design of this function.\n\tpanic(err)\n}\n\n// ConsoleFromFile returns a console using the provided file\n// nolint:revive\nfunc ConsoleFromFile(f File) (Console, error) {\n\tif err := checkConsole(f); err != nil {\n\t\treturn nil, err\n\t}\n\treturn newMaster(f)\n}\n"
  },
  {
    "path": "console_linux.go",
    "content": "//go:build linux\n// +build linux\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tmaxEvents = 128\n)\n\n// Epoller manages multiple epoll consoles using edge-triggered epoll api so we\n// dont have to deal with repeated wake-up of EPOLLER or EPOLLHUP.\n// For more details, see:\n// - https://github.com/systemd/systemd/pull/4262\n// - https://github.com/moby/moby/issues/27202\n//\n// Example usage of Epoller and EpollConsole can be as follow:\n//\n//\tepoller, _ := NewEpoller()\n//\tepollConsole, _ := epoller.Add(console)\n//\tgo epoller.Wait()\n//\tvar (\n//\t\tb  bytes.Buffer\n//\t\twg sync.WaitGroup\n//\t)\n//\twg.Add(1)\n//\tgo func() {\n//\t\tio.Copy(&b, epollConsole)\n//\t\twg.Done()\n//\t}()\n//\t// perform I/O on the console\n//\tepollConsole.Shutdown(epoller.CloseConsole)\n//\twg.Wait()\n//\tepollConsole.Close()\ntype Epoller struct {\n\tefd       int\n\tmu        sync.Mutex\n\tfdMapping map[int]*EpollConsole\n\tcloseOnce sync.Once\n}\n\n// NewEpoller returns an instance of epoller with a valid epoll fd.\nfunc NewEpoller() (*Epoller, error) {\n\tefd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Epoller{\n\t\tefd:       efd,\n\t\tfdMapping: make(map[int]*EpollConsole),\n\t}, nil\n}\n\n// Add creates an epoll console based on the provided console. The console will\n// be registered with EPOLLET (i.e. using edge-triggered notification) and its\n// file descriptor will be set to non-blocking mode. After this, user should use\n// the return console to perform I/O.\nfunc (e *Epoller) Add(console Console) (*EpollConsole, error) {\n\tsysfd := int(console.Fd())\n\t// Set sysfd to non-blocking mode\n\tif err := unix.SetNonblock(sysfd, true); err != nil {\n\t\treturn nil, err\n\t}\n\n\tev := unix.EpollEvent{\n\t\tEvents: unix.EPOLLIN | unix.EPOLLOUT | unix.EPOLLRDHUP | unix.EPOLLET,\n\t\tFd:     int32(sysfd),\n\t}\n\tif err := unix.EpollCtl(e.efd, unix.EPOLL_CTL_ADD, sysfd, &ev); err != nil {\n\t\treturn nil, err\n\t}\n\tef := &EpollConsole{\n\t\tConsole: console,\n\t\tsysfd:   sysfd,\n\t\treadc:   sync.NewCond(&sync.Mutex{}),\n\t\twritec:  sync.NewCond(&sync.Mutex{}),\n\t}\n\te.mu.Lock()\n\te.fdMapping[sysfd] = ef\n\te.mu.Unlock()\n\treturn ef, nil\n}\n\n// Wait starts the loop to wait for its consoles' notifications and signal\n// appropriate console that it can perform I/O.\nfunc (e *Epoller) Wait() error {\n\tevents := make([]unix.EpollEvent, maxEvents)\n\tfor {\n\t\tn, err := unix.EpollWait(e.efd, events, -1)\n\t\tif err != nil {\n\t\t\t// EINTR: The call was interrupted by a signal handler before either\n\t\t\t// any of the requested events occurred or the timeout expired\n\t\t\tif err == unix.EINTR {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < n; i++ {\n\t\t\tev := &events[i]\n\t\t\t// the console is ready to be read from\n\t\t\tif ev.Events&(unix.EPOLLIN|unix.EPOLLHUP|unix.EPOLLERR) != 0 {\n\t\t\t\tif epfile := e.getConsole(int(ev.Fd)); epfile != nil {\n\t\t\t\t\tepfile.signalRead()\n\t\t\t\t}\n\t\t\t}\n\t\t\t// the console is ready to be written to\n\t\t\tif ev.Events&(unix.EPOLLOUT|unix.EPOLLHUP|unix.EPOLLERR) != 0 {\n\t\t\t\tif epfile := e.getConsole(int(ev.Fd)); epfile != nil {\n\t\t\t\t\tepfile.signalWrite()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n// CloseConsole unregisters the console's file descriptor from epoll interface\nfunc (e *Epoller) CloseConsole(fd int) error {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\tdelete(e.fdMapping, fd)\n\treturn unix.EpollCtl(e.efd, unix.EPOLL_CTL_DEL, fd, &unix.EpollEvent{})\n}\n\nfunc (e *Epoller) getConsole(sysfd int) *EpollConsole {\n\te.mu.Lock()\n\tf := e.fdMapping[sysfd]\n\te.mu.Unlock()\n\treturn f\n}\n\n// Close closes the epoll fd\nfunc (e *Epoller) Close() error {\n\tcloseErr := os.ErrClosed // default to \"file already closed\"\n\te.closeOnce.Do(func() {\n\t\tcloseErr = unix.Close(e.efd)\n\t})\n\treturn closeErr\n}\n\n// EpollConsole acts like a console but registers its file descriptor with an\n// epoll fd and uses epoll API to perform I/O.\ntype EpollConsole struct {\n\tConsole\n\treadc  *sync.Cond\n\twritec *sync.Cond\n\tsysfd  int\n\tclosed bool\n}\n\n// Read reads up to len(p) bytes into p. It returns the number of bytes read\n// (0 <= n <= len(p)) and any error encountered.\n//\n// If the console's read returns EAGAIN or EIO, we assume that it's a\n// temporary error because the other side went away and wait for the signal\n// generated by epoll event to continue.\nfunc (ec *EpollConsole) Read(p []byte) (n int, err error) {\n\tvar read int\n\tec.readc.L.Lock()\n\tdefer ec.readc.L.Unlock()\n\tfor {\n\t\tread, err = ec.Console.Read(p[n:])\n\t\tn += read\n\t\tif err != nil {\n\t\t\tvar hangup bool\n\t\t\tif perr, ok := err.(*os.PathError); ok {\n\t\t\t\thangup = (perr.Err == unix.EAGAIN || perr.Err == unix.EIO)\n\t\t\t} else {\n\t\t\t\thangup = (err == unix.EAGAIN || err == unix.EIO)\n\t\t\t}\n\t\t\t// if the other end disappear, assume this is temporary and wait for the\n\t\t\t// signal to continue again. Unless we didnt read anything and the\n\t\t\t// console is already marked as closed then we should exit\n\t\t\tif hangup && !(n == 0 && len(p) > 0 && ec.closed) {\n\t\t\t\tec.readc.Wait()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\t// if we didnt read anything then return io.EOF to end gracefully\n\tif n == 0 && len(p) > 0 && err == nil {\n\t\terr = io.EOF\n\t}\n\t// signal for others that we finished the read\n\tec.readc.Signal()\n\treturn n, err\n}\n\n// Writes len(p) bytes from p to the console. It returns the number of bytes\n// written from p (0 <= n <= len(p)) and any error encountered that caused\n// the write to stop early.\n//\n// If writes to the console returns EAGAIN or EIO, we assume that it's a\n// temporary error because the other side went away and wait for the signal\n// generated by epoll event to continue.\nfunc (ec *EpollConsole) Write(p []byte) (n int, err error) {\n\tvar written int\n\tec.writec.L.Lock()\n\tdefer ec.writec.L.Unlock()\n\tfor {\n\t\twritten, err = ec.Console.Write(p[n:])\n\t\tn += written\n\t\tif err != nil {\n\t\t\tvar hangup bool\n\t\t\tif perr, ok := err.(*os.PathError); ok {\n\t\t\t\thangup = (perr.Err == unix.EAGAIN || perr.Err == unix.EIO)\n\t\t\t} else {\n\t\t\t\thangup = (err == unix.EAGAIN || err == unix.EIO)\n\t\t\t}\n\t\t\t// if the other end disappears, assume this is temporary and wait for the\n\t\t\t// signal to continue again.\n\t\t\tif hangup {\n\t\t\t\tec.writec.Wait()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// unrecoverable error, break the loop and return the error\n\t\tbreak\n\t}\n\tif n < len(p) && err == nil {\n\t\terr = io.ErrShortWrite\n\t}\n\t// signal for others that we finished the write\n\tec.writec.Signal()\n\treturn n, err\n}\n\n// Shutdown closes the file descriptor and signals call waiters for this fd.\n// It accepts a callback which will be called with the console's fd. The\n// callback typically will be used to do further cleanup such as unregister the\n// console's fd from the epoll interface.\n// User should call Shutdown and wait for all I/O operation to be finished\n// before closing the console.\nfunc (ec *EpollConsole) Shutdown(close func(int) error) error {\n\tec.readc.L.Lock()\n\tdefer ec.readc.L.Unlock()\n\tec.writec.L.Lock()\n\tdefer ec.writec.L.Unlock()\n\n\tec.readc.Broadcast()\n\tec.writec.Broadcast()\n\tec.closed = true\n\treturn close(ec.sysfd)\n}\n\n// signalRead signals that the console is readable.\nfunc (ec *EpollConsole) signalRead() {\n\tec.readc.L.Lock()\n\tec.readc.Signal()\n\tec.readc.L.Unlock()\n}\n\n// signalWrite signals that the console is writable.\nfunc (ec *EpollConsole) signalWrite() {\n\tec.writec.L.Lock()\n\tec.writec.Signal()\n\tec.writec.L.Unlock()\n}\n"
  },
  {
    "path": "console_linux_test.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"sync\"\n\t\"testing\"\n)\n\nfunc TestEpollConsole(t *testing.T) {\n\tconsole, slavePath, err := NewPty()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer console.Close()\n\n\tslave, err := os.OpenFile(slavePath, os.O_RDWR, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer slave.Close()\n\n\titeration := 10\n\n\tcmd := exec.Command(\"sh\", \"-c\", fmt.Sprintf(\"for x in `seq 1 %d`; do echo -n test; done\", iteration))\n\tcmd.Stdin = slave\n\tcmd.Stdout = slave\n\tcmd.Stderr = slave\n\n\tepoller, err := NewEpoller()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tepollConsole, err := epoller.Add(console)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgo epoller.Wait()\n\n\tvar (\n\t\tb  bytes.Buffer\n\t\twg sync.WaitGroup\n\t)\n\twg.Add(1)\n\tgo func() {\n\t\tio.Copy(&b, epollConsole)\n\t\twg.Done()\n\t}()\n\n\tif err := cmd.Run(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tslave.Close()\n\tif err := epollConsole.Shutdown(epoller.CloseConsole); err != nil {\n\t\tt.Fatal(err)\n\t}\n\twg.Wait()\n\tif err := epollConsole.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\texpectedOutput := \"\"\n\tfor i := 0; i < iteration; i++ {\n\t\texpectedOutput += \"test\"\n\t}\n\tif out := b.String(); out != expectedOutput {\n\t\tt.Errorf(\"unexpected output %q\", out)\n\t}\n\n\t// make sure multiple Close calls return os.ErrClosed after the first\n\tif err := epoller.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := epoller.Close(); err != os.ErrClosed {\n\t\tt.Fatalf(\"unexpected error returned from second call to epoller.Close(): %v\", err)\n\t}\n}\n"
  },
  {
    "path": "console_other.go",
    "content": "//go:build !darwin && !freebsd && !linux && !netbsd && !openbsd && !windows && !zos\n// +build !darwin,!freebsd,!linux,!netbsd,!openbsd,!windows,!zos\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\n// NewPty creates a new pty pair\n// The master is returned as the first console and a string\n// with the path to the pty slave is returned as the second\nfunc NewPty() (Console, string, error) {\n\treturn nil, \"\", ErrNotImplemented\n}\n\n// checkConsole checks if the provided file is a console\nfunc checkConsole(f File) error {\n\treturn ErrNotAConsole\n}\n\nfunc newMaster(f File) (Console, error) {\n\treturn nil, ErrNotImplemented\n}\n"
  },
  {
    "path": "console_test.go",
    "content": "//go:build linux || zos || freebsd\n// +build linux zos freebsd\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"os\"\n\t\"os/exec\"\n\t\"sync\"\n\t\"testing\"\n)\n\nfunc TestWinSize(t *testing.T) {\n\tc, _, err := NewPty()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\tif err := c.Resize(WinSize{\n\t\tWidth:  11,\n\t\tHeight: 10,\n\t}); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tsize, err := c.Size()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tif size.Width != 11 {\n\t\tt.Errorf(\"width should be 11 but received %d\", size.Width)\n\t}\n\tif size.Height != 10 {\n\t\tt.Errorf(\"height should be 10 but received %d\", size.Height)\n\t}\n}\n\nfunc testConsolePty(t *testing.T, newPty func() (Console, string, error)) {\n\tconsole, slavePath, err := newPty()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer console.Close()\n\n\tslave, err := os.OpenFile(slavePath, os.O_RDWR, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer slave.Close()\n\n\titeration := 10\n\n\tvar (\n\t\tb  bytes.Buffer\n\t\twg sync.WaitGroup\n\t)\n\twg.Add(1)\n\tgo func() {\n\t\tio.Copy(&b, console)\n\t\twg.Done()\n\t}()\n\n\tfor i := 0; i < iteration; i++ {\n\t\tcmd := exec.Command(\"sh\", \"-c\", \"printf test\")\n\t\tcmd.Stdin = slave\n\t\tcmd.Stdout = slave\n\t\tcmd.Stderr = slave\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tslave.Close()\n\twg.Wait()\n\n\texpectedOutput := \"\"\n\tfor i := 0; i < iteration; i++ {\n\t\texpectedOutput += \"test\"\n\t}\n\tif out := b.String(); out != expectedOutput {\n\t\tt.Errorf(\"unexpected output %q\", out)\n\t}\n}\n\nfunc TestConsolePty_NewPty(t *testing.T) {\n\ttestConsolePty(t, NewPty)\n}\n\nfunc TestConsolePty_NewPtyFromFile(t *testing.T) {\n\ttestConsolePty(t, func() (Console, string, error) {\n\t\t// Equivalent to NewPty().\n\t\tf, err := openpt()\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\treturn NewPtyFromFile(f)\n\t})\n}\n"
  },
  {
    "path": "console_unix.go",
    "content": "//go:build darwin || freebsd || linux || netbsd || openbsd || zos\n// +build darwin freebsd linux netbsd openbsd zos\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"golang.org/x/sys/unix\"\n)\n\n// NewPty creates a new pty pair\n// The master is returned as the first console and a string\n// with the path to the pty slave is returned as the second\nfunc NewPty() (Console, string, error) {\n\tf, err := openpt()\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn NewPtyFromFile(f)\n}\n\n// NewPtyFromFile creates a new pty pair, just like [NewPty] except that the\n// provided [os.File] is used as the master rather than automatically creating\n// a new master from /dev/ptmx. The ownership of [os.File] is passed to the\n// returned [Console], so the caller must be careful to not call Close on the\n// underlying file.\nfunc NewPtyFromFile(f File) (Console, string, error) {\n\tslave, err := ptsname(f)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tif err := unlockpt(f); err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tm, err := newMaster(f)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn m, slave, nil\n}\n\ntype master struct {\n\tf        File\n\toriginal *unix.Termios\n}\n\nfunc (m *master) Read(b []byte) (int, error) {\n\treturn m.f.Read(b)\n}\n\nfunc (m *master) Write(b []byte) (int, error) {\n\treturn m.f.Write(b)\n}\n\nfunc (m *master) Close() error {\n\treturn m.f.Close()\n}\n\nfunc (m *master) Resize(ws WinSize) error {\n\treturn tcswinsz(m.f.Fd(), ws)\n}\n\nfunc (m *master) ResizeFrom(c Console) error {\n\tws, err := c.Size()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.Resize(ws)\n}\n\nfunc (m *master) Reset() error {\n\tif m.original == nil {\n\t\treturn nil\n\t}\n\treturn tcset(m.f.Fd(), m.original)\n}\n\nfunc (m *master) getCurrent() (unix.Termios, error) {\n\tvar termios unix.Termios\n\tif err := tcget(m.f.Fd(), &termios); err != nil {\n\t\treturn unix.Termios{}, err\n\t}\n\treturn termios, nil\n}\n\nfunc (m *master) SetRaw() error {\n\trawState, err := m.getCurrent()\n\tif err != nil {\n\t\treturn err\n\t}\n\trawState = cfmakeraw(rawState)\n\trawState.Oflag = rawState.Oflag | unix.OPOST\n\treturn tcset(m.f.Fd(), &rawState)\n}\n\nfunc (m *master) DisableEcho() error {\n\trawState, err := m.getCurrent()\n\tif err != nil {\n\t\treturn err\n\t}\n\trawState.Lflag = rawState.Lflag &^ unix.ECHO\n\treturn tcset(m.f.Fd(), &rawState)\n}\n\nfunc (m *master) Size() (WinSize, error) {\n\treturn tcgwinsz(m.f.Fd())\n}\n\nfunc (m *master) Fd() uintptr {\n\treturn m.f.Fd()\n}\n\nfunc (m *master) Name() string {\n\treturn m.f.Name()\n}\n\n// checkConsole checks if the provided file is a console\nfunc checkConsole(f File) error {\n\tvar termios unix.Termios\n\tif tcget(f.Fd(), &termios) != nil {\n\t\treturn ErrNotAConsole\n\t}\n\treturn nil\n}\n\nfunc newMaster(f File) (Console, error) {\n\tm := &master{\n\t\tf: f,\n\t}\n\tt, err := m.getCurrent()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.original = &t\n\treturn m, nil\n}\n\n// ClearONLCR sets the necessary tty_ioctl(4)s to ensure that a pty pair\n// created by us acts normally. In particular, a not-very-well-known default of\n// Linux unix98 ptys is that they have +onlcr by default. While this isn't a\n// problem for terminal emulators, because we relay data from the terminal we\n// also relay that funky line discipline.\nfunc ClearONLCR(fd uintptr) error {\n\treturn setONLCR(fd, false)\n}\n\n// SetONLCR sets the necessary tty_ioctl(4)s to ensure that a pty pair\n// created by us acts as intended for a terminal emulator.\nfunc SetONLCR(fd uintptr) error {\n\treturn setONLCR(fd, true)\n}\n"
  },
  {
    "path": "console_windows.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org/x/sys/windows\"\n)\n\nvar vtInputSupported bool\n\nfunc (m *master) initStdios() {\n\t// Note: We discard console mode warnings, because in/out can be redirected.\n\t//\n\t// TODO: Investigate opening CONOUT$/CONIN$ to handle this correctly\n\n\tm.in = windows.Handle(os.Stdin.Fd())\n\tif err := windows.GetConsoleMode(m.in, &m.inMode); err == nil {\n\t\t// Validate that windows.ENABLE_VIRTUAL_TERMINAL_INPUT is supported, but do not set it.\n\t\tif err = windows.SetConsoleMode(m.in, m.inMode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err == nil {\n\t\t\tvtInputSupported = true\n\t\t}\n\t\t// Unconditionally set the console mode back even on failure because SetConsoleMode\n\t\t// remembers invalid bits on input handles.\n\t\twindows.SetConsoleMode(m.in, m.inMode)\n\t}\n\n\tm.out = windows.Handle(os.Stdout.Fd())\n\tif err := windows.GetConsoleMode(m.out, &m.outMode); err == nil {\n\t\tif err := windows.SetConsoleMode(m.out, m.outMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err == nil {\n\t\t\tm.outMode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING\n\t\t} else {\n\t\t\twindows.SetConsoleMode(m.out, m.outMode)\n\t\t}\n\t}\n\n\tm.err = windows.Handle(os.Stderr.Fd())\n\tif err := windows.GetConsoleMode(m.err, &m.errMode); err == nil {\n\t\tif err := windows.SetConsoleMode(m.err, m.errMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err == nil {\n\t\t\tm.errMode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING\n\t\t} else {\n\t\t\twindows.SetConsoleMode(m.err, m.errMode)\n\t\t}\n\t}\n}\n\ntype master struct {\n\tin     windows.Handle\n\tinMode uint32\n\n\tout     windows.Handle\n\toutMode uint32\n\n\terr     windows.Handle\n\terrMode uint32\n}\n\nfunc (m *master) SetRaw() error {\n\tif err := makeInputRaw(m.in, m.inMode); err != nil {\n\t\treturn err\n\t}\n\n\t// Set StdOut and StdErr to raw mode, we ignore failures since\n\t// windows.DISABLE_NEWLINE_AUTO_RETURN might not be supported on this version of\n\t// Windows.\n\n\twindows.SetConsoleMode(m.out, m.outMode|windows.DISABLE_NEWLINE_AUTO_RETURN)\n\n\twindows.SetConsoleMode(m.err, m.errMode|windows.DISABLE_NEWLINE_AUTO_RETURN)\n\n\treturn nil\n}\n\nfunc (m *master) Reset() error {\n\tvar errs []error\n\n\tfor _, s := range []struct {\n\t\tfd   windows.Handle\n\t\tmode uint32\n\t}{\n\t\t{m.in, m.inMode},\n\t\t{m.out, m.outMode},\n\t\t{m.err, m.errMode},\n\t} {\n\t\tif err := windows.SetConsoleMode(s.fd, s.mode); err != nil {\n\t\t\t// we can't just abort on the first error, otherwise we might leave\n\t\t\t// the console in an unexpected state.\n\t\t\terrs = append(errs, fmt.Errorf(\"unable to restore console mode: %w\", err))\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn errs[0]\n\t}\n\n\treturn nil\n}\n\nfunc (m *master) Size() (WinSize, error) {\n\tvar info windows.ConsoleScreenBufferInfo\n\terr := windows.GetConsoleScreenBufferInfo(m.out, &info)\n\tif err != nil {\n\t\treturn WinSize{}, fmt.Errorf(\"unable to get console info: %w\", err)\n\t}\n\n\twinsize := WinSize{\n\t\tWidth:  uint16(info.Window.Right - info.Window.Left + 1),\n\t\tHeight: uint16(info.Window.Bottom - info.Window.Top + 1),\n\t}\n\n\treturn winsize, nil\n}\n\nfunc (m *master) Resize(ws WinSize) error {\n\treturn ErrNotImplemented\n}\n\nfunc (m *master) ResizeFrom(c Console) error {\n\treturn ErrNotImplemented\n}\n\nfunc (m *master) DisableEcho() error {\n\tmode := m.inMode &^ windows.ENABLE_ECHO_INPUT\n\tmode |= windows.ENABLE_PROCESSED_INPUT\n\tmode |= windows.ENABLE_LINE_INPUT\n\n\tif err := windows.SetConsoleMode(m.in, mode); err != nil {\n\t\treturn fmt.Errorf(\"unable to set console to disable echo: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (m *master) Close() error {\n\treturn nil\n}\n\nfunc (m *master) Read(b []byte) (int, error) {\n\treturn os.Stdin.Read(b)\n}\n\nfunc (m *master) Write(b []byte) (int, error) {\n\treturn os.Stdout.Write(b)\n}\n\nfunc (m *master) Fd() uintptr {\n\treturn uintptr(m.in)\n}\n\n// on windows, console can only be made from os.Std{in,out,err}, hence there\n// isnt a single name here we can use. Return a dummy \"console\" value in this\n// case should be sufficient.\nfunc (m *master) Name() string {\n\treturn \"console\"\n}\n\n// makeInputRaw puts the terminal (Windows Console) connected to the given\n// file descriptor into raw mode\nfunc makeInputRaw(fd windows.Handle, mode uint32) error {\n\t// See\n\t// -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx\n\t// -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx\n\n\t// Disable these modes\n\tmode &^= windows.ENABLE_ECHO_INPUT\n\tmode &^= windows.ENABLE_LINE_INPUT\n\tmode &^= windows.ENABLE_MOUSE_INPUT\n\tmode &^= windows.ENABLE_WINDOW_INPUT\n\tmode &^= windows.ENABLE_PROCESSED_INPUT\n\n\t// Enable these modes\n\tmode |= windows.ENABLE_EXTENDED_FLAGS\n\tmode |= windows.ENABLE_INSERT_MODE\n\tmode |= windows.ENABLE_QUICK_EDIT_MODE\n\n\tif vtInputSupported {\n\t\tmode |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT\n\t}\n\n\tif err := windows.SetConsoleMode(fd, mode); err != nil {\n\t\treturn fmt.Errorf(\"unable to set console to raw mode: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc checkConsole(f File) error {\n\tvar mode uint32\n\tif err := windows.GetConsoleMode(windows.Handle(f.Fd()), &mode); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newMaster(f File) (Console, error) {\n\tif f != os.Stdin && f != os.Stdout && f != os.Stderr {\n\t\treturn nil, errors.New(\"creating a console from a file is not supported on windows\")\n\t}\n\tm := &master{}\n\tm.initStdios()\n\treturn m, nil\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/containerd/console\n\ngo 1.13\n\nrequire golang.org/x/sys v0.1.0\n"
  },
  {
    "path": "go.sum",
    "content": "golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=\ngolang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\n"
  },
  {
    "path": "pty_freebsd_cgo.go",
    "content": "//go:build freebsd && cgo\n// +build freebsd,cgo\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n/*\n#include <fcntl.h>\n#include <stdlib.h>\n#include <unistd.h>\n*/\nimport \"C\"\n\n// openpt allocates a new pseudo-terminal and establishes a connection with its\n// control device.\nfunc openpt() (*os.File, error) {\n\tfd, err := C.posix_openpt(C.O_RDWR)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"posix_openpt: %w\", err)\n\t}\n\tif _, err := C.grantpt(fd); err != nil {\n\t\tC.close(fd)\n\t\treturn nil, fmt.Errorf(\"grantpt: %w\", err)\n\t}\n\treturn os.NewFile(uintptr(fd), \"\"), nil\n}\n"
  },
  {
    "path": "pty_freebsd_nocgo.go",
    "content": "//go:build freebsd && !cgo\n// +build freebsd,!cgo\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"os\"\n)\n\n//\n// Implementing the functions below requires cgo support.  Non-cgo stubs\n// versions are defined below to enable cross-compilation of source code\n// that depends on these functions, but the resultant cross-compiled\n// binaries cannot actually be used.  If the stub function(s) below are\n// actually invoked they will display an error message and cause the\n// calling process to exit.\n//\n\nfunc openpt() (*os.File, error) {\n\tpanic(\"openpt() support requires cgo.\")\n}\n"
  },
  {
    "path": "pty_unix.go",
    "content": "//go:build darwin || linux || netbsd || openbsd\n// +build darwin linux netbsd openbsd\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"os\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n// openpt allocates a new pseudo-terminal by opening the /dev/ptmx device\nfunc openpt() (*os.File, error) {\n\treturn os.OpenFile(\"/dev/ptmx\", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)\n}\n"
  },
  {
    "path": "pty_zos.go",
    "content": "//go:build zos\n// +build zos\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n// openpt allocates a new pseudo-terminal by opening the first available /dev/ptypXX device\nfunc openpt() (*os.File, error) {\n\tvar f *os.File\n\tvar err error\n\tfor i := 0; ; i++ {\n\t\tptyp := fmt.Sprintf(\"/dev/ptyp%04d\", i)\n\t\tf, err = os.OpenFile(ptyp, os.O_RDWR, 0600)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\t// else probably Resource Busy\n\t}\n\treturn f, nil\n}\n"
  },
  {
    "path": "tc_darwin.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TIOCGETA\n\tcmdTcSet = unix.TIOCSETA\n)\n\n// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.\n// unlockpt should be called before opening the slave side of a pty.\nfunc unlockpt(f File) error {\n\treturn unix.IoctlSetPointerInt(int(f.Fd()), unix.TIOCPTYUNLK, 0)\n}\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\tn, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCPTYGNAME)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n"
  },
  {
    "path": "tc_freebsd_cgo.go",
    "content": "//go:build freebsd && cgo\n// +build freebsd,cgo\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\n/*\n#include <stdlib.h>\n#include <unistd.h>\n*/\nimport \"C\"\n\nconst (\n\tcmdTcGet = unix.TIOCGETA\n\tcmdTcSet = unix.TIOCSETA\n)\n\n// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.\n// unlockpt should be called before opening the slave side of a pty.\nfunc unlockpt(f File) error {\n\tfd := C.int(f.Fd())\n\tif _, err := C.unlockpt(fd); err != nil {\n\t\tC.close(fd)\n\t\treturn fmt.Errorf(\"unlockpt: %w\", err)\n\t}\n\treturn nil\n}\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\tn, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n"
  },
  {
    "path": "tc_freebsd_nocgo.go",
    "content": "//go:build freebsd && !cgo\n// +build freebsd,!cgo\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TIOCGETA\n\tcmdTcSet = unix.TIOCSETA\n)\n\n//\n// Implementing the functions below requires cgo support.  Non-cgo stubs\n// versions are defined below to enable cross-compilation of source code\n// that depends on these functions, but the resultant cross-compiled\n// binaries cannot actually be used.  If the stub function(s) below are\n// actually invoked they will display an error message and cause the\n// calling process to exit.\n//\n\n// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.\n// unlockpt should be called before opening the slave side of a pty.\nfunc unlockpt(f File) error {\n\tpanic(\"unlockpt() support requires cgo.\")\n}\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\tn, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", n), nil\n}\n"
  },
  {
    "path": "tc_linux.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TCGETS\n\tcmdTcSet = unix.TCSETS\n)\n\n// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.\n// unlockpt should be called before opening the slave side of a pty.\nfunc unlockpt(f File) error {\n\tvar u int32\n\t// XXX do not use unix.IoctlSetPointerInt here, see commit dbd69c59b81.\n\tif _, _, err := unix.Syscall(unix.SYS_IOCTL, f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u))); err != 0 {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\tvar u uint32\n\t// XXX do not use unix.IoctlGetInt here, see commit dbd69c59b81.\n\tif _, _, err := unix.Syscall(unix.SYS_IOCTL, f.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&u))); err != 0 {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"/dev/pts/%d\", u), nil\n}\n"
  },
  {
    "path": "tc_netbsd.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"bytes\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TIOCGETA\n\tcmdTcSet = unix.TIOCSETA\n)\n\n// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.\n// unlockpt should be called before opening the slave side of a pty.\n// This does not exist on NetBSD, it does not allocate controlling terminals on open\nfunc unlockpt(f File) error {\n\treturn nil\n}\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\tptm, err := unix.IoctlGetPtmget(int(f.Fd()), unix.TIOCPTSNAME)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(ptm.Sn[:bytes.IndexByte(ptm.Sn[:], 0)]), nil\n}\n"
  },
  {
    "path": "tc_openbsd_cgo.go",
    "content": "//go:build openbsd && cgo\n// +build openbsd,cgo\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"golang.org/x/sys/unix\"\n)\n\n//#include <stdlib.h>\nimport \"C\"\n\nconst (\n\tcmdTcGet = unix.TIOCGETA\n\tcmdTcSet = unix.TIOCSETA\n)\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\tptspath, err := C.ptsname(C.int(f.Fd()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn C.GoString(ptspath), nil\n}\n\n// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.\n// unlockpt should be called before opening the slave side of a pty.\nfunc unlockpt(f File) error {\n\tif _, err := C.grantpt(C.int(f.Fd())); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "tc_openbsd_nocgo.go",
    "content": "//go:build openbsd && !cgo\n// +build openbsd,!cgo\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n//\n// Implementing the functions below requires cgo support.  Non-cgo stubs\n// versions are defined below to enable cross-compilation of source code\n// that depends on these functions, but the resultant cross-compiled\n// binaries cannot actually be used.  If the stub function(s) below are\n// actually invoked they will display an error message and cause the\n// calling process to exit.\n//\n\npackage console\n\nimport (\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TIOCGETA\n\tcmdTcSet = unix.TIOCSETA\n)\n\nfunc ptsname(f File) (string, error) {\n\tpanic(\"ptsname() support requires cgo.\")\n}\n\nfunc unlockpt(f File) error {\n\tpanic(\"unlockpt() support requires cgo.\")\n}\n"
  },
  {
    "path": "tc_unix.go",
    "content": "//go:build darwin || freebsd || linux || netbsd || openbsd || zos\n// +build darwin freebsd linux netbsd openbsd zos\n\n/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"golang.org/x/sys/unix\"\n)\n\nfunc tcget(fd uintptr, p *unix.Termios) error {\n\ttermios, err := unix.IoctlGetTermios(int(fd), cmdTcGet)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*p = *termios\n\treturn nil\n}\n\nfunc tcset(fd uintptr, p *unix.Termios) error {\n\treturn unix.IoctlSetTermios(int(fd), cmdTcSet, p)\n}\n\nfunc tcgwinsz(fd uintptr) (WinSize, error) {\n\tvar ws WinSize\n\n\tuws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ)\n\tif err != nil {\n\t\treturn ws, err\n\t}\n\n\t// Translate from unix.Winsize to console.WinSize\n\tws.Height = uws.Row\n\tws.Width = uws.Col\n\tws.x = uws.Xpixel\n\tws.y = uws.Ypixel\n\treturn ws, nil\n}\n\nfunc tcswinsz(fd uintptr, ws WinSize) error {\n\t// Translate from console.WinSize to unix.Winsize\n\n\tvar uws unix.Winsize\n\tuws.Row = ws.Height\n\tuws.Col = ws.Width\n\tuws.Xpixel = ws.x\n\tuws.Ypixel = ws.y\n\n\treturn unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, &uws)\n}\n\nfunc setONLCR(fd uintptr, enable bool) error {\n\tvar termios unix.Termios\n\tif err := tcget(fd, &termios); err != nil {\n\t\treturn err\n\t}\n\tif enable {\n\t\t// Set +onlcr so we can act like a real terminal\n\t\ttermios.Oflag |= unix.ONLCR\n\t} else {\n\t\t// Set -onlcr so we don't have to deal with \\r.\n\t\ttermios.Oflag &^= unix.ONLCR\n\t}\n\treturn tcset(fd, &termios)\n}\n\nfunc cfmakeraw(t unix.Termios) unix.Termios {\n\tt.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON)\n\tt.Oflag &^= unix.OPOST\n\tt.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN)\n\tt.Cflag &^= (unix.CSIZE | unix.PARENB)\n\tt.Cflag |= unix.CS8\n\tt.Cc[unix.VMIN] = 1\n\tt.Cc[unix.VTIME] = 0\n\n\treturn t\n}\n"
  },
  {
    "path": "tc_zos.go",
    "content": "/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\npackage console\n\nimport (\n\t\"strings\"\n\n\t\"golang.org/x/sys/unix\"\n)\n\nconst (\n\tcmdTcGet = unix.TCGETS\n\tcmdTcSet = unix.TCSETS\n)\n\n// unlockpt is a no-op on zos.\nfunc unlockpt(File) error {\n\treturn nil\n}\n\n// ptsname retrieves the name of the first available pts for the given master.\nfunc ptsname(f File) (string, error) {\n\treturn \"/dev/ttyp\" + strings.TrimPrefix(f.Name(), \"/dev/ptyp\"), nil\n}\n"
  }
]