]>
git.ipfire.org Git - thirdparty/git.git/blob - pkt-line.c
5 * Write a packetized stream, where each line is preceded by
6 * its length (including the header) as a 4-byte hex number.
7 * A length of 'zero' means end of stream (and a length of 1-3
10 * This is all pretty stupid, but we use this packetized line
11 * format to make a streaming format possible without ever
12 * over-running the read buffers. That way we'll never read
13 * into what might be the pack data (which should go to another
16 * The writing side could use stdio, but since the reading
17 * side can't, we stay with pure read/write interfaces.
19 ssize_t
safe_write(int fd
, const void *buf
, ssize_t n
)
23 int ret
= xwrite(fd
, buf
, n
);
25 buf
= (char *) buf
+ ret
;
30 die("write error (disk full?)");
31 die_errno("write error");
37 * If we buffered things up above (we don't, but we should),
40 void packet_flush(int fd
)
42 safe_write(fd
, "0000", 4);
45 void packet_buf_flush(struct strbuf
*buf
)
47 strbuf_add(buf
, "0000", 4);
50 #define hex(a) (hexchar[(a) & 15])
51 static char buffer
[1000];
52 static unsigned format_packet(const char *fmt
, va_list args
)
54 static char hexchar
[] = "0123456789abcdef";
57 n
= vsnprintf(buffer
+ 4, sizeof(buffer
) - 4, fmt
, args
);
58 if (n
>= sizeof(buffer
)-4)
59 die("protocol error: impossibly long line");
61 buffer
[0] = hex(n
>> 12);
62 buffer
[1] = hex(n
>> 8);
63 buffer
[2] = hex(n
>> 4);
68 void packet_write(int fd
, const char *fmt
, ...)
74 n
= format_packet(fmt
, args
);
76 safe_write(fd
, buffer
, n
);
79 void packet_buf_write(struct strbuf
*buf
, const char *fmt
, ...)
85 n
= format_packet(fmt
, args
);
87 strbuf_add(buf
, buffer
, n
);
90 static void safe_read(int fd
, void *buffer
, unsigned size
)
92 ssize_t ret
= read_in_full(fd
, buffer
, size
);
94 die_errno("read error");
96 die("The remote end hung up unexpectedly");
99 static int packet_length(const char *linelen
)
104 for (n
= 0; n
< 4; n
++) {
105 unsigned char c
= linelen
[n
];
107 if (c
>= '0' && c
<= '9') {
111 if (c
>= 'a' && c
<= 'f') {
115 if (c
>= 'A' && c
<= 'F') {
124 int packet_read_line(int fd
, char *buffer
, unsigned size
)
129 safe_read(fd
, linelen
, 4);
130 len
= packet_length(linelen
);
132 die("protocol error: bad line length character: %.4s", linelen
);
137 die("protocol error: bad line length %d", len
);
138 safe_read(fd
, buffer
, len
);
143 int packet_get_line(struct strbuf
*out
,
144 char **src_buf
, size_t *src_len
)
150 len
= packet_length(*src_buf
);
165 strbuf_add(out
, *src_buf
, len
);