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