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