Ejemplo n.º 1
0
func FuzzAll(data []byte) int {
	cfg, err := gif.DecodeConfig(bytes.NewReader(data))
	if err != nil {
		return 0
	}
	if cfg.Width*cfg.Height > 1e6 {
		return 0
	}
	img, err := gif.DecodeAll(bytes.NewReader(data))
	if err != nil {
		return 0
	}
	w := new(bytes.Buffer)
	err = gif.EncodeAll(w, img)
	if err != nil {
		panic(err)
	}
	img1, err := gif.DecodeAll(w)
	if err != nil {
		panic(err)
	}
	if img.LoopCount == 0 && img1.LoopCount == -1 {
		// https://github.com/golang/go/issues/11287
		img1.LoopCount = 0
	}
	// https://github.com/golang/go/issues/11288
	img1.Disposal = img.Disposal
	if !fuzz.DeepEqual(img, img1) {
		fmt.Printf("gif0: %#v\n", img)
		fmt.Printf("gif1: %#v\n", img1)
		panic("gif changed")
	}
	return 1
}
Ejemplo n.º 2
0
func Fuzz(data []byte) int {
	cfg, err := gif.DecodeConfig(bytes.NewReader(data))
	if err != nil {
		return 0
	}
	if cfg.Width*cfg.Height > 1e6 {
		return 0
	}
	img, err := gif.Decode(bytes.NewReader(data))
	if err != nil {
		return 0
	}
	for c := 1; c <= 256; c += 21 {
		var w bytes.Buffer
		err = gif.Encode(&w, img, &gif.Options{NumColors: c})
		if err != nil {
			panic(err)
		}
		img1, err := gif.Decode(&w)
		if err != nil {
			panic(err)
		}
		b0 := img.Bounds()
		b1 := img1.Bounds()
		if b0.Max.X-b0.Min.X != b1.Max.X-b1.Min.X || b0.Max.Y-b0.Min.Y != b1.Max.Y-b1.Min.Y {
			fmt.Printf("img0: %#v\n", img.Bounds())
			fmt.Printf("img1: %#v\n", img1.Bounds())
			panic("bounds changed")
		}
	}
	return 1
}
Ejemplo n.º 3
0
func parseGIF(r io.Reader) (int, int, error) {
	cfg, err := gif.DecodeConfig(r)
	if err != nil {
		return 0, 0, err
	}

	return cfg.Width, cfg.Height, nil
}
Ejemplo n.º 4
0
func decodeGIF(f multipart.File) (*Image, error) {
	var image Image

	ic, err := gif.DecodeConfig(f)
	_, err = f.Seek(0, 0)
	i, err := gif.Decode(f)

	if err != nil {
		return nil, fmt.Errorf("Could not decode GIF file.")
	}

	image.Config = ic
	image.Image = i

	return &image, nil
}
Ejemplo n.º 5
0
func TestHandler(t *testing.T) {
	hdr := &Handler{
		Processor: ProcessorFunc(func(g *gif.GIF, params imageserver.Params) (*gif.GIF, error) {
			return g, nil
		}),
	}
	im, err := hdr.Handle(testdata.Animated, imageserver.Params{})
	if err != nil {
		t.Fatal(err)
	}
	if im.Format != "gif" {
		t.Fatalf("unexpected Format: got %s, want %s", im.Format, "gif")
	}
	_, err = gif.DecodeConfig(bytes.NewReader(im.Data))
	if err != nil {
		t.Fatal(err)
	}
}
Ejemplo n.º 6
0
// webBugHandler blocks and blacklist web-bugs
// This handler will make the request and based on the
// response it will blacklist the URL if it finds a web-bug
// or hijack the request and serve a pixel of its own.
func webBugHandler(handler http.Handler) http.Handler {
	url_blacklist := []string{}
	fn := func(w http.ResponseWriter, r *http.Request) {

		urlStr := fmt.Sprintf("%s://%s%s", r.URL.Scheme, r.URL.Host, r.URL.Path)

		// Block web bug if it has been requested befored
		for _, u := range url_blacklist {
			if u == urlStr {
				log.Printf("INFO redirect-webbug %s", urlStr)
				atomic.AddUint64(&webBugCounter, 1)
				http.Redirect(w, r, "http://pepper/pixel.gif", 302)
				return
			}
		}

		// Get the response
		resp, err := http.DefaultClient.Get(r.RequestURI)
		if err != nil {
			log.Printf("ERROR PROXY %v", err.Error())
			handler.ServeHTTP(w, r)
			return
		}
		defer resp.Body.Close()

		// Add Web Bug URL to url url_blacklist
		if resp.ContentLength < 100 && resp.Header.Get("Content-Type") == "image/gif" {
			img, err := gif.DecodeConfig(resp.Body)
			if err != nil {
				log.Printf("ERROR %v\n", err)
				handler.ServeHTTP(w, r)
				return
			}
			if img.Width*img.Height == 1 {
				log.Printf("INFO blacklisted-url %s", urlStr)
				url_blacklist = append(url_blacklist, urlStr)
			}
		}

		handler.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}
Ejemplo n.º 7
0
func (this *UploadedFile) Dimensions() (int, int, error) {
	f, err := os.Open(this.path)
	if err != nil {
		return 0, 0, err
	}

	var cfg image.Config
	switch true {
	case this.IsGif():
		cfg, err = gif.DecodeConfig(f)
	case this.IsPng():
		cfg, err = png.DecodeConfig(f)
	case this.IsJpeg():
		cfg, err = jpeg.DecodeConfig(f)
	default:
		return 0, 0, errors.New("Invalid mime type!")
	}

	if err != nil {
		return 0, 0, err
	}

	return cfg.Width, cfg.Height, nil
}
Ejemplo n.º 8
0
func UploadHandler(conn *rtgo.Conn, data []byte, msg *rtgo.Message) {
	schema := make(map[string]interface{})
	err := json.Unmarshal(msg.Payload, &schema)
	if err != nil {
		log.Println(err)
		return
	}
	topic := schema["topic"].(string)
	now := time.Now()
	schema["timestamp"] = fmt.Sprintf("%d/%d/%d(%s)%d:%d:%d", now.Month(), now.Day(), now.Year(), now.Weekday().String()[:3], now.Hour(), now.Minute(), now.Second())
	schema["uuid"] = uuid.NewV4().String()
	hash := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s%s", schema["timestamp"], schema["uuid"]))))[:9]
	schema["hash"] = hash
	if file, ok := schema["file"].(string); ok {
		file_path := fmt.Sprintf("./static/images/uploads/%s", schema["file_name"])
		fdata, err := dataurl.DecodeString(file)
		if err != nil {
			log.Println(err)
			return
		}
		ioutil.WriteFile(file_path, fdata.Data, 0775)
		saved_file, err := os.Open(file_path)
		if err != nil {
			log.Println(err)
			return
		}
		var config image.Config
		if schema["file_mime"] == "image/jpeg" {
			config, err = jpeg.DecodeConfig(saved_file)
		} else if schema["file_mime"] == "image/png" {
			config, err = png.DecodeConfig(saved_file)
		} else if schema["file_mime"] == "image/gif" {
			config, err = gif.DecodeConfig(saved_file)
		}
		schema["file_dimensions"] = fmt.Sprintf("%dx%d", config.Width, config.Height)
		delete(schema, "file")
	}
	if schema["type"] == "thread" {
		if err := app.DB.InsertObj(topic, hash, schema); err != nil {
			return
		}
	} else if schema["type"] == "reply" {
		thread := schema["thread"].(string)
		if obj, err := app.DB.GetObj(topic, thread); err == nil {
			thisobj := obj.(map[string]interface{})
			replies := thisobj["replies"].(map[string]interface{})
			replies[hash] = schema
			tagging := schema["tagging"].([]interface{})
			for _, tag := range tagging {
				if tag.(string) == thread {
					thisobj["taggedBy"] = append(thisobj["taggedBy"].([]interface{}), hash)
				} else if _, ok := replies[tag.(string)]; ok {
					reply := replies[tag.(string)].(map[string]interface{})
					reply["taggedBy"] = append(reply["taggedBy"].([]interface{}), hash)
				}
			}
			if err := app.DB.InsertObj(topic, thread, thisobj); err != nil {
				log.Println(err)
				return
			}
		} else {
			log.Println(err)
			return
		}
	}
	payload, err := json.Marshal(&schema)
	if err != nil {
		log.Println(err)
		return
	}
	response := &rtgo.Message{
		RoomLength:    len(schema["topic"].(string)),
		Room:          schema["topic"].(string),
		EventLength:   len("new-" + schema["type"].(string)),
		Event:         "new-" + schema["type"].(string),
		DstLength:     0,
		Dst:           "",
		SrcLength:     len(conn.Id),
		Src:           conn.Id,
		PayloadLength: len(payload),
		Payload:       payload,
	}
	binary_response := rtgo.MessageToBytes(response)
	conn.Emit(binary_response, response)
	conn.Send <- binary_response
}
Ejemplo n.º 9
0
func _decode_album(src string) (Album, Album) {
	photoList, _ := filepath.Glob(src + "\\*")
	var album Album
	var albumSummary Album
	var imgInfo image.Config
	var comment_str string
	decoder := mahonia.NewDecoder("UTF-16LE")

	for key := range photoList {
		fullFileName := photoList[key]

		//读取图片长宽等信息
		photo_fi, err := os.Open(fullFileName)
		if err != nil {
			log.Fatal(err)
		}
		defer photo_fi.Close()
		switch strings.ToLower(path.Ext(fullFileName)) {
		case ".jpg", ".jpeg":
			imgInfo, err = jpeg.DecodeConfig(photo_fi)
			if err != nil {
				fmt.Println("图片解析错误:" + fullFileName)
				os.Exit(0)
			}

		case ".png":
			imgInfo, err = png.DecodeConfig(photo_fi)
			if err != nil {
				fmt.Println("图片解析错误:" + fullFileName)
				os.Exit(0)
			}

		case ".gif":
			imgInfo, err = gif.DecodeConfig(photo_fi)
			if err != nil {
				fmt.Println("图片解析错误:" + fullFileName)
				os.Exit(0)
			}
		default:
			continue
		}

		//读取图片评注信息
		photo_fi, err = os.Open(fullFileName)
		if err != nil {
			log.Fatal(err)
		}
		photo_exif, err := exif.Decode(photo_fi)
		if err != nil {
			comment_str = ""
		} else {
			comment, err := photo_exif.Get(exif.UserComment)
			if err != nil {
				comment_str = ""
			} else {
				comment_str = decoder.CConvertString(comment.Val)
			}
		}
		photo_fi.Close()

		var bigPhotoFileName, photoFileName string
		photoFileName = filepath.Base(fullFileName)
		if strings.ToLower(path.Ext(fullFileName)) == ".gif" || imgInfo.Width < siteInfo.ImgWidth { //global var : SiteInfo
			bigPhotoFileName = photoFileName
		} else {
			bigPhotoFileName = "big_" + photoFileName
		}

		//追加图片信息
		var photo = Photo{Src: fullFileName, Comment: comment_str, Width: imgInfo.Width, Height: imgInfo.Height, PhotoFileName: photoFileName, BigPhotoFileName: bigPhotoFileName}
		album = append(album, photo)
		if strings.HasPrefix(filepath.Base(fullFileName), "~") {
			albumSummary = append(albumSummary, photo)
		}

	}
	return album, albumSummary
}