libgo: Update to weekly.2011-11-02.

From-SVN: r181964
This commit is contained in:
Ian Lance Taylor 2011-12-03 02:17:34 +00:00
parent 02e9018f16
commit 2fd401c8f1
499 changed files with 4056 additions and 4239 deletions

View File

@ -21,7 +21,7 @@ func f(left, right chan int) {
func main() { func main() {
var n = 10000 var n = 10000
if len(os.Args) > 1 { if len(os.Args) > 1 {
var err os.Error var err error
n, err = strconv.Atoi(os.Args[1]) n, err = strconv.Atoi(os.Args[1])
if err != nil { if err != nil {
print("bad arg\n") print("bad arg\n")

View File

@ -14,7 +14,7 @@ import (
func main() { func main() {
ga, e0 := os.Getenverror("GOARCH") ga, e0 := os.Getenverror("GOARCH")
if e0 != nil { if e0 != nil {
print("$GOARCH: ", e0.String(), "\n") print("$GOARCH: ", e0.Error(), "\n")
os.Exit(1) os.Exit(1)
} }
if ga != runtime.GOARCH { if ga != runtime.GOARCH {
@ -23,7 +23,7 @@ func main() {
} }
xxx, e1 := os.Getenverror("DOES_NOT_EXIST") xxx, e1 := os.Getenverror("DOES_NOT_EXIST")
if e1 != os.ENOENV { if e1 != os.ENOENV {
print("$DOES_NOT_EXIST=", xxx, "; err = ", e1.String(), "\n") print("$DOES_NOT_EXIST=", xxx, "; err = ", e1.Error(), "\n")
os.Exit(1) os.Exit(1)
} }
} }

View File

@ -6,7 +6,7 @@
package main package main
import os "os" import os "os"
type _ os.Error type _ os.FileInfo
func f() (os int) { func f() (os int) {
// In the next line "os" should refer to the result variable, not // In the next line "os" should refer to the result variable, not
// to the package. // to the package.

View File

@ -6,7 +6,7 @@
package main package main
import "os" import "errors"
// Issue 481: closures and var declarations // Issue 481: closures and var declarations
// with multiple variables assigned from one // with multiple variables assigned from one
@ -22,7 +22,7 @@ func main() {
} }
}() }()
var conn, _ = Dial("tcp", "", listen.Addr().String()) var conn, _ = Dial("tcp", "", listen.Addr().Error())
_ = conn _ = conn
} }
@ -37,8 +37,8 @@ func Listen(x, y string) (T, string) {
return global, y return global, y
} }
func (t T) Addr() os.Error { func (t T) Addr() error {
return os.NewError("stringer") return errors.New("stringer")
} }
func (t T) Accept() (int, string) { func (t T) Accept() (int, string) {

View File

@ -18,9 +18,9 @@ func f() string {
return "abc" return "abc"
} }
func g() *os.Error { func g() *error {
trace += "g" trace += "g"
var x os.Error var x error
return &x return &x
} }
@ -35,7 +35,6 @@ func i() *int {
return &i return &i
} }
func main() { func main() {
m := make(map[string]int) m := make(map[string]int)
m[f()], *g() = strconv.Atoi(h()) m[f()], *g() = strconv.Atoi(h())
@ -43,7 +42,7 @@ func main() {
println("BUG", m["abc"], trace) println("BUG", m["abc"], trace)
panic("fail") panic("fail")
} }
mm := make(map[string]os.Error) mm := make(map[string]error)
trace = "" trace = ""
mm["abc"] = os.EINVAL mm["abc"] = os.EINVAL
*i(), mm[f()] = strconv.Atoi(h()) *i(), mm[f()] = strconv.Atoi(h())

View File

@ -6,36 +6,34 @@
package p package p
import "os" func f() (_ int, err error) {
func f() (_ int, err os.Error) {
return return
} }
func g() (x int, _ os.Error) { func g() (x int, _ error) {
return return
} }
func h() (_ int, _ os.Error) { func h() (_ int, _ error) {
return return
} }
func i() (int, os.Error) { func i() (int, error) {
return // ERROR "not enough arguments to return" return // ERROR "not enough arguments to return"
} }
func f1() (_ int, err os.Error) { func f1() (_ int, err error) {
return 1, nil return 1, nil
} }
func g1() (x int, _ os.Error) { func g1() (x int, _ error) {
return 1, nil return 1, nil
} }
func h1() (_ int, _ os.Error) { func h1() (_ int, _ error) {
return 1, nil return 1, nil
} }
func ii() (int, os.Error) { func ii() (int, error) {
return 1, nil return 1, nil
} }

View File

@ -6,22 +6,22 @@
package main package main
import "os" import "io"
func f() (_ string, x float64, err os.Error) { func f() (_ string, x float64, err error) {
return return
} }
func g() (_ string, x float64, err os.Error) { func g() (_ string, x float64, err error) {
return "hello", 3.14, os.EOF return "hello", 3.14, io.EOF
} }
var _ func() (string, float64, os.Error) = f var _ func() (string, float64, error) = f
var _ func() (string, float64, os.Error) = g var _ func() (string, float64, error) = g
func main() { func main() {
x, y, z := g() x, y, z := g()
if x != "hello" || y != 3.14 || z != os.EOF { if x != "hello" || y != 3.14 || z != io.EOF {
println("wrong", x, len(x), y, z) println("wrong", x, len(x), y, z)
} }
} }

View File

@ -9,12 +9,8 @@
package main package main
import (
"os"
)
type Inner struct { type Inner struct {
F func() os.Error F func() error
} }
type Outer struct { type Outer struct {
@ -23,4 +19,4 @@ type Outer struct {
// calls makeclosure twice on same closure // calls makeclosure twice on same closure
var Foo = Outer{[]Inner{Inner{func() os.Error{ return nil }}}} var Foo = Outer{[]Inner{Inner{func() error { return nil }}}}

View File

@ -5,7 +5,6 @@
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package main package main
import os "os"
type t1 int type t1 int
type t2 int type t2 int
@ -23,7 +22,7 @@ func f8(os int) int
func f9(os int) int { func f9(os int) int {
return os return os
} }
func f10(err os.Error) os.Error { func f10(err error) error {
return err return err
} }
func f11(t1 string) string { func f11(t1 string) string {

View File

@ -13,13 +13,12 @@ import _os_ "os"
import "os" import "os"
import . "os" import . "os"
func f(e os.Error) func f(e *os.File)
func main() { func main() {
var _e_ _os_.Error var _e_ *_os_.File
var dot Error var dot *File
f(_e_) f(_e_)
f(dot) f(dot)
} }

View File

@ -11,10 +11,7 @@
package main package main
import ( import "strings"
"os"
"strings"
)
var x = make([]byte, 10) var x = make([]byte, 10)
@ -33,7 +30,7 @@ func mustRecover(s string) {
if v == nil { if v == nil {
panic("expected panic") panic("expected panic")
} }
if e := v.(os.Error).String(); strings.Index(e, s) < 0 { if e := v.(error).Error(); strings.Index(e, s) < 0 {
panic("want: " + s + "; have: " + e) panic("want: " + s + "; have: " + e)
} }
} }

View File

@ -35,7 +35,7 @@ func check(name string, f func(), err string) {
println(name, "panicked but not with runtime.Error") println(name, "panicked but not with runtime.Error")
return return
} }
s := runt.String() s := runt.Error()
if strings.Index(s, err) < 0 { if strings.Index(s, err) < 0 {
bug() bug()
println(name, "panicked with", s, "not", err) println(name, "panicked with", s, "not", err)

View File

@ -1,4 +1,4 @@
941b8015061a 780c85032b17
The first line of this file holds the Mercurial revision number of the The first line of this file holds the Mercurial revision number of the
last merge done from the master library sources. last merge done from the master library sources.

View File

@ -107,6 +107,7 @@ toolexeclibgo_DATA = \
cmath.gox \ cmath.gox \
crypto.gox \ crypto.gox \
csv.gox \ csv.gox \
errors.gox \
exec.gox \ exec.gox \
expvar.gox \ expvar.gox \
flag.gox \ flag.gox \
@ -563,6 +564,9 @@ go_csv_files = \
go/csv/reader.go \ go/csv/reader.go \
go/csv/writer.go go/csv/writer.go
go_errors_files = \
go/errors/errors.go
go_exec_files = \ go_exec_files = \
go/exec/exec.go \ go/exec/exec.go \
go/exec/lp_unix.go go/exec/lp_unix.go
@ -1623,6 +1627,7 @@ libgo_go_objs = \
cmath/cmath.lo \ cmath/cmath.lo \
crypto/crypto.lo \ crypto/crypto.lo \
csv/csv.lo \ csv/csv.lo \
errors/errors.lo \
exec/exec.lo \ exec/exec.lo \
expvar/expvar.lo \ expvar/expvar.lo \
flag/flag.lo \ flag/flag.lo \
@ -1944,6 +1949,15 @@ csv/check: $(CHECK_DEPS)
@$(CHECK) @$(CHECK)
.PHONY: csv/check .PHONY: csv/check
@go_include@ errors/errors.lo.dep
errors/errors.lo.dep: $(go_errors_files)
$(BUILDDEPS)
errors/errors.lo: $(go_errors_files)
$(BUILDPACKAGE)
errors/check: $(CHECK_DEPS)
@$(CHECK)
.PHONY: errors/check
@go_include@ exec/exec.lo.dep @go_include@ exec/exec.lo.dep
exec/exec.lo.dep: $(go_exec_files) exec/exec.lo.dep: $(go_exec_files)
$(BUILDDEPS) $(BUILDDEPS)
@ -3445,6 +3459,8 @@ crypto.gox: crypto/crypto.lo
$(BUILDGOX) $(BUILDGOX)
csv.gox: csv/csv.lo csv.gox: csv/csv.lo
$(BUILDGOX) $(BUILDGOX)
errors.gox: errors/errors.lo
$(BUILDGOX)
exec.gox: exec/exec.lo exec.gox: exec/exec.lo
$(BUILDGOX) $(BUILDGOX)
expvar.gox: expvar/expvar.lo expvar.gox: expvar/expvar.lo
@ -3791,6 +3807,7 @@ TEST_PACKAGES = \
bytes/check \ bytes/check \
cmath/check \ cmath/check \
csv/check \ csv/check \
errors/check \
exec/check \ exec/check \
expvar/check \ expvar/check \
flag/check \ flag/check \

View File

@ -132,46 +132,46 @@ LTLIBRARIES = $(toolexeclib_LTLIBRARIES)
am__DEPENDENCIES_1 = am__DEPENDENCIES_1 =
am__DEPENDENCIES_2 = asn1/asn1.lo big/big.lo bufio/bufio.lo \ am__DEPENDENCIES_2 = asn1/asn1.lo big/big.lo bufio/bufio.lo \
bytes/bytes.lo bytes/index.lo cmath/cmath.lo crypto/crypto.lo \ bytes/bytes.lo bytes/index.lo cmath/cmath.lo crypto/crypto.lo \
csv/csv.lo exec/exec.lo expvar/expvar.lo flag/flag.lo \ csv/csv.lo errors/errors.lo exec/exec.lo expvar/expvar.lo \
fmt/fmt.lo gob/gob.lo hash/hash.lo html/html.lo http/http.lo \ flag/flag.lo fmt/fmt.lo gob/gob.lo hash/hash.lo html/html.lo \
image/image.lo io/io.lo json/json.lo log/log.lo math/math.lo \ http/http.lo image/image.lo io/io.lo json/json.lo log/log.lo \
mail/mail.lo mime/mime.lo net/net.lo os/os.lo patch/patch.lo \ math/math.lo mail/mail.lo mime/mime.lo net/net.lo os/os.lo \
path/path.lo rand/rand.lo reflect/reflect.lo regexp/regexp.lo \ patch/patch.lo path/path.lo rand/rand.lo reflect/reflect.lo \
rpc/rpc.lo runtime/runtime.lo scanner/scanner.lo smtp/smtp.lo \ regexp/regexp.lo rpc/rpc.lo runtime/runtime.lo \
sort/sort.lo strconv/strconv.lo strings/strings.lo \ scanner/scanner.lo smtp/smtp.lo sort/sort.lo \
sync/sync.lo syslog/syslog.lo syslog/syslog_c.lo \ strconv/strconv.lo strings/strings.lo sync/sync.lo \
tabwriter/tabwriter.lo template/template.lo time/time.lo \ syslog/syslog.lo syslog/syslog_c.lo tabwriter/tabwriter.lo \
unicode/unicode.lo url/url.lo utf16/utf16.lo utf8/utf8.lo \ template/template.lo time/time.lo unicode/unicode.lo \
websocket/websocket.lo xml/xml.lo archive/tar.lo \ url/url.lo utf16/utf16.lo utf8/utf8.lo websocket/websocket.lo \
archive/zip.lo compress/bzip2.lo compress/flate.lo \ xml/xml.lo archive/tar.lo archive/zip.lo compress/bzip2.lo \
compress/gzip.lo compress/lzw.lo compress/zlib.lo \ compress/flate.lo compress/gzip.lo compress/lzw.lo \
container/heap.lo container/list.lo container/ring.lo \ compress/zlib.lo container/heap.lo container/list.lo \
crypto/aes.lo crypto/bcrypt.lo crypto/blowfish.lo \ container/ring.lo crypto/aes.lo crypto/bcrypt.lo \
crypto/cast5.lo crypto/cipher.lo crypto/des.lo crypto/dsa.lo \ crypto/blowfish.lo crypto/cast5.lo crypto/cipher.lo \
crypto/ecdsa.lo crypto/elliptic.lo crypto/hmac.lo \ crypto/des.lo crypto/dsa.lo crypto/ecdsa.lo crypto/elliptic.lo \
crypto/md4.lo crypto/md5.lo crypto/ocsp.lo crypto/openpgp.lo \ crypto/hmac.lo crypto/md4.lo crypto/md5.lo crypto/ocsp.lo \
crypto/rand.lo crypto/rc4.lo crypto/ripemd160.lo crypto/rsa.lo \ crypto/openpgp.lo crypto/rand.lo crypto/rc4.lo \
crypto/sha1.lo crypto/sha256.lo crypto/sha512.lo \ crypto/ripemd160.lo crypto/rsa.lo crypto/sha1.lo \
crypto/subtle.lo crypto/tls.lo crypto/twofish.lo \ crypto/sha256.lo crypto/sha512.lo crypto/subtle.lo \
crypto/x509.lo crypto/xtea.lo crypto/openpgp/armor.lo \ crypto/tls.lo crypto/twofish.lo crypto/x509.lo crypto/xtea.lo \
crypto/openpgp/elgamal.lo crypto/openpgp/error.lo \ crypto/openpgp/armor.lo crypto/openpgp/elgamal.lo \
crypto/openpgp/packet.lo crypto/openpgp/s2k.lo \ crypto/openpgp/error.lo crypto/openpgp/packet.lo \
crypto/x509/pkix.lo debug/dwarf.lo debug/elf.lo debug/gosym.lo \ crypto/openpgp/s2k.lo crypto/x509/pkix.lo debug/dwarf.lo \
debug/macho.lo debug/pe.lo encoding/ascii85.lo \ debug/elf.lo debug/gosym.lo debug/macho.lo debug/pe.lo \
encoding/base32.lo encoding/base64.lo encoding/binary.lo \ encoding/ascii85.lo encoding/base32.lo encoding/base64.lo \
encoding/git85.lo encoding/hex.lo encoding/pem.lo exp/ebnf.lo \ encoding/binary.lo encoding/git85.lo encoding/hex.lo \
exp/gui.lo exp/norm.lo exp/spdy.lo exp/sql.lo exp/ssh.lo \ encoding/pem.lo exp/ebnf.lo exp/gui.lo exp/norm.lo exp/spdy.lo \
exp/terminal.lo exp/types.lo exp/gui/x11.lo exp/sql/driver.lo \ exp/sql.lo exp/ssh.lo exp/terminal.lo exp/types.lo \
exp/template/html.lo go/ast.lo go/build.lo go/doc.lo \ exp/gui/x11.lo exp/sql/driver.lo exp/template/html.lo \
go/parser.lo go/printer.lo go/scanner.lo go/token.lo \ go/ast.lo go/build.lo go/doc.lo go/parser.lo go/printer.lo \
hash/adler32.lo hash/crc32.lo hash/crc64.lo hash/fnv.lo \ go/scanner.lo go/token.lo hash/adler32.lo hash/crc32.lo \
http/cgi.lo http/fcgi.lo http/httptest.lo http/pprof.lo \ hash/crc64.lo hash/fnv.lo http/cgi.lo http/fcgi.lo \
image/bmp.lo image/color.lo image/draw.lo image/gif.lo \ http/httptest.lo http/pprof.lo image/bmp.lo image/color.lo \
image/jpeg.lo image/png.lo image/tiff.lo image/ycbcr.lo \ image/draw.lo image/gif.lo image/jpeg.lo image/png.lo \
index/suffixarray.lo io/ioutil.lo mime/multipart.lo \ image/tiff.lo image/ycbcr.lo index/suffixarray.lo io/ioutil.lo \
net/dict.lo net/textproto.lo old/netchan.lo old/regexp.lo \ mime/multipart.lo net/dict.lo net/textproto.lo old/netchan.lo \
old/template.lo $(am__DEPENDENCIES_1) os/user.lo os/signal.lo \ old/regexp.lo old/template.lo $(am__DEPENDENCIES_1) os/user.lo \
path/filepath.lo regexp/syntax.lo rpc/jsonrpc.lo \ os/signal.lo path/filepath.lo regexp/syntax.lo rpc/jsonrpc.lo \
runtime/debug.lo runtime/pprof.lo sync/atomic.lo \ runtime/debug.lo runtime/pprof.lo sync/atomic.lo \
sync/atomic_c.lo syscall/syscall.lo syscall/errno.lo \ sync/atomic_c.lo syscall/syscall.lo syscall/errno.lo \
syscall/wait.lo template/parse.lo testing/testing.lo \ syscall/wait.lo template/parse.lo testing/testing.lo \
@ -568,6 +568,7 @@ toolexeclibgo_DATA = \
cmath.gox \ cmath.gox \
crypto.gox \ crypto.gox \
csv.gox \ csv.gox \
errors.gox \
exec.gox \ exec.gox \
expvar.gox \ expvar.gox \
flag.gox \ flag.gox \
@ -947,6 +948,9 @@ go_csv_files = \
go/csv/reader.go \ go/csv/reader.go \
go/csv/writer.go go/csv/writer.go
go_errors_files = \
go/errors/errors.go
go_exec_files = \ go_exec_files = \
go/exec/exec.go \ go/exec/exec.go \
go/exec/lp_unix.go go/exec/lp_unix.go
@ -1900,6 +1904,7 @@ libgo_go_objs = \
cmath/cmath.lo \ cmath/cmath.lo \
crypto/crypto.lo \ crypto/crypto.lo \
csv/csv.lo \ csv/csv.lo \
errors/errors.lo \
exec/exec.lo \ exec/exec.lo \
expvar/expvar.lo \ expvar/expvar.lo \
flag/flag.lo \ flag/flag.lo \
@ -2167,6 +2172,7 @@ TEST_PACKAGES = \
bytes/check \ bytes/check \
cmath/check \ cmath/check \
csv/check \ csv/check \
errors/check \
exec/check \ exec/check \
expvar/check \ expvar/check \
flag/check \ flag/check \
@ -4434,6 +4440,15 @@ csv/check: $(CHECK_DEPS)
@$(CHECK) @$(CHECK)
.PHONY: csv/check .PHONY: csv/check
@go_include@ errors/errors.lo.dep
errors/errors.lo.dep: $(go_errors_files)
$(BUILDDEPS)
errors/errors.lo: $(go_errors_files)
$(BUILDPACKAGE)
errors/check: $(CHECK_DEPS)
@$(CHECK)
.PHONY: errors/check
@go_include@ exec/exec.lo.dep @go_include@ exec/exec.lo.dep
exec/exec.lo.dep: $(go_exec_files) exec/exec.lo.dep: $(go_exec_files)
$(BUILDDEPS) $(BUILDDEPS)
@ -5930,6 +5945,8 @@ crypto.gox: crypto/crypto.lo
$(BUILDGOX) $(BUILDGOX)
csv.gox: csv/csv.lo csv.gox: csv/csv.lo
$(BUILDGOX) $(BUILDGOX)
errors.gox: errors/errors.lo
$(BUILDGOX)
exec.gox: exec/exec.lo exec.gox: exec/exec.lo
$(BUILDGOX) $(BUILDGOX)
expvar.gox: expvar/expvar.lo expvar.gox: expvar/expvar.lo

View File

@ -9,6 +9,7 @@ package tar
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
@ -16,7 +17,7 @@ import (
) )
var ( var (
HeaderError = os.NewError("invalid tar header") HeaderError = errors.New("invalid tar header")
) )
// A Reader provides sequential access to the contents of a tar archive. // A Reader provides sequential access to the contents of a tar archive.
@ -39,7 +40,7 @@ var (
// } // }
type Reader struct { type Reader struct {
r io.Reader r io.Reader
err os.Error err error
nb int64 // number of unread bytes for current file entry nb int64 // number of unread bytes for current file entry
pad int64 // amount of padding (ignored) after current file entry pad int64 // amount of padding (ignored) after current file entry
} }
@ -48,7 +49,7 @@ type Reader struct {
func NewReader(r io.Reader) *Reader { return &Reader{r: r} } func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
// Next advances to the next entry in the tar archive. // Next advances to the next entry in the tar archive.
func (tr *Reader) Next() (*Header, os.Error) { func (tr *Reader) Next() (*Header, error) {
var hdr *Header var hdr *Header
if tr.err == nil { if tr.err == nil {
tr.skipUnread() tr.skipUnread()
@ -119,7 +120,7 @@ func (tr *Reader) readHeader() *Header {
return nil return nil
} }
if bytes.Equal(header, zeroBlock[0:blockSize]) { if bytes.Equal(header, zeroBlock[0:blockSize]) {
tr.err = os.EOF tr.err = io.EOF
} else { } else {
tr.err = HeaderError // zero block and then non-zero block tr.err = HeaderError // zero block and then non-zero block
} }
@ -201,10 +202,10 @@ func (tr *Reader) readHeader() *Header {
// Read reads from the current entry in the tar archive. // Read reads from the current entry in the tar archive.
// It returns 0, os.EOF when it reaches the end of that entry, // It returns 0, os.EOF when it reaches the end of that entry,
// until Next is called to advance to the next entry. // until Next is called to advance to the next entry.
func (tr *Reader) Read(b []byte) (n int, err os.Error) { func (tr *Reader) Read(b []byte) (n int, err error) {
if tr.nb == 0 { if tr.nb == 0 {
// file consumed // file consumed
return 0, os.EOF return 0, io.EOF
} }
if int64(len(b)) > tr.nb { if int64(len(b)) > tr.nb {
@ -213,7 +214,7 @@ func (tr *Reader) Read(b []byte) (n int, err os.Error) {
n, err = tr.r.Read(b) n, err = tr.r.Read(b)
tr.nb -= int64(n) tr.nb -= int64(n)
if err == os.EOF && tr.nb > 0 { if err == io.EOF && tr.nb > 0 {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
tr.err = err tr.err = err

View File

@ -132,7 +132,7 @@ testLoop:
} }
} }
hdr, err := tr.Next() hdr, err := tr.Next()
if err == os.EOF { if err == io.EOF {
break break
} }
if hdr != nil || err != nil { if hdr != nil || err != nil {
@ -195,7 +195,7 @@ func TestIncrementalRead(t *testing.T) {
// loop over all files // loop over all files
for ; ; nread++ { for ; ; nread++ {
hdr, err := tr.Next() hdr, err := tr.Next()
if hdr == nil || err == os.EOF { if hdr == nil || err == io.EOF {
break break
} }
@ -211,7 +211,7 @@ func TestIncrementalRead(t *testing.T) {
rdbuf := make([]uint8, 8) rdbuf := make([]uint8, 8)
for { for {
nr, err := tr.Read(rdbuf) nr, err := tr.Read(rdbuf)
if err == os.EOF { if err == io.EOF {
break break
} }
if err != nil { if err != nil {
@ -250,7 +250,7 @@ func TestNonSeekable(t *testing.T) {
for { for {
nr, err := f.Read(rdbuf) nr, err := f.Read(rdbuf)
w.Write(rdbuf[0:nr]) w.Write(rdbuf[0:nr])
if err == os.EOF { if err == io.EOF {
break break
} }
} }
@ -262,7 +262,7 @@ func TestNonSeekable(t *testing.T) {
for ; ; nread++ { for ; ; nread++ {
hdr, err := tr.Next() hdr, err := tr.Next()
if hdr == nil || err == os.EOF { if hdr == nil || err == io.EOF {
break break
} }
} }

View File

@ -8,15 +8,15 @@ package tar
// - catch more errors (no first header, write after close, etc.) // - catch more errors (no first header, write after close, etc.)
import ( import (
"errors"
"io" "io"
"os"
"strconv" "strconv"
) )
var ( var (
ErrWriteTooLong = os.NewError("write too long") ErrWriteTooLong = errors.New("write too long")
ErrFieldTooLong = os.NewError("header field too long") ErrFieldTooLong = errors.New("header field too long")
ErrWriteAfterClose = os.NewError("write after close") ErrWriteAfterClose = errors.New("write after close")
) )
// A Writer provides sequential writing of a tar archive in POSIX.1 format. // A Writer provides sequential writing of a tar archive in POSIX.1 format.
@ -36,7 +36,7 @@ var (
// tw.Close() // tw.Close()
type Writer struct { type Writer struct {
w io.Writer w io.Writer
err os.Error err error
nb int64 // number of unwritten bytes for current file entry nb int64 // number of unwritten bytes for current file entry
pad int64 // amount of padding to write after current file entry pad int64 // amount of padding to write after current file entry
closed bool closed bool
@ -47,7 +47,7 @@ type Writer struct {
func NewWriter(w io.Writer) *Writer { return &Writer{w: w} } func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
// Flush finishes writing the current file (optional). // Flush finishes writing the current file (optional).
func (tw *Writer) Flush() os.Error { func (tw *Writer) Flush() error {
n := tw.nb + tw.pad n := tw.nb + tw.pad
for n > 0 && tw.err == nil { for n > 0 && tw.err == nil {
nr := n nr := n
@ -107,7 +107,7 @@ func (tw *Writer) numeric(b []byte, x int64) {
// WriteHeader writes hdr and prepares to accept the file's contents. // WriteHeader writes hdr and prepares to accept the file's contents.
// WriteHeader calls Flush if it is not the first header. // WriteHeader calls Flush if it is not the first header.
// Calling after a Close will return ErrWriteAfterClose. // Calling after a Close will return ErrWriteAfterClose.
func (tw *Writer) WriteHeader(hdr *Header) os.Error { func (tw *Writer) WriteHeader(hdr *Header) error {
if tw.closed { if tw.closed {
return ErrWriteAfterClose return ErrWriteAfterClose
} }
@ -165,7 +165,7 @@ func (tw *Writer) WriteHeader(hdr *Header) os.Error {
// Write writes to the current entry in the tar archive. // Write writes to the current entry in the tar archive.
// Write returns the error ErrWriteTooLong if more than // Write returns the error ErrWriteTooLong if more than
// hdr.Size bytes are written after WriteHeader. // hdr.Size bytes are written after WriteHeader.
func (tw *Writer) Write(b []byte) (n int, err os.Error) { func (tw *Writer) Write(b []byte) (n int, err error) {
if tw.closed { if tw.closed {
err = ErrWriteTooLong err = ErrWriteTooLong
return return
@ -187,7 +187,7 @@ func (tw *Writer) Write(b []byte) (n int, err os.Error) {
// Close closes the tar archive, flushing any unwritten // Close closes the tar archive, flushing any unwritten
// data to the underlying writer. // data to the underlying writer.
func (tw *Writer) Close() os.Error { func (tw *Writer) Close() error {
if tw.err != nil || tw.closed { if tw.err != nil || tw.closed {
return tw.err return tw.err
} }

View File

@ -7,6 +7,7 @@ package zip
import ( import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"encoding/binary" "encoding/binary"
@ -16,9 +17,9 @@ import (
) )
var ( var (
FormatError = os.NewError("zip: not a valid zip file") FormatError = errors.New("zip: not a valid zip file")
UnsupportedMethod = os.NewError("zip: unsupported compression algorithm") UnsupportedMethod = errors.New("zip: unsupported compression algorithm")
ChecksumError = os.NewError("zip: checksum error") ChecksumError = errors.New("zip: checksum error")
) )
type Reader struct { type Reader struct {
@ -44,7 +45,7 @@ func (f *File) hasDataDescriptor() bool {
} }
// OpenReader will open the Zip file specified by name and return a ReadCloser. // OpenReader will open the Zip file specified by name and return a ReadCloser.
func OpenReader(name string) (*ReadCloser, os.Error) { func OpenReader(name string) (*ReadCloser, error) {
f, err := os.Open(name) f, err := os.Open(name)
if err != nil { if err != nil {
return nil, err return nil, err
@ -64,7 +65,7 @@ func OpenReader(name string) (*ReadCloser, os.Error) {
// NewReader returns a new Reader reading from r, which is assumed to // NewReader returns a new Reader reading from r, which is assumed to
// have the given size in bytes. // have the given size in bytes.
func NewReader(r io.ReaderAt, size int64) (*Reader, os.Error) { func NewReader(r io.ReaderAt, size int64) (*Reader, error) {
zr := new(Reader) zr := new(Reader)
if err := zr.init(r, size); err != nil { if err := zr.init(r, size); err != nil {
return nil, err return nil, err
@ -72,7 +73,7 @@ func NewReader(r io.ReaderAt, size int64) (*Reader, os.Error) {
return zr, nil return zr, nil
} }
func (z *Reader) init(r io.ReaderAt, size int64) os.Error { func (z *Reader) init(r io.ReaderAt, size int64) error {
end, err := readDirectoryEnd(r, size) end, err := readDirectoryEnd(r, size)
if err != nil { if err != nil {
return err return err
@ -110,13 +111,13 @@ func (z *Reader) init(r io.ReaderAt, size int64) os.Error {
} }
// Close closes the Zip file, rendering it unusable for I/O. // Close closes the Zip file, rendering it unusable for I/O.
func (rc *ReadCloser) Close() os.Error { func (rc *ReadCloser) Close() error {
return rc.f.Close() return rc.f.Close()
} }
// Open returns a ReadCloser that provides access to the File's contents. // Open returns a ReadCloser that provides access to the File's contents.
// It is safe to Open and Read from files concurrently. // It is safe to Open and Read from files concurrently.
func (f *File) Open() (rc io.ReadCloser, err os.Error) { func (f *File) Open() (rc io.ReadCloser, err error) {
bodyOffset, err := f.findBodyOffset() bodyOffset, err := f.findBodyOffset()
if err != nil { if err != nil {
return return
@ -148,10 +149,10 @@ type checksumReader struct {
zipr io.Reader // for reading the data descriptor zipr io.Reader // for reading the data descriptor
} }
func (r *checksumReader) Read(b []byte) (n int, err os.Error) { func (r *checksumReader) Read(b []byte) (n int, err error) {
n, err = r.rc.Read(b) n, err = r.rc.Read(b)
r.hash.Write(b[:n]) r.hash.Write(b[:n])
if err != os.EOF { if err != io.EOF {
return return
} }
if r.f.hasDataDescriptor() { if r.f.hasDataDescriptor() {
@ -165,9 +166,9 @@ func (r *checksumReader) Read(b []byte) (n int, err os.Error) {
return return
} }
func (r *checksumReader) Close() os.Error { return r.rc.Close() } func (r *checksumReader) Close() error { return r.rc.Close() }
func readFileHeader(f *File, r io.Reader) os.Error { func readFileHeader(f *File, r io.Reader) error {
var b [fileHeaderLen]byte var b [fileHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
return err return err
@ -197,7 +198,7 @@ func readFileHeader(f *File, r io.Reader) os.Error {
// findBodyOffset does the minimum work to verify the file has a header // findBodyOffset does the minimum work to verify the file has a header
// and returns the file body offset. // and returns the file body offset.
func (f *File) findBodyOffset() (int64, os.Error) { func (f *File) findBodyOffset() (int64, error) {
r := io.NewSectionReader(f.zipr, f.headerOffset, f.zipsize-f.headerOffset) r := io.NewSectionReader(f.zipr, f.headerOffset, f.zipsize-f.headerOffset)
var b [fileHeaderLen]byte var b [fileHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
@ -215,7 +216,7 @@ func (f *File) findBodyOffset() (int64, os.Error) {
// readDirectoryHeader attempts to read a directory header from r. // readDirectoryHeader attempts to read a directory header from r.
// It returns io.ErrUnexpectedEOF if it cannot read a complete header, // It returns io.ErrUnexpectedEOF if it cannot read a complete header,
// and FormatError if it doesn't find a valid header signature. // and FormatError if it doesn't find a valid header signature.
func readDirectoryHeader(f *File, r io.Reader) os.Error { func readDirectoryHeader(f *File, r io.Reader) error {
var b [directoryHeaderLen]byte var b [directoryHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
return err return err
@ -250,7 +251,7 @@ func readDirectoryHeader(f *File, r io.Reader) os.Error {
return nil return nil
} }
func readDataDescriptor(r io.Reader, f *File) os.Error { func readDataDescriptor(r io.Reader, f *File) error {
var b [dataDescriptorLen]byte var b [dataDescriptorLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
return err return err
@ -262,7 +263,7 @@ func readDataDescriptor(r io.Reader, f *File) os.Error {
return nil return nil
} }
func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err os.Error) { func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err error) {
// look for directoryEndSignature in the last 1k, then in the last 65k // look for directoryEndSignature in the last 1k, then in the last 65k
var b []byte var b []byte
for i, bLen := range []int64{1024, 65 * 1024} { for i, bLen := range []int64{1024, 65 * 1024} {
@ -270,7 +271,7 @@ func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err os.Erro
bLen = size bLen = size
} }
b = make([]byte, int(bLen)) b = make([]byte, int(bLen))
if _, err := r.ReadAt(b, size-bLen); err != nil && err != os.EOF { if _, err := r.ReadAt(b, size-bLen); err != nil && err != io.EOF {
return nil, err return nil, err
} }
if p := findSignatureInBlock(b); p >= 0 { if p := findSignatureInBlock(b); p >= 0 {

View File

@ -9,7 +9,6 @@ import (
"encoding/binary" "encoding/binary"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
"time" "time"
) )
@ -18,7 +17,7 @@ type ZipTest struct {
Name string Name string
Comment string Comment string
File []ZipTestFile File []ZipTestFile
Error os.Error // the error that Opening this file should return Error error // the error that Opening this file should return
} }
type ZipTestFile struct { type ZipTestFile struct {
@ -245,7 +244,7 @@ func TestInvalidFiles(t *testing.T) {
type sliceReaderAt []byte type sliceReaderAt []byte
func (r sliceReaderAt) ReadAt(b []byte, off int64) (int, os.Error) { func (r sliceReaderAt) ReadAt(b []byte, off int64) (int, error) {
copy(b, r[int(off):int(off)+len(b)]) copy(b, r[int(off):int(off)+len(b)])
return len(b), nil return len(b), nil
} }

View File

@ -11,7 +11,7 @@ This package does not support ZIP64 or disk spanning.
*/ */
package zip package zip
import "os" import "errors"
import "time" import "time"
// Compression methods. // Compression methods.
@ -60,9 +60,9 @@ type directoryEnd struct {
comment string comment string
} }
func recoverError(errp *os.Error) { func recoverError(errp *error) {
if e := recover(); e != nil { if e := recover(); e != nil {
if err, ok := e.(os.Error); ok { if err, ok := e.(error); ok {
*errp = err *errp = err
return return
} }
@ -96,11 +96,11 @@ func (h *FileHeader) Mtime_ns() int64 {
// Mode returns the permission and mode bits for the FileHeader. // Mode returns the permission and mode bits for the FileHeader.
// An error is returned in case the information is not available. // An error is returned in case the information is not available.
func (h *FileHeader) Mode() (mode uint32, err os.Error) { func (h *FileHeader) Mode() (mode uint32, err error) {
if h.CreatorVersion>>8 == creatorUnix { if h.CreatorVersion>>8 == creatorUnix {
return h.ExternalAttrs >> 16, nil return h.ExternalAttrs >> 16, nil
} }
return 0, os.NewError("file mode not available") return 0, errors.New("file mode not available")
} }
// SetMode changes the permission and mode bits for the FileHeader. // SetMode changes the permission and mode bits for the FileHeader.

View File

@ -8,10 +8,10 @@ import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"encoding/binary" "encoding/binary"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"io" "io"
"os"
) )
// TODO(adg): support zip file comments // TODO(adg): support zip file comments
@ -37,7 +37,7 @@ func NewWriter(w io.Writer) *Writer {
// Close finishes writing the zip file by writing the central directory. // Close finishes writing the zip file by writing the central directory.
// It does not (and can not) close the underlying writer. // It does not (and can not) close the underlying writer.
func (w *Writer) Close() (err os.Error) { func (w *Writer) Close() (err error) {
if w.last != nil && !w.last.closed { if w.last != nil && !w.last.closed {
if err = w.last.close(); err != nil { if err = w.last.close(); err != nil {
return return
@ -45,7 +45,7 @@ func (w *Writer) Close() (err os.Error) {
w.last = nil w.last = nil
} }
if w.closed { if w.closed {
return os.NewError("zip: writer closed twice") return errors.New("zip: writer closed twice")
} }
w.closed = true w.closed = true
@ -94,7 +94,7 @@ func (w *Writer) Close() (err os.Error) {
// It returns a Writer to which the file contents should be written. // It returns a Writer to which the file contents should be written.
// The file's contents must be written to the io.Writer before the next // The file's contents must be written to the io.Writer before the next
// call to Create, CreateHeader, or Close. // call to Create, CreateHeader, or Close.
func (w *Writer) Create(name string) (io.Writer, os.Error) { func (w *Writer) Create(name string) (io.Writer, error) {
header := &FileHeader{ header := &FileHeader{
Name: name, Name: name,
Method: Deflate, Method: Deflate,
@ -107,7 +107,7 @@ func (w *Writer) Create(name string) (io.Writer, os.Error) {
// It returns a Writer to which the file contents should be written. // It returns a Writer to which the file contents should be written.
// The file's contents must be written to the io.Writer before the next // The file's contents must be written to the io.Writer before the next
// call to Create, CreateHeader, or Close. // call to Create, CreateHeader, or Close.
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, os.Error) { func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error) {
if w.last != nil && !w.last.closed { if w.last != nil && !w.last.closed {
if err := w.last.close(); err != nil { if err := w.last.close(); err != nil {
return nil, err return nil, err
@ -148,7 +148,7 @@ func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, os.Error) {
return fw, nil return fw, nil
} }
func writeHeader(w io.Writer, h *FileHeader) (err os.Error) { func writeHeader(w io.Writer, h *FileHeader) (err error) {
defer recoverError(&err) defer recoverError(&err)
write(w, uint32(fileHeaderSignature)) write(w, uint32(fileHeaderSignature))
write(w, h.ReaderVersion) write(w, h.ReaderVersion)
@ -176,17 +176,17 @@ type fileWriter struct {
closed bool closed bool
} }
func (w *fileWriter) Write(p []byte) (int, os.Error) { func (w *fileWriter) Write(p []byte) (int, error) {
if w.closed { if w.closed {
return 0, os.NewError("zip: write to closed file") return 0, errors.New("zip: write to closed file")
} }
w.crc32.Write(p) w.crc32.Write(p)
return w.rawCount.Write(p) return w.rawCount.Write(p)
} }
func (w *fileWriter) close() (err os.Error) { func (w *fileWriter) close() (err error) {
if w.closed { if w.closed {
return os.NewError("zip: file closed twice") return errors.New("zip: file closed twice")
} }
w.closed = true w.closed = true
if err = w.comp.Close(); err != nil { if err = w.comp.Close(); err != nil {
@ -213,7 +213,7 @@ type countWriter struct {
count int64 count int64
} }
func (w *countWriter) Write(p []byte) (int, os.Error) { func (w *countWriter) Write(p []byte) (int, error) {
n, err := w.w.Write(p) n, err := w.w.Write(p)
w.count += int64(n) w.count += int64(n)
return n, err return n, err
@ -223,7 +223,7 @@ type nopCloser struct {
io.Writer io.Writer
} }
func (w nopCloser) Close() os.Error { func (w nopCloser) Close() error {
return nil return nil
} }

View File

@ -9,15 +9,15 @@ package zip
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"os" "io"
"testing" "testing"
) )
type stringReaderAt string type stringReaderAt string
func (s stringReaderAt) ReadAt(p []byte, off int64) (n int, err os.Error) { func (s stringReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
if off >= int64(len(s)) { if off >= int64(len(s)) {
return 0, os.EOF return 0, io.EOF
} }
n = copy(p, s[off:]) n = copy(p, s[off:])
return return

View File

@ -22,7 +22,6 @@ package asn1
import ( import (
"big" "big"
"fmt" "fmt"
"os"
"reflect" "reflect"
"time" "time"
) )
@ -33,20 +32,20 @@ type StructuralError struct {
Msg string Msg string
} }
func (e StructuralError) String() string { return "ASN.1 structure error: " + e.Msg } func (e StructuralError) Error() string { return "ASN.1 structure error: " + e.Msg }
// A SyntaxError suggests that the ASN.1 data is invalid. // A SyntaxError suggests that the ASN.1 data is invalid.
type SyntaxError struct { type SyntaxError struct {
Msg string Msg string
} }
func (e SyntaxError) String() string { return "ASN.1 syntax error: " + e.Msg } func (e SyntaxError) Error() string { return "ASN.1 syntax error: " + e.Msg }
// We start by dealing with each of the primitive types in turn. // We start by dealing with each of the primitive types in turn.
// BOOLEAN // BOOLEAN
func parseBool(bytes []byte) (ret bool, err os.Error) { func parseBool(bytes []byte) (ret bool, err error) {
if len(bytes) != 1 { if len(bytes) != 1 {
err = SyntaxError{"invalid boolean"} err = SyntaxError{"invalid boolean"}
return return
@ -59,7 +58,7 @@ func parseBool(bytes []byte) (ret bool, err os.Error) {
// parseInt64 treats the given bytes as a big-endian, signed integer and // parseInt64 treats the given bytes as a big-endian, signed integer and
// returns the result. // returns the result.
func parseInt64(bytes []byte) (ret int64, err os.Error) { func parseInt64(bytes []byte) (ret int64, err error) {
if len(bytes) > 8 { if len(bytes) > 8 {
// We'll overflow an int64 in this case. // We'll overflow an int64 in this case.
err = StructuralError{"integer too large"} err = StructuralError{"integer too large"}
@ -78,7 +77,7 @@ func parseInt64(bytes []byte) (ret int64, err os.Error) {
// parseInt treats the given bytes as a big-endian, signed integer and returns // parseInt treats the given bytes as a big-endian, signed integer and returns
// the result. // the result.
func parseInt(bytes []byte) (int, os.Error) { func parseInt(bytes []byte) (int, error) {
ret64, err := parseInt64(bytes) ret64, err := parseInt64(bytes)
if err != nil { if err != nil {
return 0, err return 0, err
@ -150,7 +149,7 @@ func (b BitString) RightAlign() []byte {
} }
// parseBitString parses an ASN.1 bit string from the given byte slice and returns it. // parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
func parseBitString(bytes []byte) (ret BitString, err os.Error) { func parseBitString(bytes []byte) (ret BitString, err error) {
if len(bytes) == 0 { if len(bytes) == 0 {
err = SyntaxError{"zero length BIT STRING"} err = SyntaxError{"zero length BIT STRING"}
return return
@ -189,7 +188,7 @@ func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
// parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
// returns it. An object identifier is a sequence of variable length integers // returns it. An object identifier is a sequence of variable length integers
// that are assigned in a hierarchy. // that are assigned in a hierarchy.
func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) { func parseObjectIdentifier(bytes []byte) (s []int, err error) {
if len(bytes) == 0 { if len(bytes) == 0 {
err = SyntaxError{"zero length OBJECT IDENTIFIER"} err = SyntaxError{"zero length OBJECT IDENTIFIER"}
return return
@ -227,7 +226,7 @@ type Flag bool
// parseBase128Int parses a base-128 encoded int from the given offset in the // parseBase128Int parses a base-128 encoded int from the given offset in the
// given byte slice. It returns the value and the new offset. // given byte slice. It returns the value and the new offset.
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Error) { func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
offset = initOffset offset = initOffset
for shifted := 0; offset < len(bytes); shifted++ { for shifted := 0; offset < len(bytes); shifted++ {
if shifted > 4 { if shifted > 4 {
@ -248,7 +247,7 @@ func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Erro
// UTCTime // UTCTime
func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) { func parseUTCTime(bytes []byte) (ret *time.Time, err error) {
s := string(bytes) s := string(bytes)
ret, err = time.Parse("0601021504Z0700", s) ret, err = time.Parse("0601021504Z0700", s)
if err == nil { if err == nil {
@ -260,7 +259,7 @@ func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
// parseGeneralizedTime parses the GeneralizedTime from the given byte slice // parseGeneralizedTime parses the GeneralizedTime from the given byte slice
// and returns the resulting time. // and returns the resulting time.
func parseGeneralizedTime(bytes []byte) (ret *time.Time, err os.Error) { func parseGeneralizedTime(bytes []byte) (ret *time.Time, err error) {
return time.Parse("20060102150405Z0700", string(bytes)) return time.Parse("20060102150405Z0700", string(bytes))
} }
@ -268,7 +267,7 @@ func parseGeneralizedTime(bytes []byte) (ret *time.Time, err os.Error) {
// parsePrintableString parses a ASN.1 PrintableString from the given byte // parsePrintableString parses a ASN.1 PrintableString from the given byte
// array and returns it. // array and returns it.
func parsePrintableString(bytes []byte) (ret string, err os.Error) { func parsePrintableString(bytes []byte) (ret string, err error) {
for _, b := range bytes { for _, b := range bytes {
if !isPrintable(b) { if !isPrintable(b) {
err = SyntaxError{"PrintableString contains invalid character"} err = SyntaxError{"PrintableString contains invalid character"}
@ -300,7 +299,7 @@ func isPrintable(b byte) bool {
// parseIA5String parses a ASN.1 IA5String (ASCII string) from the given // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
// byte slice and returns it. // byte slice and returns it.
func parseIA5String(bytes []byte) (ret string, err os.Error) { func parseIA5String(bytes []byte) (ret string, err error) {
for _, b := range bytes { for _, b := range bytes {
if b >= 0x80 { if b >= 0x80 {
err = SyntaxError{"IA5String contains invalid character"} err = SyntaxError{"IA5String contains invalid character"}
@ -315,7 +314,7 @@ func parseIA5String(bytes []byte) (ret string, err os.Error) {
// parseT61String parses a ASN.1 T61String (8-bit clean string) from the given // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
// byte slice and returns it. // byte slice and returns it.
func parseT61String(bytes []byte) (ret string, err os.Error) { func parseT61String(bytes []byte) (ret string, err error) {
return string(bytes), nil return string(bytes), nil
} }
@ -323,7 +322,7 @@ func parseT61String(bytes []byte) (ret string, err os.Error) {
// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
// array and returns it. // array and returns it.
func parseUTF8String(bytes []byte) (ret string, err os.Error) { func parseUTF8String(bytes []byte) (ret string, err error) {
return string(bytes), nil return string(bytes), nil
} }
@ -346,7 +345,7 @@ type RawContent []byte
// into a byte slice. It returns the parsed data and the new offset. SET and // into a byte slice. It returns the parsed data and the new offset. SET and
// SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
// don't distinguish between ordered and unordered objects in this code. // don't distinguish between ordered and unordered objects in this code.
func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err os.Error) { func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
offset = initOffset offset = initOffset
b := bytes[offset] b := bytes[offset]
offset++ offset++
@ -402,7 +401,7 @@ func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset i
// parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
// a number of ASN.1 values from the given byte slice and returns them as a // a number of ASN.1 values from the given byte slice and returns them as a
// slice of Go values of the given type. // slice of Go values of the given type.
func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err os.Error) { func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
expectedTag, compoundType, ok := getUniversalType(elemType) expectedTag, compoundType, ok := getUniversalType(elemType)
if !ok { if !ok {
err = StructuralError{"unknown Go type for slice"} err = StructuralError{"unknown Go type for slice"}
@ -466,7 +465,7 @@ func invalidLength(offset, length, sliceLength int) bool {
// parseField is the main parsing function. Given a byte slice and an offset // parseField is the main parsing function. Given a byte slice and an offset
// into the array, it will try to parse a suitable ASN.1 value out and store it // into the array, it will try to parse a suitable ASN.1 value out and store it
// in the given Value. // in the given Value.
func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err os.Error) { func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
offset = initOffset offset = initOffset
fieldType := v.Type() fieldType := v.Type()
@ -649,7 +648,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
return return
case timeType: case timeType:
var time *time.Time var time *time.Time
var err1 os.Error var err1 error
if universalTag == tagUTCTime { if universalTag == tagUTCTime {
time, err1 = parseUTCTime(innerBytes) time, err1 = parseUTCTime(innerBytes)
} else { } else {
@ -826,13 +825,13 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
// //
// Other ASN.1 types are not supported; if it encounters them, // Other ASN.1 types are not supported; if it encounters them,
// Unmarshal returns a parse error. // Unmarshal returns a parse error.
func Unmarshal(b []byte, val interface{}) (rest []byte, err os.Error) { func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
return UnmarshalWithParams(b, val, "") return UnmarshalWithParams(b, val, "")
} }
// UnmarshalWithParams allows field parameters to be specified for the // UnmarshalWithParams allows field parameters to be specified for the
// top-level element. The form of the params is the same as the field tags. // top-level element. The form of the params is the same as the field tags.
func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err os.Error) { func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
v := reflect.ValueOf(val).Elem() v := reflect.ValueOf(val).Elem()
offset, err := parseField(v, b, 0, parseFieldParameters(params)) offset, err := parseField(v, b, 0, parseFieldParameters(params))
if err != nil { if err != nil {

View File

@ -9,7 +9,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"os"
"reflect" "reflect"
"time" "time"
) )
@ -48,7 +47,7 @@ func (f *forkableWriter) Len() (l int) {
return return
} }
func (f *forkableWriter) writeTo(out io.Writer) (n int, err os.Error) { func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) {
n, err = out.Write(f.Bytes()) n, err = out.Write(f.Bytes())
if err != nil { if err != nil {
return return
@ -71,7 +70,7 @@ func (f *forkableWriter) writeTo(out io.Writer) (n int, err os.Error) {
return return
} }
func marshalBase128Int(out *forkableWriter, n int64) (err os.Error) { func marshalBase128Int(out *forkableWriter, n int64) (err error) {
if n == 0 { if n == 0 {
err = out.WriteByte(0) err = out.WriteByte(0)
return return
@ -97,7 +96,7 @@ func marshalBase128Int(out *forkableWriter, n int64) (err os.Error) {
return nil return nil
} }
func marshalInt64(out *forkableWriter, i int64) (err os.Error) { func marshalInt64(out *forkableWriter, i int64) (err error) {
n := int64Length(i) n := int64Length(i)
for ; n > 0; n-- { for ; n > 0; n-- {
@ -126,7 +125,7 @@ func int64Length(i int64) (numBytes int) {
return return
} }
func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) { func marshalBigInt(out *forkableWriter, n *big.Int) (err error) {
if n.Sign() < 0 { if n.Sign() < 0 {
// A negative number has to be converted to two's-complement // A negative number has to be converted to two's-complement
// form. So we'll subtract 1 and invert. If the // form. So we'll subtract 1 and invert. If the
@ -163,7 +162,7 @@ func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) {
return return
} }
func marshalLength(out *forkableWriter, i int) (err os.Error) { func marshalLength(out *forkableWriter, i int) (err error) {
n := lengthLength(i) n := lengthLength(i)
for ; n > 0; n-- { for ; n > 0; n-- {
@ -185,7 +184,7 @@ func lengthLength(i int) (numBytes int) {
return return
} }
func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) { func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) {
b := uint8(t.class) << 6 b := uint8(t.class) << 6
if t.isCompound { if t.isCompound {
b |= 0x20 b |= 0x20
@ -228,7 +227,7 @@ func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) {
return nil return nil
} }
func marshalBitString(out *forkableWriter, b BitString) (err os.Error) { func marshalBitString(out *forkableWriter, b BitString) (err error) {
paddingBits := byte((8 - b.BitLength%8) % 8) paddingBits := byte((8 - b.BitLength%8) % 8)
err = out.WriteByte(paddingBits) err = out.WriteByte(paddingBits)
if err != nil { if err != nil {
@ -238,7 +237,7 @@ func marshalBitString(out *forkableWriter, b BitString) (err os.Error) {
return return
} }
func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) { func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) {
if len(oid) < 2 || oid[0] > 6 || oid[1] >= 40 { if len(oid) < 2 || oid[0] > 6 || oid[1] >= 40 {
return StructuralError{"invalid object identifier"} return StructuralError{"invalid object identifier"}
} }
@ -257,7 +256,7 @@ func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) {
return return
} }
func marshalPrintableString(out *forkableWriter, s string) (err os.Error) { func marshalPrintableString(out *forkableWriter, s string) (err error) {
b := []byte(s) b := []byte(s)
for _, c := range b { for _, c := range b {
if !isPrintable(c) { if !isPrintable(c) {
@ -269,7 +268,7 @@ func marshalPrintableString(out *forkableWriter, s string) (err os.Error) {
return return
} }
func marshalIA5String(out *forkableWriter, s string) (err os.Error) { func marshalIA5String(out *forkableWriter, s string) (err error) {
b := []byte(s) b := []byte(s)
for _, c := range b { for _, c := range b {
if c > 127 { if c > 127 {
@ -281,7 +280,7 @@ func marshalIA5String(out *forkableWriter, s string) (err os.Error) {
return return
} }
func marshalTwoDigits(out *forkableWriter, v int) (err os.Error) { func marshalTwoDigits(out *forkableWriter, v int) (err error) {
err = out.WriteByte(byte('0' + (v/10)%10)) err = out.WriteByte(byte('0' + (v/10)%10))
if err != nil { if err != nil {
return return
@ -289,7 +288,7 @@ func marshalTwoDigits(out *forkableWriter, v int) (err os.Error) {
return out.WriteByte(byte('0' + v%10)) return out.WriteByte(byte('0' + v%10))
} }
func marshalUTCTime(out *forkableWriter, t *time.Time) (err os.Error) { func marshalUTCTime(out *forkableWriter, t *time.Time) (err error) {
switch { switch {
case 1950 <= t.Year && t.Year < 2000: case 1950 <= t.Year && t.Year < 2000:
err = marshalTwoDigits(out, int(t.Year-1900)) err = marshalTwoDigits(out, int(t.Year-1900))
@ -364,7 +363,7 @@ func stripTagAndLength(in []byte) []byte {
return in[offset:] return in[offset:]
} }
func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err os.Error) { func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) {
switch value.Type() { switch value.Type() {
case timeType: case timeType:
return marshalUTCTime(out, value.Interface().(*time.Time)) return marshalUTCTime(out, value.Interface().(*time.Time))
@ -452,7 +451,7 @@ func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameter
return StructuralError{"unknown Go type"} return StructuralError{"unknown Go type"}
} }
func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err os.Error) { func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) {
// If the field is an interface{} then recurse into it. // If the field is an interface{} then recurse into it.
if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 { if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 {
return marshalField(out, v.Elem(), params) return marshalField(out, v.Elem(), params)
@ -535,7 +534,7 @@ func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters)
} }
// Marshal returns the ASN.1 encoding of val. // Marshal returns the ASN.1 encoding of val.
func Marshal(val interface{}) ([]byte, os.Error) { func Marshal(val interface{}) ([]byte, error) {
var out bytes.Buffer var out bytes.Buffer
v := reflect.ValueOf(val) v := reflect.ValueOf(val)
f := newForkableWriter() f := newForkableWriter()

View File

@ -7,9 +7,9 @@
package big package big
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"os"
"rand" "rand"
"strings" "strings"
) )
@ -432,7 +432,7 @@ func (x *Int) Format(s fmt.State, ch rune) {
// ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
// ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10. // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
// //
func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) { func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, error) {
// determine sign // determine sign
ch, _, err := r.ReadRune() ch, _, err := r.ReadRune()
if err != nil { if err != nil {
@ -460,7 +460,7 @@ func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) {
// Scan is a support routine for fmt.Scanner; it sets z to the value of // Scan is a support routine for fmt.Scanner; it sets z to the value of
// the scanned number. It accepts the formats 'b' (binary), 'o' (octal), // the scanned number. It accepts the formats 'b' (binary), 'o' (octal),
// 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). // 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
func (z *Int) Scan(s fmt.ScanState, ch rune) os.Error { func (z *Int) Scan(s fmt.ScanState, ch rune) error {
s.SkipSpace() // skip leading space characters s.SkipSpace() // skip leading space characters
base := 0 base := 0
switch ch { switch ch {
@ -475,7 +475,7 @@ func (z *Int) Scan(s fmt.ScanState, ch rune) os.Error {
case 's', 'v': case 's', 'v':
// let scan determine the base // let scan determine the base
default: default:
return os.NewError("Int.Scan: invalid verb") return errors.New("Int.Scan: invalid verb")
} }
_, _, err := z.scan(s, base) _, _, err := z.scan(s, base)
return err return err
@ -513,7 +513,7 @@ func (z *Int) SetString(s string, base int) (*Int, bool) {
return nil, false return nil, false
} }
_, _, err = r.ReadRune() _, _, err = r.ReadRune()
if err != os.EOF { if err != io.EOF {
return nil, false return nil, false
} }
return z, true // err == os.EOF => scan consumed all of s return z, true // err == os.EOF => scan consumed all of s
@ -847,7 +847,7 @@ func (z *Int) Not(x *Int) *Int {
const intGobVersion byte = 1 const intGobVersion byte = 1
// GobEncode implements the gob.GobEncoder interface. // GobEncode implements the gob.GobEncoder interface.
func (z *Int) GobEncode() ([]byte, os.Error) { func (z *Int) GobEncode() ([]byte, error) {
buf := make([]byte, 1+len(z.abs)*_S) // extra byte for version and sign bit buf := make([]byte, 1+len(z.abs)*_S) // extra byte for version and sign bit
i := z.abs.bytes(buf) - 1 // i >= 0 i := z.abs.bytes(buf) - 1 // i >= 0
b := intGobVersion << 1 // make space for sign bit b := intGobVersion << 1 // make space for sign bit
@ -859,13 +859,13 @@ func (z *Int) GobEncode() ([]byte, os.Error) {
} }
// GobDecode implements the gob.GobDecoder interface. // GobDecode implements the gob.GobDecoder interface.
func (z *Int) GobDecode(buf []byte) os.Error { func (z *Int) GobDecode(buf []byte) error {
if len(buf) == 0 { if len(buf) == 0 {
return os.NewError("Int.GobDecode: no data") return errors.New("Int.GobDecode: no data")
} }
b := buf[0] b := buf[0]
if b>>1 != intGobVersion { if b>>1 != intGobVersion {
return os.NewError(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1)) return errors.New(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1))
} }
z.neg = b&1 != 0 z.neg = b&1 != 0
z.abs = z.abs.setBytes(buf[1:]) z.abs = z.abs.setBytes(buf[1:])

View File

@ -19,8 +19,8 @@ package big
// and rationals. // and rationals.
import ( import (
"errors"
"io" "io"
"os"
"rand" "rand"
) )
@ -613,10 +613,10 @@ func hexValue(ch rune) Word {
// ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
// ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10. // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
// //
func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { func (z nat) scan(r io.RuneScanner, base int) (nat, int, error) {
// reject illegal bases // reject illegal bases
if base < 0 || base == 1 || MaxBase < base { if base < 0 || base == 1 || MaxBase < base {
return z, 0, os.NewError("illegal number base") return z, 0, errors.New("illegal number base")
} }
// one char look-ahead // one char look-ahead
@ -644,7 +644,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
return z, 0, err return z, 0, err
} }
} }
case os.EOF: case io.EOF:
return z.make(0), 10, nil return z.make(0), 10, nil
default: default:
return z, 10, err return z, 10, err
@ -676,7 +676,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
} }
if ch, _, err = r.ReadRune(); err != nil { if ch, _, err = r.ReadRune(); err != nil {
if err != os.EOF { if err != io.EOF {
return z, int(b), err return z, int(b), err
} }
break break
@ -693,7 +693,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
return z, 10, nil return z, 10, nil
case base != 0 || b != 8: case base != 0 || b != 8:
// there was neither a mantissa digit nor the octal prefix 0 // there was neither a mantissa digit nor the octal prefix 0
return z, int(b), os.NewError("syntax error scanning number") return z, int(b), errors.New("syntax error scanning number")
} }
return z.norm(), int(b), nil return z.norm(), int(b), nil

View File

@ -6,7 +6,7 @@ package big
import ( import (
"fmt" "fmt"
"os" "io"
"strings" "strings"
"testing" "testing"
) )
@ -288,7 +288,7 @@ func TestScanBase(t *testing.T) {
t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base) t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base)
} }
next, _, err := r.ReadRune() next, _, err := r.ReadRune()
if err == os.EOF { if err == io.EOF {
next = 0 next = 0
err = nil err = nil
} }

View File

@ -8,8 +8,8 @@ package big
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"os"
"strings" "strings"
) )
@ -255,16 +255,16 @@ func ratTok(ch rune) bool {
// Scan is a support routine for fmt.Scanner. It accepts the formats // Scan is a support routine for fmt.Scanner. It accepts the formats
// 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent. // 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
func (z *Rat) Scan(s fmt.ScanState, ch rune) os.Error { func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
tok, err := s.Token(true, ratTok) tok, err := s.Token(true, ratTok)
if err != nil { if err != nil {
return err return err
} }
if strings.IndexRune("efgEFGv", ch) < 0 { if strings.IndexRune("efgEFGv", ch) < 0 {
return os.NewError("Rat.Scan: invalid verb") return errors.New("Rat.Scan: invalid verb")
} }
if _, ok := z.SetString(string(tok)); !ok { if _, ok := z.SetString(string(tok)); !ok {
return os.NewError("Rat.Scan: invalid syntax") return errors.New("Rat.Scan: invalid syntax")
} }
return nil return nil
} }
@ -285,7 +285,7 @@ func (z *Rat) SetString(s string) (*Rat, bool) {
return nil, false return nil, false
} }
s = s[sep+1:] s = s[sep+1:]
var err os.Error var err error
if z.b, _, err = z.b.scan(strings.NewReader(s), 10); err != nil { if z.b, _, err = z.b.scan(strings.NewReader(s), 10); err != nil {
return nil, false return nil, false
} }
@ -395,14 +395,14 @@ func (z *Rat) FloatString(prec int) string {
const ratGobVersion byte = 1 const ratGobVersion byte = 1
// GobEncode implements the gob.GobEncoder interface. // GobEncode implements the gob.GobEncoder interface.
func (z *Rat) GobEncode() ([]byte, os.Error) { func (z *Rat) GobEncode() ([]byte, error) {
buf := make([]byte, 1+4+(len(z.a.abs)+len(z.b))*_S) // extra bytes for version and sign bit (1), and numerator length (4) buf := make([]byte, 1+4+(len(z.a.abs)+len(z.b))*_S) // extra bytes for version and sign bit (1), and numerator length (4)
i := z.b.bytes(buf) i := z.b.bytes(buf)
j := z.a.abs.bytes(buf[0:i]) j := z.a.abs.bytes(buf[0:i])
n := i - j n := i - j
if int(uint32(n)) != n { if int(uint32(n)) != n {
// this should never happen // this should never happen
return nil, os.NewError("Rat.GobEncode: numerator too large") return nil, errors.New("Rat.GobEncode: numerator too large")
} }
binary.BigEndian.PutUint32(buf[j-4:j], uint32(n)) binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
j -= 1 + 4 j -= 1 + 4
@ -415,13 +415,13 @@ func (z *Rat) GobEncode() ([]byte, os.Error) {
} }
// GobDecode implements the gob.GobDecoder interface. // GobDecode implements the gob.GobDecoder interface.
func (z *Rat) GobDecode(buf []byte) os.Error { func (z *Rat) GobDecode(buf []byte) error {
if len(buf) == 0 { if len(buf) == 0 {
return os.NewError("Rat.GobDecode: no data") return errors.New("Rat.GobDecode: no data")
} }
b := buf[0] b := buf[0]
if b>>1 != ratGobVersion { if b>>1 != ratGobVersion {
return os.NewError(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1)) return errors.New(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1))
} }
const j = 1 + 4 const j = 1 + 4
i := j + binary.BigEndian.Uint32(buf[j-4:j]) i := j + binary.BigEndian.Uint32(buf[j-4:j])

View File

@ -10,7 +10,6 @@ package bufio
import ( import (
"bytes" "bytes"
"io" "io"
"os"
"strconv" "strconv"
"utf8" "utf8"
) )
@ -24,20 +23,20 @@ type Error struct {
ErrorString string ErrorString string
} }
func (err *Error) String() string { return err.ErrorString } func (err *Error) Error() string { return err.ErrorString }
var ( var (
ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"} ErrInvalidUnreadByte error = &Error{"bufio: invalid use of UnreadByte"}
ErrInvalidUnreadRune os.Error = &Error{"bufio: invalid use of UnreadRune"} ErrInvalidUnreadRune error = &Error{"bufio: invalid use of UnreadRune"}
ErrBufferFull os.Error = &Error{"bufio: buffer full"} ErrBufferFull error = &Error{"bufio: buffer full"}
ErrNegativeCount os.Error = &Error{"bufio: negative count"} ErrNegativeCount error = &Error{"bufio: negative count"}
errInternal os.Error = &Error{"bufio: internal error"} errInternal error = &Error{"bufio: internal error"}
) )
// BufSizeError is the error representing an invalid buffer size. // BufSizeError is the error representing an invalid buffer size.
type BufSizeError int type BufSizeError int
func (b BufSizeError) String() string { func (b BufSizeError) Error() string {
return "bufio: bad buffer size " + strconv.Itoa(int(b)) return "bufio: bad buffer size " + strconv.Itoa(int(b))
} }
@ -48,7 +47,7 @@ type Reader struct {
buf []byte buf []byte
rd io.Reader rd io.Reader
r, w int r, w int
err os.Error err error
lastByte int lastByte int
lastRuneSize int lastRuneSize int
} }
@ -57,7 +56,7 @@ type Reader struct {
// which must be greater than one. If the argument io.Reader is already a // which must be greater than one. If the argument io.Reader is already a
// Reader with large enough size, it returns the underlying Reader. // Reader with large enough size, it returns the underlying Reader.
// It returns the Reader and any error. // It returns the Reader and any error.
func NewReaderSize(rd io.Reader, size int) (*Reader, os.Error) { func NewReaderSize(rd io.Reader, size int) (*Reader, error) {
if size <= 1 { if size <= 1 {
return nil, BufSizeError(size) return nil, BufSizeError(size)
} }
@ -101,7 +100,7 @@ func (b *Reader) fill() {
} }
} }
func (b *Reader) readErr() os.Error { func (b *Reader) readErr() error {
err := b.err err := b.err
b.err = nil b.err = nil
return err return err
@ -111,7 +110,7 @@ func (b *Reader) readErr() os.Error {
// being valid at the next read call. If Peek returns fewer than n bytes, it // being valid at the next read call. If Peek returns fewer than n bytes, it
// also returns an error explaining why the read is short. The error is // also returns an error explaining why the read is short. The error is
// ErrBufferFull if n is larger than b's buffer size. // ErrBufferFull if n is larger than b's buffer size.
func (b *Reader) Peek(n int) ([]byte, os.Error) { func (b *Reader) Peek(n int) ([]byte, error) {
if n < 0 { if n < 0 {
return nil, ErrNegativeCount return nil, ErrNegativeCount
} }
@ -137,7 +136,7 @@ func (b *Reader) Peek(n int) ([]byte, os.Error) {
// It calls Read at most once on the underlying Reader, // It calls Read at most once on the underlying Reader,
// hence n may be less than len(p). // hence n may be less than len(p).
// At EOF, the count will be zero and err will be os.EOF. // At EOF, the count will be zero and err will be os.EOF.
func (b *Reader) Read(p []byte) (n int, err os.Error) { func (b *Reader) Read(p []byte) (n int, err error) {
n = len(p) n = len(p)
if n == 0 { if n == 0 {
return 0, b.readErr() return 0, b.readErr()
@ -174,7 +173,7 @@ func (b *Reader) Read(p []byte) (n int, err os.Error) {
// ReadByte reads and returns a single byte. // ReadByte reads and returns a single byte.
// If no byte is available, returns an error. // If no byte is available, returns an error.
func (b *Reader) ReadByte() (c byte, err os.Error) { func (b *Reader) ReadByte() (c byte, err error) {
b.lastRuneSize = -1 b.lastRuneSize = -1
for b.w == b.r { for b.w == b.r {
if b.err != nil { if b.err != nil {
@ -189,7 +188,7 @@ func (b *Reader) ReadByte() (c byte, err os.Error) {
} }
// UnreadByte unreads the last byte. Only the most recently read byte can be unread. // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
func (b *Reader) UnreadByte() os.Error { func (b *Reader) UnreadByte() error {
b.lastRuneSize = -1 b.lastRuneSize = -1
if b.r == b.w && b.lastByte >= 0 { if b.r == b.w && b.lastByte >= 0 {
b.w = 1 b.w = 1
@ -208,7 +207,7 @@ func (b *Reader) UnreadByte() os.Error {
// ReadRune reads a single UTF-8 encoded Unicode character and returns the // ReadRune reads a single UTF-8 encoded Unicode character and returns the
// rune and its size in bytes. // rune and its size in bytes.
func (b *Reader) ReadRune() (r rune, size int, err os.Error) { func (b *Reader) ReadRune() (r rune, size int, err error) {
for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil { for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil {
b.fill() b.fill()
} }
@ -230,7 +229,7 @@ func (b *Reader) ReadRune() (r rune, size int, err os.Error) {
// the buffer was not a ReadRune, UnreadRune returns an error. (In this // the buffer was not a ReadRune, UnreadRune returns an error. (In this
// regard it is stricter than UnreadByte, which will unread the last byte // regard it is stricter than UnreadByte, which will unread the last byte
// from any read operation.) // from any read operation.)
func (b *Reader) UnreadRune() os.Error { func (b *Reader) UnreadRune() error {
if b.lastRuneSize < 0 || b.r == 0 { if b.lastRuneSize < 0 || b.r == 0 {
return ErrInvalidUnreadRune return ErrInvalidUnreadRune
} }
@ -253,7 +252,7 @@ func (b *Reader) Buffered() int { return b.w - b.r }
// by the next I/O operation, most clients should use // by the next I/O operation, most clients should use
// ReadBytes or ReadString instead. // ReadBytes or ReadString instead.
// ReadSlice returns err != nil if and only if line does not end in delim. // ReadSlice returns err != nil if and only if line does not end in delim.
func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) { func (b *Reader) ReadSlice(delim byte) (line []byte, err error) {
// Look in buffer. // Look in buffer.
if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 { if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 {
line1 := b.buf[b.r : b.r+i+1] line1 := b.buf[b.r : b.r+i+1]
@ -295,7 +294,7 @@ func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) {
// of the line. The returned buffer is only valid until the next call to // of the line. The returned buffer is only valid until the next call to
// ReadLine. ReadLine either returns a non-nil line or it returns an error, // ReadLine. ReadLine either returns a non-nil line or it returns an error,
// never both. // never both.
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err os.Error) { func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) {
line, err = b.ReadSlice('\n') line, err = b.ReadSlice('\n')
if err == ErrBufferFull { if err == ErrBufferFull {
// Handle the case where "\r\n" straddles the buffer. // Handle the case where "\r\n" straddles the buffer.
@ -333,7 +332,7 @@ func (b *Reader) ReadLine() (line []byte, isPrefix bool, err os.Error) {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in // ReadBytes returns err != nil if and only if the returned data does not end in
// delim. // delim.
func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) { func (b *Reader) ReadBytes(delim byte) (line []byte, err error) {
// Use ReadSlice to look for array, // Use ReadSlice to look for array,
// accumulating full buffers. // accumulating full buffers.
var frag []byte var frag []byte
@ -341,7 +340,7 @@ func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) {
err = nil err = nil
for { for {
var e os.Error var e error
frag, e = b.ReadSlice(delim) frag, e = b.ReadSlice(delim)
if e == nil { // got final fragment if e == nil { // got final fragment
break break
@ -380,7 +379,7 @@ func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadString returns err != nil if and only if the returned data does not end in // ReadString returns err != nil if and only if the returned data does not end in
// delim. // delim.
func (b *Reader) ReadString(delim byte) (line string, err os.Error) { func (b *Reader) ReadString(delim byte) (line string, err error) {
bytes, e := b.ReadBytes(delim) bytes, e := b.ReadBytes(delim)
return string(bytes), e return string(bytes), e
} }
@ -389,7 +388,7 @@ func (b *Reader) ReadString(delim byte) (line string, err os.Error) {
// Writer implements buffering for an io.Writer object. // Writer implements buffering for an io.Writer object.
type Writer struct { type Writer struct {
err os.Error err error
buf []byte buf []byte
n int n int
wr io.Writer wr io.Writer
@ -399,7 +398,7 @@ type Writer struct {
// which must be greater than zero. If the argument io.Writer is already a // which must be greater than zero. If the argument io.Writer is already a
// Writer with large enough size, it returns the underlying Writer. // Writer with large enough size, it returns the underlying Writer.
// It returns the Writer and any error. // It returns the Writer and any error.
func NewWriterSize(wr io.Writer, size int) (*Writer, os.Error) { func NewWriterSize(wr io.Writer, size int) (*Writer, error) {
if size <= 0 { if size <= 0 {
return nil, BufSizeError(size) return nil, BufSizeError(size)
} }
@ -425,7 +424,7 @@ func NewWriter(wr io.Writer) *Writer {
} }
// Flush writes any buffered data to the underlying io.Writer. // Flush writes any buffered data to the underlying io.Writer.
func (b *Writer) Flush() os.Error { func (b *Writer) Flush() error {
if b.err != nil { if b.err != nil {
return b.err return b.err
} }
@ -458,7 +457,7 @@ func (b *Writer) Buffered() int { return b.n }
// It returns the number of bytes written. // It returns the number of bytes written.
// If nn < len(p), it also returns an error explaining // If nn < len(p), it also returns an error explaining
// why the write is short. // why the write is short.
func (b *Writer) Write(p []byte) (nn int, err os.Error) { func (b *Writer) Write(p []byte) (nn int, err error) {
for len(p) > b.Available() && b.err == nil { for len(p) > b.Available() && b.err == nil {
var n int var n int
if b.Buffered() == 0 { if b.Buffered() == 0 {
@ -483,7 +482,7 @@ func (b *Writer) Write(p []byte) (nn int, err os.Error) {
} }
// WriteByte writes a single byte. // WriteByte writes a single byte.
func (b *Writer) WriteByte(c byte) os.Error { func (b *Writer) WriteByte(c byte) error {
if b.err != nil { if b.err != nil {
return b.err return b.err
} }
@ -497,7 +496,7 @@ func (b *Writer) WriteByte(c byte) os.Error {
// WriteRune writes a single Unicode code point, returning // WriteRune writes a single Unicode code point, returning
// the number of bytes written and any error. // the number of bytes written and any error.
func (b *Writer) WriteRune(r rune) (size int, err os.Error) { func (b *Writer) WriteRune(r rune) (size int, err error) {
if r < utf8.RuneSelf { if r < utf8.RuneSelf {
err = b.WriteByte(byte(r)) err = b.WriteByte(byte(r))
if err != nil { if err != nil {
@ -528,7 +527,7 @@ func (b *Writer) WriteRune(r rune) (size int, err os.Error) {
// It returns the number of bytes written. // It returns the number of bytes written.
// If the count is less than len(s), it also returns an error explaining // If the count is less than len(s), it also returns an error explaining
// why the write is short. // why the write is short.
func (b *Writer) WriteString(s string) (int, os.Error) { func (b *Writer) WriteString(s string) (int, error) {
nn := 0 nn := 0
for len(s) > b.Available() && b.err == nil { for len(s) > b.Available() && b.err == nil {
n := copy(b.buf[b.n:], s) n := copy(b.buf[b.n:], s)

View File

@ -28,7 +28,7 @@ func newRot13Reader(r io.Reader) *rot13Reader {
return r13 return r13
} }
func (r13 *rot13Reader) Read(p []byte) (int, os.Error) { func (r13 *rot13Reader) Read(p []byte) (int, error) {
n, e := r13.r.Read(p) n, e := r13.r.Read(p)
if e != nil { if e != nil {
return n, e return n, e
@ -50,14 +50,14 @@ func readBytes(buf *Reader) string {
nb := 0 nb := 0
for { for {
c, e := buf.ReadByte() c, e := buf.ReadByte()
if e == os.EOF { if e == io.EOF {
break break
} }
if e == nil { if e == nil {
b[nb] = c b[nb] = c
nb++ nb++
} else if e != iotest.ErrTimeout { } else if e != iotest.ErrTimeout {
panic("Data: " + e.String()) panic("Data: " + e.Error())
} }
} }
return string(b[0:nb]) return string(b[0:nb])
@ -95,11 +95,11 @@ func readLines(b *Reader) string {
s := "" s := ""
for { for {
s1, e := b.ReadString('\n') s1, e := b.ReadString('\n')
if e == os.EOF { if e == io.EOF {
break break
} }
if e != nil && e != iotest.ErrTimeout { if e != nil && e != iotest.ErrTimeout {
panic("GetLines: " + e.String()) panic("GetLines: " + e.Error())
} }
s += s1 s += s1
} }
@ -113,7 +113,7 @@ func reads(buf *Reader, m int) string {
for { for {
n, e := buf.Read(b[nb : nb+m]) n, e := buf.Read(b[nb : nb+m])
nb += n nb += n
if e == os.EOF { if e == io.EOF {
break break
} }
} }
@ -179,13 +179,13 @@ type StringReader struct {
step int step int
} }
func (r *StringReader) Read(p []byte) (n int, err os.Error) { func (r *StringReader) Read(p []byte) (n int, err error) {
if r.step < len(r.data) { if r.step < len(r.data) {
s := r.data[r.step] s := r.data[r.step]
n = copy(p, s) n = copy(p, s)
r.step++ r.step++
} else { } else {
err = os.EOF err = io.EOF
} }
return return
} }
@ -197,7 +197,7 @@ func readRuneSegments(t *testing.T, segments []string) {
for { for {
r, _, err := r.ReadRune() r, _, err := r.ReadRune()
if err != nil { if err != nil {
if err != os.EOF { if err != io.EOF {
return return
} }
break break
@ -235,7 +235,7 @@ func TestUnreadRune(t *testing.T) {
for { for {
r1, _, err := r.ReadRune() r1, _, err := r.ReadRune()
if err != nil { if err != nil {
if err != os.EOF { if err != io.EOF {
t.Error("unexpected EOF") t.Error("unexpected EOF")
} }
break break
@ -328,7 +328,7 @@ func TestUnreadRuneAtEOF(t *testing.T) {
_, _, err := r.ReadRune() _, _, err := r.ReadRune()
if err == nil { if err == nil {
t.Error("expected error at EOF") t.Error("expected error at EOF")
} else if err != os.EOF { } else if err != io.EOF {
t.Error("expected EOF; got", err) t.Error("expected EOF; got", err)
} }
} }
@ -413,11 +413,11 @@ func TestWriter(t *testing.T) {
type errorWriterTest struct { type errorWriterTest struct {
n, m int n, m int
err os.Error err error
expect os.Error expect error
} }
func (w errorWriterTest) Write(p []byte) (int, os.Error) { func (w errorWriterTest) Write(p []byte) (int, error) {
return len(p) * w.n / w.m, w.err return len(p) * w.n / w.m, w.err
} }
@ -559,7 +559,7 @@ func TestPeek(t *testing.T) {
if s, err := buf.Peek(0); string(s) != "" || err != nil { if s, err := buf.Peek(0); string(s) != "" || err != nil {
t.Fatalf("want %q got %q, err=%v", "", string(s), err) t.Fatalf("want %q got %q, err=%v", "", string(s), err)
} }
if _, err := buf.Peek(1); err != os.EOF { if _, err := buf.Peek(1); err != io.EOF {
t.Fatalf("want EOF got %v", err) t.Fatalf("want EOF got %v", err)
} }
} }
@ -583,7 +583,7 @@ type testReader struct {
stride int stride int
} }
func (t *testReader) Read(buf []byte) (n int, err os.Error) { func (t *testReader) Read(buf []byte) (n int, err error) {
n = t.stride n = t.stride
if n > len(t.data) { if n > len(t.data) {
n = len(t.data) n = len(t.data)
@ -594,7 +594,7 @@ func (t *testReader) Read(buf []byte) (n int, err os.Error) {
copy(buf, t.data) copy(buf, t.data)
t.data = t.data[n:] t.data = t.data[n:]
if len(t.data) == 0 { if len(t.data) == 0 {
err = os.EOF err = io.EOF
} }
return return
} }
@ -614,7 +614,7 @@ func testReadLine(t *testing.T, input []byte) {
t.Errorf("ReadLine returned prefix") t.Errorf("ReadLine returned prefix")
} }
if err != nil { if err != nil {
if err != os.EOF { if err != io.EOF {
t.Fatalf("Got unknown error: %s", err) t.Fatalf("Got unknown error: %s", err)
} }
break break
@ -679,7 +679,7 @@ func TestReadAfterLines(t *testing.T) {
func TestReadEmptyBuffer(t *testing.T) { func TestReadEmptyBuffer(t *testing.T) {
l, _ := NewReaderSize(bytes.NewBuffer(nil), 10) l, _ := NewReaderSize(bytes.NewBuffer(nil), 10)
line, isPrefix, err := l.ReadLine() line, isPrefix, err := l.ReadLine()
if err != os.EOF { if err != io.EOF {
t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
} }
} }
@ -693,7 +693,7 @@ func TestLinesAfterRead(t *testing.T) {
} }
line, isPrefix, err := l.ReadLine() line, isPrefix, err := l.ReadLine()
if err != os.EOF { if err != io.EOF {
t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
} }
} }
@ -701,7 +701,7 @@ func TestLinesAfterRead(t *testing.T) {
type readLineResult struct { type readLineResult struct {
line []byte line []byte
isPrefix bool isPrefix bool
err os.Error err error
} }
var readLineNewlinesTests = []struct { var readLineNewlinesTests = []struct {
@ -714,27 +714,27 @@ var readLineNewlinesTests = []struct {
{nil, false, nil}, {nil, false, nil},
{[]byte("b"), true, nil}, {[]byte("b"), true, nil},
{nil, false, nil}, {nil, false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
{"hello\r\nworld\r\n", 6, []readLineResult{ {"hello\r\nworld\r\n", 6, []readLineResult{
{[]byte("hello"), true, nil}, {[]byte("hello"), true, nil},
{nil, false, nil}, {nil, false, nil},
{[]byte("world"), true, nil}, {[]byte("world"), true, nil},
{nil, false, nil}, {nil, false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
{"hello\rworld\r", 6, []readLineResult{ {"hello\rworld\r", 6, []readLineResult{
{[]byte("hello"), true, nil}, {[]byte("hello"), true, nil},
{[]byte("\rworld"), true, nil}, {[]byte("\rworld"), true, nil},
{[]byte("\r"), false, nil}, {[]byte("\r"), false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
{"h\ri\r\n\r", 2, []readLineResult{ {"h\ri\r\n\r", 2, []readLineResult{
{[]byte("h"), true, nil}, {[]byte("h"), true, nil},
{[]byte("\ri"), true, nil}, {[]byte("\ri"), true, nil},
{nil, false, nil}, {nil, false, nil},
{[]byte("\r"), false, nil}, {[]byte("\r"), false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
} }

View File

@ -7,8 +7,8 @@ package bytes
// Simple byte buffer for marshaling data. // Simple byte buffer for marshaling data.
import ( import (
"errors"
"io" "io"
"os"
"utf8" "utf8"
) )
@ -94,7 +94,7 @@ func (b *Buffer) grow(n int) int {
// Write appends the contents of p to the buffer. The return // Write appends the contents of p to the buffer. The return
// value n is the length of p; err is always nil. // value n is the length of p; err is always nil.
func (b *Buffer) Write(p []byte) (n int, err os.Error) { func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
m := b.grow(len(p)) m := b.grow(len(p))
copy(b.buf[m:], p) copy(b.buf[m:], p)
@ -103,7 +103,7 @@ func (b *Buffer) Write(p []byte) (n int, err os.Error) {
// WriteString appends the contents of s to the buffer. The return // WriteString appends the contents of s to the buffer. The return
// value n is the length of s; err is always nil. // value n is the length of s; err is always nil.
func (b *Buffer) WriteString(s string) (n int, err os.Error) { func (b *Buffer) WriteString(s string) (n int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
m := b.grow(len(s)) m := b.grow(len(s))
return copy(b.buf[m:], s), nil return copy(b.buf[m:], s), nil
@ -119,7 +119,7 @@ const MinRead = 512
// The return value n is the number of bytes read. // The return value n is the number of bytes read.
// Any error except os.EOF encountered during the read // Any error except os.EOF encountered during the read
// is also returned. // is also returned.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) { func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
// If buffer is empty, reset to recover space. // If buffer is empty, reset to recover space.
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
@ -143,7 +143,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]) m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
b.buf = b.buf[0 : len(b.buf)+m] b.buf = b.buf[0 : len(b.buf)+m]
n += int64(m) n += int64(m)
if e == os.EOF { if e == io.EOF {
break break
} }
if e != nil { if e != nil {
@ -157,7 +157,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
// occurs. The return value n is the number of bytes written; it always // occurs. The return value n is the number of bytes written; it always
// fits into an int, but it is int64 to match the io.WriterTo interface. // fits into an int, but it is int64 to match the io.WriterTo interface.
// Any error encountered during the write is also returned. // Any error encountered during the write is also returned.
func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) { func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off < len(b.buf) { if b.off < len(b.buf) {
m, e := w.Write(b.buf[b.off:]) m, e := w.Write(b.buf[b.off:])
@ -177,7 +177,7 @@ func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) {
// WriteByte appends the byte c to the buffer. // WriteByte appends the byte c to the buffer.
// The returned error is always nil, but is included // The returned error is always nil, but is included
// to match bufio.Writer's WriteByte. // to match bufio.Writer's WriteByte.
func (b *Buffer) WriteByte(c byte) os.Error { func (b *Buffer) WriteByte(c byte) error {
b.lastRead = opInvalid b.lastRead = opInvalid
m := b.grow(1) m := b.grow(1)
b.buf[m] = c b.buf[m] = c
@ -188,7 +188,7 @@ func (b *Buffer) WriteByte(c byte) os.Error {
// code point r to the buffer, returning its length and // code point r to the buffer, returning its length and
// an error, which is always nil but is included // an error, which is always nil but is included
// to match bufio.Writer's WriteRune. // to match bufio.Writer's WriteRune.
func (b *Buffer) WriteRune(r rune) (n int, err os.Error) { func (b *Buffer) WriteRune(r rune) (n int, err error) {
if r < utf8.RuneSelf { if r < utf8.RuneSelf {
b.WriteByte(byte(r)) b.WriteByte(byte(r))
return 1, nil return 1, nil
@ -202,12 +202,12 @@ func (b *Buffer) WriteRune(r rune) (n int, err os.Error) {
// is drained. The return value n is the number of bytes read. If the // is drained. The return value n is the number of bytes read. If the
// buffer has no data to return, err is os.EOF even if len(p) is zero; // buffer has no data to return, err is os.EOF even if len(p) is zero;
// otherwise it is nil. // otherwise it is nil.
func (b *Buffer) Read(p []byte) (n int, err os.Error) { func (b *Buffer) Read(p []byte) (n int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space. // Buffer is empty, reset to recover space.
b.Truncate(0) b.Truncate(0)
return 0, os.EOF return 0, io.EOF
} }
n = copy(p, b.buf[b.off:]) n = copy(p, b.buf[b.off:])
b.off += n b.off += n
@ -237,12 +237,12 @@ func (b *Buffer) Next(n int) []byte {
// ReadByte reads and returns the next byte from the buffer. // ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns error os.EOF. // If no byte is available, it returns error os.EOF.
func (b *Buffer) ReadByte() (c byte, err os.Error) { func (b *Buffer) ReadByte() (c byte, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space. // Buffer is empty, reset to recover space.
b.Truncate(0) b.Truncate(0)
return 0, os.EOF return 0, io.EOF
} }
c = b.buf[b.off] c = b.buf[b.off]
b.off++ b.off++
@ -255,12 +255,12 @@ func (b *Buffer) ReadByte() (c byte, err os.Error) {
// If no bytes are available, the error returned is os.EOF. // If no bytes are available, the error returned is os.EOF.
// If the bytes are an erroneous UTF-8 encoding, it // If the bytes are an erroneous UTF-8 encoding, it
// consumes one byte and returns U+FFFD, 1. // consumes one byte and returns U+FFFD, 1.
func (b *Buffer) ReadRune() (r rune, size int, err os.Error) { func (b *Buffer) ReadRune() (r rune, size int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space. // Buffer is empty, reset to recover space.
b.Truncate(0) b.Truncate(0)
return 0, 0, os.EOF return 0, 0, io.EOF
} }
b.lastRead = opReadRune b.lastRead = opReadRune
c := b.buf[b.off] c := b.buf[b.off]
@ -278,9 +278,9 @@ func (b *Buffer) ReadRune() (r rune, size int, err os.Error) {
// not a ReadRune, UnreadRune returns an error. (In this regard // not a ReadRune, UnreadRune returns an error. (In this regard
// it is stricter than UnreadByte, which will unread the last byte // it is stricter than UnreadByte, which will unread the last byte
// from any read operation.) // from any read operation.)
func (b *Buffer) UnreadRune() os.Error { func (b *Buffer) UnreadRune() error {
if b.lastRead != opReadRune { if b.lastRead != opReadRune {
return os.NewError("bytes.Buffer: UnreadRune: previous operation was not ReadRune") return errors.New("bytes.Buffer: UnreadRune: previous operation was not ReadRune")
} }
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off > 0 { if b.off > 0 {
@ -293,9 +293,9 @@ func (b *Buffer) UnreadRune() os.Error {
// UnreadByte unreads the last byte returned by the most recent // UnreadByte unreads the last byte returned by the most recent
// read operation. If write has happened since the last read, UnreadByte // read operation. If write has happened since the last read, UnreadByte
// returns an error. // returns an error.
func (b *Buffer) UnreadByte() os.Error { func (b *Buffer) UnreadByte() error {
if b.lastRead != opReadRune && b.lastRead != opRead { if b.lastRead != opReadRune && b.lastRead != opRead {
return os.NewError("bytes.Buffer: UnreadByte: previous operation was not a read") return errors.New("bytes.Buffer: UnreadByte: previous operation was not a read")
} }
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off > 0 { if b.off > 0 {
@ -310,12 +310,12 @@ func (b *Buffer) UnreadByte() os.Error {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in // ReadBytes returns err != nil if and only if the returned data does not end in
// delim. // delim.
func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) { func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
i := IndexByte(b.buf[b.off:], delim) i := IndexByte(b.buf[b.off:], delim)
size := i + 1 size := i + 1
if i < 0 { if i < 0 {
size = len(b.buf) - b.off size = len(b.buf) - b.off
err = os.EOF err = io.EOF
} }
line = make([]byte, size) line = make([]byte, size)
copy(line, b.buf[b.off:]) copy(line, b.buf[b.off:])
@ -329,7 +329,7 @@ func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadString returns err != nil if and only if the returned data does not end // ReadString returns err != nil if and only if the returned data does not end
// in delim. // in delim.
func (b *Buffer) ReadString(delim byte) (line string, err os.Error) { func (b *Buffer) ReadString(delim byte) (line string, err error) {
bytes, err := b.ReadBytes(delim) bytes, err := b.ReadBytes(delim)
return string(bytes), err return string(bytes), err
} }

View File

@ -6,7 +6,7 @@ package bytes_test
import ( import (
. "bytes" . "bytes"
"os" "io"
"rand" "rand"
"testing" "testing"
"utf8" "utf8"
@ -344,21 +344,21 @@ var readBytesTests = []struct {
buffer string buffer string
delim byte delim byte
expected []string expected []string
err os.Error err error
}{ }{
{"", 0, []string{""}, os.EOF}, {"", 0, []string{""}, io.EOF},
{"a\x00", 0, []string{"a\x00"}, nil}, {"a\x00", 0, []string{"a\x00"}, nil},
{"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil}, {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil},
{"hello\x01world", 1, []string{"hello\x01"}, nil}, {"hello\x01world", 1, []string{"hello\x01"}, nil},
{"foo\nbar", 0, []string{"foo\nbar"}, os.EOF}, {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF},
{"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil}, {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil},
{"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, os.EOF}, {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF},
} }
func TestReadBytes(t *testing.T) { func TestReadBytes(t *testing.T) {
for _, test := range readBytesTests { for _, test := range readBytesTests {
buf := NewBufferString(test.buffer) buf := NewBufferString(test.buffer)
var err os.Error var err error
for _, expected := range test.expected { for _, expected := range test.expected {
var bytes []byte var bytes []byte
bytes, err = buf.ReadBytes(test.delim) bytes, err = buf.ReadBytes(test.delim)

View File

@ -7,25 +7,24 @@ package bzip2
import ( import (
"bufio" "bufio"
"io" "io"
"os"
) )
// bitReader wraps an io.Reader and provides the ability to read values, // bitReader wraps an io.Reader and provides the ability to read values,
// bit-by-bit, from it. Its Read* methods don't return the usual os.Error // bit-by-bit, from it. Its Read* methods don't return the usual error
// because the error handling was verbose. Instead, any error is kept and can // because the error handling was verbose. Instead, any error is kept and can
// be checked afterwards. // be checked afterwards.
type bitReader struct { type bitReader struct {
r byteReader r byteReader
n uint64 n uint64
bits uint bits uint
err os.Error err error
} }
// bitReader needs to read bytes from an io.Reader. We attempt to cast the // bitReader needs to read bytes from an io.Reader. We attempt to cast the
// given io.Reader to this interface and, if it doesn't already fit, we wrap in // given io.Reader to this interface and, if it doesn't already fit, we wrap in
// a bufio.Reader. // a bufio.Reader.
type byteReader interface { type byteReader interface {
ReadByte() (byte, os.Error) ReadByte() (byte, error)
} }
func newBitReader(r io.Reader) bitReader { func newBitReader(r io.Reader) bitReader {
@ -42,7 +41,7 @@ func newBitReader(r io.Reader) bitReader {
func (br *bitReader) ReadBits64(bits uint) (n uint64) { func (br *bitReader) ReadBits64(bits uint) (n uint64) {
for bits > br.bits { for bits > br.bits {
b, err := br.r.ReadByte() b, err := br.r.ReadByte()
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
if err != nil { if err != nil {
@ -83,6 +82,6 @@ func (br *bitReader) ReadBit() bool {
return n != 0 return n != 0
} }
func (br *bitReader) Error() os.Error { func (br *bitReader) Error() error {
return br.err return br.err
} }

View File

@ -5,10 +5,7 @@
// Package bzip2 implements bzip2 decompression. // Package bzip2 implements bzip2 decompression.
package bzip2 package bzip2
import ( import "io"
"io"
"os"
)
// There's no RFC for bzip2. I used the Wikipedia page for reference and a lot // There's no RFC for bzip2. I used the Wikipedia page for reference and a lot
// of guessing: http://en.wikipedia.org/wiki/Bzip2 // of guessing: http://en.wikipedia.org/wiki/Bzip2
@ -19,7 +16,7 @@ import (
// syntactically invalid. // syntactically invalid.
type StructuralError string type StructuralError string
func (s StructuralError) String() string { func (s StructuralError) Error() string {
return "bzip2 data invalid: " + string(s) return "bzip2 data invalid: " + string(s)
} }
@ -53,7 +50,7 @@ const bzip2BlockMagic = 0x314159265359
const bzip2FinalMagic = 0x177245385090 const bzip2FinalMagic = 0x177245385090
// setup parses the bzip2 header. // setup parses the bzip2 header.
func (bz2 *reader) setup() os.Error { func (bz2 *reader) setup() error {
br := &bz2.br br := &bz2.br
magic := br.ReadBits(16) magic := br.ReadBits(16)
@ -76,9 +73,9 @@ func (bz2 *reader) setup() os.Error {
return nil return nil
} }
func (bz2 *reader) Read(buf []byte) (n int, err os.Error) { func (bz2 *reader) Read(buf []byte) (n int, err error) {
if bz2.eof { if bz2.eof {
return 0, os.EOF return 0, io.EOF
} }
if !bz2.setupDone { if !bz2.setupDone {
@ -101,7 +98,7 @@ func (bz2 *reader) Read(buf []byte) (n int, err os.Error) {
return return
} }
func (bz2 *reader) read(buf []byte) (n int, err os.Error) { func (bz2 *reader) read(buf []byte) (n int, err error) {
// bzip2 is a block based compressor, except that it has a run-length // bzip2 is a block based compressor, except that it has a run-length
// preprocessing step. The block based nature means that we can // preprocessing step. The block based nature means that we can
// preallocate fixed-size buffers and reuse them. However, the RLE // preallocate fixed-size buffers and reuse them. However, the RLE
@ -162,7 +159,7 @@ func (bz2 *reader) read(buf []byte) (n int, err os.Error) {
if magic == bzip2FinalMagic { if magic == bzip2FinalMagic {
br.ReadBits64(32) // ignored CRC br.ReadBits64(32) // ignored CRC
bz2.eof = true bz2.eof = true
return 0, os.EOF return 0, io.EOF
} else if magic != bzip2BlockMagic { } else if magic != bzip2BlockMagic {
return 0, StructuralError("bad magic value found") return 0, StructuralError("bad magic value found")
} }
@ -176,7 +173,7 @@ func (bz2 *reader) read(buf []byte) (n int, err os.Error) {
} }
// readBlock reads a bzip2 block. The magic number should already have been consumed. // readBlock reads a bzip2 block. The magic number should already have been consumed.
func (bz2 *reader) readBlock() (err os.Error) { func (bz2 *reader) readBlock() (err error) {
br := &bz2.br br := &bz2.br
br.ReadBits64(32) // skip checksum. TODO: check it if we can figure out what it is. br.ReadBits64(32) // skip checksum. TODO: check it if we can figure out what it is.
randomized := br.ReadBits(1) randomized := br.ReadBits(1)

View File

@ -9,7 +9,6 @@ import (
"encoding/hex" "encoding/hex"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
@ -46,7 +45,7 @@ func readerFromHex(s string) io.Reader {
return bytes.NewBuffer(data) return bytes.NewBuffer(data)
} }
func decompressHex(s string) (out []byte, err os.Error) { func decompressHex(s string) (out []byte, err error) {
r := NewReader(readerFromHex(s)) r := NewReader(readerFromHex(s))
return ioutil.ReadAll(r) return ioutil.ReadAll(r)
} }

View File

@ -4,10 +4,7 @@
package bzip2 package bzip2
import ( import "sort"
"os"
"sort"
)
// A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a // A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a
// symbol. // symbol.
@ -63,7 +60,7 @@ func (t huffmanTree) Decode(br *bitReader) (v uint16) {
// newHuffmanTree builds a Huffman tree from a slice containing the code // newHuffmanTree builds a Huffman tree from a slice containing the code
// lengths of each symbol. The maximum code length is 32 bits. // lengths of each symbol. The maximum code length is 32 bits.
func newHuffmanTree(lengths []uint8) (huffmanTree, os.Error) { func newHuffmanTree(lengths []uint8) (huffmanTree, error) {
// There are many possible trees that assign the same code length to // There are many possible trees that assign the same code length to
// each symbol (consider reflecting a tree down the middle, for // each symbol (consider reflecting a tree down the middle, for
// example). Since the code length assignments determine the // example). Since the code length assignments determine the
@ -176,7 +173,7 @@ func (n huffmanCodes) Swap(i, j int) {
// buildHuffmanNode takes a slice of sorted huffmanCodes and builds a node in // buildHuffmanNode takes a slice of sorted huffmanCodes and builds a node in
// the Huffman tree at the given level. It returns the index of the newly // the Huffman tree at the given level. It returns the index of the newly
// constructed node. // constructed node.
func buildHuffmanNode(t *huffmanTree, codes []huffmanCode, level uint32) (nodeIndex uint16, err os.Error) { func buildHuffmanNode(t *huffmanTree, codes []huffmanCode, level uint32) (nodeIndex uint16, err error) {
test := uint32(1) << (31 - level) test := uint32(1) << (31 - level)
// We have to search the list of codes to find the divide between the left and right sides. // We have to search the list of codes to find the divide between the left and right sides.

View File

@ -7,7 +7,6 @@ package flate
import ( import (
"io" "io"
"math" "math"
"os"
) )
const ( const (
@ -89,7 +88,7 @@ type compressor struct {
offset int offset int
hash int hash int
maxInsertIndex int maxInsertIndex int
err os.Error err error
} }
func (d *compressor) fillDeflate(b []byte) int { func (d *compressor) fillDeflate(b []byte) int {
@ -123,7 +122,7 @@ func (d *compressor) fillDeflate(b []byte) int {
return n return n
} }
func (d *compressor) writeBlock(tokens []token, index int, eof bool) os.Error { func (d *compressor) writeBlock(tokens []token, index int, eof bool) error {
if index > 0 || eof { if index > 0 || eof {
var window []byte var window []byte
if d.blockStart <= index { if d.blockStart <= index {
@ -194,7 +193,7 @@ func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead
return return
} }
func (d *compressor) writeStoredBlock(buf []byte) os.Error { func (d *compressor) writeStoredBlock(buf []byte) error {
if d.w.writeStoredHeader(len(buf), false); d.w.err != nil { if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
return d.w.err return d.w.err
} }
@ -365,7 +364,7 @@ func (d *compressor) store() {
d.windowEnd = 0 d.windowEnd = 0
} }
func (d *compressor) write(b []byte) (n int, err os.Error) { func (d *compressor) write(b []byte) (n int, err error) {
n = len(b) n = len(b)
b = b[d.fill(d, b):] b = b[d.fill(d, b):]
for len(b) > 0 { for len(b) > 0 {
@ -375,7 +374,7 @@ func (d *compressor) write(b []byte) (n int, err os.Error) {
return n, d.err return n, d.err
} }
func (d *compressor) syncFlush() os.Error { func (d *compressor) syncFlush() error {
d.sync = true d.sync = true
d.step(d) d.step(d)
if d.err == nil { if d.err == nil {
@ -387,7 +386,7 @@ func (d *compressor) syncFlush() os.Error {
return d.err return d.err
} }
func (d *compressor) init(w io.Writer, level int) (err os.Error) { func (d *compressor) init(w io.Writer, level int) (err error) {
d.w = newHuffmanBitWriter(w) d.w = newHuffmanBitWriter(w)
switch { switch {
@ -409,7 +408,7 @@ func (d *compressor) init(w io.Writer, level int) (err os.Error) {
return nil return nil
} }
func (d *compressor) close() os.Error { func (d *compressor) close() error {
d.sync = true d.sync = true
d.step(d) d.step(d)
if d.err != nil { if d.err != nil {
@ -455,7 +454,7 @@ type dictWriter struct {
enabled bool enabled bool
} }
func (w *dictWriter) Write(b []byte) (n int, err os.Error) { func (w *dictWriter) Write(b []byte) (n int, err error) {
if w.enabled { if w.enabled {
return w.w.Write(b) return w.w.Write(b)
} }
@ -470,7 +469,7 @@ type Writer struct {
// Write writes data to w, which will eventually write the // Write writes data to w, which will eventually write the
// compressed form of data to its underlying writer. // compressed form of data to its underlying writer.
func (w *Writer) Write(data []byte) (n int, err os.Error) { func (w *Writer) Write(data []byte) (n int, err error) {
return w.d.write(data) return w.d.write(data)
} }
@ -481,13 +480,13 @@ func (w *Writer) Write(data []byte) (n int, err os.Error) {
// If the underlying writer returns an error, Flush returns that error. // If the underlying writer returns an error, Flush returns that error.
// //
// In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH. // In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
func (w *Writer) Flush() os.Error { func (w *Writer) Flush() error {
// For more about flushing: // For more about flushing:
// http://www.bolet.org/~pornin/deflate-flush.html // http://www.bolet.org/~pornin/deflate-flush.html
return w.d.syncFlush() return w.d.syncFlush()
} }
// Close flushes and closes the writer. // Close flushes and closes the writer.
func (w *Writer) Close() os.Error { func (w *Writer) Close() error {
return w.d.close() return w.d.close()
} }

View File

@ -9,7 +9,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"sync" "sync"
"testing" "testing"
) )
@ -102,7 +101,7 @@ func newSyncBuffer() *syncBuffer {
return &syncBuffer{ready: make(chan bool, 1)} return &syncBuffer{ready: make(chan bool, 1)}
} }
func (b *syncBuffer) Read(p []byte) (n int, err os.Error) { func (b *syncBuffer) Read(p []byte) (n int, err error) {
for { for {
b.mu.RLock() b.mu.RLock()
n, err = b.buf.Read(p) n, err = b.buf.Read(p)
@ -122,7 +121,7 @@ func (b *syncBuffer) signal() {
} }
} }
func (b *syncBuffer) Write(p []byte) (n int, err os.Error) { func (b *syncBuffer) Write(p []byte) (n int, err error) {
n, err = b.buf.Write(p) n, err = b.buf.Write(p)
b.signal() b.signal()
return return
@ -137,7 +136,7 @@ func (b *syncBuffer) ReadMode() {
b.signal() b.signal()
} }
func (b *syncBuffer) Close() os.Error { func (b *syncBuffer) Close() error {
b.closed = true b.closed = true
b.signal() b.signal()
return nil return nil
@ -204,7 +203,7 @@ func testSync(t *testing.T, level int, input []byte, name string) {
} }
buf.ReadMode() buf.ReadMode()
out := make([]byte, 10) out := make([]byte, 10)
if n, err := r.Read(out); n > 0 || err != os.EOF { if n, err := r.Read(out); n > 0 || err != io.EOF {
t.Errorf("testSync (%d, %d, %s): final Read: %d, %v (hex: %x)", level, len(input), name, n, err, out[0:n]) t.Errorf("testSync (%d, %d, %s): final Read: %d, %v (hex: %x)", level, len(input), name, n, err, out[0:n])
} }
if buf.buf.Len() != 0 { if buf.buf.Len() != 0 {
@ -225,7 +224,7 @@ func testSync(t *testing.T, level int, input []byte, name string) {
} }
} }
func testToFromWithLevel(t *testing.T, level int, input []byte, name string) os.Error { func testToFromWithLevel(t *testing.T, level int, input []byte, name string) error {
buffer := bytes.NewBuffer(nil) buffer := bytes.NewBuffer(nil)
w := NewWriter(buffer, level) w := NewWriter(buffer, level)
w.Write(input) w.Write(input)

View File

@ -7,7 +7,6 @@ package flate
import ( import (
"io" "io"
"math" "math"
"os"
"strconv" "strconv"
) )
@ -83,7 +82,7 @@ type huffmanBitWriter struct {
literalEncoding *huffmanEncoder literalEncoding *huffmanEncoder
offsetEncoding *huffmanEncoder offsetEncoding *huffmanEncoder
codegenEncoding *huffmanEncoder codegenEncoding *huffmanEncoder
err os.Error err error
} }
type WrongValueError struct { type WrongValueError struct {
@ -106,7 +105,7 @@ func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
} }
} }
func (err WrongValueError) String() string { func (err WrongValueError) Error() string {
return "huffmanBitWriter: " + err.name + " should belong to [" + strconv.Itoa64(int64(err.from)) + ";" + return "huffmanBitWriter: " + err.name + " should belong to [" + strconv.Itoa64(int64(err.from)) + ";" +
strconv.Itoa64(int64(err.to)) + "] but actual value is " + strconv.Itoa64(int64(err.value)) strconv.Itoa64(int64(err.to)) + "] but actual value is " + strconv.Itoa64(int64(err.value))
} }

View File

@ -10,7 +10,6 @@ package flate
import ( import (
"bufio" "bufio"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -25,33 +24,33 @@ const (
// A CorruptInputError reports the presence of corrupt input at a given offset. // A CorruptInputError reports the presence of corrupt input at a given offset.
type CorruptInputError int64 type CorruptInputError int64
func (e CorruptInputError) String() string { func (e CorruptInputError) Error() string {
return "flate: corrupt input before offset " + strconv.Itoa64(int64(e)) return "flate: corrupt input before offset " + strconv.Itoa64(int64(e))
} }
// An InternalError reports an error in the flate code itself. // An InternalError reports an error in the flate code itself.
type InternalError string type InternalError string
func (e InternalError) String() string { return "flate: internal error: " + string(e) } func (e InternalError) Error() string { return "flate: internal error: " + string(e) }
// A ReadError reports an error encountered while reading input. // A ReadError reports an error encountered while reading input.
type ReadError struct { type ReadError struct {
Offset int64 // byte offset where error occurred Offset int64 // byte offset where error occurred
Error os.Error // error returned by underlying Read Err error // error returned by underlying Read
} }
func (e *ReadError) String() string { func (e *ReadError) Error() string {
return "flate: read error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Error.String() return "flate: read error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Err.Error()
} }
// A WriteError reports an error encountered while writing output. // A WriteError reports an error encountered while writing output.
type WriteError struct { type WriteError struct {
Offset int64 // byte offset where error occurred Offset int64 // byte offset where error occurred
Error os.Error // error returned by underlying Write Err error // error returned by underlying Write
} }
func (e *WriteError) String() string { func (e *WriteError) Error() string {
return "flate: write error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Error.String() return "flate: write error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Err.Error()
} }
// Huffman decoder is based on // Huffman decoder is based on
@ -190,7 +189,7 @@ var fixedHuffmanDecoder = huffmanDecoder{
// the NewReader will introduce its own buffering. // the NewReader will introduce its own buffering.
type Reader interface { type Reader interface {
io.Reader io.Reader
ReadByte() (c byte, err os.Error) ReadByte() (c byte, err error)
} }
// Decompress state. // Decompress state.
@ -224,7 +223,7 @@ type decompressor struct {
// and decompression state. // and decompression state.
step func(*decompressor) step func(*decompressor)
final bool final bool
err os.Error err error
toRead []byte toRead []byte
hl, hd *huffmanDecoder hl, hd *huffmanDecoder
copyLen int copyLen int
@ -237,7 +236,7 @@ func (f *decompressor) nextBlock() {
f.flush((*decompressor).nextBlock) f.flush((*decompressor).nextBlock)
return return
} }
f.err = os.EOF f.err = io.EOF
return return
} }
for f.nb < 1+2 { for f.nb < 1+2 {
@ -272,7 +271,7 @@ func (f *decompressor) nextBlock() {
} }
} }
func (f *decompressor) Read(b []byte) (int, os.Error) { func (f *decompressor) Read(b []byte) (int, error) {
for { for {
if len(f.toRead) > 0 { if len(f.toRead) > 0 {
n := copy(b, f.toRead) n := copy(b, f.toRead)
@ -287,8 +286,8 @@ func (f *decompressor) Read(b []byte) (int, os.Error) {
panic("unreachable") panic("unreachable")
} }
func (f *decompressor) Close() os.Error { func (f *decompressor) Close() error {
if f.err == os.EOF { if f.err == io.EOF {
return nil return nil
} }
return f.err return f.err
@ -299,7 +298,7 @@ func (f *decompressor) Close() os.Error {
var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
func (f *decompressor) readHuffman() os.Error { func (f *decompressor) readHuffman() error {
// HLIT[5], HDIST[5], HCLEN[4]. // HLIT[5], HDIST[5], HCLEN[4].
for f.nb < 5+5+4 { for f.nb < 5+5+4 {
if err := f.moreBits(); err != nil { if err := f.moreBits(); err != nil {
@ -625,10 +624,10 @@ func (f *decompressor) setDict(dict []byte) {
f.hw = f.hp f.hw = f.hp
} }
func (f *decompressor) moreBits() os.Error { func (f *decompressor) moreBits() error {
c, err := f.r.ReadByte() c, err := f.r.ReadByte()
if err != nil { if err != nil {
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return err return err
@ -640,7 +639,7 @@ func (f *decompressor) moreBits() os.Error {
} }
// Read the next Huffman-encoded symbol from f according to h. // Read the next Huffman-encoded symbol from f according to h.
func (f *decompressor) huffSym(h *huffmanDecoder) (int, os.Error) { func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) {
for n := uint(h.min); n <= uint(h.max); n++ { for n := uint(h.min); n <= uint(h.max); n++ {
lim := h.limit[n] lim := h.limit[n]
if lim == -1 { if lim == -1 {

View File

@ -9,10 +9,10 @@ package gzip
import ( import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"io" "io"
"os"
) )
// BUG(nigeltao): Comments and Names don't properly map UTF-8 character codes outside of // BUG(nigeltao): Comments and Names don't properly map UTF-8 character codes outside of
@ -36,8 +36,8 @@ func makeReader(r io.Reader) flate.Reader {
return bufio.NewReader(r) return bufio.NewReader(r)
} }
var HeaderError = os.NewError("invalid gzip header") var HeaderError = errors.New("invalid gzip header")
var ChecksumError = os.NewError("gzip checksum error") var ChecksumError = errors.New("gzip checksum error")
// The gzip file stores a header giving metadata about the compressed file. // The gzip file stores a header giving metadata about the compressed file.
// That header is exposed as the fields of the Compressor and Decompressor structs. // That header is exposed as the fields of the Compressor and Decompressor structs.
@ -71,13 +71,13 @@ type Decompressor struct {
size uint32 size uint32
flg byte flg byte
buf [512]byte buf [512]byte
err os.Error err error
} }
// NewReader creates a new Decompressor reading the given reader. // NewReader creates a new Decompressor reading the given reader.
// The implementation buffers input and may read more data than necessary from r. // The implementation buffers input and may read more data than necessary from r.
// It is the caller's responsibility to call Close on the Decompressor when done. // It is the caller's responsibility to call Close on the Decompressor when done.
func NewReader(r io.Reader) (*Decompressor, os.Error) { func NewReader(r io.Reader) (*Decompressor, error) {
z := new(Decompressor) z := new(Decompressor)
z.r = makeReader(r) z.r = makeReader(r)
z.digest = crc32.NewIEEE() z.digest = crc32.NewIEEE()
@ -93,8 +93,8 @@ func get4(p []byte) uint32 {
return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24 return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
} }
func (z *Decompressor) readString() (string, os.Error) { func (z *Decompressor) readString() (string, error) {
var err os.Error var err error
for i := 0; ; i++ { for i := 0; ; i++ {
if i >= len(z.buf) { if i >= len(z.buf) {
return "", HeaderError return "", HeaderError
@ -112,7 +112,7 @@ func (z *Decompressor) readString() (string, os.Error) {
panic("not reached") panic("not reached")
} }
func (z *Decompressor) read2() (uint32, os.Error) { func (z *Decompressor) read2() (uint32, error) {
_, err := io.ReadFull(z.r, z.buf[0:2]) _, err := io.ReadFull(z.r, z.buf[0:2])
if err != nil { if err != nil {
return 0, err return 0, err
@ -120,7 +120,7 @@ func (z *Decompressor) read2() (uint32, os.Error) {
return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil
} }
func (z *Decompressor) readHeader(save bool) os.Error { func (z *Decompressor) readHeader(save bool) error {
_, err := io.ReadFull(z.r, z.buf[0:10]) _, err := io.ReadFull(z.r, z.buf[0:10])
if err != nil { if err != nil {
return err return err
@ -186,7 +186,7 @@ func (z *Decompressor) readHeader(save bool) os.Error {
return nil return nil
} }
func (z *Decompressor) Read(p []byte) (n int, err os.Error) { func (z *Decompressor) Read(p []byte) (n int, err error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
@ -197,7 +197,7 @@ func (z *Decompressor) Read(p []byte) (n int, err os.Error) {
n, err = z.decompressor.Read(p) n, err = z.decompressor.Read(p)
z.digest.Write(p[0:n]) z.digest.Write(p[0:n])
z.size += uint32(n) z.size += uint32(n)
if n != 0 || err != os.EOF { if n != 0 || err != io.EOF {
z.err = err z.err = err
return return
} }
@ -227,4 +227,4 @@ func (z *Decompressor) Read(p []byte) (n int, err os.Error) {
} }
// Calling Close does not close the wrapped io.Reader originally passed to NewReader. // Calling Close does not close the wrapped io.Reader originally passed to NewReader.
func (z *Decompressor) Close() os.Error { return z.decompressor.Close() } func (z *Decompressor) Close() error { return z.decompressor.Close() }

View File

@ -7,7 +7,6 @@ package gzip
import ( import (
"bytes" "bytes"
"io" "io"
"os"
"testing" "testing"
) )
@ -16,7 +15,7 @@ type gunzipTest struct {
desc string desc string
raw string raw string
gzip []byte gzip []byte
err os.Error err error
} }
var gunzipTests = []gunzipTest{ var gunzipTests = []gunzipTest{

View File

@ -6,10 +6,10 @@ package gzip
import ( import (
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"io" "io"
"os"
) )
// These constants are copied from the flate package, so that code that imports // These constants are copied from the flate package, so that code that imports
@ -32,11 +32,11 @@ type Compressor struct {
size uint32 size uint32
closed bool closed bool
buf [10]byte buf [10]byte
err os.Error err error
} }
// NewWriter calls NewWriterLevel with the default compression level. // NewWriter calls NewWriterLevel with the default compression level.
func NewWriter(w io.Writer) (*Compressor, os.Error) { func NewWriter(w io.Writer) (*Compressor, error) {
return NewWriterLevel(w, DefaultCompression) return NewWriterLevel(w, DefaultCompression)
} }
@ -47,7 +47,7 @@ func NewWriter(w io.Writer) (*Compressor, os.Error) {
// It is the caller's responsibility to call Close on the WriteCloser when done. // It is the caller's responsibility to call Close on the WriteCloser when done.
// level is the compression level, which can be DefaultCompression, NoCompression, // level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive). // or any integer value between BestSpeed and BestCompression (inclusive).
func NewWriterLevel(w io.Writer, level int) (*Compressor, os.Error) { func NewWriterLevel(w io.Writer, level int) (*Compressor, error) {
z := new(Compressor) z := new(Compressor)
z.OS = 255 // unknown z.OS = 255 // unknown
z.w = w z.w = w
@ -70,9 +70,9 @@ func put4(p []byte, v uint32) {
} }
// writeBytes writes a length-prefixed byte slice to z.w. // writeBytes writes a length-prefixed byte slice to z.w.
func (z *Compressor) writeBytes(b []byte) os.Error { func (z *Compressor) writeBytes(b []byte) error {
if len(b) > 0xffff { if len(b) > 0xffff {
return os.NewError("gzip.Write: Extra data is too large") return errors.New("gzip.Write: Extra data is too large")
} }
put2(z.buf[0:2], uint16(len(b))) put2(z.buf[0:2], uint16(len(b)))
_, err := z.w.Write(z.buf[0:2]) _, err := z.w.Write(z.buf[0:2])
@ -84,12 +84,12 @@ func (z *Compressor) writeBytes(b []byte) os.Error {
} }
// writeString writes a string (in ISO 8859-1 (Latin-1) format) to z.w. // writeString writes a string (in ISO 8859-1 (Latin-1) format) to z.w.
func (z *Compressor) writeString(s string) os.Error { func (z *Compressor) writeString(s string) error {
// GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1). // GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1).
// TODO(nigeltao): Convert from UTF-8 to ISO 8859-1 (Latin-1). // TODO(nigeltao): Convert from UTF-8 to ISO 8859-1 (Latin-1).
for _, v := range s { for _, v := range s {
if v == 0 || v > 0x7f { if v == 0 || v > 0x7f {
return os.NewError("gzip.Write: non-ASCII header string") return errors.New("gzip.Write: non-ASCII header string")
} }
} }
_, err := io.WriteString(z.w, s) _, err := io.WriteString(z.w, s)
@ -102,7 +102,7 @@ func (z *Compressor) writeString(s string) os.Error {
return err return err
} }
func (z *Compressor) Write(p []byte) (int, os.Error) { func (z *Compressor) Write(p []byte) (int, error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
@ -162,7 +162,7 @@ func (z *Compressor) Write(p []byte) (int, os.Error) {
} }
// Calling Close does not close the wrapped io.Writer originally passed to NewWriter. // Calling Close does not close the wrapped io.Writer originally passed to NewWriter.
func (z *Compressor) Close() os.Error { func (z *Compressor) Close() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }

View File

@ -16,6 +16,7 @@ package lzw
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -45,9 +46,9 @@ type decoder struct {
bits uint32 bits uint32
nBits uint nBits uint
width uint width uint
read func(*decoder) (uint16, os.Error) // readLSB or readMSB read func(*decoder) (uint16, error) // readLSB or readMSB
litWidth int // width in bits of literal codes litWidth int // width in bits of literal codes
err os.Error err error
// The first 1<<litWidth codes are literal codes. // The first 1<<litWidth codes are literal codes.
// The next two codes mean clear and EOF. // The next two codes mean clear and EOF.
@ -78,7 +79,7 @@ type decoder struct {
} }
// readLSB returns the next code for "Least Significant Bits first" data. // readLSB returns the next code for "Least Significant Bits first" data.
func (d *decoder) readLSB() (uint16, os.Error) { func (d *decoder) readLSB() (uint16, error) {
for d.nBits < d.width { for d.nBits < d.width {
x, err := d.r.ReadByte() x, err := d.r.ReadByte()
if err != nil { if err != nil {
@ -94,7 +95,7 @@ func (d *decoder) readLSB() (uint16, os.Error) {
} }
// readMSB returns the next code for "Most Significant Bits first" data. // readMSB returns the next code for "Most Significant Bits first" data.
func (d *decoder) readMSB() (uint16, os.Error) { func (d *decoder) readMSB() (uint16, error) {
for d.nBits < d.width { for d.nBits < d.width {
x, err := d.r.ReadByte() x, err := d.r.ReadByte()
if err != nil { if err != nil {
@ -109,7 +110,7 @@ func (d *decoder) readMSB() (uint16, os.Error) {
return code, nil return code, nil
} }
func (d *decoder) Read(b []byte) (int, os.Error) { func (d *decoder) Read(b []byte) (int, error) {
for { for {
if len(d.toRead) > 0 { if len(d.toRead) > 0 {
n := copy(b, d.toRead) n := copy(b, d.toRead)
@ -132,7 +133,7 @@ func (d *decoder) decode() {
for { for {
code, err := d.read(d) code, err := d.read(d)
if err != nil { if err != nil {
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
d.err = err d.err = err
@ -156,7 +157,7 @@ func (d *decoder) decode() {
continue continue
case code == d.eof: case code == d.eof:
d.flush() d.flush()
d.err = os.EOF d.err = io.EOF
return return
case code <= d.hi: case code <= d.hi:
c, i := code, len(d.output)-1 c, i := code, len(d.output)-1
@ -186,7 +187,7 @@ func (d *decoder) decode() {
d.prefix[d.hi] = d.last d.prefix[d.hi] = d.last
} }
default: default:
d.err = os.NewError("lzw: invalid code") d.err = errors.New("lzw: invalid code")
return return
} }
d.last, d.hi = code, d.hi+1 d.last, d.hi = code, d.hi+1
@ -211,7 +212,7 @@ func (d *decoder) flush() {
d.o = 0 d.o = 0
} }
func (d *decoder) Close() os.Error { func (d *decoder) Close() error {
d.err = os.EINVAL // in case any Reads come along d.err = os.EINVAL // in case any Reads come along
return nil return nil
} }
@ -230,7 +231,7 @@ func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser {
case MSB: case MSB:
d.read = (*decoder).readMSB d.read = (*decoder).readMSB
default: default:
d.err = os.NewError("lzw: unknown order") d.err = errors.New("lzw: unknown order")
return d return d
} }
if litWidth < 2 || 8 < litWidth { if litWidth < 2 || 8 < litWidth {

View File

@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
@ -19,7 +18,7 @@ type lzwTest struct {
desc string desc string
raw string raw string
compressed string compressed string
err os.Error err error
} }
var lzwTests = []lzwTest{ var lzwTests = []lzwTest{

View File

@ -6,6 +6,7 @@ package lzw
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -13,20 +14,20 @@ import (
// A writer is a buffered, flushable writer. // A writer is a buffered, flushable writer.
type writer interface { type writer interface {
WriteByte(byte) os.Error WriteByte(byte) error
Flush() os.Error Flush() error
} }
// An errWriteCloser is an io.WriteCloser that always returns a given error. // An errWriteCloser is an io.WriteCloser that always returns a given error.
type errWriteCloser struct { type errWriteCloser struct {
err os.Error err error
} }
func (e *errWriteCloser) Write([]byte) (int, os.Error) { func (e *errWriteCloser) Write([]byte) (int, error) {
return 0, e.err return 0, e.err
} }
func (e *errWriteCloser) Close() os.Error { func (e *errWriteCloser) Close() error {
return e.err return e.err
} }
@ -50,7 +51,7 @@ type encoder struct {
w writer w writer
// write, bits, nBits and width are the state for converting a code stream // write, bits, nBits and width are the state for converting a code stream
// into a byte stream. // into a byte stream.
write func(*encoder, uint32) os.Error write func(*encoder, uint32) error
bits uint32 bits uint32
nBits uint nBits uint
width uint width uint
@ -64,7 +65,7 @@ type encoder struct {
savedCode uint32 savedCode uint32
// err is the first error encountered during writing. Closing the encoder // err is the first error encountered during writing. Closing the encoder
// will make any future Write calls return os.EINVAL. // will make any future Write calls return os.EINVAL.
err os.Error err error
// table is the hash table from 20-bit keys to 12-bit values. Each table // table is the hash table from 20-bit keys to 12-bit values. Each table
// entry contains key<<12|val and collisions resolve by linear probing. // entry contains key<<12|val and collisions resolve by linear probing.
// The keys consist of a 12-bit code prefix and an 8-bit byte suffix. // The keys consist of a 12-bit code prefix and an 8-bit byte suffix.
@ -73,7 +74,7 @@ type encoder struct {
} }
// writeLSB writes the code c for "Least Significant Bits first" data. // writeLSB writes the code c for "Least Significant Bits first" data.
func (e *encoder) writeLSB(c uint32) os.Error { func (e *encoder) writeLSB(c uint32) error {
e.bits |= c << e.nBits e.bits |= c << e.nBits
e.nBits += e.width e.nBits += e.width
for e.nBits >= 8 { for e.nBits >= 8 {
@ -87,7 +88,7 @@ func (e *encoder) writeLSB(c uint32) os.Error {
} }
// writeMSB writes the code c for "Most Significant Bits first" data. // writeMSB writes the code c for "Most Significant Bits first" data.
func (e *encoder) writeMSB(c uint32) os.Error { func (e *encoder) writeMSB(c uint32) error {
e.bits |= c << (32 - e.width - e.nBits) e.bits |= c << (32 - e.width - e.nBits)
e.nBits += e.width e.nBits += e.width
for e.nBits >= 8 { for e.nBits >= 8 {
@ -102,12 +103,12 @@ func (e *encoder) writeMSB(c uint32) os.Error {
// errOutOfCodes is an internal error that means that the encoder has run out // errOutOfCodes is an internal error that means that the encoder has run out
// of unused codes and a clear code needs to be sent next. // of unused codes and a clear code needs to be sent next.
var errOutOfCodes = os.NewError("lzw: out of codes") var errOutOfCodes = errors.New("lzw: out of codes")
// incHi increments e.hi and checks for both overflow and running out of // incHi increments e.hi and checks for both overflow and running out of
// unused codes. In the latter case, incHi sends a clear code, resets the // unused codes. In the latter case, incHi sends a clear code, resets the
// encoder state and returns errOutOfCodes. // encoder state and returns errOutOfCodes.
func (e *encoder) incHi() os.Error { func (e *encoder) incHi() error {
e.hi++ e.hi++
if e.hi == e.overflow { if e.hi == e.overflow {
e.width++ e.width++
@ -130,7 +131,7 @@ func (e *encoder) incHi() os.Error {
} }
// Write writes a compressed representation of p to e's underlying writer. // Write writes a compressed representation of p to e's underlying writer.
func (e *encoder) Write(p []byte) (int, os.Error) { func (e *encoder) Write(p []byte) (int, error) {
if e.err != nil { if e.err != nil {
return 0, e.err return 0, e.err
} }
@ -188,7 +189,7 @@ loop:
// Close closes the encoder, flushing any pending output. It does not close or // Close closes the encoder, flushing any pending output. It does not close or
// flush e's underlying writer. // flush e's underlying writer.
func (e *encoder) Close() os.Error { func (e *encoder) Close() error {
if e.err != nil { if e.err != nil {
if e.err == os.EINVAL { if e.err == os.EINVAL {
return nil return nil
@ -230,14 +231,14 @@ func (e *encoder) Close() os.Error {
// The number of bits to use for literal codes, litWidth, must be in the // The number of bits to use for literal codes, litWidth, must be in the
// range [2,8] and is typically 8. // range [2,8] and is typically 8.
func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser { func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser {
var write func(*encoder, uint32) os.Error var write func(*encoder, uint32) error
switch order { switch order {
case LSB: case LSB:
write = (*encoder).writeLSB write = (*encoder).writeLSB
case MSB: case MSB:
write = (*encoder).writeMSB write = (*encoder).writeMSB
default: default:
return &errWriteCloser{os.NewError("lzw: unknown order")} return &errWriteCloser{errors.New("lzw: unknown order")}
} }
if litWidth < 2 || 8 < litWidth { if litWidth < 2 || 8 < litWidth {
return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)} return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)}

View File

@ -45,7 +45,7 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) {
var b [4096]byte var b [4096]byte
for { for {
n, err0 := raw.Read(b[:]) n, err0 := raw.Read(b[:])
if err0 != nil && err0 != os.EOF { if err0 != nil && err0 != io.EOF {
t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0) t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0)
return return
} }
@ -58,7 +58,7 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) {
t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1) t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1)
return return
} }
if err0 == os.EOF { if err0 == io.EOF {
break break
} }
} }

View File

@ -26,36 +26,36 @@ package zlib
import ( import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/adler32" "hash/adler32"
"io" "io"
"os"
) )
const zlibDeflate = 8 const zlibDeflate = 8
var ChecksumError = os.NewError("zlib checksum error") var ChecksumError = errors.New("zlib checksum error")
var HeaderError = os.NewError("invalid zlib header") var HeaderError = errors.New("invalid zlib header")
var DictionaryError = os.NewError("invalid zlib dictionary") var DictionaryError = errors.New("invalid zlib dictionary")
type reader struct { type reader struct {
r flate.Reader r flate.Reader
decompressor io.ReadCloser decompressor io.ReadCloser
digest hash.Hash32 digest hash.Hash32
err os.Error err error
scratch [4]byte scratch [4]byte
} }
// NewReader creates a new io.ReadCloser that satisfies reads by decompressing data read from r. // NewReader creates a new io.ReadCloser that satisfies reads by decompressing data read from r.
// The implementation buffers input and may read more data than necessary from r. // The implementation buffers input and may read more data than necessary from r.
// It is the caller's responsibility to call Close on the ReadCloser when done. // It is the caller's responsibility to call Close on the ReadCloser when done.
func NewReader(r io.Reader) (io.ReadCloser, os.Error) { func NewReader(r io.Reader) (io.ReadCloser, error) {
return NewReaderDict(r, nil) return NewReaderDict(r, nil)
} }
// NewReaderDict is like NewReader but uses a preset dictionary. // NewReaderDict is like NewReader but uses a preset dictionary.
// NewReaderDict ignores the dictionary if the compressed data does not refer to it. // NewReaderDict ignores the dictionary if the compressed data does not refer to it.
func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, os.Error) { func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error) {
z := new(reader) z := new(reader)
if fr, ok := r.(flate.Reader); ok { if fr, ok := r.(flate.Reader); ok {
z.r = fr z.r = fr
@ -87,7 +87,7 @@ func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, os.Error) {
return z, nil return z, nil
} }
func (z *reader) Read(p []byte) (n int, err os.Error) { func (z *reader) Read(p []byte) (n int, err error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
@ -97,7 +97,7 @@ func (z *reader) Read(p []byte) (n int, err os.Error) {
n, err = z.decompressor.Read(p) n, err = z.decompressor.Read(p)
z.digest.Write(p[0:n]) z.digest.Write(p[0:n])
if n != 0 || err != os.EOF { if n != 0 || err != io.EOF {
z.err = err z.err = err
return return
} }
@ -117,7 +117,7 @@ func (z *reader) Read(p []byte) (n int, err os.Error) {
} }
// Calling Close does not close the wrapped io.Reader originally passed to NewReader. // Calling Close does not close the wrapped io.Reader originally passed to NewReader.
func (z *reader) Close() os.Error { func (z *reader) Close() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }

View File

@ -7,7 +7,6 @@ package zlib
import ( import (
"bytes" "bytes"
"io" "io"
"os"
"testing" "testing"
) )
@ -16,7 +15,7 @@ type zlibTest struct {
raw string raw string
compressed []byte compressed []byte
dict []byte dict []byte
err os.Error err error
} }
// Compare-to-golden test data was generated by the ZLIB example program at // Compare-to-golden test data was generated by the ZLIB example program at

View File

@ -6,10 +6,10 @@ package zlib
import ( import (
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/adler32" "hash/adler32"
"io" "io"
"os"
) )
// These constants are copied from the flate package, so that code that imports // These constants are copied from the flate package, so that code that imports
@ -27,17 +27,17 @@ type Writer struct {
w io.Writer w io.Writer
compressor *flate.Writer compressor *flate.Writer
digest hash.Hash32 digest hash.Hash32
err os.Error err error
scratch [4]byte scratch [4]byte
} }
// NewWriter calls NewWriterLevel with the default compression level. // NewWriter calls NewWriterLevel with the default compression level.
func NewWriter(w io.Writer) (*Writer, os.Error) { func NewWriter(w io.Writer) (*Writer, error) {
return NewWriterLevel(w, DefaultCompression) return NewWriterLevel(w, DefaultCompression)
} }
// NewWriterLevel calls NewWriterDict with no dictionary. // NewWriterLevel calls NewWriterDict with no dictionary.
func NewWriterLevel(w io.Writer, level int) (*Writer, os.Error) { func NewWriterLevel(w io.Writer, level int) (*Writer, error) {
return NewWriterDict(w, level, nil) return NewWriterDict(w, level, nil)
} }
@ -46,7 +46,7 @@ func NewWriterLevel(w io.Writer, level int) (*Writer, os.Error) {
// level is the compression level, which can be DefaultCompression, NoCompression, // level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive). // or any integer value between BestSpeed and BestCompression (inclusive).
// dict is the preset dictionary to compress with, or nil to use no dictionary. // dict is the preset dictionary to compress with, or nil to use no dictionary.
func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) { func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
z := new(Writer) z := new(Writer)
// ZLIB has a two-byte header (as documented in RFC 1950). // ZLIB has a two-byte header (as documented in RFC 1950).
// The first four bits is the CINFO (compression info), which is 7 for the default deflate window size. // The first four bits is the CINFO (compression info), which is 7 for the default deflate window size.
@ -66,7 +66,7 @@ func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) {
case 7, 8, 9: case 7, 8, 9:
z.scratch[1] = 3 << 6 z.scratch[1] = 3 << 6
default: default:
return nil, os.NewError("level out of range") return nil, errors.New("level out of range")
} }
if dict != nil { if dict != nil {
z.scratch[1] |= 1 << 5 z.scratch[1] |= 1 << 5
@ -94,7 +94,7 @@ func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) {
return z, nil return z, nil
} }
func (z *Writer) Write(p []byte) (n int, err os.Error) { func (z *Writer) Write(p []byte) (n int, err error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
@ -111,7 +111,7 @@ func (z *Writer) Write(p []byte) (n int, err os.Error) {
} }
// Flush flushes the underlying compressor. // Flush flushes the underlying compressor.
func (z *Writer) Flush() os.Error { func (z *Writer) Flush() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }
@ -120,7 +120,7 @@ func (z *Writer) Flush() os.Error {
} }
// Calling Close does not close the wrapped io.Writer originally passed to NewWriter. // Calling Close does not close the wrapped io.Writer originally passed to NewWriter.
func (z *Writer) Close() os.Error { func (z *Writer) Close() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }

View File

@ -4,10 +4,7 @@
package aes package aes
import ( import "strconv"
"os"
"strconv"
)
// The AES block size in bytes. // The AES block size in bytes.
const BlockSize = 16 const BlockSize = 16
@ -20,7 +17,7 @@ type Cipher struct {
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/aes: invalid key size " + strconv.Itoa(int(k)) return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
} }
@ -28,7 +25,7 @@ func (k KeySizeError) String() string {
// The key argument should be the AES key, // The key argument should be the AES key,
// either 16, 24, or 32 bytes to select // either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256. // AES-128, AES-192, or AES-256.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
k := len(key) k := len(key)
switch k { switch k {
default: default:

View File

@ -4,10 +4,7 @@
package bcrypt package bcrypt
import ( import "encoding/base64"
"encoding/base64"
"os"
)
const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@ -23,7 +20,7 @@ func base64Encode(src []byte) []byte {
return dst[:n] return dst[:n]
} }
func base64Decode(src []byte) ([]byte, os.Error) { func base64Decode(src []byte) ([]byte, error) {
numOfEquals := 4 - (len(src) % 4) numOfEquals := 4 - (len(src) % 4)
for i := 0; i < numOfEquals; i++ { for i := 0; i < numOfEquals; i++ {
src = append(src, '=') src = append(src, '=')

View File

@ -11,9 +11,9 @@ import (
"crypto/blowfish" "crypto/blowfish"
"crypto/rand" "crypto/rand"
"crypto/subtle" "crypto/subtle"
"errors"
"fmt" "fmt"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -25,30 +25,30 @@ const (
// The error returned from CompareHashAndPassword when a password and hash do // The error returned from CompareHashAndPassword when a password and hash do
// not match. // not match.
var MismatchedHashAndPasswordError = os.NewError("crypto/bcrypt: hashedPassword is not the hash of the given password") var MismatchedHashAndPasswordError = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password")
// The error returned from CompareHashAndPassword when a hash is too short to // The error returned from CompareHashAndPassword when a hash is too short to
// be a bcrypt hash. // be a bcrypt hash.
var HashTooShortError = os.NewError("crypto/bcrypt: hashedSecret too short to be a bcrypted password") var HashTooShortError = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password")
// The error returned from CompareHashAndPassword when a hash was created with // The error returned from CompareHashAndPassword when a hash was created with
// a bcrypt algorithm newer than this implementation. // a bcrypt algorithm newer than this implementation.
type HashVersionTooNewError byte type HashVersionTooNewError byte
func (hv HashVersionTooNewError) String() string { func (hv HashVersionTooNewError) Error() string {
return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion) return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion)
} }
// The error returned from CompareHashAndPassword when a hash starts with something other than '$' // The error returned from CompareHashAndPassword when a hash starts with something other than '$'
type InvalidHashPrefixError byte type InvalidHashPrefixError byte
func (ih InvalidHashPrefixError) String() string { func (ih InvalidHashPrefixError) Error() string {
return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih)) return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih))
} }
type InvalidCostError int type InvalidCostError int
func (ic InvalidCostError) String() string { func (ic InvalidCostError) Error() string {
return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost)) return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost))
} }
@ -85,7 +85,7 @@ type hashed struct {
// cost. If the cost given is less than MinCost, the cost will be set to // cost. If the cost given is less than MinCost, the cost will be set to
// MinCost, instead. Use CompareHashAndPassword, as defined in this package, // MinCost, instead. Use CompareHashAndPassword, as defined in this package,
// to compare the returned hashed password with its cleartext version. // to compare the returned hashed password with its cleartext version.
func GenerateFromPassword(password []byte, cost int) ([]byte, os.Error) { func GenerateFromPassword(password []byte, cost int) ([]byte, error) {
p, err := newFromPassword(password, cost) p, err := newFromPassword(password, cost)
if err != nil { if err != nil {
return nil, err return nil, err
@ -96,7 +96,7 @@ func GenerateFromPassword(password []byte, cost int) ([]byte, os.Error) {
// CompareHashAndPassword compares a bcrypt hashed password with its possible // CompareHashAndPassword compares a bcrypt hashed password with its possible
// plaintext equivalent. Note: Using bytes.Equal for this job is // plaintext equivalent. Note: Using bytes.Equal for this job is
// insecure. Returns nil on success, or an error on failure. // insecure. Returns nil on success, or an error on failure.
func CompareHashAndPassword(hashedPassword, password []byte) os.Error { func CompareHashAndPassword(hashedPassword, password []byte) error {
p, err := newFromHash(hashedPassword) p, err := newFromHash(hashedPassword)
if err != nil { if err != nil {
return err return err
@ -115,7 +115,7 @@ func CompareHashAndPassword(hashedPassword, password []byte) os.Error {
return MismatchedHashAndPasswordError return MismatchedHashAndPasswordError
} }
func newFromPassword(password []byte, cost int) (*hashed, os.Error) { func newFromPassword(password []byte, cost int) (*hashed, error) {
if cost < MinCost { if cost < MinCost {
cost = DefaultCost cost = DefaultCost
} }
@ -144,7 +144,7 @@ func newFromPassword(password []byte, cost int) (*hashed, os.Error) {
return p, err return p, err
} }
func newFromHash(hashedSecret []byte) (*hashed, os.Error) { func newFromHash(hashedSecret []byte) (*hashed, error) {
if len(hashedSecret) < minHashSize { if len(hashedSecret) < minHashSize {
return nil, HashTooShortError return nil, HashTooShortError
} }
@ -172,7 +172,7 @@ func newFromHash(hashedSecret []byte) (*hashed, os.Error) {
return p, nil return p, nil
} }
func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, os.Error) { func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, error) {
cipherData := make([]byte, len(magicCipherData)) cipherData := make([]byte, len(magicCipherData))
copy(cipherData, magicCipherData) copy(cipherData, magicCipherData)
@ -193,7 +193,7 @@ func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, os.Error) {
return hsh, nil return hsh, nil
} }
func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, os.Error) { func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {
csalt, err := base64Decode(salt) csalt, err := base64Decode(salt)
if err != nil { if err != nil {
@ -240,7 +240,7 @@ func (p *hashed) Hash() []byte {
return arr[:n] return arr[:n]
} }
func (p *hashed) decodeVersion(sbytes []byte) (int, os.Error) { func (p *hashed) decodeVersion(sbytes []byte) (int, error) {
if sbytes[0] != '$' { if sbytes[0] != '$' {
return -1, InvalidHashPrefixError(sbytes[0]) return -1, InvalidHashPrefixError(sbytes[0])
} }
@ -257,7 +257,7 @@ func (p *hashed) decodeVersion(sbytes []byte) (int, os.Error) {
} }
// sbytes should begin where decodeVersion left off. // sbytes should begin where decodeVersion left off.
func (p *hashed) decodeCost(sbytes []byte) (int, os.Error) { func (p *hashed) decodeCost(sbytes []byte) (int, error) {
cost, err := strconv.Atoi(string(sbytes[0:2])) cost, err := strconv.Atoi(string(sbytes[0:2]))
if err != nil { if err != nil {
return -1, err return -1, err
@ -274,7 +274,7 @@ func (p *hashed) String() string {
return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor) return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor)
} }
func checkCost(cost int) os.Error { func checkCost(cost int) error {
if cost < MinCost || cost > MaxCost { if cost < MinCost || cost > MaxCost {
return InvalidCostError(cost) return InvalidCostError(cost)
} }

View File

@ -6,7 +6,6 @@ package bcrypt
import ( import (
"bytes" "bytes"
"os"
"testing" "testing"
) )
@ -68,7 +67,7 @@ func TestTooLongPasswordsWork(t *testing.T) {
} }
type InvalidHashTest struct { type InvalidHashTest struct {
err os.Error err error
hash []byte hash []byte
} }
@ -81,7 +80,7 @@ var invalidTests = []InvalidHashTest{
} }
func TestInvalidHashErrors(t *testing.T) { func TestInvalidHashErrors(t *testing.T) {
check := func(name string, expected, err os.Error) { check := func(name string, expected, err error) {
if err == nil { if err == nil {
t.Errorf("%s: Should have returned an error", name) t.Errorf("%s: Should have returned an error", name)
} }

View File

@ -8,10 +8,7 @@ package blowfish
// The code is a port of Bruce Schneier's C implementation. // The code is a port of Bruce Schneier's C implementation.
// See http://www.schneier.com/blowfish.html. // See http://www.schneier.com/blowfish.html.
import ( import "strconv"
"os"
"strconv"
)
// The Blowfish block size in bytes. // The Blowfish block size in bytes.
const BlockSize = 8 const BlockSize = 8
@ -24,13 +21,13 @@ type Cipher struct {
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k))
} }
// NewCipher creates and returns a Cipher. // NewCipher creates and returns a Cipher.
// The key argument should be the Blowfish key, 4 to 56 bytes. // The key argument should be the Blowfish key, 4 to 56 bytes.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
var result Cipher var result Cipher
k := len(key) k := len(key)
if k < 4 || k > 56 { if k < 4 || k > 56 {
@ -45,7 +42,7 @@ func NewCipher(key []byte) (*Cipher, os.Error) {
// schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is
// sufficient and desirable. For bcrypt compatiblity, the key can be over 56 // sufficient and desirable. For bcrypt compatiblity, the key can be over 56
// bytes. // bytes.
func NewSaltedCipher(key, salt []byte) (*Cipher, os.Error) { func NewSaltedCipher(key, salt []byte) (*Cipher, error) {
var result Cipher var result Cipher
k := len(key) k := len(key)
if k < 4 { if k < 4 {

View File

@ -6,9 +6,7 @@
// OpenPGP cipher. // OpenPGP cipher.
package cast5 package cast5
import ( import "errors"
"os"
)
const BlockSize = 8 const BlockSize = 8
const KeySize = 16 const KeySize = 16
@ -18,9 +16,9 @@ type Cipher struct {
rotate [16]uint8 rotate [16]uint8
} }
func NewCipher(key []byte) (c *Cipher, err os.Error) { func NewCipher(key []byte) (c *Cipher, err error) {
if len(key) != KeySize { if len(key) != KeySize {
return nil, os.NewError("CAST5: keys must be 16 bytes") return nil, errors.New("CAST5: keys must be 16 bytes")
} }
c = new(Cipher) c = new(Cipher)

View File

@ -4,10 +4,7 @@
package cipher package cipher
import ( import "io"
"os"
"io"
)
// The Stream* objects are so simple that all their members are public. Users // The Stream* objects are so simple that all their members are public. Users
// can create them themselves. // can create them themselves.
@ -19,7 +16,7 @@ type StreamReader struct {
R io.Reader R io.Reader
} }
func (r StreamReader) Read(dst []byte) (n int, err os.Error) { func (r StreamReader) Read(dst []byte) (n int, err error) {
n, err = r.R.Read(dst) n, err = r.R.Read(dst)
r.S.XORKeyStream(dst[:n], dst[:n]) r.S.XORKeyStream(dst[:n], dst[:n])
return return
@ -31,10 +28,10 @@ func (r StreamReader) Read(dst []byte) (n int, err os.Error) {
type StreamWriter struct { type StreamWriter struct {
S Stream S Stream
W io.Writer W io.Writer
Err os.Error Err error
} }
func (w StreamWriter) Write(src []byte) (n int, err os.Error) { func (w StreamWriter) Write(src []byte) (n int, err error) {
if w.Err != nil { if w.Err != nil {
return 0, w.Err return 0, w.Err
} }
@ -50,7 +47,7 @@ func (w StreamWriter) Write(src []byte) (n int, err os.Error) {
return return
} }
func (w StreamWriter) Close() os.Error { func (w StreamWriter) Close() error {
// This saves us from either requiring a WriteCloser or having a // This saves us from either requiring a WriteCloser or having a
// StreamWriterCloser. // StreamWriterCloser.
return w.W.(io.Closer).Close() return w.W.(io.Closer).Close()

View File

@ -4,17 +4,14 @@
package des package des
import ( import "strconv"
"os"
"strconv"
)
// The DES block size in bytes. // The DES block size in bytes.
const BlockSize = 8 const BlockSize = 8
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/des: invalid key size " + strconv.Itoa(int(k)) return "crypto/des: invalid key size " + strconv.Itoa(int(k))
} }
@ -24,7 +21,7 @@ type Cipher struct {
} }
// NewCipher creates and returns a new Cipher. // NewCipher creates and returns a new Cipher.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
if len(key) != 8 { if len(key) != 8 {
return nil, KeySizeError(len(key)) return nil, KeySizeError(len(key))
} }
@ -60,7 +57,7 @@ type TripleDESCipher struct {
} }
// NewCipher creates and returns a new Cipher. // NewCipher creates and returns a new Cipher.
func NewTripleDESCipher(key []byte) (*TripleDESCipher, os.Error) { func NewTripleDESCipher(key []byte) (*TripleDESCipher, error) {
if len(key) != 24 { if len(key) != 24 {
return nil, KeySizeError(len(key)) return nil, KeySizeError(len(key))
} }

View File

@ -7,8 +7,8 @@ package dsa
import ( import (
"big" "big"
"errors"
"io" "io"
"os"
) )
// Parameters represents the domain parameters for a key. These parameters can // Parameters represents the domain parameters for a key. These parameters can
@ -31,7 +31,7 @@ type PrivateKey struct {
type invalidPublicKeyError int type invalidPublicKeyError int
func (invalidPublicKeyError) String() string { func (invalidPublicKeyError) Error() string {
return "crypto/dsa: invalid public key" return "crypto/dsa: invalid public key"
} }
@ -58,7 +58,7 @@ const numMRTests = 64
// GenerateParameters puts a random, valid set of DSA parameters into params. // GenerateParameters puts a random, valid set of DSA parameters into params.
// This function takes many seconds, even on fast machines. // This function takes many seconds, even on fast machines.
func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err os.Error) { func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err error) {
// This function doesn't follow FIPS 186-3 exactly in that it doesn't // This function doesn't follow FIPS 186-3 exactly in that it doesn't
// use a verification seed to generate the primes. The verification // use a verification seed to generate the primes. The verification
// seed doesn't appear to be exported or used by other code and // seed doesn't appear to be exported or used by other code and
@ -79,7 +79,7 @@ func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes
L = 3072 L = 3072
N = 256 N = 256
default: default:
return os.NewError("crypto/dsa: invalid ParameterSizes") return errors.New("crypto/dsa: invalid ParameterSizes")
} }
qBytes := make([]byte, N/8) qBytes := make([]byte, N/8)
@ -156,9 +156,9 @@ GeneratePrimes:
// GenerateKey generates a public&private key pair. The Parameters of the // GenerateKey generates a public&private key pair. The Parameters of the
// PrivateKey must already be valid (see GenerateParameters). // PrivateKey must already be valid (see GenerateParameters).
func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error { func GenerateKey(priv *PrivateKey, rand io.Reader) error {
if priv.P == nil || priv.Q == nil || priv.G == nil { if priv.P == nil || priv.Q == nil || priv.G == nil {
return os.NewError("crypto/dsa: parameters not set up before generating key") return errors.New("crypto/dsa: parameters not set up before generating key")
} }
x := new(big.Int) x := new(big.Int)
@ -185,7 +185,7 @@ func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error {
// larger message) using the private key, priv. It returns the signature as a // larger message) using the private key, priv. It returns the signature as a
// pair of integers. The security of the private key depends on the entropy of // pair of integers. The security of the private key depends on the entropy of
// rand. // rand.
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err os.Error) { func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
// FIPS 186-3, section 4.6 // FIPS 186-3, section 4.6
n := priv.Q.BitLen() n := priv.Q.BitLen()

View File

@ -16,7 +16,6 @@ import (
"big" "big"
"crypto/elliptic" "crypto/elliptic"
"io" "io"
"os"
) )
// PublicKey represents an ECDSA public key. // PublicKey represents an ECDSA public key.
@ -35,7 +34,7 @@ var one = new(big.Int).SetInt64(1)
// randFieldElement returns a random element of the field underlying the given // randFieldElement returns a random element of the field underlying the given
// curve using the procedure given in [NSA] A.2.1. // curve using the procedure given in [NSA] A.2.1.
func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err os.Error) { func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
b := make([]byte, c.BitSize/8+8) b := make([]byte, c.BitSize/8+8)
_, err = io.ReadFull(rand, b) _, err = io.ReadFull(rand, b)
if err != nil { if err != nil {
@ -50,7 +49,7 @@ func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err os.Err
} }
// GenerateKey generates a public&private key pair. // GenerateKey generates a public&private key pair.
func GenerateKey(c *elliptic.Curve, rand io.Reader) (priv *PrivateKey, err os.Error) { func GenerateKey(c *elliptic.Curve, rand io.Reader) (priv *PrivateKey, err error) {
k, err := randFieldElement(c, rand) k, err := randFieldElement(c, rand)
if err != nil { if err != nil {
return return
@ -86,7 +85,7 @@ func hashToInt(hash []byte, c *elliptic.Curve) *big.Int {
// larger message) using the private key, priv. It returns the signature as a // larger message) using the private key, priv. It returns the signature as a
// pair of integers. The security of the private key depends on the entropy of // pair of integers. The security of the private key depends on the entropy of
// rand. // rand.
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err os.Error) { func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
// See [NSA] 3.4.1 // See [NSA] 3.4.1
c := priv.PublicKey.Curve c := priv.PublicKey.Curve

View File

@ -16,7 +16,6 @@ package elliptic
import ( import (
"big" "big"
"io" "io"
"os"
"sync" "sync"
) )
@ -249,7 +248,7 @@ var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
// GenerateKey returns a public/private key pair. The private key is generated // GenerateKey returns a public/private key pair. The private key is generated
// using the given reader, which must return random data. // using the given reader, which must return random data.
func (curve *Curve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err os.Error) { func (curve *Curve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) {
byteLen := (curve.BitSize + 7) >> 3 byteLen := (curve.BitSize + 7) >> 3
priv = make([]byte, byteLen) priv = make([]byte, byteLen)

View File

@ -13,7 +13,6 @@ import (
"crypto/sha1" "crypto/sha1"
"crypto/sha256" "crypto/sha256"
"hash" "hash"
"os"
) )
// FIPS 198: // FIPS 198:
@ -60,7 +59,7 @@ func (h *hmac) Sum() []byte {
return h.outer.Sum() return h.outer.Sum()
} }
func (h *hmac) Write(p []byte) (n int, err os.Error) { func (h *hmac) Write(p []byte) (n int, err error) {
return h.inner.Write(p) return h.inner.Write(p)
} }

View File

@ -8,7 +8,6 @@ package md4
import ( import (
"crypto" "crypto"
"hash" "hash"
"os"
) )
func init() { func init() {
@ -52,7 +51,7 @@ func New() hash.Hash {
func (d *digest) Size() int { return Size } func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) { func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p) nn = len(p)
d.len += uint64(nn) d.len += uint64(nn)
if d.nx > 0 { if d.nx > 0 {

View File

@ -8,7 +8,6 @@ package md5
import ( import (
"crypto" "crypto"
"hash" "hash"
"os"
) )
func init() { func init() {
@ -52,7 +51,7 @@ func New() hash.Hash {
func (d *digest) Size() int { return Size } func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) { func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p) nn = len(p)
d.len += uint64(nn) d.len += uint64(nn)
if d.nx > 0 { if d.nx > 0 {

View File

@ -14,7 +14,6 @@ import (
_ "crypto/sha1" _ "crypto/sha1"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"os"
"time" "time"
) )
@ -106,7 +105,7 @@ type Response struct {
// ParseError results from an invalid OCSP response. // ParseError results from an invalid OCSP response.
type ParseError string type ParseError string
func (p ParseError) String() string { func (p ParseError) Error() string {
return string(p) return string(p)
} }
@ -114,7 +113,7 @@ func (p ParseError) String() string {
// responses for a single certificate and only those using RSA signatures. // responses for a single certificate and only those using RSA signatures.
// Non-RSA responses will result in an x509.UnsupportedAlgorithmError. // Non-RSA responses will result in an x509.UnsupportedAlgorithmError.
// Signature errors or parse failures will result in a ParseError. // Signature errors or parse failures will result in a ParseError.
func ParseResponse(bytes []byte) (*Response, os.Error) { func ParseResponse(bytes []byte) (*Response, error) {
var resp responseASN1 var resp responseASN1
rest, err := asn1.Unmarshal(bytes, &resp) rest, err := asn1.Unmarshal(bytes, &resp)
if err != nil { if err != nil {

View File

@ -9,10 +9,9 @@ package armor
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"encoding/base64" "encoding/base64"
"io" "io"
"os"
) )
// A Block represents an OpenPGP armored structure. // A Block represents an OpenPGP armored structure.
@ -36,7 +35,7 @@ type Block struct {
oReader openpgpReader oReader openpgpReader
} }
var ArmorCorrupt os.Error = error.StructuralError("armor invalid") var ArmorCorrupt error = error_.StructuralError("armor invalid")
const crc24Init = 0xb704ce const crc24Init = 0xb704ce
const crc24Poly = 0x1864cfb const crc24Poly = 0x1864cfb
@ -69,9 +68,9 @@ type lineReader struct {
crc uint32 crc uint32
} }
func (l *lineReader) Read(p []byte) (n int, err os.Error) { func (l *lineReader) Read(p []byte) (n int, err error) {
if l.eof { if l.eof {
return 0, os.EOF return 0, io.EOF
} }
if len(l.buf) > 0 { if len(l.buf) > 0 {
@ -101,7 +100,7 @@ func (l *lineReader) Read(p []byte) (n int, err os.Error) {
uint32(expectedBytes[2]) uint32(expectedBytes[2])
line, _, err = l.in.ReadLine() line, _, err = l.in.ReadLine()
if err != nil && err != os.EOF { if err != nil && err != io.EOF {
return return
} }
if !bytes.HasPrefix(line, armorEnd) { if !bytes.HasPrefix(line, armorEnd) {
@ -109,7 +108,7 @@ func (l *lineReader) Read(p []byte) (n int, err os.Error) {
} }
l.eof = true l.eof = true
return 0, os.EOF return 0, io.EOF
} }
if len(line) > 64 { if len(line) > 64 {
@ -138,11 +137,11 @@ type openpgpReader struct {
currentCRC uint32 currentCRC uint32
} }
func (r *openpgpReader) Read(p []byte) (n int, err os.Error) { func (r *openpgpReader) Read(p []byte) (n int, err error) {
n, err = r.b64Reader.Read(p) n, err = r.b64Reader.Read(p)
r.currentCRC = crc24(r.currentCRC, p[:n]) r.currentCRC = crc24(r.currentCRC, p[:n])
if err == os.EOF { if err == io.EOF {
if r.lReader.crc != uint32(r.currentCRC&crc24Mask) { if r.lReader.crc != uint32(r.currentCRC&crc24Mask) {
return 0, ArmorCorrupt return 0, ArmorCorrupt
} }
@ -155,7 +154,7 @@ func (r *openpgpReader) Read(p []byte) (n int, err os.Error) {
// leading garbage. If it doesn't find a block, it will return nil, os.EOF. The // leading garbage. If it doesn't find a block, it will return nil, os.EOF. The
// given Reader is not usable after calling this function: an arbitrary amount // given Reader is not usable after calling this function: an arbitrary amount
// of data may have been read past the end of the block. // of data may have been read past the end of the block.
func Decode(in io.Reader) (p *Block, err os.Error) { func Decode(in io.Reader) (p *Block, err error) {
r, _ := bufio.NewReaderSize(in, 100) r, _ := bufio.NewReaderSize(in, 100)
var line []byte var line []byte
ignoreNext := false ignoreNext := false

View File

@ -7,7 +7,6 @@ package armor
import ( import (
"encoding/base64" "encoding/base64"
"io" "io"
"os"
) )
var armorHeaderSep = []byte(": ") var armorHeaderSep = []byte(": ")
@ -16,7 +15,7 @@ var newline = []byte("\n")
var armorEndOfLineOut = []byte("-----\n") var armorEndOfLineOut = []byte("-----\n")
// writeSlices writes its arguments to the given Writer. // writeSlices writes its arguments to the given Writer.
func writeSlices(out io.Writer, slices ...[]byte) (err os.Error) { func writeSlices(out io.Writer, slices ...[]byte) (err error) {
for _, s := range slices { for _, s := range slices {
_, err = out.Write(s) _, err = out.Write(s)
if err != nil { if err != nil {
@ -45,7 +44,7 @@ func newLineBreaker(out io.Writer, lineLength int) *lineBreaker {
} }
} }
func (l *lineBreaker) Write(b []byte) (n int, err os.Error) { func (l *lineBreaker) Write(b []byte) (n int, err error) {
n = len(b) n = len(b)
if n == 0 { if n == 0 {
@ -81,7 +80,7 @@ func (l *lineBreaker) Write(b []byte) (n int, err os.Error) {
return return
} }
func (l *lineBreaker) Close() (err os.Error) { func (l *lineBreaker) Close() (err error) {
if l.used > 0 { if l.used > 0 {
_, err = l.out.Write(l.line[0:l.used]) _, err = l.out.Write(l.line[0:l.used])
if err != nil { if err != nil {
@ -106,12 +105,12 @@ type encoding struct {
blockType []byte blockType []byte
} }
func (e *encoding) Write(data []byte) (n int, err os.Error) { func (e *encoding) Write(data []byte) (n int, err error) {
e.crc = crc24(e.crc, data) e.crc = crc24(e.crc, data)
return e.b64.Write(data) return e.b64.Write(data)
} }
func (e *encoding) Close() (err os.Error) { func (e *encoding) Close() (err error) {
err = e.b64.Close() err = e.b64.Close()
if err != nil { if err != nil {
return return
@ -131,7 +130,7 @@ func (e *encoding) Close() (err os.Error) {
// Encode returns a WriteCloser which will encode the data written to it in // Encode returns a WriteCloser which will encode the data written to it in
// OpenPGP armor. // OpenPGP armor.
func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err os.Error) { func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) {
bType := []byte(blockType) bType := []byte(blockType)
err = writeSlices(out, armorStart, bType, armorEndOfLineOut) err = writeSlices(out, armorStart, bType, armorEndOfLineOut)
if err != nil { if err != nil {

View File

@ -4,10 +4,7 @@
package openpgp package openpgp
import ( import "hash"
"hash"
"os"
)
// NewCanonicalTextHash reformats text written to it into the canonical // NewCanonicalTextHash reformats text written to it into the canonical
// form and then applies the hash h. See RFC 4880, section 5.2.1. // form and then applies the hash h. See RFC 4880, section 5.2.1.
@ -22,7 +19,7 @@ type canonicalTextHash struct {
var newline = []byte{'\r', '\n'} var newline = []byte{'\r', '\n'}
func (cth *canonicalTextHash) Write(buf []byte) (int, os.Error) { func (cth *canonicalTextHash) Write(buf []byte) (int, error) {
start := 0 start := 0
for i, c := range buf { for i, c := range buf {

View File

@ -6,7 +6,6 @@ package openpgp
import ( import (
"bytes" "bytes"
"os"
"testing" "testing"
) )
@ -14,7 +13,7 @@ type recordingHash struct {
buf *bytes.Buffer buf *bytes.Buffer
} }
func (r recordingHash) Write(b []byte) (n int, err os.Error) { func (r recordingHash) Write(b []byte) (n int, err error) {
return r.buf.Write(b) return r.buf.Write(b)
} }

View File

@ -16,8 +16,8 @@ import (
"big" "big"
"crypto/rand" "crypto/rand"
"crypto/subtle" "crypto/subtle"
"errors"
"io" "io"
"os"
) )
// PublicKey represents an ElGamal public key. // PublicKey represents an ElGamal public key.
@ -34,10 +34,10 @@ type PrivateKey struct {
// Encrypt encrypts the given message to the given public key. The result is a // Encrypt encrypts the given message to the given public key. The result is a
// pair of integers. Errors can result from reading random, or because msg is // pair of integers. Errors can result from reading random, or because msg is
// too large to be encrypted to the public key. // too large to be encrypted to the public key.
func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err os.Error) { func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) {
pLen := (pub.P.BitLen() + 7) / 8 pLen := (pub.P.BitLen() + 7) / 8
if len(msg) > pLen-11 { if len(msg) > pLen-11 {
err = os.NewError("elgamal: message too long") err = errors.New("elgamal: message too long")
return return
} }
@ -74,7 +74,7 @@ func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err
// be used to break the cryptosystem. See ``Chosen Ciphertext Attacks // be used to break the cryptosystem. See ``Chosen Ciphertext Attacks
// Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel // Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel
// Bleichenbacher, Advances in Cryptology (Crypto '98), // Bleichenbacher, Advances in Cryptology (Crypto '98),
func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) { func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) {
s := new(big.Int).Exp(c1, priv.X, priv.P) s := new(big.Int).Exp(c1, priv.X, priv.P)
s.ModInverse(s, priv.P) s.ModInverse(s, priv.P)
s.Mul(s, c2) s.Mul(s, c2)
@ -97,13 +97,13 @@ func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) {
} }
if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 {
return nil, os.NewError("elgamal: decryption error") return nil, errors.New("elgamal: decryption error")
} }
return em[index+1:], nil return em[index+1:], nil
} }
// nonZeroRandomBytes fills the given slice with non-zero random octets. // nonZeroRandomBytes fills the given slice with non-zero random octets.
func nonZeroRandomBytes(s []byte, rand io.Reader) (err os.Error) { func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
_, err = io.ReadFull(rand, s) _, err = io.ReadFull(rand, s)
if err != nil { if err != nil {
return return

View File

@ -13,7 +13,7 @@ import (
// invalid. // invalid.
type StructuralError string type StructuralError string
func (s StructuralError) String() string { func (s StructuralError) Error() string {
return "OpenPGP data invalid: " + string(s) return "OpenPGP data invalid: " + string(s)
} }
@ -21,7 +21,7 @@ func (s StructuralError) String() string {
// makes use of currently unimplemented features. // makes use of currently unimplemented features.
type UnsupportedError string type UnsupportedError string
func (s UnsupportedError) String() string { func (s UnsupportedError) Error() string {
return "OpenPGP feature unsupported: " + string(s) return "OpenPGP feature unsupported: " + string(s)
} }
@ -29,7 +29,7 @@ func (s UnsupportedError) String() string {
// incorrect value. // incorrect value.
type InvalidArgumentError string type InvalidArgumentError string
func (i InvalidArgumentError) String() string { func (i InvalidArgumentError) Error() string {
return "OpenPGP argument invalid: " + string(i) return "OpenPGP argument invalid: " + string(i)
} }
@ -37,13 +37,13 @@ func (i InvalidArgumentError) String() string {
// validate. // validate.
type SignatureError string type SignatureError string
func (b SignatureError) String() string { func (b SignatureError) Error() string {
return "OpenPGP signature invalid: " + string(b) return "OpenPGP signature invalid: " + string(b)
} }
type keyIncorrectError int type keyIncorrectError int
func (ki keyIncorrectError) String() string { func (ki keyIncorrectError) Error() string {
return "the given key was incorrect" return "the given key was incorrect"
} }
@ -51,7 +51,7 @@ var KeyIncorrectError = keyIncorrectError(0)
type unknownIssuerError int type unknownIssuerError int
func (unknownIssuerError) String() string { func (unknownIssuerError) Error() string {
return "signature make by unknown entity" return "signature make by unknown entity"
} }
@ -59,6 +59,6 @@ var UnknownIssuerError = unknownIssuerError(0)
type UnknownPacketTypeError uint8 type UnknownPacketTypeError uint8
func (upte UnknownPacketTypeError) String() string { func (upte UnknownPacketTypeError) Error() string {
return "unknown OpenPGP packet type: " + strconv.Itoa(int(upte)) return "unknown OpenPGP packet type: " + strconv.Itoa(int(upte))
} }

View File

@ -7,11 +7,10 @@ package openpgp
import ( import (
"crypto" "crypto"
"crypto/openpgp/armor" "crypto/openpgp/armor"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/packet" "crypto/openpgp/packet"
"crypto/rsa" "crypto/rsa"
"io" "io"
"os"
"time" "time"
) )
@ -178,16 +177,16 @@ func (el EntityList) DecryptionKeys() (keys []Key) {
} }
// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) { func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
block, err := armor.Decode(r) block, err := armor.Decode(r)
if err == os.EOF { if err == io.EOF {
return nil, error.InvalidArgumentError("no armored data found") return nil, error_.InvalidArgumentError("no armored data found")
} }
if err != nil { if err != nil {
return nil, err return nil, err
} }
if block.Type != PublicKeyType && block.Type != PrivateKeyType { if block.Type != PublicKeyType && block.Type != PrivateKeyType {
return nil, error.InvalidArgumentError("expected public or private key block, got: " + block.Type) return nil, error_.InvalidArgumentError("expected public or private key block, got: " + block.Type)
} }
return ReadKeyRing(block.Body) return ReadKeyRing(block.Body)
@ -195,19 +194,19 @@ func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) {
// ReadKeyRing reads one or more public/private keys. Unsupported keys are // ReadKeyRing reads one or more public/private keys. Unsupported keys are
// ignored as long as at least a single valid key is found. // ignored as long as at least a single valid key is found.
func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) { func ReadKeyRing(r io.Reader) (el EntityList, err error) {
packets := packet.NewReader(r) packets := packet.NewReader(r)
var lastUnsupportedError os.Error var lastUnsupportedError error
for { for {
var e *Entity var e *Entity
e, err = readEntity(packets) e, err = readEntity(packets)
if err != nil { if err != nil {
if _, ok := err.(error.UnsupportedError); ok { if _, ok := err.(error_.UnsupportedError); ok {
lastUnsupportedError = err lastUnsupportedError = err
err = readToNextPublicKey(packets) err = readToNextPublicKey(packets)
} }
if err == os.EOF { if err == io.EOF {
err = nil err = nil
break break
} }
@ -228,14 +227,14 @@ func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) {
// readToNextPublicKey reads packets until the start of the entity and leaves // readToNextPublicKey reads packets until the start of the entity and leaves
// the first packet of the new entity in the Reader. // the first packet of the new entity in the Reader.
func readToNextPublicKey(packets *packet.Reader) (err os.Error) { func readToNextPublicKey(packets *packet.Reader) (err error) {
var p packet.Packet var p packet.Packet
for { for {
p, err = packets.Next() p, err = packets.Next()
if err == os.EOF { if err == io.EOF {
return return
} else if err != nil { } else if err != nil {
if _, ok := err.(error.UnsupportedError); ok { if _, ok := err.(error_.UnsupportedError); ok {
err = nil err = nil
continue continue
} }
@ -253,7 +252,7 @@ func readToNextPublicKey(packets *packet.Reader) (err os.Error) {
// readEntity reads an entity (public key, identities, subkeys etc) from the // readEntity reads an entity (public key, identities, subkeys etc) from the
// given Reader. // given Reader.
func readEntity(packets *packet.Reader) (*Entity, os.Error) { func readEntity(packets *packet.Reader) (*Entity, error) {
e := new(Entity) e := new(Entity)
e.Identities = make(map[string]*Identity) e.Identities = make(map[string]*Identity)
@ -266,21 +265,21 @@ func readEntity(packets *packet.Reader) (*Entity, os.Error) {
if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
packets.Unread(p) packets.Unread(p)
return nil, error.StructuralError("first packet was not a public/private key") return nil, error_.StructuralError("first packet was not a public/private key")
} else { } else {
e.PrimaryKey = &e.PrivateKey.PublicKey e.PrimaryKey = &e.PrivateKey.PublicKey
} }
} }
if !e.PrimaryKey.PubKeyAlgo.CanSign() { if !e.PrimaryKey.PubKeyAlgo.CanSign() {
return nil, error.StructuralError("primary key cannot be used for signatures") return nil, error_.StructuralError("primary key cannot be used for signatures")
} }
var current *Identity var current *Identity
EachPacket: EachPacket:
for { for {
p, err := packets.Next() p, err := packets.Next()
if err == os.EOF { if err == io.EOF {
break break
} else if err != nil { } else if err != nil {
return nil, err return nil, err
@ -295,7 +294,7 @@ EachPacket:
for { for {
p, err = packets.Next() p, err = packets.Next()
if err == os.EOF { if err == io.EOF {
return nil, io.ErrUnexpectedEOF return nil, io.ErrUnexpectedEOF
} else if err != nil { } else if err != nil {
return nil, err return nil, err
@ -303,12 +302,12 @@ EachPacket:
sig, ok := p.(*packet.Signature) sig, ok := p.(*packet.Signature)
if !ok { if !ok {
return nil, error.StructuralError("user ID packet not followed by self-signature") return nil, error_.StructuralError("user ID packet not followed by self-signature")
} }
if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId { if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil { if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil {
return nil, error.StructuralError("user ID self-signature invalid: " + err.String()) return nil, error_.StructuralError("user ID self-signature invalid: " + err.Error())
} }
current.SelfSignature = sig current.SelfSignature = sig
break break
@ -317,7 +316,7 @@ EachPacket:
} }
case *packet.Signature: case *packet.Signature:
if current == nil { if current == nil {
return nil, error.StructuralError("signature packet found before user id packet") return nil, error_.StructuralError("signature packet found before user id packet")
} }
current.Signatures = append(current.Signatures, pkt) current.Signatures = append(current.Signatures, pkt)
case *packet.PrivateKey: case *packet.PrivateKey:
@ -344,34 +343,34 @@ EachPacket:
} }
if len(e.Identities) == 0 { if len(e.Identities) == 0 {
return nil, error.StructuralError("entity without any identities") return nil, error_.StructuralError("entity without any identities")
} }
return e, nil return e, nil
} }
func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) os.Error { func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
var subKey Subkey var subKey Subkey
subKey.PublicKey = pub subKey.PublicKey = pub
subKey.PrivateKey = priv subKey.PrivateKey = priv
p, err := packets.Next() p, err := packets.Next()
if err == os.EOF { if err == io.EOF {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
if err != nil { if err != nil {
return error.StructuralError("subkey signature invalid: " + err.String()) return error_.StructuralError("subkey signature invalid: " + err.Error())
} }
var ok bool var ok bool
subKey.Sig, ok = p.(*packet.Signature) subKey.Sig, ok = p.(*packet.Signature)
if !ok { if !ok {
return error.StructuralError("subkey packet not followed by signature") return error_.StructuralError("subkey packet not followed by signature")
} }
if subKey.Sig.SigType != packet.SigTypeSubkeyBinding { if subKey.Sig.SigType != packet.SigTypeSubkeyBinding {
return error.StructuralError("subkey signature with wrong type") return error_.StructuralError("subkey signature with wrong type")
} }
err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig) err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
if err != nil { if err != nil {
return error.StructuralError("subkey signature invalid: " + err.String()) return error_.StructuralError("subkey signature invalid: " + err.Error())
} }
e.Subkeys = append(e.Subkeys, subKey) e.Subkeys = append(e.Subkeys, subKey)
return nil return nil
@ -382,10 +381,10 @@ const defaultRSAKeyBits = 2048
// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of // single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00". // which may be empty but must not contain any of "()<>\x00".
func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, os.Error) { func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, error) {
uid := packet.NewUserId(name, comment, email) uid := packet.NewUserId(name, comment, email)
if uid == nil { if uid == nil {
return nil, error.InvalidArgumentError("user id field contained invalid characters") return nil, error_.InvalidArgumentError("user id field contained invalid characters")
} }
signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits) signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
if err != nil { if err != nil {
@ -442,7 +441,7 @@ func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email strin
// SerializePrivate serializes an Entity, including private key material, to // SerializePrivate serializes an Entity, including private key material, to
// the given Writer. For now, it must only be used on an Entity returned from // the given Writer. For now, it must only be used on an Entity returned from
// NewEntity. // NewEntity.
func (e *Entity) SerializePrivate(w io.Writer) (err os.Error) { func (e *Entity) SerializePrivate(w io.Writer) (err error) {
err = e.PrivateKey.Serialize(w) err = e.PrivateKey.Serialize(w)
if err != nil { if err != nil {
return return
@ -480,7 +479,7 @@ func (e *Entity) SerializePrivate(w io.Writer) (err os.Error) {
// Serialize writes the public part of the given Entity to w. (No private // Serialize writes the public part of the given Entity to w. (No private
// key material will be output). // key material will be output).
func (e *Entity) Serialize(w io.Writer) os.Error { func (e *Entity) Serialize(w io.Writer) error {
err := e.PrimaryKey.Serialize(w) err := e.PrimaryKey.Serialize(w)
if err != nil { if err != nil {
return err return err
@ -518,16 +517,16 @@ func (e *Entity) Serialize(w io.Writer) os.Error {
// associated with e. The provided identity must already be an element of // associated with e. The provided identity must already be an element of
// e.Identities and the private key of signer must have been decrypted if // e.Identities and the private key of signer must have been decrypted if
// necessary. // necessary.
func (e *Entity) SignIdentity(identity string, signer *Entity) os.Error { func (e *Entity) SignIdentity(identity string, signer *Entity) error {
if signer.PrivateKey == nil { if signer.PrivateKey == nil {
return error.InvalidArgumentError("signing Entity must have a private key") return error_.InvalidArgumentError("signing Entity must have a private key")
} }
if signer.PrivateKey.Encrypted { if signer.PrivateKey.Encrypted {
return error.InvalidArgumentError("signing Entity's private key must be decrypted") return error_.InvalidArgumentError("signing Entity's private key must be decrypted")
} }
ident, ok := e.Identities[identity] ident, ok := e.Identities[identity]
if !ok { if !ok {
return error.InvalidArgumentError("given identity string not found in Entity") return error_.InvalidArgumentError("given identity string not found in Entity")
} }
sig := &packet.Signature{ sig := &packet.Signature{

View File

@ -7,9 +7,8 @@ package packet
import ( import (
"compress/flate" "compress/flate"
"compress/zlib" "compress/zlib"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -19,7 +18,7 @@ type Compressed struct {
Body io.Reader Body io.Reader
} }
func (c *Compressed) parse(r io.Reader) os.Error { func (c *Compressed) parse(r io.Reader) error {
var buf [1]byte var buf [1]byte
_, err := readFull(r, buf[:]) _, err := readFull(r, buf[:])
if err != nil { if err != nil {
@ -32,7 +31,7 @@ func (c *Compressed) parse(r io.Reader) os.Error {
case 2: case 2:
c.Body, err = zlib.NewReader(r) c.Body, err = zlib.NewReader(r)
default: default:
err = error.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) err = error_.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0])))
} }
return err return err

View File

@ -7,7 +7,7 @@ package packet
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"os" "io"
"io/ioutil" "io/ioutil"
"testing" "testing"
) )
@ -26,7 +26,7 @@ func TestCompressed(t *testing.T) {
} }
contents, err := ioutil.ReadAll(c.Body) contents, err := ioutil.ReadAll(c.Body)
if err != nil && err != os.EOF { if err != nil && err != io.EOF {
t.Error(err) t.Error(err)
return return
} }

View File

@ -7,12 +7,11 @@ package packet
import ( import (
"big" "big"
"crypto/openpgp/elgamal" "crypto/openpgp/elgamal"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"encoding/binary" "encoding/binary"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -29,14 +28,14 @@ type EncryptedKey struct {
encryptedMPI1, encryptedMPI2 []byte encryptedMPI1, encryptedMPI2 []byte
} }
func (e *EncryptedKey) parse(r io.Reader) (err os.Error) { func (e *EncryptedKey) parse(r io.Reader) (err error) {
var buf [10]byte var buf [10]byte
_, err = readFull(r, buf[:]) _, err = readFull(r, buf[:])
if err != nil { if err != nil {
return return
} }
if buf[0] != encryptedKeyVersion { if buf[0] != encryptedKeyVersion {
return error.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0]))) return error_.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0])))
} }
e.KeyId = binary.BigEndian.Uint64(buf[1:9]) e.KeyId = binary.BigEndian.Uint64(buf[1:9])
e.Algo = PublicKeyAlgorithm(buf[9]) e.Algo = PublicKeyAlgorithm(buf[9])
@ -64,8 +63,8 @@ func checksumKeyMaterial(key []byte) uint16 {
// Decrypt decrypts an encrypted session key with the given private key. The // Decrypt decrypts an encrypted session key with the given private key. The
// private key must have been decrypted first. // private key must have been decrypted first.
func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error { func (e *EncryptedKey) Decrypt(priv *PrivateKey) error {
var err os.Error var err error
var b []byte var b []byte
// TODO(agl): use session key decryption routines here to avoid // TODO(agl): use session key decryption routines here to avoid
@ -78,7 +77,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
c2 := new(big.Int).SetBytes(e.encryptedMPI2) c2 := new(big.Int).SetBytes(e.encryptedMPI2)
b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2) b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
default: default:
err = error.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) err = error_.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
} }
if err != nil { if err != nil {
@ -90,7 +89,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1]) expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
checksum := checksumKeyMaterial(e.Key) checksum := checksumKeyMaterial(e.Key)
if checksum != expectedChecksum { if checksum != expectedChecksum {
return error.StructuralError("EncryptedKey checksum incorrect") return error_.StructuralError("EncryptedKey checksum incorrect")
} }
return nil return nil
@ -98,7 +97,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
// SerializeEncryptedKey serializes an encrypted key packet to w that contains // SerializeEncryptedKey serializes an encrypted key packet to w that contains
// key, encrypted to pub. // key, encrypted to pub.
func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFunc CipherFunction, key []byte) os.Error { func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFunc CipherFunction, key []byte) error {
var buf [10]byte var buf [10]byte
buf[0] = encryptedKeyVersion buf[0] = encryptedKeyVersion
binary.BigEndian.PutUint64(buf[1:9], pub.KeyId) binary.BigEndian.PutUint64(buf[1:9], pub.KeyId)
@ -117,16 +116,16 @@ func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFu
case PubKeyAlgoElGamal: case PubKeyAlgoElGamal:
return serializeEncryptedKeyElGamal(w, rand, buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock) return serializeEncryptedKeyElGamal(w, rand, buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock)
case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly: case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly:
return error.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) return error_.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
} }
return error.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) return error_.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
} }
func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) os.Error { func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error {
cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock) cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock)
if err != nil { if err != nil {
return error.InvalidArgumentError("RSA encryption failed: " + err.String()) return error_.InvalidArgumentError("RSA encryption failed: " + err.Error())
} }
packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText) packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText)
@ -142,10 +141,10 @@ func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub
return writeMPI(w, 8*uint16(len(cipherText)), cipherText) return writeMPI(w, 8*uint16(len(cipherText)), cipherText)
} }
func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) os.Error { func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error {
c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock) c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock)
if err != nil { if err != nil {
return error.InvalidArgumentError("ElGamal encryption failed: " + err.String()) return error_.InvalidArgumentError("ElGamal encryption failed: " + err.Error())
} }
packetLen := 10 /* header length */ packetLen := 10 /* header length */

View File

@ -7,7 +7,6 @@ package packet
import ( import (
"encoding/binary" "encoding/binary"
"io" "io"
"os"
) )
// LiteralData represents an encrypted file. See RFC 4880, section 5.9. // LiteralData represents an encrypted file. See RFC 4880, section 5.9.
@ -24,7 +23,7 @@ func (l *LiteralData) ForEyesOnly() bool {
return l.FileName == "_CONSOLE" return l.FileName == "_CONSOLE"
} }
func (l *LiteralData) parse(r io.Reader) (err os.Error) { func (l *LiteralData) parse(r io.Reader) (err error) {
var buf [256]byte var buf [256]byte
_, err = readFull(r, buf[:2]) _, err = readFull(r, buf[:2])
@ -55,7 +54,7 @@ func (l *LiteralData) parse(r io.Reader) (err os.Error) {
// SerializeLiteral serializes a literal data packet to w and returns a // SerializeLiteral serializes a literal data packet to w and returns a
// WriteCloser to which the data itself can be written and which MUST be closed // WriteCloser to which the data itself can be written and which MUST be closed
// on completion. The fileName is truncated to 255 bytes. // on completion. The fileName is truncated to 255 bytes.
func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err os.Error) { func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) {
var buf [4]byte var buf [4]byte
buf[0] = 't' buf[0] = 't'
if isBinary { if isBinary {

View File

@ -6,11 +6,10 @@ package packet
import ( import (
"crypto" "crypto"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"encoding/binary" "encoding/binary"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -26,7 +25,7 @@ type OnePassSignature struct {
const onePassSignatureVersion = 3 const onePassSignatureVersion = 3
func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) { func (ops *OnePassSignature) parse(r io.Reader) (err error) {
var buf [13]byte var buf [13]byte
_, err = readFull(r, buf[:]) _, err = readFull(r, buf[:])
@ -34,13 +33,13 @@ func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) {
return return
} }
if buf[0] != onePassSignatureVersion { if buf[0] != onePassSignatureVersion {
err = error.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) err = error_.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0])))
} }
var ok bool var ok bool
ops.Hash, ok = s2k.HashIdToHash(buf[2]) ops.Hash, ok = s2k.HashIdToHash(buf[2])
if !ok { if !ok {
return error.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) return error_.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2])))
} }
ops.SigType = SignatureType(buf[1]) ops.SigType = SignatureType(buf[1])
@ -51,14 +50,14 @@ func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) {
} }
// Serialize marshals the given OnePassSignature to w. // Serialize marshals the given OnePassSignature to w.
func (ops *OnePassSignature) Serialize(w io.Writer) os.Error { func (ops *OnePassSignature) Serialize(w io.Writer) error {
var buf [13]byte var buf [13]byte
buf[0] = onePassSignatureVersion buf[0] = onePassSignatureVersion
buf[1] = uint8(ops.SigType) buf[1] = uint8(ops.SigType)
var ok bool var ok bool
buf[2], ok = s2k.HashToHashId(ops.Hash) buf[2], ok = s2k.HashToHashId(ops.Hash)
if !ok { if !ok {
return error.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) return error_.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash)))
} }
buf[3] = uint8(ops.PubKeyAlgo) buf[3] = uint8(ops.PubKeyAlgo)
binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) binary.BigEndian.PutUint64(buf[4:12], ops.KeyId)

View File

@ -11,23 +11,22 @@ import (
"crypto/aes" "crypto/aes"
"crypto/cast5" "crypto/cast5"
"crypto/cipher" "crypto/cipher"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"io" "io"
"os"
) )
// readFull is the same as io.ReadFull except that reading zero bytes returns // readFull is the same as io.ReadFull except that reading zero bytes returns
// ErrUnexpectedEOF rather than EOF. // ErrUnexpectedEOF rather than EOF.
func readFull(r io.Reader, buf []byte) (n int, err os.Error) { func readFull(r io.Reader, buf []byte) (n int, err error) {
n, err = io.ReadFull(r, buf) n, err = io.ReadFull(r, buf)
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return return
} }
// readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2. // readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2.
func readLength(r io.Reader) (length int64, isPartial bool, err os.Error) { func readLength(r io.Reader) (length int64, isPartial bool, err error) {
var buf [4]byte var buf [4]byte
_, err = readFull(r, buf[:1]) _, err = readFull(r, buf[:1])
if err != nil { if err != nil {
@ -68,10 +67,10 @@ type partialLengthReader struct {
isPartial bool isPartial bool
} }
func (r *partialLengthReader) Read(p []byte) (n int, err os.Error) { func (r *partialLengthReader) Read(p []byte) (n int, err error) {
for r.remaining == 0 { for r.remaining == 0 {
if !r.isPartial { if !r.isPartial {
return 0, os.EOF return 0, io.EOF
} }
r.remaining, r.isPartial, err = readLength(r.r) r.remaining, r.isPartial, err = readLength(r.r)
if err != nil { if err != nil {
@ -86,7 +85,7 @@ func (r *partialLengthReader) Read(p []byte) (n int, err os.Error) {
n, err = r.r.Read(p[:int(toRead)]) n, err = r.r.Read(p[:int(toRead)])
r.remaining -= int64(n) r.remaining -= int64(n)
if n < int(toRead) && err == os.EOF { if n < int(toRead) && err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return return
@ -99,7 +98,7 @@ type partialLengthWriter struct {
lengthByte [1]byte lengthByte [1]byte
} }
func (w *partialLengthWriter) Write(p []byte) (n int, err os.Error) { func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
for len(p) > 0 { for len(p) > 0 {
for power := uint(14); power < 32; power-- { for power := uint(14); power < 32; power-- {
l := 1 << power l := 1 << power
@ -123,7 +122,7 @@ func (w *partialLengthWriter) Write(p []byte) (n int, err os.Error) {
return return
} }
func (w *partialLengthWriter) Close() os.Error { func (w *partialLengthWriter) Close() error {
w.lengthByte[0] = 0 w.lengthByte[0] = 0
_, err := w.w.Write(w.lengthByte[:]) _, err := w.w.Write(w.lengthByte[:])
if err != nil { if err != nil {
@ -139,16 +138,16 @@ type spanReader struct {
n int64 n int64
} }
func (l *spanReader) Read(p []byte) (n int, err os.Error) { func (l *spanReader) Read(p []byte) (n int, err error) {
if l.n <= 0 { if l.n <= 0 {
return 0, os.EOF return 0, io.EOF
} }
if int64(len(p)) > l.n { if int64(len(p)) > l.n {
p = p[0:l.n] p = p[0:l.n]
} }
n, err = l.r.Read(p) n, err = l.r.Read(p)
l.n -= int64(n) l.n -= int64(n)
if l.n > 0 && err == os.EOF { if l.n > 0 && err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return return
@ -156,14 +155,14 @@ func (l *spanReader) Read(p []byte) (n int, err os.Error) {
// readHeader parses a packet header and returns an io.Reader which will return // readHeader parses a packet header and returns an io.Reader which will return
// the contents of the packet. See RFC 4880, section 4.2. // the contents of the packet. See RFC 4880, section 4.2.
func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err os.Error) { func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
var buf [4]byte var buf [4]byte
_, err = io.ReadFull(r, buf[:1]) _, err = io.ReadFull(r, buf[:1])
if err != nil { if err != nil {
return return
} }
if buf[0]&0x80 == 0 { if buf[0]&0x80 == 0 {
err = error.StructuralError("tag byte does not have MSB set") err = error_.StructuralError("tag byte does not have MSB set")
return return
} }
if buf[0]&0x40 == 0 { if buf[0]&0x40 == 0 {
@ -209,7 +208,7 @@ func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader,
// serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section // serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section
// 4.2. // 4.2.
func serializeHeader(w io.Writer, ptype packetType, length int) (err os.Error) { func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
var buf [6]byte var buf [6]byte
var n int var n int
@ -238,7 +237,7 @@ func serializeHeader(w io.Writer, ptype packetType, length int) (err os.Error) {
// serializeStreamHeader writes an OpenPGP packet header to w where the // serializeStreamHeader writes an OpenPGP packet header to w where the
// length of the packet is unknown. It returns a io.WriteCloser which can be // length of the packet is unknown. It returns a io.WriteCloser which can be
// used to write the contents of the packet. See RFC 4880, section 4.2. // used to write the contents of the packet. See RFC 4880, section 4.2.
func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err os.Error) { func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
var buf [1]byte var buf [1]byte
buf[0] = 0x80 | 0x40 | byte(ptype) buf[0] = 0x80 | 0x40 | byte(ptype)
_, err = w.Write(buf[:]) _, err = w.Write(buf[:])
@ -252,19 +251,19 @@ func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteClos
// Packet represents an OpenPGP packet. Users are expected to try casting // Packet represents an OpenPGP packet. Users are expected to try casting
// instances of this interface to specific packet types. // instances of this interface to specific packet types.
type Packet interface { type Packet interface {
parse(io.Reader) os.Error parse(io.Reader) error
} }
// consumeAll reads from the given Reader until error, returning the number of // consumeAll reads from the given Reader until error, returning the number of
// bytes read. // bytes read.
func consumeAll(r io.Reader) (n int64, err os.Error) { func consumeAll(r io.Reader) (n int64, err error) {
var m int var m int
var buf [1024]byte var buf [1024]byte
for { for {
m, err = r.Read(buf[:]) m, err = r.Read(buf[:])
n += int64(m) n += int64(m)
if err == os.EOF { if err == io.EOF {
err = nil err = nil
return return
} }
@ -298,7 +297,7 @@ const (
// Read reads a single OpenPGP packet from the given io.Reader. If there is an // Read reads a single OpenPGP packet from the given io.Reader. If there is an
// error parsing a packet, the whole packet is consumed from the input. // error parsing a packet, the whole packet is consumed from the input.
func Read(r io.Reader) (p Packet, err os.Error) { func Read(r io.Reader) (p Packet, err error) {
tag, _, contents, err := readHeader(r) tag, _, contents, err := readHeader(r)
if err != nil { if err != nil {
return return
@ -338,7 +337,7 @@ func Read(r io.Reader) (p Packet, err os.Error) {
se.MDC = true se.MDC = true
p = se p = se
default: default:
err = error.UnknownPacketTypeError(tag) err = error_.UnknownPacketTypeError(tag)
} }
if p != nil { if p != nil {
err = p.parse(contents) err = p.parse(contents)
@ -447,7 +446,7 @@ func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
// readMPI reads a big integer from r. The bit length returned is the bit // readMPI reads a big integer from r. The bit length returned is the bit
// length that was specified in r. This is preserved so that the integer can be // length that was specified in r. This is preserved so that the integer can be
// reserialized exactly. // reserialized exactly.
func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err os.Error) { func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
var buf [2]byte var buf [2]byte
_, err = readFull(r, buf[0:]) _, err = readFull(r, buf[0:])
if err != nil { if err != nil {
@ -469,7 +468,7 @@ func mpiLength(n *big.Int) (mpiLengthInBytes int) {
} }
// writeMPI serializes a big integer to w. // writeMPI serializes a big integer to w.
func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err os.Error) { func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
_, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)}) _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
if err == nil { if err == nil {
_, err = w.Write(mpiBytes) _, err = w.Write(mpiBytes)
@ -478,6 +477,6 @@ func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err os.Error) {
} }
// writeBig serializes a *big.Int to w. // writeBig serializes a *big.Int to w.
func writeBig(w io.Writer, i *big.Int) os.Error { func writeBig(w io.Writer, i *big.Int) error {
return writeMPI(w, uint16(i.BitLen()), i.Bytes()) return writeMPI(w, uint16(i.BitLen()), i.Bytes())
} }

View File

@ -6,12 +6,11 @@ package packet
import ( import (
"bytes" "bytes"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
@ -49,7 +48,7 @@ var readLengthTests = []struct {
hexInput string hexInput string
length int64 length int64
isPartial bool isPartial bool
err os.Error err error
}{ }{
{"", 0, false, io.ErrUnexpectedEOF}, {"", 0, false, io.ErrUnexpectedEOF},
{"1f", 31, false, nil}, {"1f", 31, false, nil},
@ -87,7 +86,7 @@ func TestReadLength(t *testing.T) {
var partialLengthReaderTests = []struct { var partialLengthReaderTests = []struct {
hexInput string hexInput string
err os.Error err error
hexOutput string hexOutput string
}{ }{
{"e0", io.ErrUnexpectedEOF, ""}, {"e0", io.ErrUnexpectedEOF, ""},
@ -153,14 +152,14 @@ func TestReadHeader(t *testing.T) {
for i, test := range readHeaderTests { for i, test := range readHeaderTests {
tag, length, contents, err := readHeader(readerFromHex(test.hexInput)) tag, length, contents, err := readHeader(readerFromHex(test.hexInput))
if test.structuralError { if test.structuralError {
if _, ok := err.(error.StructuralError); ok { if _, ok := err.(error_.StructuralError); ok {
continue continue
} }
t.Errorf("%d: expected StructuralError, got:%s", i, err) t.Errorf("%d: expected StructuralError, got:%s", i, err)
continue continue
} }
if err != nil { if err != nil {
if len(test.hexInput) == 0 && err == os.EOF { if len(test.hexInput) == 0 && err == io.EOF {
continue continue
} }
if !test.unexpectedEOF || err != io.ErrUnexpectedEOF { if !test.unexpectedEOF || err != io.ErrUnexpectedEOF {

View File

@ -10,13 +10,12 @@ import (
"crypto/cipher" "crypto/cipher"
"crypto/dsa" "crypto/dsa"
"crypto/openpgp/elgamal" "crypto/openpgp/elgamal"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"crypto/rsa" "crypto/rsa"
"crypto/sha1" "crypto/sha1"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"strconv" "strconv"
) )
@ -40,7 +39,7 @@ func NewRSAPrivateKey(currentTimeSecs uint32, priv *rsa.PrivateKey, isSubkey boo
return pk return pk
} }
func (pk *PrivateKey) parse(r io.Reader) (err os.Error) { func (pk *PrivateKey) parse(r io.Reader) (err error) {
err = (&pk.PublicKey).parse(r) err = (&pk.PublicKey).parse(r)
if err != nil { if err != nil {
return return
@ -72,13 +71,13 @@ func (pk *PrivateKey) parse(r io.Reader) (err os.Error) {
pk.sha1Checksum = true pk.sha1Checksum = true
} }
default: default:
return error.UnsupportedError("deprecated s2k function in private key") return error_.UnsupportedError("deprecated s2k function in private key")
} }
if pk.Encrypted { if pk.Encrypted {
blockSize := pk.cipher.blockSize() blockSize := pk.cipher.blockSize()
if blockSize == 0 { if blockSize == 0 {
return error.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher))) return error_.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
} }
pk.iv = make([]byte, blockSize) pk.iv = make([]byte, blockSize)
_, err = readFull(r, pk.iv) _, err = readFull(r, pk.iv)
@ -111,7 +110,7 @@ func mod64kHash(d []byte) uint16 {
return h return h
} }
func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) { func (pk *PrivateKey) Serialize(w io.Writer) (err error) {
// TODO(agl): support encrypted private keys // TODO(agl): support encrypted private keys
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
err = pk.PublicKey.serializeWithoutHeaders(buf) err = pk.PublicKey.serializeWithoutHeaders(buf)
@ -126,7 +125,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) {
case *rsa.PrivateKey: case *rsa.PrivateKey:
err = serializeRSAPrivateKey(privateKeyBuf, priv) err = serializeRSAPrivateKey(privateKeyBuf, priv)
default: default:
err = error.InvalidArgumentError("non-RSA private key") err = error_.InvalidArgumentError("non-RSA private key")
} }
if err != nil { if err != nil {
return return
@ -160,7 +159,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) {
return return
} }
func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) os.Error { func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error {
err := writeBig(w, priv.D) err := writeBig(w, priv.D)
if err != nil { if err != nil {
return err return err
@ -177,7 +176,7 @@ func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) os.Error {
} }
// Decrypt decrypts an encrypted private key using a passphrase. // Decrypt decrypts an encrypted private key using a passphrase.
func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error { func (pk *PrivateKey) Decrypt(passphrase []byte) error {
if !pk.Encrypted { if !pk.Encrypted {
return nil return nil
} }
@ -192,18 +191,18 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
if pk.sha1Checksum { if pk.sha1Checksum {
if len(data) < sha1.Size { if len(data) < sha1.Size {
return error.StructuralError("truncated private key data") return error_.StructuralError("truncated private key data")
} }
h := sha1.New() h := sha1.New()
h.Write(data[:len(data)-sha1.Size]) h.Write(data[:len(data)-sha1.Size])
sum := h.Sum() sum := h.Sum()
if !bytes.Equal(sum, data[len(data)-sha1.Size:]) { if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
return error.StructuralError("private key checksum failure") return error_.StructuralError("private key checksum failure")
} }
data = data[:len(data)-sha1.Size] data = data[:len(data)-sha1.Size]
} else { } else {
if len(data) < 2 { if len(data) < 2 {
return error.StructuralError("truncated private key data") return error_.StructuralError("truncated private key data")
} }
var sum uint16 var sum uint16
for i := 0; i < len(data)-2; i++ { for i := 0; i < len(data)-2; i++ {
@ -211,7 +210,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
} }
if data[len(data)-2] != uint8(sum>>8) || if data[len(data)-2] != uint8(sum>>8) ||
data[len(data)-1] != uint8(sum) { data[len(data)-1] != uint8(sum) {
return error.StructuralError("private key checksum failure") return error_.StructuralError("private key checksum failure")
} }
data = data[:len(data)-2] data = data[:len(data)-2]
} }
@ -219,7 +218,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
return pk.parsePrivateKey(data) return pk.parsePrivateKey(data)
} }
func (pk *PrivateKey) parsePrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) {
switch pk.PublicKey.PubKeyAlgo { switch pk.PublicKey.PubKeyAlgo {
case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly: case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly:
return pk.parseRSAPrivateKey(data) return pk.parseRSAPrivateKey(data)
@ -231,7 +230,7 @@ func (pk *PrivateKey) parsePrivateKey(data []byte) (err os.Error) {
panic("impossible") panic("impossible")
} }
func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) {
rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
rsaPriv := new(rsa.PrivateKey) rsaPriv := new(rsa.PrivateKey)
rsaPriv.PublicKey = *rsaPub rsaPriv.PublicKey = *rsaPub
@ -262,7 +261,7 @@ func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) {
return nil return nil
} }
func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) {
dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey) dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey)
dsaPriv := new(dsa.PrivateKey) dsaPriv := new(dsa.PrivateKey)
dsaPriv.PublicKey = *dsaPub dsaPriv.PublicKey = *dsaPub
@ -281,7 +280,7 @@ func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err os.Error) {
return nil return nil
} }
func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) {
pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey) pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey)
priv := new(elgamal.PrivateKey) priv := new(elgamal.PrivateKey)
priv.PublicKey = *pub priv.PublicKey = *pub

View File

@ -8,14 +8,13 @@ import (
"big" "big"
"crypto/dsa" "crypto/dsa"
"crypto/openpgp/elgamal" "crypto/openpgp/elgamal"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/rsa" "crypto/rsa"
"crypto/sha1" "crypto/sha1"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"hash" "hash"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -53,7 +52,7 @@ func NewRSAPublicKey(creationTimeSecs uint32, pub *rsa.PublicKey, isSubkey bool)
return pk return pk
} }
func (pk *PublicKey) parse(r io.Reader) (err os.Error) { func (pk *PublicKey) parse(r io.Reader) (err error) {
// RFC 4880, section 5.5.2 // RFC 4880, section 5.5.2
var buf [6]byte var buf [6]byte
_, err = readFull(r, buf[:]) _, err = readFull(r, buf[:])
@ -61,7 +60,7 @@ func (pk *PublicKey) parse(r io.Reader) (err os.Error) {
return return
} }
if buf[0] != 4 { if buf[0] != 4 {
return error.UnsupportedError("public key version") return error_.UnsupportedError("public key version")
} }
pk.CreationTime = uint32(buf[1])<<24 | uint32(buf[2])<<16 | uint32(buf[3])<<8 | uint32(buf[4]) pk.CreationTime = uint32(buf[1])<<24 | uint32(buf[2])<<16 | uint32(buf[3])<<8 | uint32(buf[4])
pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5]) pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5])
@ -73,7 +72,7 @@ func (pk *PublicKey) parse(r io.Reader) (err os.Error) {
case PubKeyAlgoElGamal: case PubKeyAlgoElGamal:
err = pk.parseElGamal(r) err = pk.parseElGamal(r)
default: default:
err = error.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) err = error_.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
} }
if err != nil { if err != nil {
return return
@ -94,7 +93,7 @@ func (pk *PublicKey) setFingerPrintAndKeyId() {
// parseRSA parses RSA public key material from the given Reader. See RFC 4880, // parseRSA parses RSA public key material from the given Reader. See RFC 4880,
// section 5.5.2. // section 5.5.2.
func (pk *PublicKey) parseRSA(r io.Reader) (err os.Error) { func (pk *PublicKey) parseRSA(r io.Reader) (err error) {
pk.n.bytes, pk.n.bitLength, err = readMPI(r) pk.n.bytes, pk.n.bitLength, err = readMPI(r)
if err != nil { if err != nil {
return return
@ -105,7 +104,7 @@ func (pk *PublicKey) parseRSA(r io.Reader) (err os.Error) {
} }
if len(pk.e.bytes) > 3 { if len(pk.e.bytes) > 3 {
err = error.UnsupportedError("large public exponent") err = error_.UnsupportedError("large public exponent")
return return
} }
rsa := &rsa.PublicKey{ rsa := &rsa.PublicKey{
@ -122,7 +121,7 @@ func (pk *PublicKey) parseRSA(r io.Reader) (err os.Error) {
// parseDSA parses DSA public key material from the given Reader. See RFC 4880, // parseDSA parses DSA public key material from the given Reader. See RFC 4880,
// section 5.5.2. // section 5.5.2.
func (pk *PublicKey) parseDSA(r io.Reader) (err os.Error) { func (pk *PublicKey) parseDSA(r io.Reader) (err error) {
pk.p.bytes, pk.p.bitLength, err = readMPI(r) pk.p.bytes, pk.p.bitLength, err = readMPI(r)
if err != nil { if err != nil {
return return
@ -151,7 +150,7 @@ func (pk *PublicKey) parseDSA(r io.Reader) (err os.Error) {
// parseElGamal parses ElGamal public key material from the given Reader. See // parseElGamal parses ElGamal public key material from the given Reader. See
// RFC 4880, section 5.5.2. // RFC 4880, section 5.5.2.
func (pk *PublicKey) parseElGamal(r io.Reader) (err os.Error) { func (pk *PublicKey) parseElGamal(r io.Reader) (err error) {
pk.p.bytes, pk.p.bitLength, err = readMPI(r) pk.p.bytes, pk.p.bitLength, err = readMPI(r)
if err != nil { if err != nil {
return return
@ -199,7 +198,7 @@ func (pk *PublicKey) SerializeSignaturePrefix(h hash.Hash) {
return return
} }
func (pk *PublicKey) Serialize(w io.Writer) (err os.Error) { func (pk *PublicKey) Serialize(w io.Writer) (err error) {
length := 6 // 6 byte header length := 6 // 6 byte header
switch pk.PubKeyAlgo { switch pk.PubKeyAlgo {
@ -232,7 +231,7 @@ func (pk *PublicKey) Serialize(w io.Writer) (err os.Error) {
// serializeWithoutHeaders marshals the PublicKey to w in the form of an // serializeWithoutHeaders marshals the PublicKey to w in the form of an
// OpenPGP public key packet, not including the packet header. // OpenPGP public key packet, not including the packet header.
func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err os.Error) { func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) {
var buf [6]byte var buf [6]byte
buf[0] = 4 buf[0] = 4
buf[1] = byte(pk.CreationTime >> 24) buf[1] = byte(pk.CreationTime >> 24)
@ -254,7 +253,7 @@ func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err os.Error) {
case PubKeyAlgoElGamal: case PubKeyAlgoElGamal:
return writeMPIs(w, pk.p, pk.g, pk.y) return writeMPIs(w, pk.p, pk.g, pk.y)
} }
return error.InvalidArgumentError("bad public-key algorithm") return error_.InvalidArgumentError("bad public-key algorithm")
} }
// CanSign returns true iff this public key can generate signatures // CanSign returns true iff this public key can generate signatures
@ -264,20 +263,20 @@ func (pk *PublicKey) CanSign() bool {
// VerifySignature returns nil iff sig is a valid signature, made by this // VerifySignature returns nil iff sig is a valid signature, made by this
// public key, of the data hashed into signed. signed is mutated by this call. // public key, of the data hashed into signed. signed is mutated by this call.
func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err os.Error) { func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
if !pk.CanSign() { if !pk.CanSign() {
return error.InvalidArgumentError("public key cannot generate signatures") return error_.InvalidArgumentError("public key cannot generate signatures")
} }
signed.Write(sig.HashSuffix) signed.Write(sig.HashSuffix)
hashBytes := signed.Sum() hashBytes := signed.Sum()
if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
return error.SignatureError("hash tag doesn't match") return error_.SignatureError("hash tag doesn't match")
} }
if pk.PubKeyAlgo != sig.PubKeyAlgo { if pk.PubKeyAlgo != sig.PubKeyAlgo {
return error.InvalidArgumentError("public key and signature use different algorithms") return error_.InvalidArgumentError("public key and signature use different algorithms")
} }
switch pk.PubKeyAlgo { switch pk.PubKeyAlgo {
@ -285,13 +284,13 @@ func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err os.E
rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey) rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes) err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
if err != nil { if err != nil {
return error.SignatureError("RSA verification failure") return error_.SignatureError("RSA verification failure")
} }
return nil return nil
case PubKeyAlgoDSA: case PubKeyAlgoDSA:
dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey) dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) { if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
return error.SignatureError("DSA verification failure") return error_.SignatureError("DSA verification failure")
} }
return nil return nil
default: default:
@ -302,10 +301,10 @@ func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err os.E
// keySignatureHash returns a Hash of the message that needs to be signed for // keySignatureHash returns a Hash of the message that needs to be signed for
// pk to assert a subkey relationship to signed. // pk to assert a subkey relationship to signed.
func keySignatureHash(pk, signed *PublicKey, sig *Signature) (h hash.Hash, err os.Error) { func keySignatureHash(pk, signed *PublicKey, sig *Signature) (h hash.Hash, err error) {
h = sig.Hash.New() h = sig.Hash.New()
if h == nil { if h == nil {
return nil, error.UnsupportedError("hash function") return nil, error_.UnsupportedError("hash function")
} }
// RFC 4880, section 5.2.4 // RFC 4880, section 5.2.4
@ -318,7 +317,7 @@ func keySignatureHash(pk, signed *PublicKey, sig *Signature) (h hash.Hash, err o
// VerifyKeySignature returns nil iff sig is a valid signature, made by this // VerifyKeySignature returns nil iff sig is a valid signature, made by this
// public key, of signed. // public key, of signed.
func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) (err os.Error) { func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) (err error) {
h, err := keySignatureHash(pk, signed, sig) h, err := keySignatureHash(pk, signed, sig)
if err != nil { if err != nil {
return err return err
@ -328,10 +327,10 @@ func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) (err
// userIdSignatureHash returns a Hash of the message that needs to be signed // userIdSignatureHash returns a Hash of the message that needs to be signed
// to assert that pk is a valid key for id. // to assert that pk is a valid key for id.
func userIdSignatureHash(id string, pk *PublicKey, sig *Signature) (h hash.Hash, err os.Error) { func userIdSignatureHash(id string, pk *PublicKey, sig *Signature) (h hash.Hash, err error) {
h = sig.Hash.New() h = sig.Hash.New()
if h == nil { if h == nil {
return nil, error.UnsupportedError("hash function") return nil, error_.UnsupportedError("hash function")
} }
// RFC 4880, section 5.2.4 // RFC 4880, section 5.2.4
@ -352,7 +351,7 @@ func userIdSignatureHash(id string, pk *PublicKey, sig *Signature) (h hash.Hash,
// VerifyUserIdSignature returns nil iff sig is a valid signature, made by this // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this
// public key, of id. // public key, of id.
func (pk *PublicKey) VerifyUserIdSignature(id string, sig *Signature) (err os.Error) { func (pk *PublicKey) VerifyUserIdSignature(id string, sig *Signature) (err error) {
h, err := userIdSignatureHash(id, pk, sig) h, err := userIdSignatureHash(id, pk, sig)
if err != nil { if err != nil {
return err return err
@ -382,7 +381,7 @@ type parsedMPI struct {
// writeMPIs is a utility function for serializing several big integers to the // writeMPIs is a utility function for serializing several big integers to the
// given Writer. // given Writer.
func writeMPIs(w io.Writer, mpis ...parsedMPI) (err os.Error) { func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) {
for _, mpi := range mpis { for _, mpi := range mpis {
err = writeMPI(w, mpi.bitLength, mpi.bytes) err = writeMPI(w, mpi.bitLength, mpi.bytes)
if err != nil { if err != nil {

View File

@ -5,9 +5,8 @@
package packet package packet
import ( import (
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"io" "io"
"os"
) )
// Reader reads packets from an io.Reader and allows packets to be 'unread' so // Reader reads packets from an io.Reader and allows packets to be 'unread' so
@ -19,7 +18,7 @@ type Reader struct {
// Next returns the most recently unread Packet, or reads another packet from // Next returns the most recently unread Packet, or reads another packet from
// the top-most io.Reader. Unknown packet types are skipped. // the top-most io.Reader. Unknown packet types are skipped.
func (r *Reader) Next() (p Packet, err os.Error) { func (r *Reader) Next() (p Packet, err error) {
if len(r.q) > 0 { if len(r.q) > 0 {
p = r.q[len(r.q)-1] p = r.q[len(r.q)-1]
r.q = r.q[:len(r.q)-1] r.q = r.q[:len(r.q)-1]
@ -31,16 +30,16 @@ func (r *Reader) Next() (p Packet, err os.Error) {
if err == nil { if err == nil {
return return
} }
if err == os.EOF { if err == io.EOF {
r.readers = r.readers[:len(r.readers)-1] r.readers = r.readers[:len(r.readers)-1]
continue continue
} }
if _, ok := err.(error.UnknownPacketTypeError); !ok { if _, ok := err.(error_.UnknownPacketTypeError); !ok {
return nil, err return nil, err
} }
} }
return nil, os.EOF return nil, io.EOF
} }
// Push causes the Reader to start reading from a new io.Reader. When an EOF // Push causes the Reader to start reading from a new io.Reader. When an EOF

View File

@ -7,14 +7,13 @@ package packet
import ( import (
"crypto" "crypto"
"crypto/dsa" "crypto/dsa"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"encoding/binary" "encoding/binary"
"hash" "hash"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -53,7 +52,7 @@ type Signature struct {
outSubpackets []outputSubpacket outSubpackets []outputSubpacket
} }
func (sig *Signature) parse(r io.Reader) (err os.Error) { func (sig *Signature) parse(r io.Reader) (err error) {
// RFC 4880, section 5.2.3 // RFC 4880, section 5.2.3
var buf [5]byte var buf [5]byte
_, err = readFull(r, buf[:1]) _, err = readFull(r, buf[:1])
@ -61,7 +60,7 @@ func (sig *Signature) parse(r io.Reader) (err os.Error) {
return return
} }
if buf[0] != 4 { if buf[0] != 4 {
err = error.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) err = error_.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
return return
} }
@ -74,14 +73,14 @@ func (sig *Signature) parse(r io.Reader) (err os.Error) {
switch sig.PubKeyAlgo { switch sig.PubKeyAlgo {
case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA: case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA:
default: default:
err = error.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) err = error_.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
return return
} }
var ok bool var ok bool
sig.Hash, ok = s2k.HashIdToHash(buf[2]) sig.Hash, ok = s2k.HashIdToHash(buf[2])
if !ok { if !ok {
return error.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) return error_.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
} }
hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4]) hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4])
@ -144,7 +143,7 @@ func (sig *Signature) parse(r io.Reader) (err os.Error) {
// parseSignatureSubpackets parses subpackets of the main signature packet. See // parseSignatureSubpackets parses subpackets of the main signature packet. See
// RFC 4880, section 5.2.3.1. // RFC 4880, section 5.2.3.1.
func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err os.Error) { func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
for len(subpackets) > 0 { for len(subpackets) > 0 {
subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed) subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
if err != nil { if err != nil {
@ -153,7 +152,7 @@ func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool)
} }
if sig.CreationTime == 0 { if sig.CreationTime == 0 {
err = error.StructuralError("no creation time in signature") err = error_.StructuralError("no creation time in signature")
} }
return return
@ -174,7 +173,7 @@ const (
) )
// parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1. // parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1.
func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err os.Error) { func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
// RFC 4880, section 5.2.3.1 // RFC 4880, section 5.2.3.1
var ( var (
length uint32 length uint32
@ -207,7 +206,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
rest = subpacket[length:] rest = subpacket[length:]
subpacket = subpacket[:length] subpacket = subpacket[:length]
if len(subpacket) == 0 { if len(subpacket) == 0 {
err = error.StructuralError("zero length signature subpacket") err = error_.StructuralError("zero length signature subpacket")
return return
} }
packetType = signatureSubpacketType(subpacket[0] & 0x7f) packetType = signatureSubpacketType(subpacket[0] & 0x7f)
@ -217,11 +216,11 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
switch packetType { switch packetType {
case creationTimeSubpacket: case creationTimeSubpacket:
if !isHashed { if !isHashed {
err = error.StructuralError("signature creation time in non-hashed area") err = error_.StructuralError("signature creation time in non-hashed area")
return return
} }
if len(subpacket) != 4 { if len(subpacket) != 4 {
err = error.StructuralError("signature creation time not four bytes") err = error_.StructuralError("signature creation time not four bytes")
return return
} }
sig.CreationTime = binary.BigEndian.Uint32(subpacket) sig.CreationTime = binary.BigEndian.Uint32(subpacket)
@ -231,7 +230,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
return return
} }
if len(subpacket) != 4 { if len(subpacket) != 4 {
err = error.StructuralError("expiration subpacket with bad length") err = error_.StructuralError("expiration subpacket with bad length")
return return
} }
sig.SigLifetimeSecs = new(uint32) sig.SigLifetimeSecs = new(uint32)
@ -242,7 +241,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
return return
} }
if len(subpacket) != 4 { if len(subpacket) != 4 {
err = error.StructuralError("key expiration subpacket with bad length") err = error_.StructuralError("key expiration subpacket with bad length")
return return
} }
sig.KeyLifetimeSecs = new(uint32) sig.KeyLifetimeSecs = new(uint32)
@ -257,7 +256,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
case issuerSubpacket: case issuerSubpacket:
// Issuer, section 5.2.3.5 // Issuer, section 5.2.3.5
if len(subpacket) != 8 { if len(subpacket) != 8 {
err = error.StructuralError("issuer subpacket with bad length") err = error_.StructuralError("issuer subpacket with bad length")
return return
} }
sig.IssuerKeyId = new(uint64) sig.IssuerKeyId = new(uint64)
@ -282,7 +281,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
return return
} }
if len(subpacket) != 1 { if len(subpacket) != 1 {
err = error.StructuralError("primary user id subpacket with bad length") err = error_.StructuralError("primary user id subpacket with bad length")
return return
} }
sig.IsPrimaryId = new(bool) sig.IsPrimaryId = new(bool)
@ -295,7 +294,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
return return
} }
if len(subpacket) == 0 { if len(subpacket) == 0 {
err = error.StructuralError("empty key flags subpacket") err = error_.StructuralError("empty key flags subpacket")
return return
} }
sig.FlagsValid = true sig.FlagsValid = true
@ -314,14 +313,14 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r
default: default:
if isCritical { if isCritical {
err = error.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType))) err = error_.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
return return
} }
} }
return return
Truncated: Truncated:
err = error.StructuralError("signature subpacket truncated") err = error_.StructuralError("signature subpacket truncated")
return return
} }
@ -384,7 +383,7 @@ func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) {
} }
// buildHashSuffix constructs the HashSuffix member of sig in preparation for signing. // buildHashSuffix constructs the HashSuffix member of sig in preparation for signing.
func (sig *Signature) buildHashSuffix() (err os.Error) { func (sig *Signature) buildHashSuffix() (err error) {
hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true) hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
var ok bool var ok bool
@ -396,7 +395,7 @@ func (sig *Signature) buildHashSuffix() (err os.Error) {
sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash) sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash)
if !ok { if !ok {
sig.HashSuffix = nil sig.HashSuffix = nil
return error.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash))) return error_.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
} }
sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8) sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8)
sig.HashSuffix[5] = byte(hashedSubpacketsLen) sig.HashSuffix[5] = byte(hashedSubpacketsLen)
@ -411,7 +410,7 @@ func (sig *Signature) buildHashSuffix() (err os.Error) {
return return
} }
func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err os.Error) { func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) {
err = sig.buildHashSuffix() err = sig.buildHashSuffix()
if err != nil { if err != nil {
return return
@ -426,7 +425,7 @@ func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err os.Error)
// Sign signs a message with a private key. The hash, h, must contain // Sign signs a message with a private key. The hash, h, must contain
// the hash of the message to be signed and will be mutated by this function. // the hash of the message to be signed and will be mutated by this function.
// On success, the signature is stored in sig. Call Serialize to write it out. // On success, the signature is stored in sig. Call Serialize to write it out.
func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err os.Error) { func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err error) {
sig.outSubpackets = sig.buildSubpackets() sig.outSubpackets = sig.buildSubpackets()
digest, err := sig.signPrepareHash(h) digest, err := sig.signPrepareHash(h)
if err != nil { if err != nil {
@ -446,7 +445,7 @@ func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err os.Error) {
sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes)) sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes))
} }
default: default:
err = error.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo))) err = error_.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
} }
return return
@ -455,7 +454,7 @@ func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err os.Error) {
// SignUserId computes a signature from priv, asserting that pub is a valid // SignUserId computes a signature from priv, asserting that pub is a valid
// key for the identity id. On success, the signature is stored in sig. Call // key for the identity id. On success, the signature is stored in sig. Call
// Serialize to write it out. // Serialize to write it out.
func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey) os.Error { func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey) error {
h, err := userIdSignatureHash(id, pub, sig) h, err := userIdSignatureHash(id, pub, sig)
if err != nil { if err != nil {
return nil return nil
@ -465,7 +464,7 @@ func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey) os
// SignKey computes a signature from priv, asserting that pub is a subkey. On // SignKey computes a signature from priv, asserting that pub is a subkey. On
// success, the signature is stored in sig. Call Serialize to write it out. // success, the signature is stored in sig. Call Serialize to write it out.
func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey) os.Error { func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey) error {
h, err := keySignatureHash(&priv.PublicKey, pub, sig) h, err := keySignatureHash(&priv.PublicKey, pub, sig)
if err != nil { if err != nil {
return err return err
@ -474,12 +473,12 @@ func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey) os.Error {
} }
// Serialize marshals sig to w. SignRSA or SignDSA must have been called first. // Serialize marshals sig to w. SignRSA or SignDSA must have been called first.
func (sig *Signature) Serialize(w io.Writer) (err os.Error) { func (sig *Signature) Serialize(w io.Writer) (err error) {
if len(sig.outSubpackets) == 0 { if len(sig.outSubpackets) == 0 {
sig.outSubpackets = sig.rawSubpackets sig.outSubpackets = sig.rawSubpackets
} }
if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil { if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil {
return error.InvalidArgumentError("Signature: need to call SignRSA or SignDSA before Serialize") return error_.InvalidArgumentError("Signature: need to call SignRSA or SignDSA before Serialize")
} }
sigLength := 0 sigLength := 0

View File

@ -7,10 +7,9 @@ package packet
import ( import (
"bytes" "bytes"
"crypto/cipher" "crypto/cipher"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -30,7 +29,7 @@ type SymmetricKeyEncrypted struct {
const symmetricKeyEncryptedVersion = 4 const symmetricKeyEncryptedVersion = 4
func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err os.Error) { func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err error) {
// RFC 4880, section 5.3. // RFC 4880, section 5.3.
var buf [2]byte var buf [2]byte
_, err = readFull(r, buf[:]) _, err = readFull(r, buf[:])
@ -38,12 +37,12 @@ func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err os.Error) {
return return
} }
if buf[0] != symmetricKeyEncryptedVersion { if buf[0] != symmetricKeyEncryptedVersion {
return error.UnsupportedError("SymmetricKeyEncrypted version") return error_.UnsupportedError("SymmetricKeyEncrypted version")
} }
ske.CipherFunc = CipherFunction(buf[1]) ske.CipherFunc = CipherFunction(buf[1])
if ske.CipherFunc.KeySize() == 0 { if ske.CipherFunc.KeySize() == 0 {
return error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1]))) return error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1])))
} }
ske.s2k, err = s2k.Parse(r) ske.s2k, err = s2k.Parse(r)
@ -61,7 +60,7 @@ func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err os.Error) {
err = nil err = nil
if n != 0 { if n != 0 {
if n == maxSessionKeySizeInBytes { if n == maxSessionKeySizeInBytes {
return error.UnsupportedError("oversized encrypted session key") return error_.UnsupportedError("oversized encrypted session key")
} }
ske.encryptedKey = encryptedKey[:n] ske.encryptedKey = encryptedKey[:n]
} }
@ -73,7 +72,7 @@ func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err os.Error) {
// Decrypt attempts to decrypt an encrypted session key. If it returns nil, // Decrypt attempts to decrypt an encrypted session key. If it returns nil,
// ske.Key will contain the session key. // ske.Key will contain the session key.
func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) os.Error { func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) error {
if !ske.Encrypted { if !ske.Encrypted {
return nil return nil
} }
@ -90,13 +89,13 @@ func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) os.Error {
c.XORKeyStream(ske.encryptedKey, ske.encryptedKey) c.XORKeyStream(ske.encryptedKey, ske.encryptedKey)
ske.CipherFunc = CipherFunction(ske.encryptedKey[0]) ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
if ske.CipherFunc.blockSize() == 0 { if ske.CipherFunc.blockSize() == 0 {
return error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc))) return error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc)))
} }
ske.CipherFunc = CipherFunction(ske.encryptedKey[0]) ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
ske.Key = ske.encryptedKey[1:] ske.Key = ske.encryptedKey[1:]
if len(ske.Key)%ske.CipherFunc.blockSize() != 0 { if len(ske.Key)%ske.CipherFunc.blockSize() != 0 {
ske.Key = nil ske.Key = nil
return error.StructuralError("length of decrypted key not a multiple of block size") return error_.StructuralError("length of decrypted key not a multiple of block size")
} }
} }
@ -108,10 +107,10 @@ func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) os.Error {
// packet contains a random session key, encrypted by a key derived from the // packet contains a random session key, encrypted by a key derived from the
// given passphrase. The session key is returned and must be passed to // given passphrase. The session key is returned and must be passed to
// SerializeSymmetricallyEncrypted. // SerializeSymmetricallyEncrypted.
func SerializeSymmetricKeyEncrypted(w io.Writer, rand io.Reader, passphrase []byte, cipherFunc CipherFunction) (key []byte, err os.Error) { func SerializeSymmetricKeyEncrypted(w io.Writer, rand io.Reader, passphrase []byte, cipherFunc CipherFunction) (key []byte, err error) {
keySize := cipherFunc.KeySize() keySize := cipherFunc.KeySize()
if keySize == 0 { if keySize == 0 {
return nil, error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc))) return nil, error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
} }
s2kBuf := new(bytes.Buffer) s2kBuf := new(bytes.Buffer)

View File

@ -8,8 +8,8 @@ import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
@ -48,7 +48,7 @@ func TestSymmetricKeyEncrypted(t *testing.T) {
} }
contents, err := ioutil.ReadAll(r) contents, err := ioutil.ReadAll(r)
if err != nil && err != os.EOF { if err != nil && err != io.EOF {
t.Error(err) t.Error(err)
return return
} }

View File

@ -6,13 +6,12 @@ package packet
import ( import (
"crypto/cipher" "crypto/cipher"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/rand" "crypto/rand"
"crypto/sha1" "crypto/sha1"
"crypto/subtle" "crypto/subtle"
"hash" "hash"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -27,7 +26,7 @@ type SymmetricallyEncrypted struct {
const symmetricallyEncryptedVersion = 1 const symmetricallyEncryptedVersion = 1
func (se *SymmetricallyEncrypted) parse(r io.Reader) os.Error { func (se *SymmetricallyEncrypted) parse(r io.Reader) error {
if se.MDC { if se.MDC {
// See RFC 4880, section 5.13. // See RFC 4880, section 5.13.
var buf [1]byte var buf [1]byte
@ -36,7 +35,7 @@ func (se *SymmetricallyEncrypted) parse(r io.Reader) os.Error {
return err return err
} }
if buf[0] != symmetricallyEncryptedVersion { if buf[0] != symmetricallyEncryptedVersion {
return error.UnsupportedError("unknown SymmetricallyEncrypted version") return error_.UnsupportedError("unknown SymmetricallyEncrypted version")
} }
} }
se.contents = r se.contents = r
@ -46,13 +45,13 @@ func (se *SymmetricallyEncrypted) parse(r io.Reader) os.Error {
// Decrypt returns a ReadCloser, from which the decrypted contents of the // Decrypt returns a ReadCloser, from which the decrypted contents of the
// packet can be read. An incorrect key can, with high probability, be detected // packet can be read. An incorrect key can, with high probability, be detected
// immediately and this will result in a KeyIncorrect error being returned. // immediately and this will result in a KeyIncorrect error being returned.
func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, os.Error) { func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, error) {
keySize := c.KeySize() keySize := c.KeySize()
if keySize == 0 { if keySize == 0 {
return nil, error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c))) return nil, error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c)))
} }
if len(key) != keySize { if len(key) != keySize {
return nil, error.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length") return nil, error_.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length")
} }
if se.prefix == nil { if se.prefix == nil {
@ -62,7 +61,7 @@ func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.Read
return nil, err return nil, err
} }
} else if len(se.prefix) != c.blockSize()+2 { } else if len(se.prefix) != c.blockSize()+2 {
return nil, error.InvalidArgumentError("can't try ciphers with different block lengths") return nil, error_.InvalidArgumentError("can't try ciphers with different block lengths")
} }
ocfbResync := cipher.OCFBResync ocfbResync := cipher.OCFBResync
@ -73,7 +72,7 @@ func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.Read
s := cipher.NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync) s := cipher.NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync)
if s == nil { if s == nil {
return nil, error.KeyIncorrectError return nil, error_.KeyIncorrectError
} }
plaintext := cipher.StreamReader{S: s, R: se.contents} plaintext := cipher.StreamReader{S: s, R: se.contents}
@ -94,11 +93,11 @@ type seReader struct {
in io.Reader in io.Reader
} }
func (ser seReader) Read(buf []byte) (int, os.Error) { func (ser seReader) Read(buf []byte) (int, error) {
return ser.in.Read(buf) return ser.in.Read(buf)
} }
func (ser seReader) Close() os.Error { func (ser seReader) Close() error {
return nil return nil
} }
@ -118,13 +117,13 @@ type seMDCReader struct {
eof bool eof bool
} }
func (ser *seMDCReader) Read(buf []byte) (n int, err os.Error) { func (ser *seMDCReader) Read(buf []byte) (n int, err error) {
if ser.error { if ser.error {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
return return
} }
if ser.eof { if ser.eof {
err = os.EOF err = io.EOF
return return
} }
@ -133,7 +132,7 @@ func (ser *seMDCReader) Read(buf []byte) (n int, err os.Error) {
for ser.trailerUsed < mdcTrailerSize { for ser.trailerUsed < mdcTrailerSize {
n, err = ser.in.Read(ser.trailer[ser.trailerUsed:]) n, err = ser.in.Read(ser.trailer[ser.trailerUsed:])
ser.trailerUsed += n ser.trailerUsed += n
if err == os.EOF { if err == io.EOF {
if ser.trailerUsed != mdcTrailerSize { if ser.trailerUsed != mdcTrailerSize {
n = 0 n = 0
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
@ -161,7 +160,7 @@ func (ser *seMDCReader) Read(buf []byte) (n int, err os.Error) {
copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:]) copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:])
if n < len(buf) { if n < len(buf) {
ser.eof = true ser.eof = true
err = os.EOF err = io.EOF
} }
return return
} }
@ -171,7 +170,7 @@ func (ser *seMDCReader) Read(buf []byte) (n int, err os.Error) {
ser.h.Write(buf[:n]) ser.h.Write(buf[:n])
copy(ser.trailer[:], buf[n:]) copy(ser.trailer[:], buf[n:])
if err == os.EOF { if err == io.EOF {
ser.eof = true ser.eof = true
} }
return return
@ -180,31 +179,31 @@ func (ser *seMDCReader) Read(buf []byte) (n int, err os.Error) {
// This is a new-format packet tag byte for a type 19 (MDC) packet. // This is a new-format packet tag byte for a type 19 (MDC) packet.
const mdcPacketTagByte = byte(0x80) | 0x40 | 19 const mdcPacketTagByte = byte(0x80) | 0x40 | 19
func (ser *seMDCReader) Close() os.Error { func (ser *seMDCReader) Close() error {
if ser.error { if ser.error {
return error.SignatureError("error during reading") return error_.SignatureError("error during reading")
} }
for !ser.eof { for !ser.eof {
// We haven't seen EOF so we need to read to the end // We haven't seen EOF so we need to read to the end
var buf [1024]byte var buf [1024]byte
_, err := ser.Read(buf[:]) _, err := ser.Read(buf[:])
if err == os.EOF { if err == io.EOF {
break break
} }
if err != nil { if err != nil {
return error.SignatureError("error during reading") return error_.SignatureError("error during reading")
} }
} }
if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size { if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size {
return error.SignatureError("MDC packet not found") return error_.SignatureError("MDC packet not found")
} }
ser.h.Write(ser.trailer[:2]) ser.h.Write(ser.trailer[:2])
final := ser.h.Sum() final := ser.h.Sum()
if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 { if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 {
return error.SignatureError("hash mismatch") return error_.SignatureError("hash mismatch")
} }
return nil return nil
} }
@ -217,12 +216,12 @@ type seMDCWriter struct {
h hash.Hash h hash.Hash
} }
func (w *seMDCWriter) Write(buf []byte) (n int, err os.Error) { func (w *seMDCWriter) Write(buf []byte) (n int, err error) {
w.h.Write(buf) w.h.Write(buf)
return w.w.Write(buf) return w.w.Write(buf)
} }
func (w *seMDCWriter) Close() (err os.Error) { func (w *seMDCWriter) Close() (err error) {
var buf [mdcTrailerSize]byte var buf [mdcTrailerSize]byte
buf[0] = mdcPacketTagByte buf[0] = mdcPacketTagByte
@ -243,20 +242,20 @@ type noOpCloser struct {
w io.Writer w io.Writer
} }
func (c noOpCloser) Write(data []byte) (n int, err os.Error) { func (c noOpCloser) Write(data []byte) (n int, err error) {
return c.w.Write(data) return c.w.Write(data)
} }
func (c noOpCloser) Close() os.Error { func (c noOpCloser) Close() error {
return nil return nil
} }
// SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet // SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet
// to w and returns a WriteCloser to which the to-be-encrypted packets can be // to w and returns a WriteCloser to which the to-be-encrypted packets can be
// written. // written.
func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte) (contents io.WriteCloser, err os.Error) { func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte) (contents io.WriteCloser, err error) {
if c.KeySize() != len(key) { if c.KeySize() != len(key) {
return nil, error.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length") return nil, error_.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length")
} }
writeCloser := noOpCloser{w} writeCloser := noOpCloser{w}
ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedMDC) ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedMDC)

View File

@ -6,12 +6,11 @@ package packet
import ( import (
"bytes" "bytes"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
@ -21,7 +20,7 @@ type testReader struct {
stride int stride int
} }
func (t *testReader) Read(buf []byte) (n int, err os.Error) { func (t *testReader) Read(buf []byte) (n int, err error) {
n = t.stride n = t.stride
if n > len(t.data) { if n > len(t.data) {
n = len(t.data) n = len(t.data)
@ -32,7 +31,7 @@ func (t *testReader) Read(buf []byte) (n int, err os.Error) {
copy(buf, t.data) copy(buf, t.data)
t.data = t.data[n:] t.data = t.data[n:]
if len(t.data) == 0 { if len(t.data) == 0 {
err = os.EOF err = io.EOF
} }
return return
} }
@ -71,7 +70,7 @@ func testMDCReader(t *testing.T) {
err = mdcReader.Close() err = mdcReader.Close()
if err == nil { if err == nil {
t.Error("corruption: no error") t.Error("corruption: no error")
} else if _, ok := err.(*error.SignatureError); !ok { } else if _, ok := err.(*error_.SignatureError); !ok {
t.Errorf("corruption: expected SignatureError, got: %s", err) t.Errorf("corruption: expected SignatureError, got: %s", err)
} }
} }

View File

@ -7,7 +7,6 @@ package packet
import ( import (
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"strings" "strings"
) )
@ -65,7 +64,7 @@ func NewUserId(name, comment, email string) *UserId {
return uid return uid
} }
func (uid *UserId) parse(r io.Reader) (err os.Error) { func (uid *UserId) parse(r io.Reader) (err error) {
// RFC 4880, section 5.11 // RFC 4880, section 5.11
b, err := ioutil.ReadAll(r) b, err := ioutil.ReadAll(r)
if err != nil { if err != nil {
@ -78,7 +77,7 @@ func (uid *UserId) parse(r io.Reader) (err os.Error) {
// Serialize marshals uid to w in the form of an OpenPGP packet, including // Serialize marshals uid to w in the form of an OpenPGP packet, including
// header. // header.
func (uid *UserId) Serialize(w io.Writer) os.Error { func (uid *UserId) Serialize(w io.Writer) error {
err := serializeHeader(w, packetTypeUserId, len(uid.Id)) err := serializeHeader(w, packetTypeUserId, len(uid.Id))
if err != nil { if err != nil {
return err return err

View File

@ -8,12 +8,11 @@ package openpgp
import ( import (
"crypto" "crypto"
"crypto/openpgp/armor" "crypto/openpgp/armor"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/packet" "crypto/openpgp/packet"
_ "crypto/sha256" _ "crypto/sha256"
"hash" "hash"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -21,14 +20,14 @@ import (
var SignatureType = "PGP SIGNATURE" var SignatureType = "PGP SIGNATURE"
// readArmored reads an armored block with the given type. // readArmored reads an armored block with the given type.
func readArmored(r io.Reader, expectedType string) (body io.Reader, err os.Error) { func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) {
block, err := armor.Decode(r) block, err := armor.Decode(r)
if err != nil { if err != nil {
return return
} }
if block.Type != expectedType { if block.Type != expectedType {
return nil, error.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) return nil, error_.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
} }
return block.Body, nil return block.Body, nil
@ -56,7 +55,7 @@ type MessageDetails struct {
// been consumed. Once EOF has been seen, the following fields are // been consumed. Once EOF has been seen, the following fields are
// valid. (An authentication code failure is reported as a // valid. (An authentication code failure is reported as a
// SignatureError error when reading from UnverifiedBody.) // SignatureError error when reading from UnverifiedBody.)
SignatureError os.Error // nil if the signature is good. SignatureError error // nil if the signature is good.
Signature *packet.Signature // the signature packet itself. Signature *packet.Signature // the signature packet itself.
decrypted io.ReadCloser decrypted io.ReadCloser
@ -69,7 +68,7 @@ type MessageDetails struct {
// passphrase to try. If the decrypted private key or given passphrase isn't // passphrase to try. If the decrypted private key or given passphrase isn't
// correct, the function will be called again, forever. Any error returned will // correct, the function will be called again, forever. Any error returned will
// be passed up. // be passed up.
type PromptFunction func(keys []Key, symmetric bool) ([]byte, os.Error) type PromptFunction func(keys []Key, symmetric bool) ([]byte, error)
// A keyEnvelopePair is used to store a private key with the envelope that // A keyEnvelopePair is used to store a private key with the envelope that
// contains a symmetric key, encrypted with that key. // contains a symmetric key, encrypted with that key.
@ -81,7 +80,7 @@ type keyEnvelopePair struct {
// ReadMessage parses an OpenPGP message that may be signed and/or encrypted. // ReadMessage parses an OpenPGP message that may be signed and/or encrypted.
// The given KeyRing should contain both public keys (for signature // The given KeyRing should contain both public keys (for signature
// verification) and, possibly encrypted, private keys for decrypting. // verification) and, possibly encrypted, private keys for decrypting.
func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction) (md *MessageDetails, err os.Error) { func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction) (md *MessageDetails, err error) {
var p packet.Packet var p packet.Packet
var symKeys []*packet.SymmetricKeyEncrypted var symKeys []*packet.SymmetricKeyEncrypted
@ -131,7 +130,7 @@ ParsePackets:
case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature:
// This message isn't encrypted. // This message isn't encrypted.
if len(symKeys) != 0 || len(pubKeys) != 0 { if len(symKeys) != 0 || len(pubKeys) != 0 {
return nil, error.StructuralError("key material not followed by encrypted message") return nil, error_.StructuralError("key material not followed by encrypted message")
} }
packets.Unread(p) packets.Unread(p)
return readSignedMessage(packets, nil, keyring) return readSignedMessage(packets, nil, keyring)
@ -162,7 +161,7 @@ FindKey:
continue continue
} }
decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key)
if err != nil && err != error.KeyIncorrectError { if err != nil && err != error_.KeyIncorrectError {
return nil, err return nil, err
} }
if decrypted != nil { if decrypted != nil {
@ -180,11 +179,11 @@ FindKey:
} }
if len(candidates) == 0 && len(symKeys) == 0 { if len(candidates) == 0 && len(symKeys) == 0 {
return nil, error.KeyIncorrectError return nil, error_.KeyIncorrectError
} }
if prompt == nil { if prompt == nil {
return nil, error.KeyIncorrectError return nil, error_.KeyIncorrectError
} }
passphrase, err := prompt(candidates, len(symKeys) != 0) passphrase, err := prompt(candidates, len(symKeys) != 0)
@ -198,7 +197,7 @@ FindKey:
err = s.Decrypt(passphrase) err = s.Decrypt(passphrase)
if err == nil && !s.Encrypted { if err == nil && !s.Encrypted {
decrypted, err = se.Decrypt(s.CipherFunc, s.Key) decrypted, err = se.Decrypt(s.CipherFunc, s.Key)
if err != nil && err != error.KeyIncorrectError { if err != nil && err != error_.KeyIncorrectError {
return nil, err return nil, err
} }
if decrypted != nil { if decrypted != nil {
@ -218,7 +217,7 @@ FindKey:
// readSignedMessage reads a possibly signed message if mdin is non-zero then // readSignedMessage reads a possibly signed message if mdin is non-zero then
// that structure is updated and returned. Otherwise a fresh MessageDetails is // that structure is updated and returned. Otherwise a fresh MessageDetails is
// used. // used.
func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err os.Error) { func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) {
if mdin == nil { if mdin == nil {
mdin = new(MessageDetails) mdin = new(MessageDetails)
} }
@ -238,7 +237,7 @@ FindLiteralData:
packets.Push(p.Body) packets.Push(p.Body)
case *packet.OnePassSignature: case *packet.OnePassSignature:
if !p.IsLast { if !p.IsLast {
return nil, error.UnsupportedError("nested signatures") return nil, error_.UnsupportedError("nested signatures")
} }
h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) h, wrappedHash, err = hashForSignature(p.Hash, p.SigType)
@ -279,10 +278,10 @@ FindLiteralData:
// should be preprocessed (i.e. to normalize line endings). Thus this function // should be preprocessed (i.e. to normalize line endings). Thus this function
// returns two hashes. The second should be used to hash the message itself and // returns two hashes. The second should be used to hash the message itself and
// performs any needed preprocessing. // performs any needed preprocessing.
func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, os.Error) { func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) {
h := hashId.New() h := hashId.New()
if h == nil { if h == nil {
return nil, nil, error.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) return nil, nil, error_.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId)))
} }
switch sigType { switch sigType {
@ -292,7 +291,7 @@ func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Ha
return h, NewCanonicalTextHash(h), nil return h, NewCanonicalTextHash(h), nil
} }
return nil, nil, error.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) return nil, nil, error_.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
} }
// checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
@ -302,9 +301,9 @@ type checkReader struct {
md *MessageDetails md *MessageDetails
} }
func (cr checkReader) Read(buf []byte) (n int, err os.Error) { func (cr checkReader) Read(buf []byte) (n int, err error) {
n, err = cr.md.LiteralData.Body.Read(buf) n, err = cr.md.LiteralData.Body.Read(buf)
if err == os.EOF { if err == io.EOF {
mdcErr := cr.md.decrypted.Close() mdcErr := cr.md.decrypted.Close()
if mdcErr != nil { if mdcErr != nil {
err = mdcErr err = mdcErr
@ -322,10 +321,10 @@ type signatureCheckReader struct {
md *MessageDetails md *MessageDetails
} }
func (scr *signatureCheckReader) Read(buf []byte) (n int, err os.Error) { func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) {
n, err = scr.md.LiteralData.Body.Read(buf) n, err = scr.md.LiteralData.Body.Read(buf)
scr.wrappedHash.Write(buf[:n]) scr.wrappedHash.Write(buf[:n])
if err == os.EOF { if err == io.EOF {
var p packet.Packet var p packet.Packet
p, scr.md.SignatureError = scr.packets.Next() p, scr.md.SignatureError = scr.packets.Next()
if scr.md.SignatureError != nil { if scr.md.SignatureError != nil {
@ -334,7 +333,7 @@ func (scr *signatureCheckReader) Read(buf []byte) (n int, err os.Error) {
var ok bool var ok bool
if scr.md.Signature, ok = p.(*packet.Signature); !ok { if scr.md.Signature, ok = p.(*packet.Signature); !ok {
scr.md.SignatureError = error.StructuralError("LiteralData not followed by Signature") scr.md.SignatureError = error_.StructuralError("LiteralData not followed by Signature")
return return
} }
@ -356,7 +355,7 @@ func (scr *signatureCheckReader) Read(buf []byte) (n int, err os.Error) {
// CheckDetachedSignature takes a signed file and a detached signature and // CheckDetachedSignature takes a signed file and a detached signature and
// returns the signer if the signature is valid. If the signer isn't know, // returns the signer if the signature is valid. If the signer isn't know,
// UnknownIssuerError is returned. // UnknownIssuerError is returned.
func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err os.Error) { func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
p, err := packet.Read(signature) p, err := packet.Read(signature)
if err != nil { if err != nil {
return return
@ -364,16 +363,16 @@ func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signe
sig, ok := p.(*packet.Signature) sig, ok := p.(*packet.Signature)
if !ok { if !ok {
return nil, error.StructuralError("non signature packet found") return nil, error_.StructuralError("non signature packet found")
} }
if sig.IssuerKeyId == nil { if sig.IssuerKeyId == nil {
return nil, error.StructuralError("signature doesn't have an issuer") return nil, error_.StructuralError("signature doesn't have an issuer")
} }
keys := keyring.KeysById(*sig.IssuerKeyId) keys := keyring.KeysById(*sig.IssuerKeyId)
if len(keys) == 0 { if len(keys) == 0 {
return nil, error.UnknownIssuerError return nil, error_.UnknownIssuerError
} }
h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType) h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
@ -382,7 +381,7 @@ func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signe
} }
_, err = io.Copy(wrappedHash, signed) _, err = io.Copy(wrappedHash, signed)
if err != nil && err != os.EOF { if err != nil && err != io.EOF {
return return
} }
@ -400,12 +399,12 @@ func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signe
return return
} }
return nil, error.UnknownIssuerError return nil, error_.UnknownIssuerError
} }
// CheckArmoredDetachedSignature performs the same actions as // CheckArmoredDetachedSignature performs the same actions as
// CheckDetachedSignature but expects the signature to be armored. // CheckDetachedSignature but expects the signature to be armored.
func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err os.Error) { func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
body, err := readArmored(signature, SignatureType) body, err := readArmored(signature, SignatureType)
if err != nil { if err != nil {
return return

View File

@ -6,11 +6,10 @@ package openpgp
import ( import (
"bytes" "bytes"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"encoding/hex" "encoding/hex"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
@ -149,21 +148,21 @@ func TestSignedEncryptedMessage(t *testing.T) {
for i, test := range signedEncryptedMessageTests { for i, test := range signedEncryptedMessageTests {
expected := "Signed and encrypted message\n" expected := "Signed and encrypted message\n"
kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex)) kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex))
prompt := func(keys []Key, symmetric bool) ([]byte, os.Error) { prompt := func(keys []Key, symmetric bool) ([]byte, error) {
if symmetric { if symmetric {
t.Errorf("prompt: message was marked as symmetrically encrypted") t.Errorf("prompt: message was marked as symmetrically encrypted")
return nil, error.KeyIncorrectError return nil, error_.KeyIncorrectError
} }
if len(keys) == 0 { if len(keys) == 0 {
t.Error("prompt: no keys requested") t.Error("prompt: no keys requested")
return nil, error.KeyIncorrectError return nil, error_.KeyIncorrectError
} }
err := keys[0].PrivateKey.Decrypt([]byte("passphrase")) err := keys[0].PrivateKey.Decrypt([]byte("passphrase"))
if err != nil { if err != nil {
t.Errorf("prompt: error decrypting key: %s", err) t.Errorf("prompt: error decrypting key: %s", err)
return nil, error.KeyIncorrectError return nil, error_.KeyIncorrectError
} }
return nil, nil return nil, nil
@ -215,7 +214,7 @@ func TestUnspecifiedRecipient(t *testing.T) {
func TestSymmetricallyEncrypted(t *testing.T) { func TestSymmetricallyEncrypted(t *testing.T) {
expected := "Symmetrically encrypted.\n" expected := "Symmetrically encrypted.\n"
prompt := func(keys []Key, symmetric bool) ([]byte, os.Error) { prompt := func(keys []Key, symmetric bool) ([]byte, error) {
if len(keys) != 0 { if len(keys) != 0 {
t.Errorf("prompt: len(keys) = %d (want 0)", len(keys)) t.Errorf("prompt: len(keys) = %d (want 0)", len(keys))
} }
@ -287,7 +286,7 @@ func TestReadingArmoredPrivateKey(t *testing.T) {
func TestNoArmoredData(t *testing.T) { func TestNoArmoredData(t *testing.T) {
_, err := ReadArmoredKeyRing(bytes.NewBufferString("foo")) _, err := ReadArmoredKeyRing(bytes.NewBufferString("foo"))
if _, ok := err.(error.InvalidArgumentError); !ok { if _, ok := err.(error_.InvalidArgumentError); !ok {
t.Errorf("error was not an InvalidArgumentError: %s", err) t.Errorf("error was not an InvalidArgumentError: %s", err)
} }
} }

View File

@ -8,10 +8,9 @@ package s2k
import ( import (
"crypto" "crypto"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"hash" "hash"
"io" "io"
"os"
"strconv" "strconv"
) )
@ -76,7 +75,7 @@ func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) {
// Parse reads a binary specification for a string-to-key transformation from r // Parse reads a binary specification for a string-to-key transformation from r
// and returns a function which performs that transform. // and returns a function which performs that transform.
func Parse(r io.Reader) (f func(out, in []byte), err os.Error) { func Parse(r io.Reader) (f func(out, in []byte), err error) {
var buf [9]byte var buf [9]byte
_, err = io.ReadFull(r, buf[:2]) _, err = io.ReadFull(r, buf[:2])
@ -86,11 +85,11 @@ func Parse(r io.Reader) (f func(out, in []byte), err os.Error) {
hash, ok := HashIdToHash(buf[1]) hash, ok := HashIdToHash(buf[1])
if !ok { if !ok {
return nil, error.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1]))) return nil, error_.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1])))
} }
h := hash.New() h := hash.New()
if h == nil { if h == nil {
return nil, error.UnsupportedError("hash not available: " + strconv.Itoa(int(hash))) return nil, error_.UnsupportedError("hash not available: " + strconv.Itoa(int(hash)))
} }
switch buf[0] { switch buf[0] {
@ -120,12 +119,12 @@ func Parse(r io.Reader) (f func(out, in []byte), err os.Error) {
return f, nil return f, nil
} }
return nil, error.UnsupportedError("S2K function") return nil, error_.UnsupportedError("S2K function")
} }
// Serialize salts and stretches the given passphrase and writes the resulting // Serialize salts and stretches the given passphrase and writes the resulting
// key into key. It also serializes an S2K descriptor to w. // key into key. It also serializes an S2K descriptor to w.
func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte) os.Error { func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte) error {
var buf [11]byte var buf [11]byte
buf[0] = 3 /* iterated and salted */ buf[0] = 3 /* iterated and salted */
buf[1], _ = HashToHashId(crypto.SHA1) buf[1], _ = HashToHashId(crypto.SHA1)

View File

@ -7,45 +7,44 @@ package openpgp
import ( import (
"crypto" "crypto"
"crypto/openpgp/armor" "crypto/openpgp/armor"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/packet" "crypto/openpgp/packet"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"crypto/rand" "crypto/rand"
_ "crypto/sha256" _ "crypto/sha256"
"hash" "hash"
"io" "io"
"os"
"strconv" "strconv"
"time" "time"
) )
// DetachSign signs message with the private key from signer (which must // DetachSign signs message with the private key from signer (which must
// already have been decrypted) and writes the signature to w. // already have been decrypted) and writes the signature to w.
func DetachSign(w io.Writer, signer *Entity, message io.Reader) os.Error { func DetachSign(w io.Writer, signer *Entity, message io.Reader) error {
return detachSign(w, signer, message, packet.SigTypeBinary) return detachSign(w, signer, message, packet.SigTypeBinary)
} }
// ArmoredDetachSign signs message with the private key from signer (which // ArmoredDetachSign signs message with the private key from signer (which
// must already have been decrypted) and writes an armored signature to w. // must already have been decrypted) and writes an armored signature to w.
func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader) (err os.Error) { func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader) (err error) {
return armoredDetachSign(w, signer, message, packet.SigTypeBinary) return armoredDetachSign(w, signer, message, packet.SigTypeBinary)
} }
// DetachSignText signs message (after canonicalising the line endings) with // DetachSignText signs message (after canonicalising the line endings) with
// the private key from signer (which must already have been decrypted) and // the private key from signer (which must already have been decrypted) and
// writes the signature to w. // writes the signature to w.
func DetachSignText(w io.Writer, signer *Entity, message io.Reader) os.Error { func DetachSignText(w io.Writer, signer *Entity, message io.Reader) error {
return detachSign(w, signer, message, packet.SigTypeText) return detachSign(w, signer, message, packet.SigTypeText)
} }
// ArmoredDetachSignText signs message (after canonicalising the line endings) // ArmoredDetachSignText signs message (after canonicalising the line endings)
// with the private key from signer (which must already have been decrypted) // with the private key from signer (which must already have been decrypted)
// and writes an armored signature to w. // and writes an armored signature to w.
func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader) os.Error { func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader) error {
return armoredDetachSign(w, signer, message, packet.SigTypeText) return armoredDetachSign(w, signer, message, packet.SigTypeText)
} }
func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err os.Error) { func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err error) {
out, err := armor.Encode(w, SignatureType, nil) out, err := armor.Encode(w, SignatureType, nil)
if err != nil { if err != nil {
return return
@ -57,12 +56,12 @@ func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType p
return out.Close() return out.Close()
} }
func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err os.Error) { func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err error) {
if signer.PrivateKey == nil { if signer.PrivateKey == nil {
return error.InvalidArgumentError("signing key doesn't have a private key") return error_.InvalidArgumentError("signing key doesn't have a private key")
} }
if signer.PrivateKey.Encrypted { if signer.PrivateKey.Encrypted {
return error.InvalidArgumentError("signing key is encrypted") return error_.InvalidArgumentError("signing key is encrypted")
} }
sig := new(packet.Signature) sig := new(packet.Signature)
@ -103,7 +102,7 @@ type FileHints struct {
// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. // SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase.
// The resulting WriteCloser must be closed after the contents of the file have // The resulting WriteCloser must be closed after the contents of the file have
// been written. // been written.
func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints) (plaintext io.WriteCloser, err os.Error) { func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints) (plaintext io.WriteCloser, err error) {
if hints == nil { if hints == nil {
hints = &FileHints{} hints = &FileHints{}
} }
@ -148,12 +147,12 @@ func hashToHashId(h crypto.Hash) uint8 {
// it. hints contains optional information, that is also encrypted, that aids // it. hints contains optional information, that is also encrypted, that aids
// the recipients in processing the message. The resulting WriteCloser must // the recipients in processing the message. The resulting WriteCloser must
// be closed after the contents of the file have been written. // be closed after the contents of the file have been written.
func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints) (plaintext io.WriteCloser, err os.Error) { func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints) (plaintext io.WriteCloser, err error) {
var signer *packet.PrivateKey var signer *packet.PrivateKey
if signed != nil { if signed != nil {
signer = signed.signingKey().PrivateKey signer = signed.signingKey().PrivateKey
if signer == nil || signer.Encrypted { if signer == nil || signer.Encrypted {
return nil, error.InvalidArgumentError("signing key must be decrypted") return nil, error_.InvalidArgumentError("signing key must be decrypted")
} }
} }
@ -180,7 +179,7 @@ func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHint
for i := range to { for i := range to {
encryptKeys[i] = to[i].encryptionKey() encryptKeys[i] = to[i].encryptionKey()
if encryptKeys[i].PublicKey == nil { if encryptKeys[i].PublicKey == nil {
return nil, error.InvalidArgumentError("cannot encrypt a message to key id " + strconv.Uitob64(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys") return nil, error_.InvalidArgumentError("cannot encrypt a message to key id " + strconv.Uitob64(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
} }
sig := to[i].primaryIdentity().SelfSignature sig := to[i].primaryIdentity().SelfSignature
@ -198,7 +197,7 @@ func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHint
} }
if len(candidateCiphers) == 0 || len(candidateHashes) == 0 { if len(candidateCiphers) == 0 || len(candidateHashes) == 0 {
return nil, error.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms") return nil, error_.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
} }
cipher := packet.CipherFunction(candidateCiphers[0]) cipher := packet.CipherFunction(candidateCiphers[0])
@ -266,12 +265,12 @@ type signatureWriter struct {
signer *packet.PrivateKey signer *packet.PrivateKey
} }
func (s signatureWriter) Write(data []byte) (int, os.Error) { func (s signatureWriter) Write(data []byte) (int, error) {
s.h.Write(data) s.h.Write(data)
return s.literalData.Write(data) return s.literalData.Write(data)
} }
func (s signatureWriter) Close() os.Error { func (s signatureWriter) Close() error {
sig := &packet.Signature{ sig := &packet.Signature{
SigType: packet.SigTypeBinary, SigType: packet.SigTypeBinary,
PubKeyAlgo: s.signer.PubKeyAlgo, PubKeyAlgo: s.signer.PubKeyAlgo,
@ -299,10 +298,10 @@ type noOpCloser struct {
w io.Writer w io.Writer
} }
func (c noOpCloser) Write(data []byte) (n int, err os.Error) { func (c noOpCloser) Write(data []byte) (n int, err error) {
return c.w.Write(data) return c.w.Write(data)
} }
func (c noOpCloser) Close() os.Error { func (c noOpCloser) Close() error {
return nil return nil
} }

View File

@ -7,7 +7,6 @@ package openpgp
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"os"
"io" "io"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -106,7 +105,7 @@ func TestSymmetricEncryption(t *testing.T) {
t.Errorf("error closing plaintext writer: %s", err) t.Errorf("error closing plaintext writer: %s", err)
} }
md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, os.Error) { md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, error) {
return []byte("testing"), nil return []byte("testing"), nil
}) })
if err != nil { if err != nil {

View File

@ -6,10 +6,7 @@
// pseudorandom number generator. // pseudorandom number generator.
package rand package rand
import ( import "io"
"io"
"os"
)
// Reader is a global, shared instance of a cryptographically // Reader is a global, shared instance of a cryptographically
// strong pseudo-random generator. // strong pseudo-random generator.
@ -18,4 +15,4 @@ import (
var Reader io.Reader var Reader io.Reader
// Read is a helper function that calls Reader.Read. // Read is a helper function that calls Reader.Read.
func Read(b []byte) (n int, err os.Error) { return Reader.Read(b) } func Read(b []byte) (n int, err error) { return Reader.Read(b) }

View File

@ -30,7 +30,7 @@ type devReader struct {
mu sync.Mutex mu sync.Mutex
} }
func (r *devReader) Read(b []byte) (n int, err os.Error) { func (r *devReader) Read(b []byte) (n int, err error) {
r.mu.Lock() r.mu.Lock()
defer r.mu.Unlock() defer r.mu.Unlock()
if r.f == nil { if r.f == nil {
@ -71,7 +71,7 @@ type reader struct {
time, seed, dst, key [aes.BlockSize]byte time, seed, dst, key [aes.BlockSize]byte
} }
func (r *reader) Read(b []byte) (n int, err os.Error) { func (r *reader) Read(b []byte) (n int, err error) {
r.mu.Lock() r.mu.Lock()
defer r.mu.Unlock() defer r.mu.Unlock()
n = len(b) n = len(b)

View File

@ -23,7 +23,7 @@ type rngReader struct {
mu sync.Mutex mu sync.Mutex
} }
func (r *rngReader) Read(b []byte) (n int, err os.Error) { func (r *rngReader) Read(b []byte) (n int, err error) {
r.mu.Lock() r.mu.Lock()
if r.prov == 0 { if r.prov == 0 {
const provType = syscall.PROV_RSA_FULL const provType = syscall.PROV_RSA_FULL

View File

@ -12,7 +12,7 @@ import (
// Prime returns a number, p, of the given size, such that p is prime // Prime returns a number, p, of the given size, such that p is prime
// with high probability. // with high probability.
func Prime(rand io.Reader, bits int) (p *big.Int, err os.Error) { func Prime(rand io.Reader, bits int) (p *big.Int, err error) {
if bits < 1 { if bits < 1 {
err = os.EINVAL err = os.EINVAL
} }
@ -48,7 +48,7 @@ func Prime(rand io.Reader, bits int) (p *big.Int, err os.Error) {
} }
// Int returns a uniform random value in [0, max). // Int returns a uniform random value in [0, max).
func Int(rand io.Reader, max *big.Int) (n *big.Int, err os.Error) { func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) {
k := (max.BitLen() + 7) / 8 k := (max.BitLen() + 7) / 8
// b is the number of bits in the most significant byte of max. // b is the number of bits in the most significant byte of max.

View File

@ -9,10 +9,7 @@ package rc4
// BUG(agl): RC4 is in common use but has design weaknesses that make // BUG(agl): RC4 is in common use but has design weaknesses that make
// it a poor choice for new protocols. // it a poor choice for new protocols.
import ( import "strconv"
"os"
"strconv"
)
// A Cipher is an instance of RC4 using a particular key. // A Cipher is an instance of RC4 using a particular key.
type Cipher struct { type Cipher struct {
@ -22,13 +19,13 @@ type Cipher struct {
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/rc4: invalid key size " + strconv.Itoa(int(k)) return "crypto/rc4: invalid key size " + strconv.Itoa(int(k))
} }
// NewCipher creates and returns a new Cipher. The key argument should be the // NewCipher creates and returns a new Cipher. The key argument should be the
// RC4 key, at least 1 byte and at most 256 bytes. // RC4 key, at least 1 byte and at most 256 bytes.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
k := len(key) k := len(key)
if k < 1 || k > 256 { if k < 1 || k > 256 {
return nil, KeySizeError(k) return nil, KeySizeError(k)

View File

@ -12,7 +12,6 @@ package ripemd160
import ( import (
"crypto" "crypto"
"hash" "hash"
"os"
) )
func init() { func init() {
@ -56,7 +55,7 @@ func New() hash.Hash {
func (d *digest) Size() int { return Size } func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) { func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p) nn = len(p)
d.tc += uint64(nn) d.tc += uint64(nn)
if d.nx > 0 { if d.nx > 0 {

Some files were not shown because too many files have changed in this diff Show More