Debian Codegraph @

src/clients/spdsend/common.c

raw
1 /* common.c -- Common parts of the client and the server
2 Author: Milan Zamazal <[email protected]>
3 */
4
5 /* Copyright (C) 2004 Brailcom, o.p.s.
6
7 COPYRIGHT NOTICE
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
13
14 This program is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <limits.h>
28 #include <sys/socket.h>
29 #include <unistd.h>
30
31 #include "spdsend.h"
32
33 const long CONNECTION_ID_MIN = 1;
34 const long CONNECTION_ID_MAX = 1000;
35
36 const int EXIT_OK = 0;
37 const int EXIT_ERROR = 1;
38
39 extern Success write_data(Stream s, const void *buffer, size_t size)
40 {
41 int written;
42
43 for (; size > 0; size -= written, buffer += written) {
44 written = write(s, buffer, size);
45 if (written < 0)
46 return ERROR;
47 }
48
49 return OK;
50 }
51
52 extern int read_data(Stream s, void *buffer, size_t max_size)
53 {
54 size_t nread = 0;
55 ssize_t n;
56
57 while (nread < max_size) {
58 n = read(s, buffer, max_size);
59 if (n < 0)
60 return NONE;
61 if (n == 0)
62 break;
63 nread += n;
64 buffer += n;
65 max_size -= n;
66 }
67
68 return nread;
69 }
70
71 extern Success forward_data(Stream from, Stream to, bool closep)
72 {
73 const size_t buffer_size = 4096;
74 char buffer[buffer_size];
75 ssize_t n;
76
77 while ((n = read(from, buffer, buffer_size)) > 0) {
78 if (write_data(to, buffer, n) == ERROR)
79 return ERROR;
80 }
81 if (closep)
82 shutdown(to, SHUT_WR);
83
84 return (n == NONE ? ERROR : OK);
85 }