1#include"cache.h" 2#include"pkt-line.h" 3 4/* 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 8 * would be an error). 9 * 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 14 * process entirely). 15 * 16 * The writing side could use stdio, but since the reading 17 * side can't, we stay with pure read/write interfaces. 18 */ 19ssize_t safe_write(int fd,const void*buf, ssize_t n) 20{ 21 ssize_t nn = n; 22while(n) { 23int ret =xwrite(fd, buf, n); 24if(ret >0) { 25 buf = (char*) buf + ret; 26 n -= ret; 27continue; 28} 29if(!ret) 30die("write error (disk full?)"); 31die("write error (%s)",strerror(errno)); 32} 33return nn; 34} 35 36/* 37 * If we buffered things up above (we don't, but we should), 38 * we'd flush it here 39 */ 40voidpacket_flush(int fd) 41{ 42safe_write(fd,"0000",4); 43} 44 45#define hex(a) (hexchar[(a) & 15]) 46voidpacket_write(int fd,const char*fmt, ...) 47{ 48static char buffer[1000]; 49static char hexchar[] ="0123456789abcdef"; 50va_list args; 51unsigned n; 52 53va_start(args, fmt); 54 n =vsnprintf(buffer +4,sizeof(buffer) -4, fmt, args); 55va_end(args); 56if(n >=sizeof(buffer)-4) 57die("protocol error: impossibly long line"); 58 n +=4; 59 buffer[0] =hex(n >>12); 60 buffer[1] =hex(n >>8); 61 buffer[2] =hex(n >>4); 62 buffer[3] =hex(n); 63safe_write(fd, buffer, n); 64} 65 66static voidsafe_read(int fd,void*buffer,unsigned size) 67{ 68size_t n =0; 69 70while(n < size) { 71 ssize_t ret =xread(fd, (char*) buffer + n, size - n); 72if(ret <0) 73die("read error (%s)",strerror(errno)); 74if(!ret) 75die("The remote end hung up unexpectedly"); 76 n += ret; 77} 78} 79 80intpacket_read_line(int fd,char*buffer,unsigned size) 81{ 82int n; 83unsigned len; 84char linelen[4]; 85 86safe_read(fd, linelen,4); 87 88 len =0; 89for(n =0; n <4; n++) { 90unsigned char c = linelen[n]; 91 len <<=4; 92if(c >='0'&& c <='9') { 93 len += c -'0'; 94continue; 95} 96if(c >='a'&& c <='f') { 97 len += c -'a'+10; 98continue; 99} 100if(c >='A'&& c <='F') { 101 len += c -'A'+10; 102continue; 103} 104die("protocol error: bad line length character"); 105} 106if(!len) 107return0; 108 len -=4; 109if(len >= size) 110die("protocol error: bad line length%d", len); 111safe_read(fd, buffer, len); 112 buffer[len] =0; 113return len; 114}