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