pidl/NDR/Parser: split off ParseArrayPullGetSize() and ParseArrayPullGetLength()
[Samba.git] / source3 / lib / util_transfer_file.c
blob1e3b76fc770287be8243002c8e37d0cb5335328f
1 /*
2 * Unix SMB/CIFS implementation.
3 * Utility functions to transfer files.
5 * Copyright (C) Jeremy Allison 2001-2002
6 * Copyright (C) Michael Adam 2008
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <includes.h>
25 /****************************************************************************
26 Transfer some data between two fd's.
27 ****************************************************************************/
29 #ifndef TRANSFER_BUF_SIZE
30 #define TRANSFER_BUF_SIZE 65536
31 #endif
34 ssize_t transfer_file_internal(void *in_file,
35 void *out_file,
36 size_t n,
37 ssize_t (*read_fn)(void *, void *, size_t),
38 ssize_t (*write_fn)(void *, const void *, size_t))
40 char *buf;
41 size_t total = 0;
42 ssize_t read_ret;
43 ssize_t write_ret;
44 size_t num_to_read_thistime;
45 size_t num_written = 0;
47 if ((buf = SMB_MALLOC_ARRAY(char, TRANSFER_BUF_SIZE)) == NULL) {
48 return -1;
51 while (total < n) {
52 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
54 read_ret = (*read_fn)(in_file, buf, num_to_read_thistime);
55 if (read_ret == -1) {
56 DEBUG(0,("transfer_file_internal: read failure. "
57 "Error = %s\n", strerror(errno) ));
58 SAFE_FREE(buf);
59 return -1;
61 if (read_ret == 0) {
62 break;
65 num_written = 0;
67 while (num_written < read_ret) {
68 write_ret = (*write_fn)(out_file, buf + num_written,
69 read_ret - num_written);
71 if (write_ret == -1) {
72 DEBUG(0,("transfer_file_internal: "
73 "write failure. Error = %s\n",
74 strerror(errno) ));
75 SAFE_FREE(buf);
76 return -1;
78 if (write_ret == 0) {
79 return (ssize_t)total;
82 num_written += (size_t)write_ret;
85 total += (size_t)read_ret;
88 SAFE_FREE(buf);
89 return (ssize_t)total;
92 static ssize_t sys_read_fn(void *file, void *buf, size_t len)
94 int *fd = (int *)file;
96 return sys_read(*fd, buf, len);
99 static ssize_t sys_write_fn(void *file, const void *buf, size_t len)
101 int *fd = (int *)file;
103 return sys_write(*fd, buf, len);
106 SMB_OFF_T transfer_file(int infd, int outfd, SMB_OFF_T n)
108 return (SMB_OFF_T)transfer_file_internal(&infd, &outfd, (size_t)n,
109 sys_read_fn, sys_write_fn);