chiark / gitweb /
many improvements: use Get/SetAssocData for idtables to avoid globals, and adns bindi...
[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  *  hbytes mask-map lookup MAP-VAR ADDRESS [DEFAULT]   => DATA
69  *     error on missing default or if any prefix longer than address
70  *  hbytes mask-map amend MAP-VAR PREFIX PREFIX-LENGTH DATA
71  *     a maskmap MAP is [list [list PREFIX PREFIX-LENGTH DATA]] sorted
72  *     first by descending PREFIX-LENGTH and then by ascending PREFIX
73  *     each PREFIX _in the map_ is truncated to the shortest number of
74  *     pairs of hex digits which can represent it
75  *
76  * Error codes
77  *
78  * HBYTES BLOCKCIPHER CRYPTFAIL CRYPT  block cipher mode failed somehow (!)
79  * HBYTES BLOCKCIPHER CRYPTFAIL MAC    HMAC failed somehow (!)
80  * HBYTES BLOCKCIPHER LENGTH           block cipher input has unsuitable length
81  * HBYTES BLOCKCIPHER PARAMS           key or iv not suitable
82  * HBYTES HMAC PARAMS                  key, input or output size not suitable
83  * HBYTES LENGTH OVERRUN               block too long
84  * HBYTES LENGTH RANGE                 input length or offset is -ve or silly
85  * HBYTES LENGTH UNDERRUN              block too short (or offset too big)
86  * HBYTES LENGTH MISMATCH              when blocks must be exactly same length
87  * HBYTES SYNTAX                       supposed hex block had wrong syntax
88  * HBYTES VALUE OVERFLOW               value to be conv'd to hex too big/long
89  * HBYTES MASKMAP NOMATCH              no addr/mask matches address for lookup
90  * HBYTES MASKMAP UNDERRUN             addr value for lookup is too short
91  * HBYTES MASKMAP SYNTAX LLENGTH       value for mask-map entry not llength==3
92  * HBYTES MASKMAP SYNTAX UNDERRUN      value for mask-map entry hex too short
93  * HBYTES MASKMAP SYNTAX OVERRUN       actual mask-map entry hex too short
94  * HBYTES MASKMAP SYNTAX ORDER         actual mask-map is disordered
95  * HBYTES MASKMAP SYNTAX EXCLBITS      mask-map has 1-bits outside prefix len
96  * SOCKADDR AFUNIX LENGTH              path for AF_UNIX socket too long
97  * SOCKADDR SYNTAX IPV4                bad IPv4 socket address &/or port
98  * SOCKADDR SYNTAX OTHER               bad socket addr, couldn't tell what kind
99  * ULONG BITCOUNT NEGATIVE             -ve bitcount specified where not allowed
100  * ULONG BITCOUNT OVERRUN              attempt to use more than 32 bits
101  * ULONG BITCOUNT UNDERRUN             bitfields add up to less than 32
102  * ULONG VALUE NEGATIVE                attempt convert -ve integers to ulong
103  * ULONG VALUE OVERFLOW                converted value does not fit in result
104  * TUNTAP IFNAME LENGTH                tun/tap interface name too long
105  * TUNTAP MTU OVERRUN                  tun/tap mtu limited to 2^16 bytes
106  *
107  * Refs: HMAC: RFC2104
108  */
109
110 #ifndef HBYTES_H
111 #define HBYTES_H
112
113 #include <assert.h>
114 #include <stdlib.h>
115 #include <errno.h>
116 #include <unistd.h>
117 #include <fcntl.h>
118 #include <sys/socket.h>
119 #include <sys/uio.h>
120 #include <sys/un.h>
121 #include <arpa/inet.h>
122
123 #include <tcl8.3/tcl.h>
124
125 #include <adns.h>
126
127 typedef unsigned char Byte;
128
129 /* from hbytes.c */
130
131 int Hbytes_Init(Tcl_Interp *ip); /* called by Tcl's "load" */
132
133 /* Internal representation details: */
134 #define HBYTES_ISEMPTY(hb)    (!(hb)->begin_complex && !(hb)->end_0)
135 #define HBYTES_ISSENTINEL(hb) (!(hb)->begin_complex && (hb)->end_0)
136 #define HBYTES_ISSIMPLE(hb)   ((hb)->begin_complex && (hb)->end_0)
137 #define HBYTES_ISCOMPLEX(hb)  ((hb)->begin_complex && !(hb)->end_0)
138
139 typedef struct {
140   void *begin_complex, *end_0;
141 } HBytes_Value; /* overlays internalRep */
142
143 typedef struct {
144   Byte *dstart; /* always allocated dynamically */
145   int prespace, len, avail;
146   /*        
147    * | SPARE      | USED  | SPARE |
148    * |<-prespace->|<-len->|       |
149    * |            |<----avail---->|
150    *              ^start
151    */
152 } HBytes_ComplexValue; /* pointed to from internalRep.otherValuePtr */
153
154 /* Public interfaces: */
155
156 extern Tcl_ObjType hbytes_type;
157
158 int hbytes_len(const HBytes_Value *v);
159 Byte *hbytes_data(const HBytes_Value *v); /* caller may then modify data! */
160 int hbytes_issentinel(const HBytes_Value *v);
161
162 Byte *hbytes_prepend(HBytes_Value *upd, int el);
163 Byte *hbytes_append(HBytes_Value *upd, int el);
164   /* return value is where to put the data */
165
166 const Byte *hbytes_unprepend(HBytes_Value *upd, int rl);
167 const Byte *hbytes_unappend(HBytes_Value *upd, int rl);
168   /* return value points to the removed data, which remains valid
169    * until next op on the HBytes_Value.  If original value is
170    * shorter than rl or negative, returns 0 and does nothing. */
171
172 void hbytes_empty(HBytes_Value *returns);
173 void hbytes_sentinel(HBytes_Value *returns);
174 void hbytes_array(HBytes_Value *returns, const Byte *array, int l);
175 Byte *hbytes_arrayspace(HBytes_Value *returns, int l);
176 void hbytes_free(const HBytes_Value *frees);
177   /* _empty, _sentinel and _array do not free or read the old value;
178    * _free it first if needed.  _free leaves it garbage, so you
179    * have to call _empty to reuse it.  _arrayspace doesn't fill
180    * the array; you get a pointer and must fill it with data
181    * yourself. */
182
183 /* The value made by hbytes_sentinel should not be passed to
184  * anything except HBYTES_IS..., and hbytes_free. */
185
186 /* from sockaddr.c */
187
188 typedef struct {
189   Byte *begin, *end;
190 } SockAddr_Value;
191
192 extern Tcl_ObjType sockaddr_type;
193
194 void sockaddr_clear(SockAddr_Value*);
195 void sockaddr_create(SockAddr_Value*, const struct sockaddr *addr, int len);
196 int sockaddr_len(const SockAddr_Value*);
197 const struct sockaddr *sockaddr_addr(const SockAddr_Value*);
198 void sockaddr_free(const SockAddr_Value*);
199
200 /* from scriptinv.c */
201
202 typedef struct { /* semi-opaque - read only, and then only where commented */
203   Tcl_Interp *ip; /* valid, non-0 and useable if set */
204   Tcl_Obj *obj; /* non-0 iff set (but only test for 0/non-0) */
205   int llength;
206 } ScriptToInvoke;
207
208 void scriptinv_init(ScriptToInvoke *si);
209 int scriptinv_set(ScriptToInvoke *si, Tcl_Interp *ip, Tcl_Obj *newscript);
210 void scriptinv_cancel(ScriptToInvoke *si); /* then don't invoke */
211   /* no separate free function - just cancel */
212
213 void scriptinv_invoke(ScriptToInvoke *si, int argc, Tcl_Obj **argv);
214
215 /* from idtable.c */
216
217 typedef struct {
218   const char *valprefix, *assockey;
219   void (*destroyitem)(Tcl_Interp *ip, void *val);
220 } IdDataSpec;
221
222 /* The stored struct must start with a single int, conventionally
223  * named `ix'.  When the struct is returned for the first time ix must
224  * be -1; on subsequent occasions it must be >=0.  ix will be -1 iff
225  * the struct is registered by the iddatatable machinery. */
226
227 extern Tcl_ObjType tabledataid_nearlytype;
228 int tabledataid_parse(Tcl_Interp *ip, Tcl_Obj *o, const IdDataSpec *idds);
229 void tabledataid_disposing(Tcl_Interp *ip, void *val, const IdDataSpec *idds);
230   /* call this when you destroy the struct, to remove its name;
231    * _disposing is idempotent */
232
233 /* from adns.c */
234
235 typedef struct {
236   const char *name;
237   adns_rrtype number;
238 } AdnsTclRRTypeInfo;
239
240 extern const IdDataSpec adnstcl_queries, adnstcl_resolvers;
241
242 /* from dgram.c */
243
244 extern const IdDataSpec dgram_socks;
245 int newfdposixerr(Tcl_Interp *ip, int fd, const char *m);
246
247 /* from tuntap.c */
248
249 extern const IdDataSpec tuntap_socks;
250
251 /* from hook.c */
252
253 int staticerr(Tcl_Interp *ip, const char *m, const char *ec);
254 int posixerr(Tcl_Interp *ip, int errnoval, const char *m);
255 void objfreeir(Tcl_Obj *o);
256 int get_urandom(Tcl_Interp *ip, Byte *buffer, int l);
257
258 void obj_updatestr_array(Tcl_Obj *o, const Byte *array, int l);
259 void obj_updatestr_array_prefix(Tcl_Obj *o, const Byte *byte,
260                                 int l, const char *prefix);
261
262 void obj_updatestr_vstringls(Tcl_Obj *o, ...);
263   /* const char*, int, const char*, int, ..., (const char*)0 */
264 void obj_updatestr_string_len(Tcl_Obj *o, const char *str, int l);
265 void obj_updatestr_string(Tcl_Obj *o, const char *str);
266
267 /* from parse.c */
268
269 typedef struct {
270   Tcl_Obj *obj, *var;
271   int copied;
272 } Something_Var;
273
274 void init_somethingv(Something_Var *sth);
275 void fini_somethingv(Tcl_Interp *ip, int rc, Something_Var *sth);
276 int pat_somethingv(Tcl_Interp *ip, Tcl_Obj *var,
277                    Something_Var *sth, Tcl_ObjType *type);
278
279 typedef struct {
280   HBytes_Value *hb;
281   Something_Var sth;
282 } HBytes_Var;
283
284 /* from maskmap.c */
285
286 typedef struct MaskMap_Value MaskMap_Value;
287
288 typedef struct {
289   MaskMap_Value *mm;
290   Something_Var sth;
291 } MaskMap_Var;
292
293 extern Tcl_ObjType maskmap_type;
294
295 /* from chop.c */
296   /* only do_... functions declared in tables.h */
297
298 /* from ulong.c */
299
300 Tcl_ObjType ulong_type;
301
302 /* from enum.c */
303
304 extern Tcl_ObjType enum_nearlytype;
305 extern Tcl_ObjType enum1_nearlytype;
306
307 const void *enum_lookup_cached_func(Tcl_Interp *ip, Tcl_Obj *o,
308                                     const void *firstentry, size_t entrysize,
309                                     const char *what);
310 #define enum_lookup_cached(ip,o,table,what)                     \
311     (enum_lookup_cached_func((ip),(o),                          \
312                              &(table)[0],sizeof((table)[0]),    \
313                              (what)))
314   /* table should be a pointer to an array of structs of size
315    * entrysize, the first member of which should be a const char*.
316    * The table should finish with a null const char *.
317    * On error, 0 is returned and the ip->result will have been
318    * set to the error message.
319    */
320
321 int enum1_lookup_cached_func(Tcl_Interp *ip, Tcl_Obj *o,
322                              const char *opts, const char *what);
323   /* -1 => error */
324
325 /* from crypto.c */
326
327 void memxor(Byte *dest, const Byte *src, int l);
328
329 typedef struct {
330   const char *name;
331   int pad, use_algname;
332 } PadOp;
333
334 extern Tcl_ObjType blockcipherkey_type;
335
336 /* from algtables.c */
337
338 typedef struct {
339   const char *name;
340   int int_offset;
341 } BlockCipherPropInfo, HashAlgPropInfo;
342
343 typedef struct {
344   const char *name;
345   int hashsize, blocksize, statesize;
346   void (*init)(void *state);
347   void (*update)(void *state, const void *data, int len);
348   void (*final)(void *state, void *digest);
349   void (*oneshot)(void *digest, const void *data, int len);
350 } HashAlgInfo;
351
352 extern const HashAlgInfo hashalginfos[];
353
354 typedef struct {
355   void (*make_schedule)(void *schedule, const void *key, int keylen);
356   void (*crypt)(const void *schedule, const void *in, void *out);
357      /* in and out may be the same, but if they aren't they may not overlap */
358      /* in and out for crypt will have been through block_byteswap */
359 } BlockCipherPerDirectionInfo;
360
361 typedef struct {
362   const char *name;
363   int blocksize, schedule_size, key_min, key_max;
364   BlockCipherPerDirectionInfo encrypt, decrypt;
365 } BlockCipherAlgInfo;
366
367 extern const BlockCipherAlgInfo blockcipheralginfos[];
368
369 /* from bcmode.c */
370
371 typedef struct {
372   const char *name;
373   int iv_blocks, buf_blocks, mac_blocks;
374
375   /* Each function is allowed to use up to buf_blocks * blocksize
376    * bytes of space in buf.  data is blocks * blocksize bytes
377    * long.  data should be modified in place by encrypt and decrypt;
378    * modes may not change the size of data.  iv is always provided and
379    * is always of length iv_blocks * blocksize; encrypt and
380    * decrypt may modify the iv value (in which case the Tcl caller
381    * will get the modified IV) but this is not recommended.  mac
382    * should leave the mac, which must be mac_blocks * blocksize
383    * bytes, in buf.  (Therefore mac_blocks must be at least
384    * buf_blocks.)
385    */
386   const char *(*encrypt)(Byte *data, int nblocks,
387                          const Byte *iv, Byte *buf,
388                          const BlockCipherAlgInfo *alg, int encr,
389                          const void *sch);
390   const char *(*decrypt)(Byte *data, int nblocks,
391                          const Byte *iv, Byte *buf,
392                          const BlockCipherAlgInfo *alg, int encr,
393                          const void *sch);
394   const char *(*mac)(const Byte *data, int nblocks,
395                      const Byte *iv, Byte *buf,
396                      const BlockCipherAlgInfo *alg,
397                      const void *sch);
398 } BlockCipherModeInfo;
399
400 extern const BlockCipherModeInfo blockciphermodeinfos[];
401
402 /* from misc.c */
403
404 int setnonblock(int fd, int isnonblock);
405
406 /* useful macros */
407
408 #define OBJ_HBYTES(o) ((HBytes_Value*)&(o)->internalRep.twoPtrValue)
409 #define OBJ_SOCKADDR(o) ((SockAddr_Value*)&(o)->internalRep.twoPtrValue)
410
411 #define TALLOC(s) ((void*)Tcl_Alloc((s)))
412 #define TFREE(f) (Tcl_Free((void*)(f)))
413 #define TREALLOC(p,l) ((void*)Tcl_Realloc((void*)(p),(l)))
414
415 #endif /*HBYTES_H*/