chiark / gitweb /
rand.c: Some gratuitous reformatting.
[catacomb-python] / rand.c
1 /* -*-c-*-
2  *
3  * Random-number generators
4  *
5  * (c) 2004 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of the Python interface to Catacomb.
11  *
12  * Catacomb/Python is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * Catacomb/Python is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Catacomb/Python; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "catacomb-python.h"
30 PUBLIC_SYMBOLS;
31 #include "algorithms.h"
32 PRIVATE_SYMBOLS;
33
34 /*----- Main code ---------------------------------------------------------*/
35
36 PyTypeObject *grand_pytype;
37 static PyTypeObject *truerand_pytype;
38 static PyTypeObject *lcrand_pytype, *fibrand_pytype;
39 static PyTypeObject *dsarand_pytype, *bbs_pytype, *bbspriv_pytype;
40 static PyTypeObject *sslprf_pytype, *tlsdx_pytype, *tlsprf_pytype;
41 PyObject *rand_pyobj;
42
43 static PyObject *gccrands_dict;
44
45 static PyObject *grand_dopywrap(PyTypeObject *ty, grand *r, unsigned f)
46 {
47   grand_pyobj *g;
48
49   g = (grand_pyobj *)ty->tp_alloc(ty, 0);
50   g->r = r;
51   g->f = f;
52   return ((PyObject *)g);
53 }
54
55 PyObject *grand_pywrap(grand *r, unsigned f)
56 {
57   PyTypeObject *ty = grand_pytype;
58   PyObject *ob;
59
60   if (STRCMP(r->ops->name, ==, "rand")) ty = truerand_pytype;
61   else if (STRCMP(r->ops->name, ==, "lcrand")) ty = lcrand_pytype;
62   else if (STRCMP(r->ops->name, ==, "fibrand")) ty = fibrand_pytype;
63   else if (STRCMP(r->ops->name, ==, "dsarand")) ty = dsarand_pytype;
64   else if (STRCMP(r->ops->name, ==, "bbs")) ty = bbs_pytype;
65   else if (STRCMP(r->ops->name, ==, "sslprf")) ty = sslprf_pytype;
66   else if (STRCMP(r->ops->name, ==, "tlsdx")) ty = tlsdx_pytype;
67   else if (STRCMP(r->ops->name, ==, "tlsprf")) ty = tlsprf_pytype;
68   else if ((ob = PyMapping_GetItemString
69                    (gccrands_dict, (/*unconst*/ char *)r->ops->name)) != 0)
70     ty = (PyTypeObject *)ob;
71   return (grand_dopywrap(ty, r, f));
72 }
73
74 CONVFUNC(grand, grand *, GRAND_R)
75
76 static int grand_check(PyObject *me)
77 {
78   if (!GRAND_R(me)) VALERR("random generator object is no longer valid");
79   return (0);
80 end:
81   return (-1);
82 }
83
84 static PyObject *grmeth_byte(PyObject *me)
85 {
86   if (grand_check(me)) return (0);
87   return (PyInt_FromLong(grand_byte(GRAND_R(me))));
88 }
89
90 static PyObject *grmeth_word(PyObject *me)
91 {
92   if (grand_check(me)) return (0);
93   return (getulong(grand_word(GRAND_R(me))));
94 }
95
96 static PyObject *grmeth_range(PyObject *me, PyObject *arg)
97 {
98   PyObject *m;
99   mp *x = 0;
100   mp *y = 0;
101
102   if (!PyArg_ParseTuple(arg, "O:range", &m)) return (0);
103   if (grand_check(me)) return (0);
104   if (PyInt_Check(m)) {
105     long mm = PyInt_AS_LONG(m);
106     if (mm <= 0) goto notpos;
107     else if (mm <= 0xffffffff)
108       return (PyInt_FromLong(grand_range(GRAND_R(me), mm)));
109   }
110   if ((x = getmp(m)) == 0) goto end;
111   if (!MP_POSP(x)) goto notpos;
112   y = mprand_range(MP_NEW, x, GRAND_R(me), 0);
113   MP_DROP(x);
114   return (mp_pywrap(y));
115 notpos:
116   VALERR("range must be strictly positive");
117 end:
118   if (x) MP_DROP(x);
119   return (0);
120 }
121
122 static PyObject *grmeth_mp(PyObject *me, PyObject *arg, PyObject *kw)
123 {
124   size_t l;
125   mpw o = 0;
126   static const char *const kwlist[] = { "bits", "or", 0 };
127
128   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|O&:mp", KWLIST,
129                                    convszt, &l, convmpw, &o))
130     goto end;
131   if (grand_check(me)) return (0);
132   if (l < MPW_BITS && (o >> l)) VALERR("or mask too large");
133   return (mp_pywrap(mprand(MP_NEW, l, GRAND_R(me), o)));
134 end:
135   return (0);
136 }
137
138 static PyObject *grmeth_block(PyObject *me, PyObject *arg)
139 {
140   unsigned long n;
141   PyObject *rc = 0;
142
143   if (!PyArg_ParseTuple(arg, "O&:block", convulong, &n)) goto end;
144   if (grand_check(me)) return (0);
145   rc = bytestring_pywrap(0, n);
146   grand_fill(GRAND_R(me), BIN_PTR(rc), n);
147 end:
148   return (rc);
149 }
150
151 static int checkop(grand *r, unsigned op, const char *what)
152 {
153   if (r->ops->misc(r, GRAND_CHECK, op)) return (0);
154   PyErr_Format(PyExc_TypeError, "operation %s not supported", what);
155   return (-1);
156 }
157
158 static PyObject *grmeth_seedint(PyObject *me, PyObject *arg)
159 {
160   int i;
161   grand *r = GRAND_R(me);
162   if (!PyArg_ParseTuple(arg, "i:seedint", &i) ||
163       grand_check(me) || checkop(r, GRAND_SEEDINT, "seedint"))
164     goto end;
165   r->ops->misc(r, GRAND_SEEDINT, i);
166   RETURN_ME;
167 end:
168   return (0);
169 }
170
171 static PyObject *grmeth_seedword(PyObject *me, PyObject *arg)
172 {
173   uint32 u;
174   grand *r = GRAND_R(me);
175   if (!PyArg_ParseTuple(arg, "O&:seedword", convu32, &u) ||
176       grand_check(me) || checkop(r, GRAND_SEEDUINT32, "seedword"))
177     goto end;
178   r->ops->misc(r, GRAND_SEEDUINT32, u);
179   RETURN_ME;
180 end:
181   return (0);
182 }
183
184 static PyObject *grmeth_seedblock(PyObject *me, PyObject *arg)
185 {
186   struct bin in;
187   grand *r = GRAND_R(me);
188   if (!PyArg_ParseTuple(arg, "O&:seedblock", convbin, &in) ||
189       grand_check(me) || checkop(r, GRAND_SEEDBLOCK, "seedblock"))
190     goto end;
191   r->ops->misc(r, GRAND_SEEDBLOCK, in.p, (size_t)in.sz);
192   RETURN_ME;
193 end:
194   return (0);
195 }
196
197 static PyObject *grmeth_seedmp(PyObject *me, PyObject *arg)
198 {
199   PyObject *x;
200   mp *xx;
201   grand *r = GRAND_R(me);
202   if (!PyArg_ParseTuple(arg, "O:seedmp", &x) ||
203       grand_check(me) || checkop(r, GRAND_SEEDMP, "seedmp") ||
204       (xx = getmp(x)) == 0)
205     goto end;
206   r->ops->misc(r, GRAND_SEEDMP, xx);
207   MP_DROP(xx);
208   RETURN_ME;
209 end:
210   return (0);
211 }
212
213 static PyObject *grmeth_seedrand(PyObject *me, PyObject *arg, PyObject *kw)
214 {
215   static const char *const kwlist[] = { "rng", 0 };
216   grand *r = GRAND_R(me);
217   grand *rr = &rand_global;
218   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:seedrand", KWLIST,
219                                    convgrand, &rr) ||
220       grand_check(me) || checkop(r, GRAND_SEEDRAND, "seedrand"))
221     goto end;
222   r->ops->misc(r, GRAND_SEEDRAND, rr);
223   RETURN_ME;
224 end:
225   return (0);
226 }
227
228 static PyObject *grmeth_mask(PyObject *me, PyObject *arg)
229 {
230   grand *r = GRAND_R(me);
231   struct bin in;
232   const octet *p; size_t n;
233   octet *q;
234   PyObject *rc;
235
236   if (!PyArg_ParseTuple(arg, "O&:mask", convbin, &in)) return (0);
237   if (grand_check(me)) return (0);
238   rc = bytestring_pywrap(0, in.sz);
239   q = (octet *)BIN_PTR(rc);
240   GR_FILL(r, q, in.sz);
241   p = in.p; n = in.sz; while (n--) *q++ ^= *p++;
242   return (rc);
243 }
244
245 static void grand_pydealloc(PyObject *me)
246 {
247   grand_pyobj *g = (grand_pyobj *)me;
248   if ((g->f & f_freeme) && g->r) GR_DESTROY(g->r);
249   FREEOBJ(me);
250 }
251
252 static PyObject *grget_name(PyObject *me, void *hunoz)
253   { return (grand_check(me) ? 0 : TEXT_FROMSTR(GRAND_R(me)->ops->name)); }
254
255 static PyObject *grget_cryptop(PyObject *me, void *hunoz)
256   { return (grand_check(me) ? 0 : getbool(GRAND_R(me)->ops->f & GRAND_CRYPTO)); }
257
258 static const PyGetSetDef grand_pygetset[] = {
259 #define GETSETNAME(op, name) gr##op##_##name
260   GET   (name,          "R.name -> name of this kind of generator")
261   GET   (cryptop,       "R.cryptop -> flag: cryptographically strong?")
262 #undef GETSETNAME
263   { 0 }
264 };
265
266 static const PyMethodDef grand_pymethods[] = {
267 #define METHNAME(name) grmeth_##name
268   NAMETH(byte,          "R.byte() -> BYTE")
269   NAMETH(word,          "R.word() -> WORD")
270   METH  (block,         "R.block(N) -> STRING")
271   KWMETH(mp,            "R.mp(bits, [or = 0]) -> MP")
272   METH  (range,         "R.range(MAX) -> INT")
273   METH  (mask,          "R.mask(STR) -> STR")
274   METH  (seedint,       "R.seedint(I)")
275   METH  (seedword,      "R.seedword(I)")
276   METH  (seedblock,     "R.seedblock(BYTES)")
277   METH  (seedmp,        "R.seedmp(X)")
278   KWMETH(seedrand,      "R.seedrand(RR)")
279 #undef METHNAME
280   { 0 }
281 };
282
283 static const PyTypeObject grand_pytype_skel = {
284   PyVarObject_HEAD_INIT(0, 0)           /* Header */
285   "GRand",                              /* @tp_name@ */
286   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
287   0,                                    /* @tp_itemsize@ */
288
289   grand_pydealloc,                      /* @tp_dealloc@ */
290   0,                                    /* @tp_print@ */
291   0,                                    /* @tp_getattr@ */
292   0,                                    /* @tp_setattr@ */
293   0,                                    /* @tp_compare@ */
294   0,                                    /* @tp_repr@ */
295   0,                                    /* @tp_as_number@ */
296   0,                                    /* @tp_as_sequence@ */
297   0,                                    /* @tp_as_mapping@ */
298   0,                                    /* @tp_hash@ */
299   0,                                    /* @tp_call@ */
300   0,                                    /* @tp_str@ */
301   0,                                    /* @tp_getattro@ */
302   0,                                    /* @tp_setattro@ */
303   0,                                    /* @tp_as_buffer@ */
304   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
305     Py_TPFLAGS_BASETYPE,
306
307   /* @tp_doc@ */
308   "Generic random number source.",
309
310   0,                                    /* @tp_traverse@ */
311   0,                                    /* @tp_clear@ */
312   0,                                    /* @tp_richcompare@ */
313   0,                                    /* @tp_weaklistoffset@ */
314   0,                                    /* @tp_iter@ */
315   0,                                    /* @tp_iternext@ */
316   PYMETHODS(grand),                     /* @tp_methods@ */
317   0,                                    /* @tp_members@ */
318   PYGETSET(grand),                      /* @tp_getset@ */
319   0,                                    /* @tp_base@ */
320   0,                                    /* @tp_dict@ */
321   0,                                    /* @tp_descr_get@ */
322   0,                                    /* @tp_descr_set@ */
323   0,                                    /* @tp_dictoffset@ */
324   0,                                    /* @tp_init@ */
325   PyType_GenericAlloc,                  /* @tp_alloc@ */
326   abstract_pynew,                       /* @tp_new@ */
327   0,                                    /* @tp_free@ */
328   0                                     /* @tp_is_gc@ */
329 };
330
331 static PyObject *lcrand_pynew(PyTypeObject *me, PyObject *arg, PyObject *kw)
332 {
333   uint32 n = 0;
334   static const char *const kwlist[] = { "seed", 0 };
335   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:new", KWLIST, convu32, &n))
336     return (0);
337   return (grand_dopywrap(lcrand_pytype, lcrand_create(n), f_freeme));
338 }
339
340 static const PyTypeObject lcrand_pytype_skel = {
341   PyVarObject_HEAD_INIT(0, 0)           /* Header */
342   "LCRand",                             /* @tp_name@ */
343   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
344   0,                                    /* @tp_itemsize@ */
345
346   grand_pydealloc,                      /* @tp_dealloc@ */
347   0,                                    /* @tp_print@ */
348   0,                                    /* @tp_getattr@ */
349   0,                                    /* @tp_setattr@ */
350   0,                                    /* @tp_compare@ */
351   0,                                    /* @tp_repr@ */
352   0,                                    /* @tp_as_number@ */
353   0,                                    /* @tp_as_sequence@ */
354   0,                                    /* @tp_as_mapping@ */
355   0,                                    /* @tp_hash@ */
356   0,                                    /* @tp_call@ */
357   0,                                    /* @tp_str@ */
358   0,                                    /* @tp_getattro@ */
359   0,                                    /* @tp_setattro@ */
360   0,                                    /* @tp_as_buffer@ */
361   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
362     Py_TPFLAGS_BASETYPE,
363
364   /* @tp_doc@ */
365   "LCRand([seed = 0]): linear congruential generator.",
366
367   0,                                    /* @tp_traverse@ */
368   0,                                    /* @tp_clear@ */
369   0,                                    /* @tp_richcompare@ */
370   0,                                    /* @tp_weaklistoffset@ */
371   0,                                    /* @tp_iter@ */
372   0,                                    /* @tp_iternext@ */
373   0,                                    /* @tp_methods@ */
374   0,                                    /* @tp_members@ */
375   0,                                    /* @tp_getset@ */
376   0,                                    /* @tp_base@ */
377   0,                                    /* @tp_dict@ */
378   0,                                    /* @tp_descr_get@ */
379   0,                                    /* @tp_descr_set@ */
380   0,                                    /* @tp_dictoffset@ */
381   0,                                    /* @tp_init@ */
382   PyType_GenericAlloc,                  /* @tp_alloc@ */
383   lcrand_pynew,                         /* @tp_new@ */
384   0,                                    /* @tp_free@ */
385   0                                     /* @tp_is_gc@ */
386 };
387
388 static PyObject *fibrand_pynew(PyTypeObject *me, PyObject *arg, PyObject *kw)
389 {
390   uint32 n = 0;
391   static const char *const kwlist[] = { "seed", 0 };
392   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:new", KWLIST, convu32, &n))
393     return (0);
394   return (grand_dopywrap(fibrand_pytype, fibrand_create(n), f_freeme));
395 }
396
397 static const PyTypeObject fibrand_pytype_skel = {
398   PyVarObject_HEAD_INIT(0, 0)           /* Header */
399   "FibRand",                            /* @tp_name@ */
400   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
401   0,                                    /* @tp_itemsize@ */
402
403   grand_pydealloc,                      /* @tp_dealloc@ */
404   0,                                    /* @tp_print@ */
405   0,                                    /* @tp_getattr@ */
406   0,                                    /* @tp_setattr@ */
407   0,                                    /* @tp_compare@ */
408   0,                                    /* @tp_repr@ */
409   0,                                    /* @tp_as_number@ */
410   0,                                    /* @tp_as_sequence@ */
411   0,                                    /* @tp_as_mapping@ */
412   0,                                    /* @tp_hash@ */
413   0,                                    /* @tp_call@ */
414   0,                                    /* @tp_str@ */
415   0,                                    /* @tp_getattro@ */
416   0,                                    /* @tp_setattro@ */
417   0,                                    /* @tp_as_buffer@ */
418   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
419     Py_TPFLAGS_BASETYPE,
420
421   /* @tp_doc@ */
422   "FibRand([seed = 0]): Fibonacci generator.",
423
424   0,                                    /* @tp_traverse@ */
425   0,                                    /* @tp_clear@ */
426   0,                                    /* @tp_richcompare@ */
427   0,                                    /* @tp_weaklistoffset@ */
428   0,                                    /* @tp_iter@ */
429   0,                                    /* @tp_iternext@ */
430   0,                                    /* @tp_methods@ */
431   0,                                    /* @tp_members@ */
432   0,                                    /* @tp_getset@ */
433   0,                                    /* @tp_base@ */
434   0,                                    /* @tp_dict@ */
435   0,                                    /* @tp_descr_get@ */
436   0,                                    /* @tp_descr_set@ */
437   0,                                    /* @tp_dictoffset@ */
438   0,                                    /* @tp_init@ */
439   PyType_GenericAlloc,                  /* @tp_alloc@ */
440   fibrand_pynew,                        /* @tp_new@ */
441   0,                                    /* @tp_free@ */
442   0                                     /* @tp_is_gc@ */
443 };
444
445 /*----- True random generator ---------------------------------------------*/
446
447 static PyObject *trmeth_gate(PyObject *me)
448   { grand *r = GRAND_R(me); r->ops->misc(GRAND_R(me), RAND_GATE); RETURN_ME; }
449
450 static PyObject *trmeth_stretch(PyObject *me)
451   { grand *r = GRAND_R(me); r->ops->misc(r, RAND_STRETCH); RETURN_ME; }
452
453 static PyObject *trmeth_add(PyObject *me, PyObject *arg)
454 {
455   grand *r = GRAND_R(me);
456   struct bin in; unsigned goodbits;
457   if (!PyArg_ParseTuple(arg, "O&O&:add", convbin, &in, convuint, &goodbits))
458     return (0);
459   r->ops->misc(r, RAND_ADD, in.p, (size_t)in.sz, goodbits);
460   RETURN_ME;
461 }
462
463 static PyObject *trmeth_key(PyObject *me, PyObject *arg)
464 {
465   grand *r = GRAND_R(me);
466   struct bin k;
467   if (!PyArg_ParseTuple(arg, "O&:key", convbin, &k)) return (0);
468   r->ops->misc(r, RAND_KEY, k.p, (size_t)k.sz);
469   RETURN_ME;
470 }
471
472 static PyObject *trmeth_seed(PyObject *me, PyObject *arg)
473 {
474   grand *r = GRAND_R(me);
475   unsigned u;
476   if (!PyArg_ParseTuple(arg, "O&:seed", convuint, &u)) return (0);
477   if (u > RAND_IBITS) VALERR("pointlessly large");
478   r->ops->misc(r, RAND_SEED, u);
479   RETURN_ME;
480 end:
481   return (0);
482 }
483
484 static PyObject *trmeth_timer(PyObject *me)
485   { grand *r = GRAND_R(me); r->ops->misc(r, RAND_TIMER); RETURN_ME; }
486
487 static PyObject *truerand_pynew(PyTypeObject *ty,
488                                 PyObject *arg, PyObject *kw)
489 {
490   static const char *const kwlist[] = { 0 };
491   grand *r;
492   PyObject *rc = 0;
493   if (!PyArg_ParseTupleAndKeywords(arg, kw, ":new", KWLIST)) goto end;
494   r = rand_create();
495   r->ops->misc(r, RAND_NOISESRC, &noise_source);
496   r->ops->misc(r, RAND_SEED, 160);
497   rc = grand_dopywrap(ty, r, f_freeme);
498 end:
499   return (rc);
500 }
501
502 static const PyMethodDef truerand_pymethods[] = {
503 #define METHNAME(name) trmeth_##name
504   NAMETH(gate,          "R.gate()")
505   NAMETH(stretch,       "R.stretch()")
506   METH  (key,           "R.key(BYTES)")
507   METH  (seed,          "R.seed(NBITS)")
508   METH  (add,           "R.add(BYTES, GOODBITS")
509   NAMETH(timer,         "R.timer()")
510 #undef METHNAME
511   { 0 }
512 };
513
514 static PyObject *trget_goodbits(PyObject *me, void *hunoz)
515 {
516   grand *r = GRAND_R(me);
517   return (PyInt_FromLong(r->ops->misc(r, RAND_GOODBITS)));
518 }
519
520 static const PyGetSetDef truerand_pygetset[] = {
521 #define GETSETNAME(op, name) tr##op##_##name
522   GET   (goodbits,      "R.goodbits -> good bits of entropy remaining")
523 #undef GETSETNAME
524   { 0 }
525 };
526
527 static const PyTypeObject truerand_pytype_skel = {
528   PyVarObject_HEAD_INIT(0, 0)           /* Header */
529   "TrueRand",                           /* @tp_name@ */
530   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
531   0,                                    /* @tp_itemsize@ */
532
533   grand_pydealloc,                      /* @tp_dealloc@ */
534   0,                                    /* @tp_print@ */
535   0,                                    /* @tp_getattr@ */
536   0,                                    /* @tp_setattr@ */
537   0,                                    /* @tp_compare@ */
538   0,                                    /* @tp_repr@ */
539   0,                                    /* @tp_as_number@ */
540   0,                                    /* @tp_as_sequence@ */
541   0,                                    /* @tp_as_mapping@ */
542   0,                                    /* @tp_hash@ */
543   0,                                    /* @tp_call@ */
544   0,                                    /* @tp_str@ */
545   0,                                    /* @tp_getattro@ */
546   0,                                    /* @tp_setattro@ */
547   0,                                    /* @tp_as_buffer@ */
548   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
549     Py_TPFLAGS_BASETYPE,
550
551   /* @tp_doc@ */
552   "TrueRand(): true random number source.",
553
554   0,                                    /* @tp_traverse@ */
555   0,                                    /* @tp_clear@ */
556   0,                                    /* @tp_richcompare@ */
557   0,                                    /* @tp_weaklistoffset@ */
558   0,                                    /* @tp_iter@ */
559   0,                                    /* @tp_iternext@ */
560   PYMETHODS(truerand),                  /* @tp_methods@ */
561   0,                                    /* @tp_members@ */
562   PYGETSET(truerand),                   /* @tp_getset@ */
563   0,                                    /* @tp_base@ */
564   0,                                    /* @tp_dict@ */
565   0,                                    /* @tp_descr_get@ */
566   0,                                    /* @tp_descr_set@ */
567   0,                                    /* @tp_dictoffset@ */
568   0,                                    /* @tp_init@ */
569   PyType_GenericAlloc,                  /* @tp_alloc@ */
570   truerand_pynew,                       /* @tp_new@ */
571   0,                                    /* @tp_free@ */
572   0                                     /* @tp_is_gc@ */
573 };
574
575 /*----- Generators from symmetric encryption algorithms -------------------*/
576
577 static PyTypeObject *gccrand_pytype, *gcrand_pytype, *gclatinrand_pytype;
578
579 typedef grand *gcrand_func(const void *, size_t sz);
580 typedef grand *gcirand_func(const void *, size_t sz, uint32);
581 typedef grand *gcnrand_func(const void *, size_t sz, const void *);
582 typedef grand *gcshakerand_func(const void *, size_t,
583                                 const void *, size_t,
584                                 const void *, size_t);
585 typedef grand *gcshafuncrand_func(const void *, size_t,
586                                   const void *, size_t);
587 typedef grand *gckmacrand_func(const void *, size_t, const void *, size_t);
588 typedef struct gccrand_info {
589   const char *name;
590   const octet *keysz;
591   unsigned f;
592   size_t noncesz;
593   gcrand_func *func;
594 } gccrand_info;
595
596 #define RNGF_MASK 255u
597
598 enum {
599   RNG_PLAIN = 0,
600   RNG_SEAL,
601   RNG_LATIN,
602   RNG_SHAKE,
603   RNG_KMAC
604 };
605
606 typedef struct gccrand_pyobj {
607   PyHeapTypeObject ty;
608   const gccrand_info *info;
609 } gccrand_pyobj;
610 #define GCCRAND_INFO(o) (((gccrand_pyobj *)(o))->info)
611
612 #define GCCRAND_DEF(name, ksz, func, f, nsz)                            \
613   static const gccrand_info func##_info =                               \
614     { name, ksz, f, nsz, (gcrand_func *)func };
615 RNGS(GCCRAND_DEF)
616
617 static const gccrand_info *const gcrandtab[] = {
618 #define GCCRAND_ENTRY(name, ksz, func, f, nsz) &func##_info,
619   RNGS(GCCRAND_ENTRY)
620   0
621 };
622
623 static PyObject *gcrand_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
624 {
625   const gccrand_info *info = GCCRAND_INFO(ty);
626   static const char *const kwlist[] = { "key", 0 };
627   struct bin k;
628
629   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST,  convbin, &k))
630     goto end;
631   if (keysz(k.sz, info->keysz) != k.sz) VALERR("bad key length");
632   return (grand_dopywrap(ty, info->func(k.p, k.sz), f_freeme));
633 end:
634   return (0);
635 }
636
637 static PyObject *gcirand_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
638 {
639   const gccrand_info *info = GCCRAND_INFO(ty);
640   uint32 i = 0;
641   static const char *const kwlist[] = { "key", "i", 0 };
642   struct bin k;
643
644   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&:new", KWLIST,
645                                    convbin, &k, convu32, &i))
646     goto end;
647   if (keysz(k.sz, info->keysz) != k.sz) VALERR("bad key length");
648   return (grand_dopywrap(ty,
649                          ((gcirand_func *)info->func)(k.p, k.sz, i),
650                          f_freeme));
651 end:
652   return (0);
653 }
654
655 static PyObject *gcnrand_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
656 {
657   const gccrand_info *info = GCCRAND_INFO(ty);
658   static const char *const kwlist[] = { "key", "nonce", 0 };
659   struct bin k, n;
660
661   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&:new", KWLIST,
662                                    convbin, &k, convbin, &n))
663     goto end;
664   if (keysz(k.sz, info->keysz) != k.sz) VALERR("bad key length");
665   if (n.sz != info->noncesz) VALERR("bad nonce length");
666   return (grand_dopywrap(ty,
667                          ((gcnrand_func *)info->func)(k.p, k.sz, n.p),
668                          f_freeme));
669 end:
670   return (0);
671 }
672
673 static PyObject *gcshakyrand_pynew(PyTypeObject *ty,
674                                    PyObject *arg, PyObject *kw)
675 {
676   const gccrand_info *info = GCCRAND_INFO(ty);
677   static const char
678     *const kwlist_shake[] = { "key", "func", "perso", 0 },
679     *const kwlist_func[] = { "key", "perso", 0 };
680   struct bin k, f = { 0, 0 }, p = { 0, 0 };
681
682   if ((info->f&RNGF_MASK) == RNG_SHAKE
683         ? !PyArg_ParseTupleAndKeywords(arg, kw, "O&|O&O&:new",
684                                        (/*unconst*/ char **)kwlist_shake,
685                                        convbin, &k,
686                                        convbin, &f, convbin, &p)
687         : !PyArg_ParseTupleAndKeywords(arg, kw, "O&|O&:new",
688                                        (/*unconst*/ char **)kwlist_func,
689                                        convbin, &k, convbin, &p))
690     goto end;
691   if (keysz(k.sz, info->keysz) != k.sz) VALERR("bad key length");
692   return (grand_dopywrap(ty,
693                          (info->f&RNGF_MASK) == RNG_SHAKE
694                            ? ((gcshakerand_func *)info->func)(f.p, f.sz,
695                                                               p.p, p.sz,
696                                                               k.p, k.sz)
697                            : ((gcshafuncrand_func *)info->func)(p.p, p.sz,
698                                                                 k.p, k.sz),
699                          f_freeme));
700 end:
701   return (0);
702 }
703
704 static PyObject *gccrand_pywrap(const gccrand_info *info)
705 {
706   gccrand_pyobj *g = newtype(gccrand_pytype, 0, info->name);
707   g->info = info;
708   g->ty.ht_type.tp_basicsize = sizeof(grand_pyobj);
709   switch (info->f&RNGF_MASK) {
710     case RNG_LATIN: g->ty.ht_type.tp_base = gclatinrand_pytype; break;
711     default: g->ty.ht_type.tp_base = gcrand_pytype; break;
712   }
713   Py_INCREF(g->ty.ht_type.tp_base);
714   g->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
715                             Py_TPFLAGS_BASETYPE |
716                             Py_TPFLAGS_HEAPTYPE);
717   g->ty.ht_type.tp_alloc = PyType_GenericAlloc;
718   g->ty.ht_type.tp_free = 0;
719   switch (info->f&RNGF_MASK) {
720     case RNG_LATIN: g->ty.ht_type.tp_new = gcnrand_pynew; break;
721     case RNG_SEAL: g->ty.ht_type.tp_new = gcirand_pynew; break;
722     case RNG_SHAKE: case RNG_KMAC:
723       g->ty.ht_type.tp_new = gcshakyrand_pynew; break;
724     default: g->ty.ht_type.tp_new = gcrand_pynew; break;
725   }
726   typeready(&g->ty.ht_type);
727   return ((PyObject *)g);
728 }
729
730 static PyObject *gccrget_name(PyObject *me, void *hunoz)
731   { return (TEXT_FROMSTR(GCCRAND_INFO(me)->name)); }
732 static PyObject *gccrget_keysz(PyObject *me, void *hunoz)
733   { return (keysz_pywrap(GCCRAND_INFO(me)->keysz)); }
734
735 static PyObject *gclrmeth_tell(PyObject *me)
736 {
737   grand *r = GRAND_R(me);
738   PyObject *rc = 0;
739   kludge64 off;
740
741   r->ops->misc(r, SALSA20_TELLU64, &off);
742   rc = getk64(off);
743   return (rc);
744 }
745
746 static PyObject *gclrmeth_seek(PyObject *me, PyObject *arg)
747 {
748   grand *r = GRAND_R(me);
749   kludge64 off;
750
751   if (!PyArg_ParseTuple(arg, "O&:seek", convk64, &off)) return (0);
752   r->ops->misc(r, SALSA20_SEEKU64, off);
753   RETURN_ME;
754 }
755
756 static const PyGetSetDef gccrand_pygetset[] = {
757 #define GETSETNAME(op, name) gccr##op##_##name
758   GET   (keysz,         "CR.keysz -> acceptable key sizes")
759   GET   (name,          "CR.name -> name of this kind of generator")
760 #undef GETSETNAME
761   { 0 }
762 };
763
764 static const PyMethodDef gclatinrand_pymethods[] = {
765 #define METHNAME(name) gclrmeth_##name
766   NAMETH(tell,          "R.tell() -> OFF")
767   METH  (seek,          "R.seek(OFF)")
768 #undef METHNAME
769   { 0 }
770 };
771
772 static const PyTypeObject gccrand_pytype_skel = {
773   PyVarObject_HEAD_INIT(0, 0)           /* Header */
774   "GCCRand",                            /* @tp_name@ */
775   sizeof(gccrand_pyobj),                /* @tp_basicsize@ */
776   0,                                    /* @tp_itemsize@ */
777
778   0,                                    /* @tp_dealloc@ */
779   0,                                    /* @tp_print@ */
780   0,                                    /* @tp_getattr@ */
781   0,                                    /* @tp_setattr@ */
782   0,                                    /* @tp_compare@ */
783   0,                                    /* @tp_repr@ */
784   0,                                    /* @tp_as_number@ */
785   0,                                    /* @tp_as_sequence@ */
786   0,                                    /* @tp_as_mapping@ */
787   0,                                    /* @tp_hash@ */
788   0,                                    /* @tp_call@ */
789   0,                                    /* @tp_str@ */
790   0,                                    /* @tp_getattro@ */
791   0,                                    /* @tp_setattro@ */
792   0,                                    /* @tp_as_buffer@ */
793   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
794     Py_TPFLAGS_BASETYPE,
795
796   /* @tp_doc@ */
797   "Metaclass for symmetric crypto-based generators.",
798
799   0,                                    /* @tp_traverse@ */
800   0,                                    /* @tp_clear@ */
801   0,                                    /* @tp_richcompare@ */
802   0,                                    /* @tp_weaklistoffset@ */
803   0,                                    /* @tp_iter@ */
804   0,                                    /* @tp_iternext@ */
805   0,                                    /* @tp_methods@ */
806   0,                                    /* @tp_members@ */
807   PYGETSET(gccrand),                    /* @tp_getset@ */
808   0,                                    /* @tp_base@ */
809   0,                                    /* @tp_dict@ */
810   0,                                    /* @tp_descr_get@ */
811   0,                                    /* @tp_descr_set@ */
812   0,                                    /* @tp_dictoffset@ */
813   0,                                    /* @tp_init@ */
814   PyType_GenericAlloc,                  /* @tp_alloc@ */
815   abstract_pynew,                       /* @tp_new@ */
816   0,                                    /* @tp_free@ */
817   0                                     /* @tp_is_gc@ */
818 };
819
820 static const PyTypeObject gcrand_pytype_skel = {
821   PyVarObject_HEAD_INIT(0, 0)           /* Header */
822   "GCRand",                             /* @tp_name@ */
823   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
824   0,                                    /* @tp_itemsize@ */
825
826   grand_pydealloc,                      /* @tp_dealloc@ */
827   0,                                    /* @tp_print@ */
828   0,                                    /* @tp_getattr@ */
829   0,                                    /* @tp_setattr@ */
830   0,                                    /* @tp_compare@ */
831   0,                                    /* @tp_repr@ */
832   0,                                    /* @tp_as_number@ */
833   0,                                    /* @tp_as_sequence@ */
834   0,                                    /* @tp_as_mapping@ */
835   0,                                    /* @tp_hash@ */
836   0,                                    /* @tp_call@ */
837   0,                                    /* @tp_str@ */
838   0,                                    /* @tp_getattro@ */
839   0,                                    /* @tp_setattro@ */
840   0,                                    /* @tp_as_buffer@ */
841   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
842     Py_TPFLAGS_BASETYPE,
843
844   /* @tp_doc@ */
845   "Abstract base class for symmetric crypto-based generators.",
846
847   0,                                    /* @tp_traverse@ */
848   0,                                    /* @tp_clear@ */
849   0,                                    /* @tp_richcompare@ */
850   0,                                    /* @tp_weaklistoffset@ */
851   0,                                    /* @tp_iter@ */
852   0,                                    /* @tp_iternext@ */
853   0,                                    /* @tp_methods@ */
854   0,                                    /* @tp_members@ */
855   0,                                    /* @tp_getset@ */
856   0,                                    /* @tp_base@ */
857   0,                                    /* @tp_dict@ */
858   0,                                    /* @tp_descr_get@ */
859   0,                                    /* @tp_descr_set@ */
860   0,                                    /* @tp_dictoffset@ */
861   0,                                    /* @tp_init@ */
862   PyType_GenericAlloc,                  /* @tp_alloc@ */
863   abstract_pynew,                       /* @tp_new@ */
864   0,                                    /* @tp_free@ */
865   0                                     /* @tp_is_gc@ */
866 };
867
868 static const PyTypeObject gclatinrand_pytype_skel = {
869   PyVarObject_HEAD_INIT(0, 0)           /* Header */
870   "GCLatinRand",                        /* @tp_name@ */
871   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
872   0,                                    /* @tp_itemsize@ */
873
874   grand_pydealloc,                      /* @tp_dealloc@ */
875   0,                                    /* @tp_print@ */
876   0,                                    /* @tp_getattr@ */
877   0,                                    /* @tp_setattr@ */
878   0,                                    /* @tp_compare@ */
879   0,                                    /* @tp_repr@ */
880   0,                                    /* @tp_as_number@ */
881   0,                                    /* @tp_as_sequence@ */
882   0,                                    /* @tp_as_mapping@ */
883   0,                                    /* @tp_hash@ */
884   0,                                    /* @tp_call@ */
885   0,                                    /* @tp_str@ */
886   0,                                    /* @tp_getattro@ */
887   0,                                    /* @tp_setattro@ */
888   0,                                    /* @tp_as_buffer@ */
889   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
890     Py_TPFLAGS_BASETYPE,
891
892   /* @tp_doc@ */
893   "Abstract base class for symmetric crypto-based generators.",
894
895   0,                                    /* @tp_traverse@ */
896   0,                                    /* @tp_clear@ */
897   0,                                    /* @tp_richcompare@ */
898   0,                                    /* @tp_weaklistoffset@ */
899   0,                                    /* @tp_iter@ */
900   0,                                    /* @tp_iternext@ */
901   PYMETHODS(gclatinrand),               /* @tp_methods@ */
902   0,                                    /* @tp_members@ */
903   0,                                    /* @tp_getset@ */
904   0,                                    /* @tp_base@ */
905   0,                                    /* @tp_dict@ */
906   0,                                    /* @tp_descr_get@ */
907   0,                                    /* @tp_descr_set@ */
908   0,                                    /* @tp_dictoffset@ */
909   0,                                    /* @tp_init@ */
910   PyType_GenericAlloc,                  /* @tp_alloc@ */
911   abstract_pynew,                       /* @tp_new@ */
912   0,                                    /* @tp_free@ */
913   0                                     /* @tp_is_gc@ */
914 };
915
916 /*----- SSL and TLS generators --------------------------------------------*/
917
918 static PyObject *sslprf_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
919 {
920   struct bin k, s;
921   const gchash *hco = &md5, *hci = &sha;
922   PyObject *rc = 0;
923   static const char *const kwlist[] = { "key", "seed", "ohash", "ihash", 0 };
924
925   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&|O&O&:new", KWLIST,
926                                    convbin, &k, convbin, &s,
927                                    convgchash, &hco, convgchash, &hci))
928     goto end;
929   rc = grand_dopywrap(ty, sslprf_rand(hco, hci, k.p, k.sz, s.p, s.sz),
930                       f_freeme);
931 end:
932   return (rc);
933 }
934
935 static PyObject *tlsdx_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
936 {
937   struct bin k, s;
938   const gcmac *mc = &sha_hmac;
939   PyObject *rc = 0;
940   static const char *const kwlist[] = { "key", "seed", "mac", 0 };
941
942   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&|O&:new", KWLIST,
943                                    convbin, &k, convbin, &s,
944                                    convgcmac, &mc))
945     goto end;
946   rc = grand_dopywrap(ty, tlsdx_rand(mc, k.p, k.sz, s.p, s.sz), f_freeme);
947 end:
948   return (rc);
949 }
950
951 static PyObject *tlsprf_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
952 {
953   struct bin k, s;
954   const gcmac *mcl = &md5_hmac, *mcr = &sha_hmac;
955   PyObject *rc = 0;
956   static const char *const kwlist[] = { "key", "seed", "lmac", "rmac", 0 };
957
958   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&|O&O&:new", KWLIST,
959                                    convbin, &k, convbin, &s,
960                                    convgcmac, &mcl, convgcmac, &mcr))
961     goto end;
962   rc = grand_dopywrap(ty, tlsprf_rand(mcl, mcr, k.p, k.sz, s.p, s.sz),
963                       f_freeme);
964 end:
965   return (rc);
966 }
967
968 static const PyTypeObject sslprf_pytype_skel = {
969   PyVarObject_HEAD_INIT(0, 0)           /* Header */
970   "SSLRand",                            /* @tp_name@ */
971   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
972   0,                                    /* @tp_itemsize@ */
973
974   grand_pydealloc,                      /* @tp_dealloc@ */
975   0,                                    /* @tp_print@ */
976   0,                                    /* @tp_getattr@ */
977   0,                                    /* @tp_setattr@ */
978   0,                                    /* @tp_compare@ */
979   0,                                    /* @tp_repr@ */
980   0,                                    /* @tp_as_number@ */
981   0,                                    /* @tp_as_sequence@ */
982   0,                                    /* @tp_as_mapping@ */
983   0,                                    /* @tp_hash@ */
984   0,                                    /* @tp_call@ */
985   0,                                    /* @tp_str@ */
986   0,                                    /* @tp_getattro@ */
987   0,                                    /* @tp_setattro@ */
988   0,                                    /* @tp_as_buffer@ */
989   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
990     Py_TPFLAGS_BASETYPE,
991
992   /* @tp_doc@ */
993   "SSLRand(KEY, SEED, [ohash = md5], [ihash = sha]):\n"
994   "  RNG for SSL master secret.",
995
996   0,                                    /* @tp_traverse@ */
997   0,                                    /* @tp_clear@ */
998   0,                                    /* @tp_richcompare@ */
999   0,                                    /* @tp_weaklistoffset@ */
1000   0,                                    /* @tp_iter@ */
1001   0,                                    /* @tp_iternext@ */
1002   0,                                    /* @tp_methods@ */
1003   0,                                    /* @tp_members@ */
1004   0,                                    /* @tp_getset@ */
1005   0,                                    /* @tp_base@ */
1006   0,                                    /* @tp_dict@ */
1007   0,                                    /* @tp_descr_get@ */
1008   0,                                    /* @tp_descr_set@ */
1009   0,                                    /* @tp_dictoffset@ */
1010   0,                                    /* @tp_init@ */
1011   PyType_GenericAlloc,                  /* @tp_alloc@ */
1012   sslprf_pynew,                         /* @tp_new@ */
1013   0,                                    /* @tp_free@ */
1014   0                                     /* @tp_is_gc@ */
1015 };
1016
1017 static const PyTypeObject tlsdx_pytype_skel = {
1018   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1019   "TLSDataExpansion",                   /* @tp_name@ */
1020   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
1021   0,                                    /* @tp_itemsize@ */
1022
1023   grand_pydealloc,                      /* @tp_dealloc@ */
1024   0,                                    /* @tp_print@ */
1025   0,                                    /* @tp_getattr@ */
1026   0,                                    /* @tp_setattr@ */
1027   0,                                    /* @tp_compare@ */
1028   0,                                    /* @tp_repr@ */
1029   0,                                    /* @tp_as_number@ */
1030   0,                                    /* @tp_as_sequence@ */
1031   0,                                    /* @tp_as_mapping@ */
1032   0,                                    /* @tp_hash@ */
1033   0,                                    /* @tp_call@ */
1034   0,                                    /* @tp_str@ */
1035   0,                                    /* @tp_getattro@ */
1036   0,                                    /* @tp_setattro@ */
1037   0,                                    /* @tp_as_buffer@ */
1038   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1039     Py_TPFLAGS_BASETYPE,
1040
1041   /* @tp_doc@ */
1042   "TLSDataExpansion(KEY, SEED, [mac = sha_hmac]):\n"
1043   "  TLS data expansion function.",
1044
1045   0,                                    /* @tp_traverse@ */
1046   0,                                    /* @tp_clear@ */
1047   0,                                    /* @tp_richcompare@ */
1048   0,                                    /* @tp_weaklistoffset@ */
1049   0,                                    /* @tp_iter@ */
1050   0,                                    /* @tp_iternext@ */
1051   0,                                    /* @tp_methods@ */
1052   0,                                    /* @tp_members@ */
1053   0,                                    /* @tp_getset@ */
1054   0,                                    /* @tp_base@ */
1055   0,                                    /* @tp_dict@ */
1056   0,                                    /* @tp_descr_get@ */
1057   0,                                    /* @tp_descr_set@ */
1058   0,                                    /* @tp_dictoffset@ */
1059   0,                                    /* @tp_init@ */
1060   PyType_GenericAlloc,                  /* @tp_alloc@ */
1061   tlsdx_pynew,                          /* @tp_new@ */
1062   0,                                    /* @tp_free@ */
1063   0                                     /* @tp_is_gc@ */
1064 };
1065
1066 static const PyTypeObject tlsprf_pytype_skel = {
1067   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1068   "TLSPRF",                             /* @tp_name@ */
1069   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
1070   0,                                    /* @tp_itemsize@ */
1071
1072   grand_pydealloc,                      /* @tp_dealloc@ */
1073   0,                                    /* @tp_print@ */
1074   0,                                    /* @tp_getattr@ */
1075   0,                                    /* @tp_setattr@ */
1076   0,                                    /* @tp_compare@ */
1077   0,                                    /* @tp_repr@ */
1078   0,                                    /* @tp_as_number@ */
1079   0,                                    /* @tp_as_sequence@ */
1080   0,                                    /* @tp_as_mapping@ */
1081   0,                                    /* @tp_hash@ */
1082   0,                                    /* @tp_call@ */
1083   0,                                    /* @tp_str@ */
1084   0,                                    /* @tp_getattro@ */
1085   0,                                    /* @tp_setattro@ */
1086   0,                                    /* @tp_as_buffer@ */
1087   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1088     Py_TPFLAGS_BASETYPE,
1089
1090   /* @tp_doc@ */
1091   "TLSPRF(KEY, SEED, [lmac = md5_hmac], [rmac = sha_hmac]):\n"
1092   "  TLS pseudorandom function.",
1093
1094   0,                                    /* @tp_traverse@ */
1095   0,                                    /* @tp_clear@ */
1096   0,                                    /* @tp_richcompare@ */
1097   0,                                    /* @tp_weaklistoffset@ */
1098   0,                                    /* @tp_iter@ */
1099   0,                                    /* @tp_iternext@ */
1100   0,                                    /* @tp_methods@ */
1101   0,                                    /* @tp_members@ */
1102   0,                                    /* @tp_getset@ */
1103   0,                                    /* @tp_base@ */
1104   0,                                    /* @tp_dict@ */
1105   0,                                    /* @tp_descr_get@ */
1106   0,                                    /* @tp_descr_set@ */
1107   0,                                    /* @tp_dictoffset@ */
1108   0,                                    /* @tp_init@ */
1109   PyType_GenericAlloc,                  /* @tp_alloc@ */
1110   tlsprf_pynew,                         /* @tp_new@ */
1111   0,                                    /* @tp_free@ */
1112   0                                     /* @tp_is_gc@ */
1113 };
1114
1115 /*----- DSA generator -----------------------------------------------------*/
1116
1117 static PyObject *dsarand_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1118 {
1119   struct bin in;
1120   PyObject *rc = 0;
1121   static const char *const kwlist[] = { "seed", 0 };
1122
1123   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convbin, &in))
1124     goto end;
1125   rc = grand_dopywrap(ty, dsarand_create(in.p, in.sz), f_freeme);
1126 end:
1127   return (rc);
1128 }
1129
1130 static PyObject *drget_seed(PyObject *me, void *hunoz)
1131 {
1132   grand *r = GRAND_R(me);
1133   int n = r->ops->misc(r, DSARAND_SEEDSZ);
1134   PyObject *rc = bytestring_pywrap(0, n);
1135   r->ops->misc(r, DSARAND_GETSEED, BIN_PTR(rc));
1136   return (rc);
1137 }
1138
1139 static const PyGetSetDef dsarand_pygetset[] = {
1140 #define GETSETNAME(op, name) dr##op##_##name
1141   GET   (seed,          "R.seed -> current generator seed")
1142 #undef GETSETNAME
1143   { 0 }
1144 };
1145
1146 static const PyTypeObject dsarand_pytype_skel = {
1147   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1148   "DSARand",                            /* @tp_name@ */
1149   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
1150   0,                                    /* @tp_itemsize@ */
1151
1152   grand_pydealloc,                      /* @tp_dealloc@ */
1153   0,                                    /* @tp_print@ */
1154   0,                                    /* @tp_getattr@ */
1155   0,                                    /* @tp_setattr@ */
1156   0,                                    /* @tp_compare@ */
1157   0,                                    /* @tp_repr@ */
1158   0,                                    /* @tp_as_number@ */
1159   0,                                    /* @tp_as_sequence@ */
1160   0,                                    /* @tp_as_mapping@ */
1161   0,                                    /* @tp_hash@ */
1162   0,                                    /* @tp_call@ */
1163   0,                                    /* @tp_str@ */
1164   0,                                    /* @tp_getattro@ */
1165   0,                                    /* @tp_setattro@ */
1166   0,                                    /* @tp_as_buffer@ */
1167   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1168     Py_TPFLAGS_BASETYPE,
1169
1170   /* @tp_doc@ */
1171   "DSARand(SEED): pseudorandom number generator for DSA parameters.",
1172
1173   0,                                    /* @tp_traverse@ */
1174   0,                                    /* @tp_clear@ */
1175   0,                                    /* @tp_richcompare@ */
1176   0,                                    /* @tp_weaklistoffset@ */
1177   0,                                    /* @tp_iter@ */
1178   0,                                    /* @tp_iternext@ */
1179   0,                                    /* @tp_methods@ */
1180   0,                                    /* @tp_members@ */
1181   PYGETSET(dsarand),                    /* @tp_getset@ */
1182   0,                                    /* @tp_base@ */
1183   0,                                    /* @tp_dict@ */
1184   0,                                    /* @tp_descr_get@ */
1185   0,                                    /* @tp_descr_set@ */
1186   0,                                    /* @tp_dictoffset@ */
1187   0,                                    /* @tp_init@ */
1188   PyType_GenericAlloc,                  /* @tp_alloc@ */
1189   dsarand_pynew,                        /* @tp_new@ */
1190   0,                                    /* @tp_free@ */
1191   0                                     /* @tp_is_gc@ */
1192 };
1193
1194 /*----- Blum-Blum-Shub generator ------------------------------------------*/
1195
1196 static PyObject *bbs_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1197 {
1198   mp *n = 0, *x = MP_TWO;
1199   PyObject *rc = 0;
1200   static const char *const kwlist[] = { "n", "x", 0 };
1201
1202   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|O&:new", KWLIST,
1203                                    convmp, &n, convmp, &x))
1204     goto end;
1205   rc = grand_dopywrap(ty, bbs_rand(n, x), f_freeme);
1206 end:
1207   mp_drop(n);
1208   mp_drop(x);
1209   return (rc);
1210 }
1211
1212 static PyObject *bbsmeth_step(PyObject *me)
1213   { grand *r = GRAND_R(me); r->ops->misc(r, BBS_STEP); RETURN_ME; }
1214
1215 static PyObject *bbsmeth_bits(PyObject *me, PyObject *arg)
1216 {
1217   grand *r = GRAND_R(me); unsigned n; uint32 w;
1218   if (!PyArg_ParseTuple(arg, "O&:bits", convuint, &n)) goto end;
1219   if (n > 32) VALERR("can't get more than 32 bits");
1220   r->ops->misc(r, BBS_BITS, n, &w); return (getulong(w));
1221 end:
1222   return (0);
1223 }
1224
1225 static PyObject *bbsmeth_wrap(PyObject *me)
1226   { grand *r = GRAND_R(me); r->ops->misc(r, BBS_WRAP); RETURN_ME; }
1227
1228 static PyObject *bbsget_n(PyObject *me, void *hunoz)
1229 {
1230   mp *x = MP_NEW; grand *r = GRAND_R(me);
1231   r->ops->misc(r, BBS_MOD, &x); return (mp_pywrap(x));
1232 }
1233
1234 static PyObject *bbsget_x(PyObject *me, void *hunoz)
1235 {
1236   mp *x = MP_NEW; grand *r = GRAND_R(me);
1237   r->ops->misc(r, BBS_STATE, &x); return (mp_pywrap(x));
1238 }
1239
1240 static int bbsset_x(PyObject *me, PyObject *val, void *hunoz)
1241 {
1242   mp *x = 0; grand *r = GRAND_R(me); int rc = -1; if (!val) NIERR("__del__");
1243   if ((x = getmp(val)) == 0) goto end;
1244   r->ops->misc(r, BBS_SET, x); rc = 0;
1245   end: mp_drop(x); return (rc);
1246 }
1247
1248 static PyObject *bbsget_stepsz(PyObject *me, void *hunoz)
1249 {
1250   grand *r = GRAND_R(me);
1251   return (PyInt_FromLong(r->ops->misc(r, BBS_STEPSZ)));
1252 }
1253
1254 static const PyMethodDef bbs_pymethods[] = {
1255 #define METHNAME(name) bbsmeth_##name
1256   NAMETH(step,          "R.step(): steps the generator (not useful)")
1257   METH  (bits,   "R.bits(N) -> W: returns N bits (<= 32) from the generator")
1258   NAMETH(wrap,          "R.wrap(): flushes unused bits in internal buffer")
1259 #undef METHNAME
1260   { 0 }
1261 };
1262
1263 static const PyGetSetDef bbs_pygetset[] = {
1264 #define GETSETNAME(op, name) bbs##op##_##name
1265   GET   (n,             "R.n -> Blum modulus")
1266   GETSET(x,             "R.x -> current seed value")
1267   GET   (stepsz,        "R.stepsz -> number of bits generated per step")
1268 #undef GETSETNAME
1269   { 0 }
1270 };
1271
1272 static const PyTypeObject bbs_pytype_skel = {
1273   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1274   "BlumBlumShub",                       /* @tp_name@ */
1275   sizeof(grand_pyobj),                  /* @tp_basicsize@ */
1276   0,                                    /* @tp_itemsize@ */
1277
1278   grand_pydealloc,                      /* @tp_dealloc@ */
1279   0,                                    /* @tp_print@ */
1280   0,                                    /* @tp_getattr@ */
1281   0,                                    /* @tp_setattr@ */
1282   0,                                    /* @tp_compare@ */
1283   0,                                    /* @tp_repr@ */
1284   0,                                    /* @tp_as_number@ */
1285   0,                                    /* @tp_as_sequence@ */
1286   0,                                    /* @tp_as_mapping@ */
1287   0,                                    /* @tp_hash@ */
1288   0,                                    /* @tp_call@ */
1289   0,                                    /* @tp_str@ */
1290   0,                                    /* @tp_getattro@ */
1291   0,                                    /* @tp_setattro@ */
1292   0,                                    /* @tp_as_buffer@ */
1293   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1294     Py_TPFLAGS_BASETYPE,
1295
1296   /* @tp_doc@ */
1297   "BlumBlumShub(N, [x = 2]): Blum-Blum-Shub pseudorandom number generator.",
1298
1299   0,                                    /* @tp_traverse@ */
1300   0,                                    /* @tp_clear@ */
1301   0,                                    /* @tp_richcompare@ */
1302   0,                                    /* @tp_weaklistoffset@ */
1303   0,                                    /* @tp_iter@ */
1304   0,                                    /* @tp_iternext@ */
1305   PYMETHODS(bbs),                       /* @tp_methods@ */
1306   0,                                    /* @tp_members@ */
1307   PYGETSET(bbs),                        /* @tp_getset@ */
1308   0,                                    /* @tp_base@ */
1309   0,                                    /* @tp_dict@ */
1310   0,                                    /* @tp_descr_get@ */
1311   0,                                    /* @tp_descr_set@ */
1312   0,                                    /* @tp_dictoffset@ */
1313   0,                                    /* @tp_init@ */
1314   PyType_GenericAlloc,                  /* @tp_alloc@ */
1315   bbs_pynew,                            /* @tp_new@ */
1316   0,                                    /* @tp_free@ */
1317   0                                     /* @tp_is_gc@ */
1318 };
1319
1320 typedef struct bbspriv_pyobj {
1321   grand_pyobj gr;
1322   bbs_priv bp;
1323 } bbspriv_pyobj;
1324
1325 #define BBSPRIV_BP(o) (&((bbspriv_pyobj *)(o))->bp)
1326
1327 static PyObject *bbspriv_pynew(PyTypeObject *ty,
1328                                PyObject *arg, PyObject *kw)
1329 {
1330   mp *p = 0, *q = 0, *n = 0, *x = MP_TWO;
1331   bbspriv_pyobj *rc = 0;
1332   static const char *const kwlist[] = { "n", "p", "q", "seed", 0 };
1333
1334   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&O&O&O&:new", KWLIST,
1335                                    convmp, &n, convmp, &p, convmp, &q,
1336                                    convmp, &x))
1337     goto end;
1338   if (!n + !p + !q > 1) VALERR("must specify at least two of n, p, q");
1339   if (!n) n = mp_mul(MP_NEW, p, q);
1340   else if (!p) mp_div(&p, 0, n, q);
1341   else if (!q) mp_div(&q, 0, n, p);
1342   rc = (bbspriv_pyobj *)ty->tp_alloc(ty, 0);
1343   rc->gr.r = bbs_rand(n, x);
1344   rc->gr.f = f_freeme;
1345   rc->bp.p = MP_COPY(p);
1346   rc->bp.q = MP_COPY(q);
1347   rc->bp.n = MP_COPY(n);
1348 end:
1349   mp_drop(p); mp_drop(q); mp_drop(n); mp_drop(x);
1350   return ((PyObject *)rc);
1351 }
1352
1353 static PyObject *bpmeth_generate(PyObject *me, PyObject *arg, PyObject *kw)
1354 {
1355   bbs_priv bp = { 0 };
1356   mp *x = MP_TWO;
1357   struct excinfo exc = EXCINFO_INIT;
1358   pypgev evt = { { 0 } };
1359   unsigned nbits, n = 0;
1360   grand *r = &rand_global;
1361   static const char *const kwlist[] =
1362     { "nbits", "event", "rng", "nsteps", "seed", 0 };
1363   bbspriv_pyobj *rc = 0;
1364
1365   evt.exc = &exc;
1366   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|O&O&O&O&:generate", KWLIST,
1367                                    convuint, &nbits, convpgev, &evt,
1368                                    convgrand, &r, convuint, &n, convmp, &x))
1369     goto end;
1370   if (bbs_gen(&bp, nbits, r, n, evt.ev.proc, evt.ev.ctx))
1371     PGENERR(&exc);
1372   rc = PyObject_New(bbspriv_pyobj, bbspriv_pytype);
1373   rc->gr.r = bbs_rand(bp.n, x);
1374   rc->gr.f = f_freeme;
1375   rc->bp.p = MP_COPY(bp.p);
1376   rc->bp.q = MP_COPY(bp.q);
1377   rc->bp.n = MP_COPY(bp.n);
1378 end:
1379   mp_drop(bp.p); mp_drop(bp.q); mp_drop(bp.n); mp_drop(x);
1380   return ((PyObject *)rc);
1381 }
1382
1383 static void bbspriv_pydealloc(PyObject *me)
1384 {
1385   bbs_priv *bp = BBSPRIV_BP(me);
1386   mp_drop(bp->n);
1387   mp_drop(bp->p);
1388   mp_drop(bp->q);
1389   grand_pydealloc(me);
1390 }
1391
1392 static PyObject *bpmeth_ff(PyObject *me, PyObject *arg)
1393 {
1394   mp *n = 0; grand *r = GRAND_R(me); bbs_priv *bp = BBSPRIV_BP(me);
1395   if (!PyArg_ParseTuple(arg, "O&:ff", convmp, &n)) return (0);
1396   r->ops->misc(r, BBS_FF, bp, n); RETURN_ME;
1397 }
1398
1399 static PyObject *bpmeth_rew(PyObject *me, PyObject *arg)
1400 {
1401   mp *n = 0; grand *r = GRAND_R(me); bbs_priv *bp = BBSPRIV_BP(me);
1402   if (!PyArg_ParseTuple(arg, "O&:rew", convmp, &n)) return (0);
1403   r->ops->misc(r, BBS_REW, bp, n); RETURN_ME;
1404 }
1405
1406 static PyObject *bpget_n(PyObject *me, void *hunoz)
1407   { return (mp_pywrap(MP_COPY(BBSPRIV_BP(me)->n))); }
1408
1409 static PyObject *bpget_p(PyObject *me, void *hunoz)
1410   { return (mp_pywrap(MP_COPY(BBSPRIV_BP(me)->p))); }
1411
1412 static PyObject *bpget_q(PyObject *me, void *hunoz)
1413   { return (mp_pywrap(MP_COPY(BBSPRIV_BP(me)->q))); }
1414
1415 static const PyMethodDef bbspriv_pymethods[] = {
1416 #define METHNAME(name) bpmeth_##name
1417   METH  (ff,            "R.ff(N): fast-forward N places")
1418   METH  (rew,           "R.rew(N): rewind N places")
1419   KWSMTH(generate,      "generate(NBITS, [event = pgen_nullev], "
1420                               "[rng = rand], [nsteps = 0], [seed = 2]) -> R")
1421 #undef METHNAME
1422   { 0 }
1423 };
1424
1425 static const PyGetSetDef bbspriv_pygetset[] = {
1426 #define GETSETNAME(op, name) bp##op##_##name
1427   GET   (n,             "R.n -> Blum modulus")
1428   GET   (p,             "R.p -> one of the factors of the modulus")
1429   GET   (q,             "R.q -> one of the factors of the modulus")
1430 #undef GETSETNAME
1431   { 0 }
1432 };
1433
1434 static const PyTypeObject bbspriv_pytype_skel = {
1435   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1436   "BBSPriv",                            /* @tp_name@ */
1437   sizeof(bbspriv_pyobj),                /* @tp_basicsize@ */
1438   0,                                    /* @tp_itemsize@ */
1439
1440   bbspriv_pydealloc,                    /* @tp_dealloc@ */
1441   0,                                    /* @tp_print@ */
1442   0,                                    /* @tp_getattr@ */
1443   0,                                    /* @tp_setattr@ */
1444   0,                                    /* @tp_compare@ */
1445   0,                                    /* @tp_repr@ */
1446   0,                                    /* @tp_as_number@ */
1447   0,                                    /* @tp_as_sequence@ */
1448   0,                                    /* @tp_as_mapping@ */
1449   0,                                    /* @tp_hash@ */
1450   0,                                    /* @tp_call@ */
1451   0,                                    /* @tp_str@ */
1452   0,                                    /* @tp_getattro@ */
1453   0,                                    /* @tp_setattro@ */
1454   0,                                    /* @tp_as_buffer@ */
1455   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1456     Py_TPFLAGS_BASETYPE,
1457
1458   /* @tp_doc@ */
1459   "BBSPriv(..., [seed = 2]): Blum-Blum-Shub, with private key.\n"
1460   "  Keywords: n, p, q; must provide at least two",
1461
1462   0,                                    /* @tp_traverse@ */
1463   0,                                    /* @tp_clear@ */
1464   0,                                    /* @tp_richcompare@ */
1465   0,                                    /* @tp_weaklistoffset@ */
1466   0,                                    /* @tp_iter@ */
1467   0,                                    /* @tp_iternext@ */
1468   PYMETHODS(bbspriv),                   /* @tp_methods@ */
1469   0,                                    /* @tp_members@ */
1470   PYGETSET(bbspriv),                    /* @tp_getset@ */
1471   0,                                    /* @tp_base@ */
1472   0,                                    /* @tp_dict@ */
1473   0,                                    /* @tp_descr_get@ */
1474   0,                                    /* @tp_descr_set@ */
1475   0,                                    /* @tp_dictoffset@ */
1476   0,                                    /* @tp_init@ */
1477   PyType_GenericAlloc,                  /* @tp_alloc@ */
1478   bbspriv_pynew,                        /* @tp_new@ */
1479   0,                                    /* @tp_free@ */
1480   0                                     /* @tp_is_gc@ */
1481 };
1482
1483 /*----- Global stuff ------------------------------------------------------*/
1484
1485 static const struct nameval consts[] = {
1486   CONST(RAND_IBITS),
1487   { 0 }
1488 };
1489
1490 void rand_pyinit(void)
1491 {
1492   INITTYPE(grand, root);
1493   INITTYPE(truerand, grand);
1494   INITTYPE(fibrand, grand);
1495   INITTYPE(lcrand, grand);
1496   INITTYPE(dsarand, grand);
1497   INITTYPE(bbs, grand);
1498   INITTYPE(bbspriv, bbs);
1499   INITTYPE(sslprf, grand);
1500   INITTYPE(tlsdx, grand);
1501   INITTYPE(tlsprf, grand);
1502   INITTYPE(gccrand, type);
1503   INITTYPE(gcrand, grand);
1504   INITTYPE(gclatinrand, gcrand);
1505   rand_noisesrc(RAND_GLOBAL, &noise_source);
1506   rand_seed(RAND_GLOBAL, 160);
1507 }
1508
1509 static const char *crand_namefn(const void *p)
1510   { const gccrand_info *const *cls = p; return (*cls ? (*cls)->name : 0); }
1511 static PyObject *crand_valfn(const void *p)
1512   { const gccrand_info *const *cls = p; return (gccrand_pywrap(*cls)); }
1513
1514 void rand_pyinsert(PyObject *mod)
1515 {
1516   INSERT("GRand", grand_pytype);
1517   INSERT("TrueRand", truerand_pytype);
1518   INSERT("LCRand", lcrand_pytype);
1519   INSERT("FibRand", fibrand_pytype);
1520   INSERT("SSLRand", sslprf_pytype);
1521   INSERT("TLSDataExpansion", tlsdx_pytype);
1522   INSERT("TLSPRF", tlsprf_pytype);
1523   INSERT("DSARand", dsarand_pytype);
1524   INSERT("BlumBlumShub", bbs_pytype);
1525   INSERT("BBSPriv", bbspriv_pytype);
1526   INSERT("GCCRand", gccrand_pytype);
1527   INSERT("GCRand", gcrand_pytype);
1528   INSERT("GCLatinRand", gclatinrand_pytype);
1529   rand_pyobj = grand_pywrap(&rand_global, 0); Py_INCREF(rand_pyobj);
1530   gccrands_dict = make_algtab(gcrandtab, sizeof(gccrand_info *),
1531                               crand_namefn, crand_valfn);
1532   INSERT("gccrands", gccrands_dict); Py_INCREF(gccrands_dict);
1533   INSERT("rand", rand_pyobj);
1534   setconstants(mod, consts);
1535 }
1536
1537 /*----- That's all, folks -------------------------------------------------*/