Giter Site home page Giter Site logo

go-tftp's Introduction

pack.ag/tftp

Go Report Card Coverage Status Build Status Build status GoDoc MIT licensed

pack.ag/tftp is a cross-platform, concurrent TFTP client and server implementation for Go.

Standards Implemented

Unique Features

  • Single Port Mode

    TL;DR: It allows TFTP to work through firewalls.

    A standard TFTP server implementation receives requests on port 69 and allocates a new high port (over 1024) dedicated to that request. In single port mode, the same port is used for transmit and receive. If the server is started on port 69, all communication will be done on port 69.

    The primary use case of this feature is to play nicely with firewalls. Most firewalls will prevent the typical case where the server responds back on a random port because they have no way of knowing that it is in response to a request that went out on port 69. In single port mode, the firewall will see a request go out to a server on port 69 and that server respond back on the same port, which most firewalls will allow.

    Of course if the firewall in question is configured to block TFTP connections, this setting won't help you.

    Enable single port mode with the --single-port flag. This is currently marked experimental as is diverges from the TFTP standard.

Installation

go get -u pack.ag/tftp

API

The API was inspired by Go's well-known net/http API. If you can write a net/http handler or middleware, you should have no problem doing the same with pack.ag/tftp.

Configuration Functions

One area that is noticeably different from net/http is the configuration of clients and servers. pack.ag/tftp uses "configuration functions" rather than the direct modification of the Client/Server struct or a configuration struct passed into the factory functions.

A few explanations of this pattern:

If this sounds complicated, don't worry, the public API is quiet simple. The NewClient and NewServer functions take zero or more configuration functions.

Want all defaults? Don't pass anything.

Want a Client configured for blocksize 9000 and windowsize 16? Pass in ClientBlocksize(9000) and ClientWindowsize(16).

// Default Client
tftp.NewClient()

// Client with blocksize 9000, windowsize 16
tftp.NewClient(tftp.ClientBlocksize(9000), tftp.ClientWindowsize(16))

// Configuring with a slice of options
opts := []tftp.ClientOpt{
    tftp.ClientMode(tftp.ModeOctet),
    tftp.ClientBlocksize(9000),
    tftp.ClientWindowsize(16),
    tftp.ClientTimeout(1),
    tftp.ClientTransferSize(true),
    tftp.ClientRetransmit(3),
}

tftp.NewClient(opts...)

Examples

Read File From Server, Print to stdout

client := tftp.NewClient()
resp, err := client.Get("myftp.local/myfile")
if err != nil {
    log.Fatalln(err)
}

err := io.Copy(os.Stdout, resp)
if err != nil {
    log.Fatalln(err)
}

Write File to Server

file, err := os.Open("myfile")
if err != nil {
    log.Fatalln(err)
}
defer file.Close()

// Get the file info se we can send size (not required)
fileInfo, err := file.Stat()
if err != nil {
    log.Println("error getting file size:", err)
}

client := tftp.NewClient()
err := client.Put("myftp.local/myfile", file, fileInfo.Size())
if err != nil {
    log.Fatalln(err)
}

HTTP Proxy

This rather contrived example proxies an incoming GET request to GitHub's public API. A more realistic use case might be proxying to PXE boot files on an HTTP server.

const baseURL = "https://api.github.com/"

func proxyTFTP(w tftp.ReadRequest) {
	// Append the requested path to the baseURL
	url := baseURL + w.Name()

	// Send the HTTP request
	resp, err := http.DefaultClient.Get(url)
	if err != nil {
		// This could send more specific errors, but here we'read
		// choosing to simply send "file not found"" with the error
		// message from the HTTP client back to the TFTP client.
		w.WriteError(tftp.ErrCodeFileNotFound, err.Error())
		return
	}
	defer resp.Body.Close()

	// Copy the body of the response to the TFTP client.
	if _, err := io.Copy(w, resp.Body); err != nil {
		log.Println(err)
	}
}

This function doesn't itself implement the required ReadHandler interface, but we can make it a ReadHandler with the ReadHandlerFunc adapter (much like http.HandlerFunc).

readHandler := tftp.ReadHandlerFunc(proxyTFTP)

server.ReadHandler(readHandler)

server.ListenAndServe()
# trivialt get localhost:6900 repos/golang/go -o - | jq
{
  "id": 23096959,
  "name": "go",
  "full_name": "golang/go",
  ...
}

Full example in examples/httpproxy/httpproxy.go.

Save Files to Database

Here tftpDB implements the WriteHandler interface directly.

// tftpDB embeds a *sql.DB and implements the tftp.ReadHandler interface.
type tftpDB struct {
	*sql.DB
}

func (db *tftpDB) ReceiveTFTP(w tftp.WriteRequest) {
	// Read the data from the client into memory
	data, err := ioutil.ReadAll(w)
	if err != nil {
		log.Println(err)
		return
	}

	// Insert the IP address of the client and the data into the database
	res, err := db.Exec("INSERT INTO tftplogs (ip, log) VALUES (?, ?)", w.Addr().IP.String(), string(data))
	if err != nil {
		log.Println(err)
		return
	}

	// Log a message with the details
	id, _ := res.LastInsertId()
	log.Printf("Inserted %d bytes of data from %s. (ID=%d)", len(data), w.Addr().IP, id)
}
# go run examples/database/database.go
2016/04/30 11:20:27 Inserted 32 bytes of data from 127.0.0.1. (ID=13)

Full example including checking the size before accepting the request in examples/database/database.go.

go-tftp's People

Contributors

herrera-luis-alberto avatar vcabbage avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.