[
  {
    "path": ".github/workflows/hydrun.yaml",
    "content": "name: hydrun CI\n\non:\n  push:\n  pull_request:\n  schedule:\n    - cron: \"0 0 * * 0\"\n\njobs:\n  build-linux:\n    runs-on: ${{ matrix.target.runner }}\n    permissions:\n      contents: read\n    strategy:\n      matrix:\n        target:\n          # Tests\n          - id: test\n            src: .\n            os: golang:bookworm\n            flags: -e '-v /tmp/ccache:/root/.cache/go-build'\n            cmd: GOFLAGS=\"-short\" ./Hydrunfile test\n            dst: out/nonexistent\n            runner: ubuntu-latest\n\n          # We don't vendor the binaries\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n      - name: Restore ccache\n        uses: actions/cache/restore@v4\n        with:\n          path: |\n            /tmp/ccache\n          key: cache-ccache-${{ matrix.target.id }}\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n      - name: Set up hydrun\n        run: |\n          curl -L -o /tmp/hydrun \"https://github.com/pojntfx/hydrun/releases/latest/download/hydrun.linux-$(uname -m)\"\n          sudo install /tmp/hydrun /usr/local/bin\n      - name: Build with hydrun\n        working-directory: ${{ matrix.target.src }}\n        run: hydrun -o ${{ matrix.target.os }} ${{ matrix.target.flags }} \"${{ matrix.target.cmd }}\"\n      - name: Fix permissions for output\n        run: sudo chown -R $USER .\n      - name: Save ccache\n        uses: actions/cache/save@v4\n        with:\n          path: |\n            /tmp/ccache\n          key: cache-ccache-${{ matrix.target.id }}\n      - name: Upload output\n        uses: actions/upload-artifact@v4\n        with:\n          name: ${{ matrix.target.id }}\n          path: ${{ matrix.target.dst }}\n\n  publish-linux:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n    needs: build-linux\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n      - name: Download output\n        uses: actions/download-artifact@v4\n        with:\n          path: /tmp/out\n      - name: Extract branch name\n        id: extract_branch\n        run: echo \"##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})\"\n      - name: Publish pre-release to GitHub releases\n        if: ${{ github.ref == 'refs/heads/main' }}\n        uses: softprops/action-gh-release@v2\n        with:\n          tag_name: release-${{ steps.extract_branch.outputs.branch }}\n          prerelease: true\n          files: |\n            /tmp/out/*/*\n      - name: Publish release to GitHub releases\n        if: startsWith(github.ref, 'refs/tags/v')\n        uses: softprops/action-gh-release@v2\n        with:\n          prerelease: false\n          files: |\n            /tmp/out/*/*\n"
  },
  {
    "path": ".gitignore",
    "content": "out\n"
  },
  {
    "path": "Hydrunfile",
    "content": "#!/bin/bash\n\nset -e\n\n# Test\nif [ \"$1\" = \"test\" ]; then\n  # Configure Git\n  git config --global --add safe.directory '*'\n\n  # Generate dependencies\n  make depend\n\n  # Run tests\n  make test\n\n  exit 0\nfi\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n\"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n\"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\n\n\"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\n\n\"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\n\n\"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\n\n\"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\n\n     (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n     (b) You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n     (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\n\n     (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.\n\n     You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\nTo apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!)  The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "Makefile",
    "content": "# Public variables\nDESTDIR ?=\nPREFIX ?= /usr/local\nOUTPUT_DIR ?= out\nDST ?=\n\n# Private variables\nobj = go-nbd-example-client go-nbd-example-server-file go-nbd-example-server-memory\nall: $(addprefix build/,$(obj))\n\n# Build\nbuild: $(addprefix build/,$(obj))\n$(addprefix build/,$(obj)):\nifdef DST\n\tgo build -o $(DST) ./cmd/$(subst build/,,$@)\nelse\n\tgo build -o $(OUTPUT_DIR)/$(subst build/,,$@) ./cmd/$(subst build/,,$@)\nendif\n\n# Install\ninstall: $(addprefix install/,$(obj))\n$(addprefix install/,$(obj)):\n\tinstall -D -m 0755 $(OUTPUT_DIR)/$(subst install/,,$@) $(DESTDIR)$(PREFIX)/bin/$(subst install/,,$@)\n\n# Uninstall\nuninstall: $(addprefix uninstall/,$(obj))\n$(addprefix uninstall/,$(obj)):\n\trm $(DESTDIR)$(PREFIX)/bin/$(subst uninstall/,,$@)\n\n# Run\n$(addprefix run/,$(obj)):\n\t$(subst run/,,$@) $(ARGS)\n\n# Test\ntest:\n\tgo test -timeout 3600s -parallel $(shell nproc) ./...\n\n# Benchmark\nbenchmark:\n\tgo test -timeout 3600s -bench=./... ./...\n\n# Clean\nclean:\n\trm -rf out\n\n# Dependencies\ndepend:\n\ttrue"
  },
  {
    "path": "README.md",
    "content": "<img alt=\"Project icon\" style=\"vertical-align: middle;\" src=\"./docs/icon.svg\" width=\"128\" height=\"128\" align=\"left\">\n\n# go-nbd\n\nPure Go NBD server and client library.\n\n<br/>\n\n[![hydrun CI](https://github.com/pojntfx/go-nbd/actions/workflows/hydrun.yaml/badge.svg)](https://github.com/pojntfx/go-nbd/actions/workflows/hydrun.yaml)\n![Go Version](https://img.shields.io/badge/go%20version-%3E=1.20-61CFDD.svg)\n[![Go Reference](https://pkg.go.dev/badge/github.com/pojntfx/go-nbd.svg)](https://pkg.go.dev/github.com/pojntfx/go-nbd)\n[![Matrix](https://img.shields.io/matrix/go-nbd:matrix.org)](https://matrix.to/#/#go-nbd:matrix.org?via=matrix.org)\n\n## Overview\n\ngo-nbd is a lean NBD server and client library supporting the baseline protocol.\n\nIt enables you to:\n\n- **Build NBD servers and clients in Go:** Develop Network Block Device servers and clients using the efficient and easy-to-understand Go programming language, without having to fallback to CGo.\n- **Expose any `io.ReadWriter` as a block device:** Effortlessly turn a file, byte slice, S3 bucket or other `io.ReadWriter` into a fully-fledged block device.\n- **Bridge with legacy services:** If you need to make your application's dynamic data available to a legacy system, providing a NBD interface can be the perfect solution.\n\n## Installation\n\nYou can add go-nbd to your Go project by running the following:\n\n```shell\n$ go get github.com/pojntfx/go-nbd/...@latest\n```\n\n## Tutorial\n\n> TL;DR: Define a backend, expose it with a server, connect a block device with the client and setup/mount the filesystem.\n\n### 1. Define a Backend\n\nFirst, define a backend; it should conform to this simple interface:\n\n```go\ntype Backend interface {\n\tReadAt(p []byte, off int64) (n int, err error)\n\tWriteAt(p []byte, off int64) (n int, err error)\n\tSize() (int64, error)\n\tSync() error\n}\n```\n\nA simple file-based backend could look like this:\n\n```go\n// server/main.go\n\ntype FileBackend struct {\n\tfile *os.File\n\tlock sync.RWMutex\n}\n\nfunc NewFileBackend(file *os.File) *FileBackend {\n\treturn &FileBackend{file, sync.RWMutex{}}\n}\n\nfunc (b *FileBackend) ReadAt(p []byte, off int64) (n int, err error) {\n\tb.lock.RLock()\n\n\tn, err = b.file.ReadAt(p, off)\n\n\tb.lock.RUnlock()\n\n\treturn\n}\n\nfunc (b *FileBackend) WriteAt(p []byte, off int64) (n int, err error) {\n\tb.lock.Lock()\n\n\tn, err = b.file.WriteAt(p, off)\n\n\tb.lock.Unlock()\n\n\treturn\n}\n\nfunc (b *FileBackend) Size() (int64, error) {\n\tstat, err := b.file.Stat()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn stat.Size(), nil\n}\n\nfunc (b *FileBackend) Sync() error {\n\treturn b.file.Sync()\n}\n```\n\nSee [pkg/backend](./pkg/backend) for more backend examples.\n\n### 2. Expose the Backend With a Server\n\nNext, create the backend and expose it with a server:\n\n```go\n// server/main.go\n\nb := NewFileBackend(f)\n\nfor {\n\tconn, err := l.Accept()\n\tif err != nil {\n\t\tcontinue\n\t}\n\n\tgo func() {\n\t\tif err := server.Handle(\n\t\t\tconn,\n\t\t\t[]server.Export{\n\t\t\t\t{\n\t\t\t\t\tName:        *name,\n\t\t\t\t\tDescription: *description,\n\t\t\t\t\tBackend:     b,\n\t\t\t\t},\n\t\t\t},\n\t\t\t&server.Options{\n\t\t\t\tReadOnly:           *readOnly,\n\t\t\t\tMinimumBlockSize:   uint32(*minimumBlockSize),\n\t\t\t\tPreferredBlockSize: uint32(*preferredBlockSize),\n\t\t\t\tMaximumBlockSize:   uint32(*maximumBlockSize),\n\t\t\t}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}\n```\n\nSee [cmd/go-nbd-example-server-file/main.go](./cmd/go-nbd-example-server-file/main.go) for the full example.\n\n### 3. Connect to the Server with a Client\n\nIn a new `main` package, connect to the server by creating a client; note that you'll have to `modprobe nbd` and run the command as `root`:\n\n```go\n// client/main.go\n\nif err := client.Connect(conn, f, &client.Options{\n\tExportName: *name,\n\tBlockSize:  uint32(*blockSize),\n}); err != nil {\n\tpanic(err)\n}\n```\n\nSee [cmd/go-nbd-example-client/main.go](./cmd/go-nbd-example-client/main.go) for the full example.\n\n### 4. Setup and Mount the Filesystem\n\nLastly, create a filesystem on the block device and mount it:\n\n```shell\n$ sudo mkfs.ext4 /dev/nbd0\n$ sudo mkdir -p /mnt\n$ sudo mount -t ext4 /dev/nbd0 /mnt\n```\n\nYou should now be able to use the mounted filesystem by navigating to `/mnt`.\n\n🚀 That's it! We can't wait to see what you're going to build with go-nbd.\n\n## Examples\n\nTo make getting started with go-nbd easier, take a look at the following examples:\n\n- [NBD File Server](./cmd/go-nbd-example-server-file/main.go)\n- [NBD Memory Server](./cmd/go-nbd-example-server-memory/main.go)\n- [NBD Client](./cmd/go-nbd-example-client/main.go)\n\n## Acknowledgements\n\n- [abligh/gonbdserver](https://github.com/abligh/gonbdserver/) provided the initial inspiration for this project.\n- [NetworkBlockDevice/nbd](https://github.com/NetworkBlockDevice/nbd/blob/master/doc/proto.md) provided the NBD protocol documentation.\n\n## Contributing\n\nTo contribute, please use the [GitHub flow](https://guides.github.com/introduction/flow/) and follow our [Code of Conduct](./CODE_OF_CONDUCT.md).\n\nTo build and start a development version of one of the examples locally, run the following:\n\n```shell\n$ git clone https://github.com/pojntfx/go-nbd.git\n$ cd go-nbd\n$ mkdir -p out && rm -f out/disk.img && truncate -s 10G out/disk.img && go run ./cmd/go-nbd-example-server-file --file out/disk.img\n$ go run ./cmd/go-nbd-example-server-memory\n\n# With the C NBD client\n$ sudo umount ~/Downloads/mnt; sudo nbd-client -d /dev/nbd1 && echo 'NBD starting' | sudo tee /dev/kmsg && sudo nbd-client -N default localhost 10809 /dev/nbd1\n\n# With the Go NBD client\n$ sudo umount ~/Downloads/mnt; go build -o /tmp/go-nbd-example-client ./cmd/go-nbd-example-client/ && sudo /tmp/go-nbd-example-client --file /dev/nbd1\n\n$ sudo mkfs.ext4 /dev/nbd1\n$ sync -f ~/Downloads/mnt; sudo umount ~/Downloads/mnt; sudo rm -rf ~/Downloads/mnt && sudo mkdir -p ~/Downloads/mnt && sudo mount -t ext4 /dev/nbd1 ~/Downloads/mnt && sudo chown -R \"${USER}\" ~/Downloads/mnt\n```\n\nHave any questions or need help? Chat with us [on Matrix](https://matrix.to/#/#go-nbd:matrix.org?via=matrix.org)!\n\n## License\n\ngo-nbd (c) 2024 Felicitas Pojtinger and contributors\n\nSPDX-License-Identifier: Apache-2.0\n"
  },
  {
    "path": "cmd/go-nbd-example-client/main.go",
    "content": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/pojntfx/go-nbd/pkg/client\"\n)\n\nfunc main() {\n\tfile := flag.String(\"file\", \"/dev/nbd0\", \"Path to device file to create\")\n\traddr := flag.String(\"raddr\", \"127.0.0.1:10809\", \"Remote address\")\n\tnetwork := flag.String(\"network\", \"tcp\", \"Remote network (e.g. `tcp` or `unix`)\")\n\tname := flag.String(\"name\", \"default\", \"Export name\")\n\tlist := flag.Bool(\"list\", false, \"List the exports and exit\")\n\tblockSize := flag.Uint(\"block-size\", 0, \"Block size to use; 0 uses the server's preferred block size\")\n\n\tflag.Parse()\n\n\tconn, err := net.Dial(*network, *raddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer conn.Close()\n\n\tlog.Println(\"Connected to\", conn.RemoteAddr())\n\n\tif *list {\n\t\texports, err := client.List(conn)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif err := json.NewEncoder(os.Stdout).Encode(exports); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\treturn\n\t}\n\n\tf, err := os.Open(*file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, os.Interrupt)\n\n\tgo func() {\n\t\tfor range sigCh {\n\t\t\tif err := client.Disconnect(f); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\tif err := client.Connect(conn, f, &client.Options{\n\t\tExportName: *name,\n\t\tBlockSize:  uint32(*blockSize),\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  },
  {
    "path": "cmd/go-nbd-example-server-file/main.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com/pojntfx/go-nbd/pkg/backend\"\n\t\"github.com/pojntfx/go-nbd/pkg/client\"\n\t\"github.com/pojntfx/go-nbd/pkg/server\"\n)\n\nfunc main() {\n\tfile := flag.String(\"file\", \"disk.img\", \"Path to file to expose\")\n\tladdr := flag.String(\"laddr\", \":10809\", \"Listen address\")\n\tnetwork := flag.String(\"network\", \"tcp\", \"Listen network (e.g. `tcp` or `unix`)\")\n\tname := flag.String(\"name\", \"default\", \"Export name\")\n\tdescription := flag.String(\"description\", \"The default export\", \"Export description\")\n\treadOnly := flag.Bool(\"read-only\", false, \"Whether the export should be read-only\")\n\tminimumBlockSize := flag.Uint(\"minimum-block-size\", 1, \"Minimum block size\")\n\tpreferredBlockSize := flag.Uint(\"preferred-block-size\", client.MaximumBlockSize, \"Preferred block size\")\n\tmaximumBlockSize := flag.Uint(\"maximum-block-size\", 0xffffffff, \"Maximum block size\")\n\tmultiConn := flag.Bool(\"multi-conn\", true, \"Whether to advertise support for multiple simultaneous connections\")\n\n\tflag.Parse()\n\n\tl, err := net.Listen(*network, *laddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\n\tlog.Println(\"Listening on\", l.Addr())\n\n\tvar f *os.File\n\tif *readOnly {\n\t\tf, err = os.OpenFile(*file, os.O_RDONLY, 0644)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tf, err = os.OpenFile(*file, os.O_RDWR, 0644)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tdefer f.Close()\n\n\tb := backend.NewFileBackend(f)\n\n\tclients := 0\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Could not accept connection, continuing:\", err)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tclients++\n\n\t\tlog.Printf(\"%v clients connected\", clients)\n\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\t_ = conn.Close()\n\n\t\t\t\tclients--\n\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tlog.Printf(\"Client disconnected with error: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tlog.Printf(\"%v clients connected\", clients)\n\t\t\t}()\n\n\t\t\tif err := server.Handle(\n\t\t\t\tconn,\n\t\t\t\t[]*server.Export{\n\t\t\t\t\t{\n\t\t\t\t\t\tName:        *name,\n\t\t\t\t\t\tDescription: *description,\n\t\t\t\t\t\tBackend:     b,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&server.Options{\n\t\t\t\t\tReadOnly:           *readOnly,\n\t\t\t\t\tMinimumBlockSize:   uint32(*minimumBlockSize),\n\t\t\t\t\tPreferredBlockSize: uint32(*preferredBlockSize),\n\t\t\t\t\tMaximumBlockSize:   uint32(*maximumBlockSize),\n\t\t\t\t\tSupportsMultiConn:  *multiConn,\n\t\t\t\t}); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\t}\n}\n"
  },
  {
    "path": "cmd/go-nbd-example-server-memory/main.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\"\n\n\t\"github.com/pojntfx/go-nbd/pkg/backend\"\n\t\"github.com/pojntfx/go-nbd/pkg/client\"\n\t\"github.com/pojntfx/go-nbd/pkg/server\"\n)\n\nfunc main() {\n\tsize := flag.Int64(\"size\", 1073741824, \"Size of the memory region to expose\")\n\tladdr := flag.String(\"laddr\", \":10809\", \"Listen address\")\n\tnetwork := flag.String(\"network\", \"tcp\", \"Listen network (e.g. `tcp` or `unix`)\")\n\tname := flag.String(\"name\", \"default\", \"Export name\")\n\tdescription := flag.String(\"description\", \"The default export\", \"Export description\")\n\treadOnly := flag.Bool(\"read-only\", false, \"Whether the export should be read-only\")\n\tminimumBlockSize := flag.Uint(\"minimum-block-size\", 1, \"Minimum block size\")\n\tpreferredBlockSize := flag.Uint(\"preferred-block-size\", client.MaximumBlockSize, \"Preferred block size\")\n\tmaximumBlockSize := flag.Uint(\"maximum-block-size\", 0xffffffff, \"Maximum block size\")\n\tmultiConn := flag.Bool(\"multi-conn\", true, \"Whether to advertise support for multiple simultaneous connections\")\n\n\tflag.Parse()\n\n\tl, err := net.Listen(*network, *laddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\n\tlog.Println(\"Listening on\", l.Addr())\n\n\tb := backend.NewMemoryBackend(make([]byte, *size))\n\n\tclients := 0\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Could not accept connection, continuing:\", err)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tclients++\n\n\t\tlog.Printf(\"%v clients connected\", clients)\n\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\t_ = conn.Close()\n\n\t\t\t\tclients--\n\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tlog.Printf(\"Client disconnected with error: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tlog.Printf(\"%v clients connected\", clients)\n\t\t\t}()\n\n\t\t\tif err := server.Handle(\n\t\t\t\tconn,\n\t\t\t\t[]*server.Export{\n\t\t\t\t\t{\n\t\t\t\t\t\tName:        *name,\n\t\t\t\t\t\tDescription: *description,\n\t\t\t\t\t\tBackend:     b,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&server.Options{\n\t\t\t\t\tReadOnly:           *readOnly,\n\t\t\t\t\tMinimumBlockSize:   uint32(*minimumBlockSize),\n\t\t\t\t\tPreferredBlockSize: uint32(*preferredBlockSize),\n\t\t\t\t\tMaximumBlockSize:   uint32(*maximumBlockSize),\n\t\t\t\t\tSupportsMultiConn:  *multiConn,\n\t\t\t\t}); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\t}\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/pojntfx/go-nbd\n\ngo 1.20\n\nrequire github.com/pilebones/go-udev v0.9.0\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/pilebones/go-udev v0.9.0 h1:N1uEO/SxUwtIctc0WLU0t69JeBxIYEYnj8lT/Nabl9Q=\ngithub.com/pilebones/go-udev v0.9.0/go.mod h1:T2eI2tUSK0hA2WS5QLjXJUfQkluZQu+18Cqvem3CaXI=\n"
  },
  {
    "path": "pkg/backend/backend.go",
    "content": "package backend\n\nimport \"io\"\n\ntype Backend interface {\n\tio.ReaderAt\n\tio.WriterAt\n\n\tSize() (int64, error)\n\tSync() error\n}\n"
  },
  {
    "path": "pkg/backend/file.go",
    "content": "package backend\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n)\n\ntype FileBackend struct {\n\tfile *os.File\n\tlock sync.RWMutex\n}\n\nfunc NewFileBackend(file *os.File) *FileBackend {\n\treturn &FileBackend{file, sync.RWMutex{}}\n}\n\nfunc (b *FileBackend) ReadAt(p []byte, off int64) (n int, err error) {\n\tb.lock.RLock()\n\n\tn, err = b.file.ReadAt(p, off)\n\n\tb.lock.RUnlock()\n\n\treturn\n}\n\nfunc (b *FileBackend) WriteAt(p []byte, off int64) (n int, err error) {\n\tb.lock.Lock()\n\n\tn, err = b.file.WriteAt(p, off)\n\n\tb.lock.Unlock()\n\n\treturn\n}\n\nfunc (b *FileBackend) Size() (int64, error) {\n\tsize, err := b.file.Seek(0, io.SeekEnd)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn size, nil\n}\n\nfunc (b *FileBackend) Sync() error {\n\treturn b.file.Sync()\n}\n"
  },
  {
    "path": "pkg/backend/memory.go",
    "content": "package backend\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\ntype MemoryBackend struct {\n\tmemory []byte\n\tlock   sync.Mutex\n}\n\nfunc NewMemoryBackend(memory []byte) *MemoryBackend {\n\treturn &MemoryBackend{memory, sync.Mutex{}}\n}\n\nfunc (b *MemoryBackend) ReadAt(p []byte, off int64) (n int, err error) {\n\tb.lock.Lock()\n\n\tif off >= int64(len(b.memory)) {\n\t\treturn 0, io.EOF\n\t}\n\n\tn = copy(p, b.memory[off:off+int64(len(p))])\n\n\tb.lock.Unlock()\n\n\treturn\n}\n\nfunc (b *MemoryBackend) WriteAt(p []byte, off int64) (n int, err error) {\n\tb.lock.Lock()\n\n\tif off >= int64(len(b.memory)) {\n\t\treturn 0, io.EOF\n\t}\n\n\tn = copy(b.memory[off:off+int64(len(p))], p)\n\n\tif n < len(p) {\n\t\treturn n, io.ErrShortWrite\n\t}\n\n\tb.lock.Unlock()\n\n\treturn\n}\n\nfunc (b *MemoryBackend) Size() (int64, error) {\n\treturn int64(len(b.memory)), nil\n}\n\nfunc (b *MemoryBackend) Sync() error {\n\treturn nil\n}\n"
  },
  {
    "path": "pkg/client/nbd.go",
    "content": "package client\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/pilebones/go-udev/netlink\"\n\t\"github.com/pojntfx/go-nbd/pkg/ioctl\"\n\t\"github.com/pojntfx/go-nbd/pkg/protocol\"\n\t\"github.com/pojntfx/go-nbd/pkg/server\"\n)\n\nconst (\n\tMinimumBlockSize = 512  // This is the minimum value that works in practice, else the client stops with \"invalid argument\"\n\tMaximumBlockSize = 4096 // This is the maximum value that works in practice, else the client stops with \"invalid argument\"\n)\n\nvar (\n\tErrUnsupportedNetwork         = errors.New(\"unsupported network\")\n\tErrUnknownReply               = errors.New(\"unknown reply\")\n\tErrUnknownInfo                = errors.New(\"unknown info\")\n\tErrUnknownErr                 = errors.New(\"unknown error\")\n\tErrUnsupportedServerBlockSize = errors.New(\"server proposed unsupported block size\")\n\tErrMinimumBlockSize           = errors.New(\"block size below mimimum requested\")\n\tErrMaximumBlockSize           = errors.New(\"block size above maximum requested\")\n\tErrBlockSizeNotPowerOfTwo     = errors.New(\"block size is not a power of 2\")\n)\n\ntype Options struct {\n\tExportName             string\n\tBlockSize              uint32\n\tOnConnected            func()\n\tReadyCheckUdev         bool\n\tReadyCheckPollInterval time.Duration\n\tTimeout                int\n}\n\nfunc negotiateNewstyle(conn net.Conn) error {\n\tvar newstyleHeader protocol.NegotiationNewstyleHeader\n\tif err := binary.Read(conn, binary.BigEndian, &newstyleHeader); err != nil {\n\t\treturn err\n\t}\n\n\tif newstyleHeader.OldstyleMagic != protocol.NEGOTIATION_MAGIC_OLDSTYLE {\n\t\treturn server.ErrInvalidMagic\n\t}\n\n\tif newstyleHeader.OptionMagic != protocol.NEGOTIATION_MAGIC_OPTION {\n\t\treturn server.ErrInvalidMagic\n\t}\n\n\tif _, err := conn.Write(make([]byte, 4)); err != nil { // Send client flags (uint32)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Connect(conn net.Conn, device *os.File, options *Options) error {\n\tif options == nil {\n\t\toptions = &Options{}\n\t}\n\n\tif options.ExportName == \"\" {\n\t\toptions.ExportName = \"default\"\n\t}\n\n\tif !options.ReadyCheckUdev && options.ReadyCheckPollInterval <= 0 {\n\t\toptions.ReadyCheckPollInterval = time.Millisecond\n\t}\n\n\tvar cfd uintptr\n\tswitch c := conn.(type) {\n\tcase *net.TCPConn:\n\t\tfile, err := c.File()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcfd = uintptr(file.Fd())\n\tcase *net.UnixConn:\n\t\tfile, err := c.File()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcfd = uintptr(file.Fd())\n\tdefault:\n\t\treturn ErrUnsupportedNetwork\n\t}\n\n\tfatal := make(chan error)\n\tif options.OnConnected != nil {\n\t\tif options.ReadyCheckUdev {\n\t\t\tudevConn := new(netlink.UEventConn)\n\t\t\tif err := udevConn.Connect(netlink.UdevEvent); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer udevConn.Close()\n\n\t\t\tvar (\n\t\t\t\tudevReadyCh = make(chan netlink.UEvent)\n\t\t\t\tudevErrCh   = make(chan error)\n\t\t\t\tudevQuit    = udevConn.Monitor(udevReadyCh, udevErrCh, &netlink.RuleDefinitions{\n\t\t\t\t\tRules: []netlink.RuleDefinition{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEnv: map[string]string{\n\t\t\t\t\t\t\t\t\"DEVNAME\": device.Name(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t)\n\t\t\tdefer close(udevQuit)\n\n\t\t\tgo func() {\n\t\t\t\tselect {\n\t\t\t\tcase <-udevReadyCh:\n\t\t\t\t\tclose(udevQuit)\n\n\t\t\t\t\toptions.OnConnected()\n\n\t\t\t\t\treturn\n\t\t\t\tcase err := <-udevErrCh:\n\t\t\t\t\tfatal <- err\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}()\n\t\t} else {\n\t\t\tgo func() {\n\t\t\t\tsizeFile, err := os.Open(filepath.Join(\"/sys\", \"block\", filepath.Base(device.Name()), \"size\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tfatal <- err\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer sizeFile.Close()\n\n\t\t\t\tfor {\n\t\t\t\t\tif _, err := sizeFile.Seek(0, io.SeekStart); err != nil {\n\t\t\t\t\t\tfatal <- err\n\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\trsize, err := io.ReadAll(sizeFile)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfatal <- err\n\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tsize, err := strconv.ParseInt(strings.TrimSpace(string(rsize)), 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfatal <- err\n\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tif size > 0 {\n\t\t\t\t\t\toptions.OnConnected()\n\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\ttime.Sleep(options.ReadyCheckPollInterval)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.NEGOTIATION_IOCTL_SET_SOCK,\n\t\tuintptr(cfd),\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\tif err := negotiateNewstyle(conn); err != nil {\n\t\treturn err\n\t}\n\n\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationOptionHeader{\n\t\tOptionMagic: protocol.NEGOTIATION_MAGIC_OPTION,\n\t\tID:          protocol.NEGOTIATION_ID_OPTION_GO,\n\t\tLength:      0,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\texportName := []byte(options.ExportName)\n\n\tif err := binary.Write(conn, binary.BigEndian, uint32(len(exportName))); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := conn.Write([]byte(exportName)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := binary.Write(conn, binary.BigEndian, uint16(0)); err != nil { // Send information request count (uint16)\n\t\treturn err\n\t}\n\n\tsize := uint64(0)\n\tchosenBlockSize := uint32(1)\n\nn:\n\tfor {\n\t\tvar replyHeader protocol.NegotiationReplyHeader\n\t\tif err := binary.Read(conn, binary.BigEndian, &replyHeader); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif replyHeader.ReplyMagic != protocol.NEGOTIATION_MAGIC_REPLY {\n\t\t\treturn server.ErrInvalidMagic\n\t\t}\n\n\t\tswitch replyHeader.Type {\n\t\tcase protocol.NEGOTIATION_TYPE_REPLY_INFO:\n\t\t\tinfoRaw := make([]byte, replyHeader.Length)\n\t\t\tif _, err := io.ReadFull(conn, infoRaw); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar infoType uint16\n\t\t\tif err := binary.Read(bytes.NewBuffer(infoRaw), binary.BigEndian, &infoType); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tswitch infoType {\n\t\t\tcase protocol.NEGOTIATION_TYPE_INFO_EXPORT:\n\t\t\t\tvar info protocol.NegotiationReplyInfo\n\t\t\t\tif err := binary.Read(bytes.NewBuffer(infoRaw), binary.BigEndian, &info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tsize = info.Size\n\t\t\tcase protocol.NEGOTIATION_TYPE_INFO_NAME:\n\t\t\t\t// Discard export name\n\t\t\tcase protocol.NEGOTIATION_TYPE_INFO_DESCRIPTION:\n\t\t\t\t// Discard export description\n\t\t\tcase protocol.NEGOTIATION_TYPE_INFO_BLOCKSIZE:\n\t\t\t\tvar info protocol.NegotiationReplyBlockSize\n\t\t\t\tif err := binary.Read(bytes.NewBuffer(infoRaw), binary.BigEndian, &info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif options.BlockSize == 0 {\n\t\t\t\t\tchosenBlockSize = info.PreferredBlockSize\n\t\t\t\t} else if options.BlockSize >= info.MinimumBlockSize && options.BlockSize <= info.MaximumBlockSize {\n\t\t\t\t\tchosenBlockSize = options.BlockSize\n\t\t\t\t} else {\n\t\t\t\t\treturn ErrUnsupportedServerBlockSize\n\t\t\t\t}\n\n\t\t\t\tif chosenBlockSize > MaximumBlockSize {\n\t\t\t\t\treturn ErrMaximumBlockSize\n\t\t\t\t} else if chosenBlockSize < MinimumBlockSize {\n\t\t\t\t\treturn ErrMinimumBlockSize\n\t\t\t\t}\n\n\t\t\t\tif !((chosenBlockSize > 0) && ((chosenBlockSize & (chosenBlockSize - 1)) == 0)) {\n\t\t\t\t\treturn ErrBlockSizeNotPowerOfTwo\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn ErrUnknownInfo\n\t\t\t}\n\t\tcase protocol.NEGOTIATION_TYPE_REPLY_ACK:\n\t\t\tbreak n\n\t\tcase protocol.NEGOTIATION_TYPE_REPLY_ERR_UNKNOWN:\n\t\t\treturn ErrUnknownErr\n\t\tdefault:\n\t\t\treturn ErrUnknownReply\n\t\t}\n\t}\n\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.NEGOTIATION_IOCTL_SET_BLOCKSIZE,\n\t\tuintptr(chosenBlockSize),\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.NEGOTIATION_IOCTL_SET_SIZE_BLOCKS,\n\t\tuintptr(size/uint64(chosenBlockSize)),\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.NEGOTIATION_IOCTL_SET_TIMEOUT,\n\t\tuintptr(options.Timeout),\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tclose(fatal)\n\t\t}()\n\n\t\tif _, _, err := syscall.Syscall(\n\t\t\tsyscall.SYS_IOCTL,\n\t\t\tdevice.Fd(),\n\t\t\tioctl.NEGOTIATION_IOCTL_DO_IT,\n\t\t\t0,\n\t\t); err != 0 {\n\t\t\tfatal <- err\n\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn <-fatal\n}\n\nfunc Disconnect(device *os.File) error {\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.TRANSMISSION_IOCTL_CLEAR_QUE,\n\t\t0,\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.TRANSMISSION_IOCTL_DISCONNECT,\n\t\t0,\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\tif _, _, err := syscall.Syscall(\n\t\tsyscall.SYS_IOCTL,\n\t\tdevice.Fd(),\n\t\tioctl.TRANSMISSION_IOCTL_CLEAR_SOCK,\n\t\t0,\n\t); err != 0 {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc List(conn net.Conn) ([]string, error) {\n\tif err := negotiateNewstyle(conn); err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationOptionHeader{\n\t\tOptionMagic: protocol.NEGOTIATION_MAGIC_OPTION,\n\t\tID:          protocol.NEGOTIATION_ID_OPTION_LIST,\n\t\tLength:      0,\n\t}); err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tvar replyHeader protocol.NegotiationReplyHeader\n\tif err := binary.Read(conn, binary.BigEndian, &replyHeader); err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tif replyHeader.ReplyMagic != protocol.NEGOTIATION_MAGIC_REPLY {\n\t\treturn []string{}, server.ErrInvalidMagic\n\t}\n\n\tinfoRaw := make([]byte, replyHeader.Length)\n\tif _, err := io.ReadFull(conn, infoRaw); err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tinfo := bytes.NewBuffer(infoRaw)\n\n\texportNames := []string{}\n\tfor {\n\t\tvar exportNameLength uint32\n\t\tif err := binary.Read(info, binary.BigEndian, &exportNameLength); err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\texportName := make([]byte, exportNameLength)\n\t\tif _, err := io.ReadFull(info, exportName); err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\texportNames = append(exportNames, string(exportName))\n\t}\n\n\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationOptionHeader{\n\t\tOptionMagic: protocol.NEGOTIATION_MAGIC_OPTION,\n\t\tID:          protocol.NEGOTIATION_ID_OPTION_ABORT,\n\t\tLength:      0,\n\t}); err != nil {\n\t\treturn []string{}, err\n\t}\n\n\treturn exportNames, nil\n}\n"
  },
  {
    "path": "pkg/ioctl/negotiation_cgo.go",
    "content": "//go:build linux && cgo\n\npackage ioctl\n\n/*\n#include <sys/ioctl.h>\n#include <linux/nbd.h>\n*/\nimport \"C\"\n\nconst (\n\tNEGOTIATION_IOCTL_SET_SOCK        = C.NBD_SET_SOCK\n\tNEGOTIATION_IOCTL_SET_BLOCKSIZE   = C.NBD_SET_BLKSIZE\n\tNEGOTIATION_IOCTL_SET_SIZE_BLOCKS = C.NBD_SET_SIZE_BLOCKS\n\tNEGOTIATION_IOCTL_DO_IT           = C.NBD_DO_IT\n\tNEGOTIATION_IOCTL_SET_TIMEOUT     = C.NBD_SET_TIMEOUT\n)\n"
  },
  {
    "path": "pkg/ioctl/negotiation_go_amd64.go",
    "content": "//go:build linux && !cgo && amd64\n\npackage ioctl\n\n// See /usr/include/linux/nbd.h\n\nconst (\n\tNEGOTIATION_IOCTL_SET_SOCK        = 43776\n\tNEGOTIATION_IOCTL_SET_BLOCKSIZE   = 43777\n\tNEGOTIATION_IOCTL_SET_SIZE_BLOCKS = 43783\n\tNEGOTIATION_IOCTL_DO_IT           = 43779\n\tNEGOTIATION_IOCTL_SET_TIMEOUT     = 43785\n)\n"
  },
  {
    "path": "pkg/ioctl/transmission_cgo.go",
    "content": "//go:build linux && cgo\n\npackage ioctl\n\n/*\n#include <sys/ioctl.h>\n#include <linux/nbd.h>\n*/\nimport \"C\"\n\nconst (\n\tTRANSMISSION_IOCTL_DISCONNECT = C.NBD_DISCONNECT\n\tTRANSMISSION_IOCTL_CLEAR_SOCK = C.NBD_CLEAR_SOCK\n\tTRANSMISSION_IOCTL_CLEAR_QUE  = C.NBD_CLEAR_QUE\n)\n"
  },
  {
    "path": "pkg/ioctl/transmission_go_amd64.go",
    "content": "//go:build linux && !cgo && amd64\n\npackage ioctl\n\nconst (\n\tTRANSMISSION_IOCTL_DISCONNECT = 43784\n\tTRANSMISSION_IOCTL_CLEAR_SOCK = 43780\n\tTRANSMISSION_IOCTL_CLEAR_QUE  = 43781\n)\n"
  },
  {
    "path": "pkg/protocol/negotiation.go",
    "content": "package protocol\n\n// See https://github.com/NetworkBlockDevice/nbd/blob/master/doc/proto.md and https://github.com/abligh/gonbdserver/\n\nconst (\n\tNEGOTIATION_MAGIC_OLDSTYLE = uint64(0x4e42444d41474943)\n\tNEGOTIATION_MAGIC_OPTION   = uint64(0x49484156454F5054)\n\tNEGOTIATION_MAGIC_REPLY    = uint64(0x3e889045565a9)\n\n\tNEGOTIATION_HANDSHAKE_FLAG_FIXED_NEWSTYLE = uint16(1 << 0)\n\n\tNEGOTIATION_ID_OPTION_ABORT = uint32(2)\n\tNEGOTIATION_ID_OPTION_LIST  = uint32(3)\n\tNEGOTIATION_ID_OPTION_INFO  = uint32(6)\n\tNEGOTIATION_ID_OPTION_GO    = uint32(7)\n\n\tNEGOTIATION_TYPE_REPLY_ACK             = uint32(1)\n\tNEGOTIATION_TYPE_REPLY_SERVER          = uint32(2)\n\tNEGOTIATION_TYPE_REPLY_INFO            = uint32(3)\n\tNEGOTIATION_TYPE_REPLY_ERR_UNSUPPORTED = uint32(1 | uint32(1<<31))\n\tNEGOTIATION_TYPE_REPLY_ERR_UNKNOWN     = uint32(6 | uint32(1<<31))\n\n\tNEGOTIATION_TYPE_INFO_EXPORT      = uint16(0)\n\tNEGOTIATION_TYPE_INFO_NAME        = uint16(1)\n\tNEGOTIATION_TYPE_INFO_DESCRIPTION = uint16(2)\n\tNEGOTIATION_TYPE_INFO_BLOCKSIZE   = uint16(3)\n\n\tNEGOTIATION_REPLY_FLAGS_HAS_FLAGS      = uint16((1 << 0))\n\tNEGOTIATION_REPLY_FLAGS_CAN_MULTI_CONN = uint16((1 << 8))\n)\n\ntype NegotiationNewstyleHeader struct {\n\tOldstyleMagic  uint64\n\tOptionMagic    uint64\n\tHandshakeFlags uint16\n}\n\ntype NegotiationOptionHeader struct {\n\tOptionMagic uint64\n\tID          uint32\n\tLength      uint32\n}\n\ntype NegotiationReplyHeader struct {\n\tReplyMagic uint64\n\tID         uint32\n\tType       uint32\n\tLength     uint32\n}\n\ntype NegotiationReplyInfo struct {\n\tType              uint16\n\tSize              uint64\n\tTransmissionFlags uint16\n}\n\ntype NegotiationReplyNameHeader struct {\n\tType uint16\n}\n\ntype NegotiationReplyDescriptionHeader NegotiationReplyNameHeader\n\ntype NegotiationReplyBlockSize struct {\n\tType               uint16\n\tMinimumBlockSize   uint32\n\tPreferredBlockSize uint32\n\tMaximumBlockSize   uint32\n}\n"
  },
  {
    "path": "pkg/protocol/transmission.go",
    "content": "package protocol\n\nconst (\n\tTRANSMISSION_MAGIC_REQUEST = uint32(0x25609513)\n\tTRANSMISSION_MAGIC_REPLY   = uint32(0x67446698)\n\n\tTRANSMISSION_TYPE_REQUEST_READ  = uint16(0)\n\tTRANSMISSION_TYPE_REQUEST_WRITE = uint16(1)\n\tTRANSMISSION_TYPE_REQUEST_DISC  = uint16(2)\n\n\tTRANSMISSION_ERROR_EPERM  = uint32(1)\n\tTRANSMISSION_ERROR_EINVAL = uint32(22)\n)\n\ntype TransmissionRequestHeader struct {\n\tRequestMagic uint32\n\tCommandFlags uint16\n\tType         uint16\n\tHandle       uint64\n\tOffset       uint64\n\tLength       uint32\n}\n\ntype TransmissionReplyHeader struct {\n\tReplyMagic uint32\n\tError      uint32\n\tHandle     uint64\n}\n"
  },
  {
    "path": "pkg/server/nbd.go",
    "content": "package server\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\n\t\"github.com/pojntfx/go-nbd/pkg/backend\"\n\t\"github.com/pojntfx/go-nbd/pkg/protocol\"\n)\n\nvar (\n\tErrInvalidMagic     = errors.New(\"invalid magic\")\n\tErrInvalidBlocksize = errors.New(\"invalid blocksize\")\n)\n\nconst (\n\tdefaultMaximumRequestSize = 32 * 1024 * 1024 // Support for a 32M maximum packet size is expected: https://sourceforge.net/p/nbd/mailman/message/35081223/\n)\n\ntype Export struct {\n\tName        string\n\tDescription string\n\n\tBackend backend.Backend\n}\n\ntype Options struct {\n\tReadOnly bool\n\n\tMinimumBlockSize   uint32\n\tPreferredBlockSize uint32\n\tMaximumBlockSize   uint32\n\n\tMaximumRequestSize int\n\tSupportsMultiConn  bool\n}\n\nfunc Handle(conn net.Conn, exports []*Export, options *Options) error {\n\tif options == nil {\n\t\toptions = &Options{\n\t\t\tReadOnly:          false,\n\t\t\tSupportsMultiConn: true,\n\t\t}\n\t}\n\n\tif options.MinimumBlockSize == 0 {\n\t\toptions.MinimumBlockSize = 1\n\t}\n\n\tif options.PreferredBlockSize == 0 {\n\t\toptions.PreferredBlockSize = 4096\n\t}\n\n\tif options.MaximumBlockSize == 0 {\n\t\toptions.MaximumBlockSize = defaultMaximumRequestSize\n\t}\n\n\tif options.MaximumRequestSize == 0 {\n\t\toptions.MaximumRequestSize = defaultMaximumRequestSize\n\t}\n\n\t// Negotiation\n\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationNewstyleHeader{\n\t\tOldstyleMagic:  protocol.NEGOTIATION_MAGIC_OLDSTYLE,\n\t\tOptionMagic:    protocol.NEGOTIATION_MAGIC_OPTION,\n\t\tHandshakeFlags: protocol.NEGOTIATION_HANDSHAKE_FLAG_FIXED_NEWSTYLE,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := io.CopyN(io.Discard, conn, 4) // Discard client flags (uint32)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar export *Export\nn:\n\tfor {\n\t\tvar optionHeader protocol.NegotiationOptionHeader\n\t\tif err := binary.Read(conn, binary.BigEndian, &optionHeader); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif optionHeader.OptionMagic != protocol.NEGOTIATION_MAGIC_OPTION {\n\t\t\treturn ErrInvalidMagic\n\t\t}\n\n\t\tswitch optionHeader.ID {\n\t\tcase protocol.NEGOTIATION_ID_OPTION_INFO, protocol.NEGOTIATION_ID_OPTION_GO:\n\t\t\tvar exportNameLength uint32\n\t\t\tif err := binary.Read(conn, binary.BigEndian, &exportNameLength); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\texportName := make([]byte, exportNameLength)\n\t\t\tif _, err := io.ReadFull(conn, exportName); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, candidate := range exports {\n\t\t\t\tif candidate.Name == string(exportName) {\n\t\t\t\t\texport = candidate\n\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif export == nil {\n\t\t\t\tif length := int64(optionHeader.Length) - 4 - int64(exportNameLength); length > 0 { // Discard the option's data, minus the export name length and export name we've already read\n\t\t\t\t\t_, err := io.CopyN(io.Discard, conn, length)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\t\tID:         optionHeader.ID,\n\t\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_ERR_UNKNOWN,\n\t\t\t\t\tLength:     0,\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tsize, err := export.Backend.Size()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tvar informationRequestCount uint16\n\t\t\t\tif err := binary.Read(conn, binary.BigEndian, &informationRequestCount); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t_, err := io.CopyN(io.Discard, conn, 2*int64(informationRequestCount)) // Discard information requests (uint16s)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t{\n\t\t\t\ttransmissionFlags := uint16(0)\n\t\t\t\tif options.SupportsMultiConn {\n\t\t\t\t\ttransmissionFlags = protocol.NEGOTIATION_REPLY_FLAGS_HAS_FLAGS | protocol.NEGOTIATION_REPLY_FLAGS_CAN_MULTI_CONN\n\t\t\t\t}\n\n\t\t\t\tinfo := &bytes.Buffer{}\n\t\t\t\tif err := binary.Write(info, binary.BigEndian, protocol.NegotiationReplyInfo{\n\t\t\t\t\tType:              protocol.NEGOTIATION_TYPE_INFO_EXPORT,\n\t\t\t\t\tSize:              uint64(size),\n\t\t\t\t\tTransmissionFlags: transmissionFlags,\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\t\tID:         optionHeader.ID,\n\t\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_INFO,\n\t\t\t\t\tLength:     uint32(info.Len()),\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif _, err := io.Copy(conn, info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tinfo := &bytes.Buffer{}\n\t\t\t\tif err := binary.Write(info, binary.BigEndian, protocol.NegotiationReplyNameHeader{\n\t\t\t\t\tType: protocol.NEGOTIATION_TYPE_INFO_NAME,\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif _, err := info.Write([]byte(exportName)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\t\tID:         optionHeader.ID,\n\t\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_INFO,\n\t\t\t\t\tLength:     uint32(info.Len()),\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif _, err := io.Copy(conn, info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tinfo := &bytes.Buffer{}\n\t\t\t\tif err := binary.Write(info, binary.BigEndian, protocol.NegotiationReplyDescriptionHeader{\n\t\t\t\t\tType: protocol.NEGOTIATION_TYPE_INFO_DESCRIPTION,\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(info, binary.BigEndian, []byte(export.Description)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\t\tID:         optionHeader.ID,\n\t\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_INFO,\n\t\t\t\t\tLength:     uint32(info.Len()),\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif _, err := io.Copy(conn, info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tinfo := &bytes.Buffer{}\n\t\t\t\tif err := binary.Write(info, binary.BigEndian, protocol.NegotiationReplyBlockSize{\n\t\t\t\t\tType:               protocol.NEGOTIATION_TYPE_INFO_BLOCKSIZE,\n\t\t\t\t\tMinimumBlockSize:   options.MinimumBlockSize,\n\t\t\t\t\tPreferredBlockSize: options.PreferredBlockSize,\n\t\t\t\t\tMaximumBlockSize:   options.MaximumBlockSize,\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\t\tID:         optionHeader.ID,\n\t\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_INFO,\n\t\t\t\t\tLength:     uint32(info.Len()),\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif _, err := io.Copy(conn, info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\tID:         optionHeader.ID,\n\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_ACK,\n\t\t\t\tLength:     0,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif optionHeader.ID == protocol.NEGOTIATION_ID_OPTION_GO {\n\t\t\t\tbreak n\n\t\t\t}\n\t\tcase protocol.NEGOTIATION_ID_OPTION_ABORT:\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\tID:         optionHeader.ID,\n\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_ACK,\n\t\t\t\tLength:     0,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\tcase protocol.NEGOTIATION_ID_OPTION_LIST:\n\t\t\t{\n\t\t\t\tinfo := &bytes.Buffer{}\n\n\t\t\t\tfor _, export := range exports {\n\t\t\t\t\texportName := []byte(export.Name)\n\n\t\t\t\t\tif err := binary.Write(info, binary.BigEndian, uint32(len(exportName))); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\tif err := binary.Write(info, binary.BigEndian, exportName); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\t\tID:         optionHeader.ID,\n\t\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_SERVER,\n\t\t\t\t\tLength:     uint32(info.Len()),\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif _, err := io.Copy(conn, info); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\tID:         optionHeader.ID,\n\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_ACK,\n\t\t\t\tLength:     0,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\t_, err := io.CopyN(io.Discard, conn, int64(optionHeader.Length)) // Discard the unknown option's data\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.NegotiationReplyHeader{\n\t\t\t\tReplyMagic: protocol.NEGOTIATION_MAGIC_REPLY,\n\t\t\t\tID:         optionHeader.ID,\n\t\t\t\tType:       protocol.NEGOTIATION_TYPE_REPLY_ERR_UNSUPPORTED,\n\t\t\t\tLength:     0,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Transmission\n\tb := []byte{}\n\tfor {\n\t\tvar requestHeader protocol.TransmissionRequestHeader\n\t\tif err := binary.Read(conn, binary.BigEndian, &requestHeader); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif requestHeader.RequestMagic != protocol.TRANSMISSION_MAGIC_REQUEST {\n\t\t\treturn ErrInvalidMagic\n\t\t}\n\n\t\tlength := requestHeader.Length\n\t\tif length > defaultMaximumRequestSize {\n\t\t\treturn ErrInvalidBlocksize\n\t\t}\n\n\t\tif length != uint32(len(b)) {\n\t\t\tb = make([]byte, length)\n\t\t}\n\n\t\tswitch requestHeader.Type {\n\t\tcase protocol.TRANSMISSION_TYPE_REQUEST_READ:\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.TransmissionReplyHeader{\n\t\t\t\tReplyMagic: protocol.TRANSMISSION_MAGIC_REPLY,\n\t\t\t\tError:      0,\n\t\t\t\tHandle:     requestHeader.Handle,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tn, err := export.Backend.ReadAt(b[:length], int64(requestHeader.Offset))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif _, err := conn.Write(b[:n]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase protocol.TRANSMISSION_TYPE_REQUEST_WRITE:\n\t\t\tif options.ReadOnly {\n\t\t\t\t_, err := io.CopyN(io.Discard, conn, int64(requestHeader.Length)) // Discard the write command's data\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.TransmissionReplyHeader{\n\t\t\t\t\tReplyMagic: protocol.TRANSMISSION_MAGIC_REPLY,\n\t\t\t\t\tError:      protocol.TRANSMISSION_ERROR_EPERM,\n\t\t\t\t\tHandle:     requestHeader.Handle,\n\t\t\t\t}); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tn, err := io.ReadAtLeast(conn, b[:length], int(requestHeader.Length))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif _, err := export.Backend.WriteAt(b[:n], int64(requestHeader.Offset)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.TransmissionReplyHeader{\n\t\t\t\tReplyMagic: protocol.TRANSMISSION_MAGIC_REPLY,\n\t\t\t\tError:      0,\n\t\t\t\tHandle:     requestHeader.Handle,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase protocol.TRANSMISSION_TYPE_REQUEST_DISC:\n\t\t\tif !options.ReadOnly {\n\t\t\t\tif err := export.Backend.Sync(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\tdefault:\n\t\t\t_, err := io.CopyN(io.Discard, conn, int64(requestHeader.Length)) // Discard the unknown command's data\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := binary.Write(conn, binary.BigEndian, protocol.TransmissionReplyHeader{\n\t\t\t\tReplyMagic: protocol.TRANSMISSION_MAGIC_REPLY,\n\t\t\t\tError:      protocol.TRANSMISSION_ERROR_EINVAL,\n\t\t\t\tHandle:     requestHeader.Handle,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}\n"
  }
]