get.go 6.64 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2 3 4 5
package commands

import (
	"archive/tar"
	"bytes"
6
	"fmt"
Matt Bell's avatar
Matt Bell committed
7
	"io"
8
	"os"
Matt Bell's avatar
Matt Bell committed
9
	p "path"
10 11
	fp "path/filepath"
	"strings"
12
	"sync"
Matt Bell's avatar
Matt Bell committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

	cmds "github.com/jbenet/go-ipfs/commands"
	core "github.com/jbenet/go-ipfs/core"
	dag "github.com/jbenet/go-ipfs/merkledag"
	uio "github.com/jbenet/go-ipfs/unixfs/io"
	upb "github.com/jbenet/go-ipfs/unixfs/pb"

	proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
)

var GetCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Download IPFS objects",
		ShortDescription: `
Retrieves the object named by <ipfs-path> and stores the data to disk.

By default, the output will be stored at ./<ipfs-path>, but an alternate path
can be specified with '--output=<path>' or '-o=<path>'.

To output a TAR archive instead of unpacked files, use '--archive' or '-a'.
`,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted").EnableStdin(),
	},
	Options: []cmds.Option{
		cmds.StringOption("output", "o", "The path where output should be stored"),
		cmds.BoolOption("archive", "a", "Output a TAR archive"),
	},
	Run: func(req cmds.Request, res cmds.Response) {
		node, err := req.Context().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

50
		reader, err := get(node, req.Arguments()[0])
Matt Bell's avatar
Matt Bell committed
51 52 53 54 55 56
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(reader)
	},
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	PostRun: func(req cmds.Request, res cmds.Response) {
		reader := res.Output().(io.Reader)
		res.SetOutput(nil)

		outPath, _, _ := res.Request().Option("output").String()
		if len(outPath) == 0 {
			outPath = res.Request().Arguments()[0]
		}

		if archive, _, _ := res.Request().Option("archive").Bool(); archive {
			if !strings.HasSuffix(outPath, ".tar") {
				outPath += ".tar"
			}
			fmt.Printf("Saving archive to %s\n", outPath)

			file, err := os.Create(outPath)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			defer file.Close()

			_, err = io.Copy(file, reader)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			return
		}

		fmt.Printf("Saving file(s) to %s\n", outPath)

		preexisting := true
		pathIsDir := false
		if stat, err := os.Stat(outPath); err != nil && os.IsNotExist(err) {
			preexisting = false
		} else if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		} else if stat.IsDir() {
			pathIsDir = true
		}

		tarReader := tar.NewReader(reader)

		for i := 0; ; i++ {
			header, err := tarReader.Next()
			if err != nil && err != io.EOF {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			if header == nil || err == io.EOF {
				break
			}

			if header.Typeflag == tar.TypeDir {
				pathElements := strings.Split(header.Name, "/")
				if !preexisting {
					pathElements = pathElements[1:]
				}
				path := fp.Join(pathElements...)
				path = fp.Join(outPath, path)
				if i == 0 {
					outPath = path
				}

				err = os.MkdirAll(path, 0755)
				if err != nil {
					res.SetError(err, cmds.ErrNormal)
					return
				}
				continue
			}

			var path string
			if i == 0 {
				if preexisting {
					if !pathIsDir {
						res.SetError(os.ErrExist, cmds.ErrNormal)
						return
					}
					path = fp.Join(outPath, header.Name)
				} else {
					path = outPath
				}
			} else {
				pathElements := strings.Split(header.Name, "/")[1:]
				path = fp.Join(pathElements...)
				path = fp.Join(outPath, path)
			}

			file, err := os.Create(path)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			_, err = io.Copy(file, tarReader)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			err = file.Close()
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
		}
	},
Matt Bell's avatar
Matt Bell committed
168 169
}

170 171
func get(node *core.IpfsNode, path string) (io.Reader, error) {
	buf := NewBufReadWriter()
Matt Bell's avatar
Matt Bell committed
172 173

	go func() {
174
		err := copyFilesAsTar(node, buf, path)
Matt Bell's avatar
Matt Bell committed
175 176 177 178 179 180
		if err != nil {
			log.Error(err)
			return
		}
	}()

181
	return buf, nil
Matt Bell's avatar
Matt Bell committed
182 183
}

184 185 186 187 188 189 190 191
func copyFilesAsTar(node *core.IpfsNode, buf *bufReadWriter, path string) error {
	writer := tar.NewWriter(buf)

	err := _copyFilesAsTar(node, writer, buf, path, nil)
	if err != nil {
		return err
	}

192
	err = writer.Close()
193 194 195 196 197 198 199 200 201
	if err != nil {
		return err
	}
	buf.Close()
	buf.Signal()
	return nil
}

