chiark / gitweb /
initial import and build-faff, wip
[chiark-tcl.git] / hbytes / hbytes.h
1 /*
2  */
3 /*
4  *  hbytes raw2h BINARY                          => hex
5  *  hbytes h2raw HEX                             => binary
6  *
7  *  hbytes length VALUE                          => count
8  *  hbytes prepend VAR [VALUE ...]         = set VAR [concat VALUE ... $VAR]
9  *  hbytes append VAR [VALUE ...]          = set VAR [concat $VAR VALUE ...]
10  *  hbytes concat VAR [VALUE ...]          = set VAR [concat VALUE ...]
11  *  hbytes unprepend VAR PREFIXLENGTH            => prefix (removed from VAR)
12  *  hbytes unappend VAR SUFFIXLENGTH             => suffix (removed from VAR)
13  *  hbytes chopto VAR NEWVARLENGTH               => suffix (removed from VAR)
14  *                                                  (too short? error)
15  *
16  *  hbytes range VALUE START SIZE                => substring (or error)
17  *  hbytes overwrite VAR START VALUE
18  *  hbytes trimleft VAR                         removes any leading 0 octets
19  *  hbytes repeat VALUE COUNT                    => COUNT copies of VALUE
20  *  hbytes zeroes COUNT                          => COUNT zero bytes
21  *  hbytes random COUNT                          => COUNT random bytes
22  *  hbytes xor VAR VALUE                         $VAR (+)= VALUE
23  *
24  *  hbytes ushort2h LONG           => LONG must be <2^16, returns as hex
25  *  hbytes h2ushort HEX            => |HEX| must be 2 bytes, returns as ulong
26  *
27  *  hbytes compare A B
28  *      =>  -2   A is lexically earlier than B and not a prefix of B  (A<B)
29  *          -1   A is prefix of B but not equal                       (A<B)
30  *           0   A == B
31  *          +1   A is B plus a nonempty suffix (ie, A has B as a prefix)
32  *          +2   A is lexically later than B and does not have B as a prefix
33  *
34  *  hbytes pad pa|ua VAR ALG METH [METHARGS]       => worked? (always 1 for p)
35  *  hbytes pad pn|un VAR BS METH [METHARGS]        => worked? (always 1 for p)
36  *  hbytes pad pa|pn VAR ALG|BS pkcs5              => 1
37  *  hbytes pad ua|un VAR ALG|BS pkcs5              => worked?
38  *  hbytes pad pa|pn VAR ALG|BS rfc2406 NXTHDR     => 1
39  *  hbytes pad ua|un VAR ALG|BS rfc2406 NXTHDRVAR  => worked?
40  *
41  *  hbytes blockcipher d|e VAR ALG KEY MODE [IV] => IV
42  *  hbytes blockcipher mac MSG ALG KEY MODE IV   => final block
43  *  hbytes blockcipher prop PROPERTY ALG         => property value
44  *
45  *  hbytes hash ALG MESSAGE                      => hash
46  *  hbytes hmac ALG MESSAGE KEY [MACLENGTH]      => mac
47  *  hbytes hash-prop PROPERTY ALG                => property value
48  *
49  *  ulong ul2int ULONG    => INT           can fail if >INT_MAX
50  *  ulong int2ul INT      => ULONG         can fail if <0
51  *  ulong mask A B                         => A & B
52  *  ulong add A B                          => A + B  (mod 2^32)
53  *  ulong subtract A B                     => A - B  (mod 2^32)
54  *  ulong compare A B                      => 0  -1 (A<B)  +1 (A>B)
55  *  ulong shift l|r ULONG BITS             fails if BITS >32
56  *
57  *  ulong ul2bitfields VALUE [SIZE TYPE [TYPE-ARG...] ...]  => 0/1
58  *  ulong bitfields2ul BASE  [SIZE TYPE [TYPE-ARG...] ...]  => ULONG
59  *      goes from left (MSbit) to right (LSbit) where
60  *            SIZE is size in bits
61  *            TYPE [TYPE-ARGS...] is as below
62  *               zero
63  *               ignore
64  *               fixed ULONG-VALUE
65  *               uint VARNAME/VALUE         (VARNAME if ul2bitfields;
66  *               ulong VARNAME/VALUE         VALUE if bitfields2ul)
67  *
68  * Address ranges (addrmap.c):
69  *
70  *  An address range is a slightly efficient partial mapping from
71  *  addresses to arbitrary data values.  An address is a number of
72  *  octets expressed as an hbytes.  All the addresses covered by the
73  *  same addrmap should have the same length.
74  *
75  *  hbytes addr-map lookup MAP-VAR ADDRESS [DEFAULT]   => DATA
76  *     Error on missing default or if any prefix longer than ADDRESS.
77  *
78  *  hbytes addr-map amend-range MAP-VAR START END DATA
79  *  hbytes addr-map amend-mask MAP-VAR PREFIX PREFIX-LENGTH DATA
80  *     Sets all of the addresses in PREFIX/PREFIX-LENGTH to the
81  *     relevant value.
82  *
83  *  Representation:
84  *     An address map MAP is
85  *           [list BIT-LENGTH                           \
86  *                 [list START END DATA-VALUE]          \
87  *                 [list START' END' DATA-VALUE']       \
88  *                 ...
89  *            ]
90  *     The list is sorted by ascending START and entries do not overlap.
91  *     START and END are both inclusive.  BIT-LENGTH is in usual Tcl
92  *     integer notation and must be a multiple of 8.
93  *
94  * Error codes
95  *
96  * HBYTES BLOCKCIPHER CRYPTFAIL CRYPT  block cipher mode failed somehow (!)
97  * HBYTES BLOCKCIPHER CRYPTFAIL MAC    HMAC failed somehow (!)
98  * HBYTES BLOCKCIPHER LENGTH           block cipher input has unsuitable length
99  * HBYTES BLOCKCIPHER PARAMS           key or iv not suitable
100  * HBYTES HMAC PARAMS                  key, input or output size not suitable
101  * HBYTES LENGTH OVERRUN               block too long
102  * HBYTES LENGTH RANGE                 input length or offset is -ve or silly
103  * HBYTES LENGTH UNDERRUN              block too short (or offset too big)
104  * HBYTES LENGTH MISMATCH              when blocks must be exactly same length
105  * HBYTES SYNTAX                       supposed hex block had wrong syntax
106  * HBYTES VALUE OVERFLOW               value to be conv'd to hex too big/long
107  * HBYTES ADDRMAP NOMATCH              no addr/mask matches address for lookup
108  * HBYTES ADDRMAP UNDERRUN             addr for lookup or amend is too short
109  * HBYTES ADDRMAP OVERRUN              addr for lookup or amend is too long
110  * HBYTES ADDRMAP EXCLBITS             amend-mask 1-bits outside prefix len
111  * HBYTES ADDRMAP BADRANGE             amend-range start > end
112  * HBYTES ADDRMAP VALUE                addr-map string value is erroneous
113  * SOCKADDR AFUNIX LENGTH              path for AF_UNIX socket too long
114  * SOCKADDR SYNTAX IPV4                bad IPv4 socket address &/or port
115  * SOCKADDR SYNTAX OTHER               bad socket addr, couldn't tell what kind
116  * ULONG BITCOUNT NEGATIVE             -ve bitcount specified where not allowed
117  * ULONG BITCOUNT OVERRUN              attempt to use more than 32 bits
118  * ULONG BITCOUNT UNDERRUN             bitfields add up to less than 32
119  * ULONG VALUE NEGATIVE                attempt convert -ve integers to ulong
120  * ULONG VALUE OVERFLOW                converted value does not fit in result
121  * TUNTAP IFNAME LENGTH                tun/tap interface name too long
122  * TUNTAP MTU OVERRUN                  tun/tap mtu limited to 2^16 bytes
123  *
124  * Refs: HMAC: RFC2104 */
125
126 #ifndef HBYTES_H
127 #define HBYTES_H
128
129 #include <assert.h>
130 #include <stdlib.h>
131 #include <errno.h>
132 #include <unistd.h>
133 #include <fcntl.h>
134 #include <sys/socket.h>
135 #include <sys/uio.h>
136 #include <sys/un.h>
137 #include <arpa/inet.h>
138
139 #include <tcl8.3/tcl.h>
140
141 #include <adns.h>
142
143 typedef unsigned char Byte;
144
145 /* from hbytes.c */
146
147 int Hbytes_Init(Tcl_Interp *ip); /* called by Tcl's "load" */
148
149 /* Internal representation details: */
150 #define HBYTES_ISEMPTY(hb)    (!(hb)->begin_complex && !(hb)->end_0)
151 #define HBYTES_ISSENTINEL(hb) (!(hb)->begin_complex && (hb)->end_0)
152 #define HBYTES_ISSIMPLE(hb)   ((hb)->begin_complex && (hb)->end_0)
153 #define HBYTES_ISCOMPLEX(hb)  ((hb)->begin_complex && !(hb)->end_0)
154
155 typedef struct {
156   void *begin_complex, *end_0;
157 } HBytes_Value; /* overlays internalRep */
158
159 typedef struct {
160   Byte *dstart; /* always allocated dynamically */
161   int prespace, len, avail;
162   /*        
163    * | SPARE      | USED  | SPARE |
164    * |<-prespace->|<-len->|       |
165    * |            |<----avail---->|
166    *              ^start
167    */
168 } HBytes_ComplexValue; /* pointed to from internalRep.otherValuePtr */
169
170 /* Public interfaces: */
171
172 extern Tcl_ObjType hbytes_type;
173
174 int hbytes_len(const HBytes_Value *v);
175 Byte *hbytes_data(const HBytes_Value *v); /* caller may then modify data! */
176 int hbytes_issentinel(const HBytes_Value *v);
177
178 Byte *hbytes_prepend(HBytes_Value *upd, int el);
179 Byte *hbytes_append(HBytes_Value *upd, int el);
180   /* return value is where to put the data */
181
182 const Byte *hbytes_unprepend(HBytes_Value *upd, int rl);
183 const Byte *hbytes_unappend(HBytes_Value *upd, int rl);
184   /* return value points to the removed data, which remains valid
185    * until next op on the HBytes_Value.  If original value is
186    * shorter than rl or negative, returns 0 and does nothing. */
187
188 void hbytes_empty(HBytes_Value *returns);
189 void hbytes_sentinel(HBytes_Value *returns);
190 void hbytes_array(HBytes_Value *returns, const Byte *array, int l);
191 Byte *hbytes_arrayspace(HBytes_Value *returns, int l);
192 void hbytes_free(const HBytes_Value *frees);
193   /* _empty, _sentinel and _array do not free or read the old value;
194    * _free it first if needed.  _free leaves it garbage, so you
195    * have to call _empty to reuse it.  _arrayspace doesn't fill
196    * the array; you get a pointer and must fill it with data
197    * yourself. */
198
199 /* The value made by hbytes_sentinel should not be passed to
200  * anything except HBYTES_IS..., and hbytes_free. */
201
202 /* from sockaddr.c */
203
204 typedef struct {
205   Byte *begin, *end;
206 } SockAddr_Value;
207
208 extern Tcl_ObjType sockaddr_type;
209
210 void sockaddr_clear(SockAddr_Value*);
211 void sockaddr_create(SockAddr_Value*, const struct sockaddr *addr, int len);
212 int sockaddr_len(const SockAddr_Value*);
213 const struct sockaddr *sockaddr_addr(const SockAddr_Value*);
214 void sockaddr_free(const SockAddr_Value*);
215
216 /* from scriptinv.c */
217
218 typedef struct { /* semi-opaque - read only, and then only where commented */
219   Tcl_Interp *ip; /* valid, non-0 and useable if set */
220   Tcl_Obj *obj; /* non-0 iff set (but only test for 0/non-0) */
221   Tcl_Obj *xargs;
222   int llength;
223 } ScriptToInvoke;
224
225 void scriptinv_init(ScriptToInvoke *si);
226 int scriptinv_set(ScriptToInvoke *si, Tcl_Interp *ip,
227                   Tcl_Obj *newscript, Tcl_Obj *xargs);
228 void scriptinv_cancel(ScriptToInvoke *si); /* then don't invoke */
229   /* no separate free function - just cancel */
230
231 void scriptinv_invoke(ScriptToInvoke *si, int argc, Tcl_Obj *const *argv);
232
233 /* from idtable.c */
234
235 typedef struct {
236   const char *valprefix, *assockey;
237   void (*destroyitem)(Tcl_Interp *ip, void *val);
238 } IdDataSpec;
239
240 /* The stored struct must start with a single int, conventionally
241  * named `ix'.  When the struct is returned for the first time ix must
242  * be -1; on subsequent occasions it must be >=0.  ix will be -1 iff
243  * the struct is registered by the iddatatable machinery. */
244
245 extern Tcl_ObjType tabledataid_nearlytype;
246 int tabledataid_parse(Tcl_Interp *ip, Tcl_Obj *o, const IdDataSpec *idds);
247 void tabledataid_disposing(Tcl_Interp *ip, void *val, const IdDataSpec *idds);
248   /* call this when you destroy the struct, to remove its name;
249    * _disposing is idempotent */
250
251 /* from adns.c */
252
253 typedef struct {
254   const char *name;
255   adns_rrtype number;
256 } AdnsTclRRTypeInfo;
257
258 extern const IdDataSpec adnstcl_queries, adnstcl_resolvers;
259
260 /* from dgram.c */
261
262 extern const IdDataSpec dgram_socks;
263
264 /* from tuntap.c */
265
266 extern const IdDataSpec tuntap_socks;
267
268 /* from hook.c */
269
270 int staticerr(Tcl_Interp *ip, const char *m, const char *ec);
271 int posixerr(Tcl_Interp *ip, int errnoval, const char *m);
272 void objfreeir(Tcl_Obj *o);
273 int get_urandom(Tcl_Interp *ip, Byte *buffer, int l);
274
275 void obj_updatestr_array(Tcl_Obj *o, const Byte *array, int l);
276 void obj_updatestr_array_prefix(Tcl_Obj *o, const Byte *byte,
277                                 int l, const char *prefix);
278
279 void obj_updatestr_vstringls(Tcl_Obj *o, ...);
280   /* const char*, int, const char*, int, ..., (const char*)0 */
281 void obj_updatestr_string_len(Tcl_Obj *o, const char *str, int l);
282 void obj_updatestr_string(Tcl_Obj *o, const char *str);
283
284 /* from parse.c */
285
286 typedef struct {
287   Tcl_Obj *obj, *var;
288   int copied;
289 } Something_Var;
290
291 void init_somethingv(Something_Var *sth);
292 void fini_somethingv(Tcl_Interp *ip, int rc, Something_Var *sth);
293 int pat_somethingv(Tcl_Interp *ip, Tcl_Obj *var,
294                    Something_Var *sth, Tcl_ObjType *type);
295
296 typedef struct {
297   HBytes_Value *hb;
298   Something_Var sth;
299 } HBytes_Var;
300
301 /* from addrmap.c */
302
303 typedef struct AddrMap_Value AddrMap_Value;
304
305 typedef struct {
306   AddrMap_Value *am;
307   Something_Var sth;
308 } AddrMap_Var;
309
310 extern Tcl_ObjType addrmap_type;
311
312 /* from chop.c */
313   /* only do_... functions declared in tables.h */
314
315 /* from ulong.c */
316
317 Tcl_ObjType ulong_type;
318
319 /* from enum.c */
320
321 extern Tcl_ObjType enum_nearlytype;
322 extern Tcl_ObjType enum1_nearlytype;
323
324 const void *enum_lookup_cached_func(Tcl_Interp *ip, Tcl_Obj *o,
325                                     const void *firstentry, size_t entrysize,
326                                     const char *what);
327 #define enum_lookup_cached(ip,o,table,what)                     \
328     (enum_lookup_cached_func((ip),(o),                          \
329                              &(table)[0],sizeof((table)[0]),    \
330                              (what)))
331   /* table should be a pointer to an array of structs of size
332    * entrysize, the first member of which should be a const char*.
333    * The table should finish with a null const char *.
334    * On error, 0 is returned and the ip->result will have been
335    * set to the error message.
336    */
337
338 int enum1_lookup_cached_func(Tcl_Interp *ip, Tcl_Obj *o,
339                              const char *opts, const char *what);
340   /* -1 => error */
341
342 /* from crypto.c */
343
344 void memxor(Byte *dest, const Byte *src, int l);
345
346 typedef struct {
347   const char *name;
348   int pad, use_algname;
349 } PadOp;
350
351 extern Tcl_ObjType blockcipherkey_type;
352
353 /* from algtables.c */
354
355 typedef struct {
356   const char *name;
357   int int_offset;
358 } BlockCipherPropInfo, HashAlgPropInfo;
359
360 typedef struct {
361   const char *name;
362   int hashsize, blocksize, statesize;
363   void (*init)(void *state);
364   void (*update)(void *state, const void *data, int len);
365   void (*final)(void *state, void *digest);
366   void (*oneshot)(void *digest, const void *data, int len);
367 } HashAlgInfo;
368
369 extern const HashAlgInfo hashalginfos[];
370
371 typedef struct {
372   void (*make_schedule)(void *schedule, const void *key, int keylen);
373   void (*crypt)(const void *schedule, const void *in, void *out);
374      /* in and out may be the same, but if they aren't they may not overlap */
375      /* in and out for crypt will have been through block_byteswap */
376 } BlockCipherPerDirectionInfo;
377
378 typedef struct {
379   const char *name;
380   int blocksize, schedule_size, key_min, key_max;
381   BlockCipherPerDirectionInfo encrypt, decrypt;
382 } BlockCipherAlgInfo;
383
384 extern const BlockCipherAlgInfo blockcipheralginfos[];
385
386 /* from bcmode.c */
387
388 typedef struct {
389   const char *name;
390   int iv_blocks, buf_blocks, mac_blocks;
391
392   /* Each function is allowed to use up to buf_blocks * blocksize
393    * bytes of space in buf.  data is blocks * blocksize bytes
394    * long.  data should be modified in place by encrypt and decrypt;
395    * modes may not change the size of data.  iv is always provided and
396    * is always of length iv_blocks * blocksize; encrypt and
397    * decrypt may modify the iv value (in which case the Tcl caller
398    * will get the modified IV) but this is not recommended.  mac
399    * should leave the mac, which must be mac_blocks * blocksize
400    * bytes, in buf.  (Therefore mac_blocks must be at least
401    * buf_blocks.)
402    */
403   const char *(*encrypt)(Byte *data, int nblocks,
404                          const Byte *iv, Byte *buf,
405                          const BlockCipherAlgInfo *alg, int encr,
406                          const void *sch);
407   const char *(*decrypt)(Byte *data, int nblocks,
408                          const Byte *iv, Byte *buf,
409                          const BlockCipherAlgInfo *alg, int encr,
410                          const void *sch);
411   const char *(*mac)(const Byte *data, int nblocks,
412                      const Byte *iv, Byte *buf,
413                      const BlockCipherAlgInfo *alg,
414                      const void *sch);
415 } BlockCipherModeInfo;
416
417 extern const BlockCipherModeInfo blockciphermodeinfos[];
418
419 /* from misc.c */
420
421 int setnonblock(int fd, int isnonblock);
422
423 /* useful macros */
424
425 #define OBJ_HBYTES(o) ((HBytes_Value*)&(o)->internalRep.twoPtrValue)
426 #define OBJ_SOCKADDR(o) ((SockAddr_Value*)&(o)->internalRep.twoPtrValue)
427
428 #define TALLOC(s) ((void*)Tcl_Alloc((s)))
429 #define TFREE(f) (Tcl_Free((void*)(f)))
430 #define TREALLOC(p,l) ((void*)Tcl_Realloc((void*)(p),(l)))
431
432 #endif /*HBYTES_H*/