102 lines
2.0 KiB
Go
102 lines
2.0 KiB
Go
package messenger
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"github.com/disintegration/imaging"
|
|
"image"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
// imaging handles JPEG APP1 orientation. PNG stores the same TIFF data in eXIf.
|
|
// Read only inside the already capped upload, with bounds checks on every IFD.
|
|
func pngOrientation(path string) int {
|
|
f, e := os.Open(path)
|
|
if e != nil {
|
|
return 1
|
|
}
|
|
defer f.Close()
|
|
if _, e = f.Seek(8, io.SeekStart); e != nil {
|
|
return 1
|
|
}
|
|
for {
|
|
var h [8]byte
|
|
if _, e = io.ReadFull(f, h[:]); e != nil {
|
|
return 1
|
|
}
|
|
n := binary.BigEndian.Uint32(h[:4])
|
|
if n > maxUpload {
|
|
return 1
|
|
}
|
|
if string(h[4:]) == "eXIf" {
|
|
b := make([]byte, n)
|
|
if _, e = io.ReadFull(f, b); e != nil {
|
|
return 1
|
|
}
|
|
return tiffOrientation(b)
|
|
}
|
|
if string(h[4:]) == "IEND" {
|
|
return 1
|
|
}
|
|
if _, e = f.Seek(int64(n)+4, io.SeekCurrent); e != nil {
|
|
return 1
|
|
}
|
|
}
|
|
}
|
|
func tiffOrientation(b []byte) int {
|
|
if len(b) < 8 {
|
|
return 1
|
|
}
|
|
var order binary.ByteOrder
|
|
switch string(b[:2]) {
|
|
case "II":
|
|
order = binary.LittleEndian
|
|
case "MM":
|
|
order = binary.BigEndian
|
|
default:
|
|
return 1
|
|
}
|
|
if order.Uint16(b[2:4]) != 42 {
|
|
return 1
|
|
}
|
|
offset := uint64(order.Uint32(b[4:8]))
|
|
if offset+2 > uint64(len(b)) {
|
|
return 1
|
|
}
|
|
count := int(order.Uint16(b[offset : offset+2]))
|
|
for i := 0; i < count; i++ {
|
|
pos := offset + 2 + uint64(i)*12
|
|
if pos+12 > uint64(len(b)) {
|
|
return 1
|
|
}
|
|
entry := b[pos : pos+12]
|
|
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
|
|
v := int(order.Uint16(entry[8:10]))
|
|
if v >= 1 && v <= 8 {
|
|
return v
|
|
}
|
|
return 1
|
|
}
|
|
}
|
|
return 1
|
|
}
|
|
func orientPNG(img image.Image, orientation int) image.Image {
|
|
switch orientation {
|
|
case 2:
|
|
return imaging.FlipH(img)
|
|
case 3:
|
|
return imaging.Rotate180(img)
|
|
case 4:
|
|
return imaging.FlipV(img)
|
|
case 5:
|
|
return imaging.Transpose(img)
|
|
case 6:
|
|
return imaging.Rotate270(img)
|
|
case 7:
|
|
return imaging.Transverse(img)
|
|
case 8:
|
|
return imaging.Rotate90(img)
|
|
}
|
|
return img
|
|
}
|