func _copyFilesAsTar(node *core.IpfsNode, writer *tar.Writer, buf *bufReadWriter, path string, dagnode *dag.Node) error {
Matt Bell's avatar
Matt Bell committed
202 203 204 205
	var err error
	if dagnode == nil {
		dagnode, err = node.Resolver.ResolvePath(path)
		if err != nil {
206
			return err
Matt Bell's avatar
Matt Bell committed
207 208 209 210 211 212
		}
	}

	pb := new(upb.Data)
	err = proto.Unmarshal(dagnode.Data, pb)
	if err != nil {
213
		return err
Matt Bell's avatar
Matt Bell committed
214 215 216
	}

	if pb.GetType() == upb.Data_Directory {
217
		buf.mutex.Lock()
Matt Bell's avatar
Matt Bell committed
218 219 220 221 222 223
		err = writer.WriteHeader(&tar.Header{
			Name:     path,
			Typeflag: tar.TypeDir,
			Mode:     0777,
			// TODO: set mode, dates, etc. when added to unixFS
		})
224
		buf.mutex.Unlock()
Matt Bell's avatar
Matt Bell committed
225
		if err != nil {
226
			return err
Matt Bell's avatar
Matt Bell committed
227 228 229
		}

		for _, link := range dagnode.Links {
230
			err := _copyFilesAsTar(node, writer, buf, p.Join(path, link.Name), link.Node)
Matt Bell's avatar
Matt Bell committed
231
			if err != nil {
232
				return err
Matt Bell's avatar
Matt Bell committed
233 234 235
			}
		}

236 237
		return nil
	}
Matt Bell's avatar
Matt Bell committed
238

239 240 241 242 243 244 245 246 247 248 249 250
	buf.mutex.Lock()
	err = writer.WriteHeader(&tar.Header{
		Name:     path,
		Size:     int64(pb.GetFilesize()),
		Typeflag: tar.TypeReg,
		Mode:     0644,
		// TODO: set mode, dates, etc. when added to unixFS
	})
	buf.mutex.Unlock()
	if err != nil {
		return err
	}
Matt Bell's avatar
Matt Bell committed
251

252 253 254 255 256 257 258 259
	reader, err := uio.NewDagReader(dagnode, node.DAG)
	if err != nil {
		return err
	}

	_, err = syncCopy(writer, reader, buf)
	if err != nil {
		return err
Matt Bell's avatar
Matt Bell committed
260
	}
261 262

	return nil
Matt Bell's avatar
Matt Bell committed
263 264
}

265
type bufReadWriter struct {
Matt Bell's avatar
Matt Bell committed
266 267 268
	buf        bytes.Buffer
	closed     bool
	signalChan chan struct{}
269 270 271 272 273 274 275 276
	mutex      *sync.Mutex
}

func NewBufReadWriter() *bufReadWriter {
	return &bufReadWriter{
		signalChan: make(chan struct{}),
		mutex:      &sync.Mutex{},
	}
Matt Bell's avatar
Matt Bell committed
277 278
}

279
func (i *bufReadWriter) Read(p []byte) (int, error) {
Matt Bell's avatar
Matt Bell committed
280
	<-i.signalChan
281 282 283 284 285 286 287 288 289 290
	i.mutex.Lock()
	defer i.mutex.Unlock()

	if i.buf.Len() == 0 {
		if i.closed {
			return 0, io.EOF
		}
		return 0, nil
	}

Matt Bell's avatar
Matt Bell committed
291
	n, err := i.buf.Read(p)
292
	if err == io.EOF && !i.closed || i.buf.Len() > 0 {
Matt Bell's avatar
Matt Bell committed
293 294 295 296 297
		return n, nil
	}
	return n, err
}

298 299 300 301 302
func (i *bufReadWriter) Write(p []byte) (int, error) {
	return i.buf.Write(p)
}

func (i *bufReadWriter) Signal() {
Matt Bell's avatar
Matt Bell committed
303 304 305
	i.signalChan <- struct{}{}
}

306
func (i *bufReadWriter) Close() error {
Matt Bell's avatar
Matt Bell committed
307
	i.closed = true
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	return nil
}

func syncCopy(writer io.Writer, reader io.Reader, buf *bufReadWriter) (int64, error) {
	written := int64(0)
	copyBuf := make([]byte, 32*1024)
	for {
		nr, err := reader.Read(copyBuf)
		if nr > 0 {
			buf.mutex.Lock()
			nw, err := writer.Write(copyBuf[:nr])
			buf.mutex.Unlock()
			if err != nil {
				return written, err
			}
			written += int64(nw)
			buf.Signal()
		}
		if err == io.EOF {
			break
		}
		if err != nil {
			return written, err
		}
	}
	return written, nil
Matt Bell's avatar
Matt Bell committed
334
}