utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. package oss
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "hash/crc32"
  7. "hash/crc64"
  8. "io"
  9. "net/http"
  10. "os"
  11. "os/exec"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. var sys_name string
  18. var sys_release string
  19. var sys_machine string
  20. func init() {
  21. sys_name = runtime.GOOS
  22. sys_release = "-"
  23. sys_machine = runtime.GOARCH
  24. if out, err := exec.Command("uname", "-s").CombinedOutput(); err == nil {
  25. sys_name = string(bytes.TrimSpace(out))
  26. }
  27. if out, err := exec.Command("uname", "-r").CombinedOutput(); err == nil {
  28. sys_release = string(bytes.TrimSpace(out))
  29. }
  30. if out, err := exec.Command("uname", "-m").CombinedOutput(); err == nil {
  31. sys_machine = string(bytes.TrimSpace(out))
  32. }
  33. }
  34. // userAgent gets user agent
  35. // It has the SDK version information, OS information and GO version
  36. func userAgent() string {
  37. sys := getSysInfo()
  38. return fmt.Sprintf("aliyun-sdk-go/%s (%s/%s/%s;%s)", Version, sys.name,
  39. sys.release, sys.machine, runtime.Version())
  40. }
  41. type sysInfo struct {
  42. name string // OS name such as windows/Linux
  43. release string // OS version 2.6.32-220.23.2.ali1089.el5.x86_64 etc
  44. machine string // CPU type amd64/x86_64
  45. }
  46. // getSysInfo gets system info
  47. // gets the OS information and CPU type
  48. func getSysInfo() sysInfo {
  49. return sysInfo{name: sys_name, release: sys_release, machine: sys_machine}
  50. }
  51. // GetRangeConfig gets the download range from the options.
  52. func GetRangeConfig(options []Option) (*UnpackedRange, error) {
  53. rangeOpt, err := FindOption(options, HTTPHeaderRange, nil)
  54. if err != nil || rangeOpt == nil {
  55. return nil, err
  56. }
  57. return ParseRange(rangeOpt.(string))
  58. }
  59. // UnpackedRange
  60. type UnpackedRange struct {
  61. HasStart bool // Flag indicates if the start point is specified
  62. HasEnd bool // Flag indicates if the end point is specified
  63. Start int64 // Start point
  64. End int64 // End point
  65. }
  66. // InvalidRangeError returns invalid range error
  67. func InvalidRangeError(r string) error {
  68. return fmt.Errorf("InvalidRange %s", r)
  69. }
  70. func GetRangeString(unpackRange UnpackedRange) string {
  71. var strRange string
  72. if unpackRange.HasStart && unpackRange.HasEnd {
  73. strRange = fmt.Sprintf("%d-%d", unpackRange.Start, unpackRange.End)
  74. } else if unpackRange.HasStart {
  75. strRange = fmt.Sprintf("%d-", unpackRange.Start)
  76. } else if unpackRange.HasEnd {
  77. strRange = fmt.Sprintf("-%d", unpackRange.End)
  78. }
  79. return strRange
  80. }
  81. // ParseRange parse various styles of range such as bytes=M-N
  82. func ParseRange(normalizedRange string) (*UnpackedRange, error) {
  83. var err error
  84. hasStart := false
  85. hasEnd := false
  86. var start int64
  87. var end int64
  88. // Bytes==M-N or ranges=M-N
  89. nrSlice := strings.Split(normalizedRange, "=")
  90. if len(nrSlice) != 2 || nrSlice[0] != "bytes" {
  91. return nil, InvalidRangeError(normalizedRange)
  92. }
  93. // Bytes=M-N,X-Y
  94. rSlice := strings.Split(nrSlice[1], ",")
  95. rStr := rSlice[0]
  96. if strings.HasSuffix(rStr, "-") { // M-
  97. startStr := rStr[:len(rStr)-1]
  98. start, err = strconv.ParseInt(startStr, 10, 64)
  99. if err != nil {
  100. return nil, InvalidRangeError(normalizedRange)
  101. }
  102. hasStart = true
  103. } else if strings.HasPrefix(rStr, "-") { // -N
  104. len := rStr[1:]
  105. end, err = strconv.ParseInt(len, 10, 64)
  106. if err != nil {
  107. return nil, InvalidRangeError(normalizedRange)
  108. }
  109. if end == 0 { // -0
  110. return nil, InvalidRangeError(normalizedRange)
  111. }
  112. hasEnd = true
  113. } else { // M-N
  114. valSlice := strings.Split(rStr, "-")
  115. if len(valSlice) != 2 {
  116. return nil, InvalidRangeError(normalizedRange)
  117. }
  118. start, err = strconv.ParseInt(valSlice[0], 10, 64)
  119. if err != nil {
  120. return nil, InvalidRangeError(normalizedRange)
  121. }
  122. hasStart = true
  123. end, err = strconv.ParseInt(valSlice[1], 10, 64)
  124. if err != nil {
  125. return nil, InvalidRangeError(normalizedRange)
  126. }
  127. hasEnd = true
  128. }
  129. return &UnpackedRange{hasStart, hasEnd, start, end}, nil
  130. }
  131. // AdjustRange returns adjusted range, adjust the range according to the length of the file
  132. func AdjustRange(ur *UnpackedRange, size int64) (start, end int64) {
  133. if ur == nil {
  134. return 0, size
  135. }
  136. if ur.HasStart && ur.HasEnd {
  137. start = ur.Start
  138. end = ur.End + 1
  139. if ur.Start < 0 || ur.Start >= size || ur.End > size || ur.Start > ur.End {
  140. start = 0
  141. end = size
  142. }
  143. } else if ur.HasStart {
  144. start = ur.Start
  145. end = size
  146. if ur.Start < 0 || ur.Start >= size {
  147. start = 0
  148. }
  149. } else if ur.HasEnd {
  150. start = size - ur.End
  151. end = size
  152. if ur.End < 0 || ur.End > size {
  153. start = 0
  154. end = size
  155. }
  156. }
  157. return
  158. }
  159. // GetNowSec returns Unix time, the number of seconds elapsed since January 1, 1970 UTC.
  160. // gets the current time in Unix time, in seconds.
  161. func GetNowSec() int64 {
  162. return time.Now().Unix()
  163. }
  164. // GetNowNanoSec returns t as a Unix time, the number of nanoseconds elapsed
  165. // since January 1, 1970 UTC. The result is undefined if the Unix time
  166. // in nanoseconds cannot be represented by an int64. Note that this
  167. // means the result of calling UnixNano on the zero Time is undefined.
  168. // gets the current time in Unix time, in nanoseconds.
  169. func GetNowNanoSec() int64 {
  170. return time.Now().UnixNano()
  171. }
  172. // GetNowGMT gets the current time in GMT format.
  173. func GetNowGMT() string {
  174. return time.Now().UTC().Format(http.TimeFormat)
  175. }
  176. // FileChunk is the file chunk definition
  177. type FileChunk struct {
  178. Number int // Chunk number
  179. Offset int64 // Chunk offset
  180. Size int64 // Chunk size.
  181. }
  182. // SplitFileByPartNum splits big file into parts by the num of parts.
  183. // Split the file with specified parts count, returns the split result when error is nil.
  184. func SplitFileByPartNum(fileName string, chunkNum int) ([]FileChunk, error) {
  185. if chunkNum <= 0 || chunkNum > 10000 {
  186. return nil, errors.New("chunkNum invalid")
  187. }
  188. file, err := os.Open(fileName)
  189. if err != nil {
  190. return nil, err
  191. }
  192. defer file.Close()
  193. stat, err := file.Stat()
  194. if err != nil {
  195. return nil, err
  196. }
  197. if int64(chunkNum) > stat.Size() {
  198. return nil, errors.New("oss: chunkNum invalid")
  199. }
  200. var chunks []FileChunk
  201. var chunk = FileChunk{}
  202. var chunkN = (int64)(chunkNum)
  203. for i := int64(0); i < chunkN; i++ {
  204. chunk.Number = int(i + 1)
  205. chunk.Offset = i * (stat.Size() / chunkN)
  206. if i == chunkN-1 {
  207. chunk.Size = stat.Size()/chunkN + stat.Size()%chunkN
  208. } else {
  209. chunk.Size = stat.Size() / chunkN
  210. }
  211. chunks = append(chunks, chunk)
  212. }
  213. return chunks, nil
  214. }
  215. // SplitFileByPartSize splits big file into parts by the size of parts.
  216. // Splits the file by the part size. Returns the FileChunk when error is nil.
  217. func SplitFileByPartSize(fileName string, chunkSize int64) ([]FileChunk, error) {
  218. if chunkSize <= 0 {
  219. return nil, errors.New("chunkSize invalid")
  220. }
  221. file, err := os.Open(fileName)
  222. if err != nil {
  223. return nil, err
  224. }
  225. defer file.Close()
  226. stat, err := file.Stat()
  227. if err != nil {
  228. return nil, err
  229. }
  230. var chunkN = stat.Size() / chunkSize
  231. if chunkN >= 10000 {
  232. return nil, errors.New("Too many parts, please increase part size")
  233. }
  234. var chunks []FileChunk
  235. var chunk = FileChunk{}
  236. for i := int64(0); i < chunkN; i++ {
  237. chunk.Number = int(i + 1)
  238. chunk.Offset = i * chunkSize
  239. chunk.Size = chunkSize
  240. chunks = append(chunks, chunk)
  241. }
  242. if stat.Size()%chunkSize > 0 {
  243. chunk.Number = len(chunks) + 1
  244. chunk.Offset = int64(len(chunks)) * chunkSize
  245. chunk.Size = stat.Size() % chunkSize
  246. chunks = append(chunks, chunk)
  247. }
  248. return chunks, nil
  249. }
  250. // GetPartEnd calculates the end position
  251. func GetPartEnd(begin int64, total int64, per int64) int64 {
  252. if begin+per > total {
  253. return total - 1
  254. }
  255. return begin + per - 1
  256. }
  257. // CrcTable returns the table constructed from the specified polynomial
  258. var CrcTable = func() *crc64.Table {
  259. return crc64.MakeTable(crc64.ECMA)
  260. }
  261. // CrcTable returns the table constructed from the specified polynomial
  262. var crc32Table = func() *crc32.Table {
  263. return crc32.MakeTable(crc32.IEEE)
  264. }
  265. // choiceTransferPartOption choices valid option supported by Uploadpart or DownloadPart
  266. func ChoiceTransferPartOption(options []Option) []Option {
  267. var outOption []Option
  268. listener, _ := FindOption(options, progressListener, nil)
  269. if listener != nil {
  270. outOption = append(outOption, Progress(listener.(ProgressListener)))
  271. }
  272. payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
  273. if payer != nil {
  274. outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
  275. }
  276. versionId, _ := FindOption(options, "versionId", nil)
  277. if versionId != nil {
  278. outOption = append(outOption, VersionId(versionId.(string)))
  279. }
  280. trafficLimit, _ := FindOption(options, HTTPHeaderOssTrafficLimit, nil)
  281. if trafficLimit != nil {
  282. speed, _ := strconv.ParseInt(trafficLimit.(string), 10, 64)
  283. outOption = append(outOption, TrafficLimitHeader(speed))
  284. }
  285. respHeader, _ := FindOption(options, responseHeader, nil)
  286. if respHeader != nil {
  287. outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
  288. }
  289. return outOption
  290. }
  291. // ChoiceCompletePartOption choices valid option supported by CompleteMulitiPart
  292. func ChoiceCompletePartOption(options []Option) []Option {
  293. var outOption []Option
  294. listener, _ := FindOption(options, progressListener, nil)
  295. if listener != nil {
  296. outOption = append(outOption, Progress(listener.(ProgressListener)))
  297. }
  298. payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
  299. if payer != nil {
  300. outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
  301. }
  302. acl, _ := FindOption(options, HTTPHeaderOssObjectACL, nil)
  303. if acl != nil {
  304. outOption = append(outOption, ObjectACL(ACLType(acl.(string))))
  305. }
  306. callback, _ := FindOption(options, HTTPHeaderOssCallback, nil)
  307. if callback != nil {
  308. outOption = append(outOption, Callback(callback.(string)))
  309. }
  310. callbackVar, _ := FindOption(options, HTTPHeaderOssCallbackVar, nil)
  311. if callbackVar != nil {
  312. outOption = append(outOption, CallbackVar(callbackVar.(string)))
  313. }
  314. respHeader, _ := FindOption(options, responseHeader, nil)
  315. if respHeader != nil {
  316. outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
  317. }
  318. forbidOverWrite, _ := FindOption(options, HTTPHeaderOssForbidOverWrite, nil)
  319. if forbidOverWrite != nil {
  320. if forbidOverWrite.(string) == "true" {
  321. outOption = append(outOption, ForbidOverWrite(true))
  322. } else {
  323. outOption = append(outOption, ForbidOverWrite(false))
  324. }
  325. }
  326. return outOption
  327. }
  328. // ChoiceAbortPartOption choices valid option supported by AbortMultipartUpload
  329. func ChoiceAbortPartOption(options []Option) []Option {
  330. var outOption []Option
  331. payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
  332. if payer != nil {
  333. outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
  334. }
  335. respHeader, _ := FindOption(options, responseHeader, nil)
  336. if respHeader != nil {
  337. outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
  338. }
  339. return outOption
  340. }
  341. // ChoiceHeadObjectOption choices valid option supported by HeadObject
  342. func ChoiceHeadObjectOption(options []Option) []Option {
  343. var outOption []Option
  344. // not select HTTPHeaderRange to get whole object length
  345. payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
  346. if payer != nil {
  347. outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
  348. }
  349. versionId, _ := FindOption(options, "versionId", nil)
  350. if versionId != nil {
  351. outOption = append(outOption, VersionId(versionId.(string)))
  352. }
  353. respHeader, _ := FindOption(options, responseHeader, nil)
  354. if respHeader != nil {
  355. outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
  356. }
  357. return outOption
  358. }
  359. func CheckBucketName(bucketName string) error {
  360. nameLen := len(bucketName)
  361. if nameLen < 3 || nameLen > 63 {
  362. return fmt.Errorf("bucket name %s len is between [3-63],now is %d", bucketName, nameLen)
  363. }
  364. for _, v := range bucketName {
  365. if !(('a' <= v && v <= 'z') || ('0' <= v && v <= '9') || v == '-') {
  366. return fmt.Errorf("bucket name %s can only include lowercase letters, numbers, and -", bucketName)
  367. }
  368. }
  369. if bucketName[0] == '-' || bucketName[nameLen-1] == '-' {
  370. return fmt.Errorf("bucket name %s must start and end with a lowercase letter or number", bucketName)
  371. }
  372. return nil
  373. }
  374. func GetReaderLen(reader io.Reader) (int64, error) {
  375. var contentLength int64
  376. var err error
  377. switch v := reader.(type) {
  378. case *bytes.Buffer:
  379. contentLength = int64(v.Len())
  380. case *bytes.Reader:
  381. contentLength = int64(v.Len())
  382. case *strings.Reader:
  383. contentLength = int64(v.Len())
  384. case *os.File:
  385. fInfo, fError := v.Stat()
  386. if fError != nil {
  387. err = fmt.Errorf("can't get reader content length,%s", fError.Error())
  388. } else {
  389. contentLength = fInfo.Size()
  390. }
  391. case *io.LimitedReader:
  392. contentLength = int64(v.N)
  393. case *LimitedReadCloser:
  394. contentLength = int64(v.N)
  395. default:
  396. err = fmt.Errorf("can't get reader content length,unkown reader type")
  397. }
  398. return contentLength, err
  399. }
  400. func LimitReadCloser(r io.Reader, n int64) io.Reader {
  401. var lc LimitedReadCloser
  402. lc.R = r
  403. lc.N = n
  404. return &lc
  405. }
  406. // LimitedRC support Close()
  407. type LimitedReadCloser struct {
  408. io.LimitedReader
  409. }
  410. func (lc *LimitedReadCloser) Close() error {
  411. if closer, ok := lc.R.(io.ReadCloser); ok {
  412. return closer.Close()
  413. }
  414. return nil
  415. }
  416. type DiscardReadCloser struct {
  417. RC io.ReadCloser
  418. Discard int
  419. }
  420. func (drc *DiscardReadCloser) Read(b []byte) (int, error) {
  421. n, err := drc.RC.Read(b)
  422. if drc.Discard == 0 || n <= 0 {
  423. return n, err
  424. }
  425. if n <= drc.Discard {
  426. drc.Discard -= n
  427. return 0, err
  428. }
  429. realLen := n - drc.Discard
  430. copy(b[0:realLen], b[drc.Discard:n])
  431. drc.Discard = 0
  432. return realLen, err
  433. }
  434. func (drc *DiscardReadCloser) Close() error {
  435. closer, ok := drc.RC.(io.ReadCloser)
  436. if ok {
  437. return closer.Close()
  438. }
  439. return nil
  440. }