lib: Add msghdr_prep_recv_fds
[Samba.git] / source3 / lib / util_transfer_file.c
blobd415d7f98e0d1b0b25a15d4f0bcc7d291ea2f7cd
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>
24 #include "transfer_file.h"
25 #include "lib/sys_rw.h"
27 /****************************************************************************
28 Transfer some data between two fd's.
29 ****************************************************************************/
31 #ifndef TRANSFER_BUF_SIZE
32 #define TRANSFER_BUF_SIZE 65536
33 #endif
36 ssize_t transfer_file_internal(void *in_file,
37 void *out_file,
38 size_t n,
39 ssize_t (*read_fn)(void *, void *, size_t),
40 ssize_t (*write_fn)(void *, const void *, size_t))
42 char *buf;
43 size_t total = 0;
44 ssize_t read_ret;
45 ssize_t write_ret;
46 size_t num_to_read_thistime;
47 size_t num_written = 0;
49 if (n == 0) {
50 return 0;
53 if ((buf = SMB_MALLOC_ARRAY(char, TRANSFER_BUF_SIZE)) == NULL) {
54 return -1;
57 do {
58 num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
60 read_ret = (*read_fn)(in_file, buf, num_to_read_thistime);
61 if (read_ret == -1) {
62 DEBUG(0,("transfer_file_internal: read failure. "
63 "Error = %s\n", strerror(errno) ));
64 SAFE_FREE(buf);
65 return -1;
67 if (read_ret == 0) {
68 break;
71 num_written = 0;
73 while (num_written < read_ret) {
74 write_ret = (*write_fn)(out_file, buf + num_written,
75 read_ret - num_written);
77 if (write_ret == -1) {
78 DEBUG(0,("transfer_file_internal: "
79 "write failure. Error = %s\n",
80 strerror(errno) ));
81 SAFE_FREE(buf);
82 return -1;
84 if (write_ret == 0) {
85 return (ssize_t)total;
88 num_written += (size_t)write_ret;
91 total += (size_t)read_ret;
92 } while (total < n);
94 SAFE_FREE(buf);
95 return (ssize_t)total;
98 static ssize_t sys_read_fn(void *file, void *buf, size_t len)
100 int *fd = (int *)file;
102 return sys_read(*fd, buf, len);
105 static ssize_t sys_write_fn(void *file, const void *buf, size_t len)
107 int *fd = (int *)file;
109 return sys_write(*fd, buf, len);
112 off_t transfer_file(int infd, int outfd, off_t n)
114 return (off_t)transfer_file_internal(&infd, &outfd, (size_t)n,
115 sys_read_fn, sys_write_fn);