1/*
2** Zabbix
3** Copyright (C) 2001-2021 Zabbix SIA
4**
5** This program is free software; you can redistribute it and/or modify
6** it under the terms of the GNU General Public License as published by
7** the Free Software Foundation; either version 2 of the License, or
8** (at your option) any later version.
9**
10** This program is distributed in the hope that it will be useful,
11** but WITHOUT ANY WARRANTY; without even the implied warranty of
12** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13** GNU General Public License for more details.
14**
15** You should have received a copy of the GNU General Public License
16** along with this program; if not, write to the Free Software
17** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18**/
19
20package file
21
22import (
23	"crypto/md5"
24	"errors"
25	"fmt"
26	"io"
27	"time"
28)
29
30func (p *Plugin) exportMd5sum(params []string) (result interface{}, err error) {
31	if len(params) > 1 {
32		return nil, errors.New("Too many parameters.")
33	}
34	if len(params) == 0 || params[0] == "" {
35		return nil, errors.New("Invalid first parameter.")
36	}
37
38	start := time.Now()
39
40	file, err := stdOs.Open(params[0])
41	if err != nil {
42		return nil, fmt.Errorf("Cannot open file: %s", err)
43	}
44	defer file.Close()
45
46	var bnum int64
47	bnum = 16 * 1024
48	buf := make([]byte, bnum)
49
50	hash := md5.New()
51
52	for bnum > 0 {
53		bnum, _ = io.CopyBuffer(hash, file, buf)
54		if time.Since(start) > time.Duration(p.options.Timeout)*time.Second {
55			return nil, errors.New("Timeout while processing item")
56		}
57	}
58
59	return fmt.Sprintf("%x", hash.Sum(nil)), nil
60
61}
62