summaryrefslogtreecommitdiffstats
path: root/source4/lib/registry/rpc.c
blob: a8f8382ec5b40982f8f2ee87bf4d5aefde71e67a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
   Samba Unix/Linux SMB implementation
   RPC backend for the registry library
   Copyright (C) 2003-2007 Jelmer Vernooij, jelmer@samba.org
   Copyright (C) 2008 Matthias Dieter Wallnöfer, mwallnoefer@yahoo.de

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include "includes.h"
#include "registry.h"
#include "librpc/gen_ndr/ndr_winreg_c.h"

#define MAX_NAMESIZE 512
#define MAX_VALSIZE 32768

struct rpc_key {
	struct registry_key key;
	struct policy_handle pol;
	struct dcerpc_binding_handle *binding_handle;
	const char* classname;	
	uint32_t num_subkeys;
	uint32_t max_subkeylen;
	uint32_t max_classlen;
	uint32_t num_values;
	uint32_t max_valnamelen;
	uint32_t max_valbufsize;
	uint32_t secdescsize;
	NTTIME last_changed_time;
};

struct rpc_registry_context {
	struct registry_context context;
	struct dcerpc_pipe *pipe;
	struct dcerpc_binding_handle *binding_handle;
};

static struct registry_operations reg_backend_rpc;

/**
 * This is the RPC backend for the registry library.
 */

#define openhive(u) static WERROR open_ ## u(struct dcerpc_binding_handle *b, TALLOC_CTX *mem_ctx, struct policy_handle *hnd) \
{ \
	struct winreg_Open ## u r; \
	NTSTATUS status; \
\
	ZERO_STRUCT(r); \
	r.in.system_name = NULL; \
	r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; \
	r.out.handle = hnd;\
\
	status = dcerpc_winreg_Open ## u ## _r(b, mem_ctx, &r); \
\
	if (!NT_STATUS_IS_OK(status)) { \
		DEBUG(1, ("OpenHive failed - %s\n", nt_errstr(status))); \
		return ntstatus_to_werror(status); \
	} \
\
	return r.out.result;\
}

openhive(HKLM)
openhive(HKCU)
openhive(HKPD)
openhive(HKU)
openhive(HKCR)
openhive(HKDD)
openhive(HKCC)

static struct {
	uint32_t hkey;
	WERROR (*open) (struct dcerpc_binding_handle *b, TALLOC_CTX *,
			struct policy_handle *h);
} known_hives[] = {
	{ HKEY_LOCAL_MACHINE, open_HKLM },
	{ HKEY_CURRENT_USER, open_HKCU },
	{ HKEY_CLASSES_ROOT, open_HKCR },
	{ HKEY_PERFORMANCE_DATA, open_HKPD },
	{ HKEY_USERS, open_HKU },
	{ HKEY_DYN_DATA, open_HKDD },
	{ HKEY_CURRENT_CONFIG, open_HKCC },
	{ 0, NULL }
};

static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k);

static WERROR rpc_get_predefined_key(struct registry_context *ctx,
				     uint32_t hkey_type,
				     struct registry_key **k)
{
	int n;
	struct rpc_key *mykeydata;
	struct rpc_registry_context *rctx = talloc_get_type(ctx, struct rpc_registry_context);

	*k = NULL;

	for(n = 0; known_hives[n].hkey; n++) {
		if(known_hives[n].hkey == hkey_type)
			break;
	}

	if (known_hives[n].open == NULL)  {
		DEBUG(1, ("No such hive %d\n", hkey_type));
		return WERR_NO_MORE_ITEMS;
	}

	mykeydata = talloc_zero(ctx, struct rpc_key);
	W_ERROR_HAVE_NO_MEMORY(mykeydata);
	mykeydata->key.context = ctx;
	mykeydata->binding_handle = rctx->binding_handle;
	mykeydata->num_values = -1;
	mykeydata->num_subkeys = -1;
	*k = (struct registry_key *)mykeydata;
	return known_hives[n].open(mykeydata->binding_handle, mykeydata, &mykeydata->pol);
}

#if 0
static WERROR rpc_key_put_rpc_data(TALLOC_CTX *mem_ctx, struct registry_key *k)
{
	struct winreg_OpenKey r;
	struct rpc_key_data *mykeydata;

	k->backend_data = mykeydata = talloc_zero(mem_ctx, struct rpc_key_data);
	mykeydata->num_values = -1;
	mykeydata->num_subkeys = -1;

	/* Then, open the handle using the hive */

	ZERO_STRUCT(r);
	r.in.handle = &(((struct rpc_key_data *)k->hive->root->backend_data)->pol);
	r.in.keyname.name = k->path;
	r.in.unknown = 0x00000000;
	r.in.access_mask = 0x02000000;
	r.out.handle = &mykeydata->pol;

	dcerpc_winreg_OpenKey((struct dcerpc_pipe *)k->hive->backend_data,
			      mem_ctx, &r);

	return r.out.result;
}
#endif

static WERROR rpc_open_key(TALLOC_CTX *mem_ctx, struct registry_key *h,
			   const char *name, struct registry_key **key)
{
	struct rpc_key *parentkeydata = talloc_get_type(h, struct rpc_key),
						    *mykeydata;
	struct winreg_OpenKey r;
	NTSTATUS status;

	mykeydata = talloc_zero(mem_ctx, struct rpc_key);
	W_ERROR_HAVE_NO_MEMORY(mykeydata);
	mykeydata->key.context = parentkeydata->key.context;
	mykeydata->binding_handle = parentkeydata->binding_handle;
	mykeydata->num_values = -1;
	mykeydata->num_subkeys = -1;
	*key = (struct registry_key *)mykeydata;

	/* Then, open the handle using the hive */
	ZERO_STRUCT(r);
	r.in.parent_handle = &parentkeydata->pol;
	r.in.keyname.name = name;
	r.in.options = 0x00000000;
	r.in.access_mask = 0x02000000;
	r.out.handle = &mykeydata->pol;

	status = dcerpc_winreg_OpenKey_r(mykeydata->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("OpenKey failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	return r.out.result;
}

static WERROR rpc_get_value_by_index(TALLOC_CTX *mem_ctx,
				     const struct registry_key *parent,
				     uint32_t n,
				     const char **value_name,
				     uint32_t *type,
				     DATA_BLOB *data)
{
	struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key);
	struct winreg_EnumValue r;
	struct winreg_ValNameBuf name;
	uint8_t value;
	uint32_t val_size = MAX_VALSIZE;
	uint32_t zero = 0;
	WERROR error;
	NTSTATUS status;

	if (mykeydata->num_values == -1) {
		error = rpc_query_key(mem_ctx, parent);
		if(!W_ERROR_IS_OK(error)) return error;
	}

	name.name = "";
	name.size = MAX_NAMESIZE;

	ZERO_STRUCT(r);
	r.in.handle = &mykeydata->pol;
	r.in.enum_index = n;
	r.in.name = &name;
	r.in.type = (enum winreg_Type *) type;
	r.in.value = &value;
	r.in.size = &val_size;
	r.in.length = &zero;
	r.out.name = &name;
	r.out.type = (enum winreg_Type *) type;
	r.out.value = &value;
	r.out.size = &val_size;
	r.out.length = &zero;

	status = dcerpc_winreg_EnumValue_r(mykeydata->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("EnumValue failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	*value_name = talloc_steal(mem_ctx, r.out.name->name);
	*type = *(r.out.type);
	*data = data_blob_talloc(mem_ctx, r.out.value, *r.out.length);

	return r.out.result;
}

static WERROR rpc_get_value_by_name(TALLOC_CTX *mem_ctx,
				     const struct registry_key *parent,
				     const char *value_name,
				     uint32_t *type,
				     DATA_BLOB *data)
{
	struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key);
	struct winreg_QueryValue r;
	struct winreg_String name;
	uint8_t value;
	uint32_t val_size = MAX_VALSIZE;
	uint32_t zero = 0;
	WERROR error;
	NTSTATUS status;

	if (mykeydata->num_values == -1) {
		error = rpc_query_key(mem_ctx, parent);
		if(!W_ERROR_IS_OK(error)) return error;
	}

	name.name = value_name;

	ZERO_STRUCT(r);
	r.in.handle = &mykeydata->pol;
	r.in.value_name = &name;
	r.in.type = (enum winreg_Type *) type;
	r.in.data = &value;
	r.in.data_size = &val_size;
	r.in.data_length = &zero;
	r.out.type = (enum winreg_Type *) type;
	r.out.data = &value;
	r.out.data_size = &val_size;
	r.out.data_length = &zero;

	status = dcerpc_winreg_QueryValue_r(mykeydata->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("QueryValue failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	*type = *(r.out.type);
	*data = data_blob_talloc(mem_ctx, r.out.data, *r.out.data_length);

	return r.out.result;
}

static WERROR rpc_get_subkey_by_index(TALLOC_CTX *mem_ctx,
				      const struct registry_key *parent,
				      uint32_t n,
				      const char **name,
				      const char **keyclass,
				      NTTIME *last_changed_time)
{
	struct winreg_EnumKey r;
	struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key);
	struct winreg_StringBuf namebuf, classbuf;
	NTTIME change_time = 0;
	NTSTATUS status;

	namebuf.name = "";
	namebuf.size = MAX_NAMESIZE;
	classbuf.name = NULL;
	classbuf.size = 0;

	ZERO_STRUCT(r);
	r.in.handle = &mykeydata->pol;
	r.in.enum_index = n;
	r.in.name = &namebuf;
	r.in.keyclass = &classbuf;
	r.in.last_changed_time = &change_time;
	r.out.name = &namebuf;
	r.out.keyclass = &classbuf;
	r.out.last_changed_time = &change_time;

	status = dcerpc_winreg_EnumKey_r(mykeydata->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("EnumKey failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	if (name != NULL)
		*name = talloc_steal(mem_ctx, r.out.name->name);
	if (keyclass != NULL)
		*keyclass = talloc_steal(mem_ctx, r.out.keyclass->name);
	if (last_changed_time != NULL)
		*last_changed_time = *(r.out.last_changed_time);

	return r.out.result;
}

static WERROR rpc_add_key(TALLOC_CTX *mem_ctx,
			  struct registry_key *parent, const char *path,
			  const char *key_class,
			  struct security_descriptor *sec,
			  struct registry_key **key)
{
	struct winreg_CreateKey r;
	struct rpc_key *parentkd = talloc_get_type(parent, struct rpc_key);
	struct rpc_key *rpck = talloc(mem_ctx, struct rpc_key);
	
	NTSTATUS status;

	ZERO_STRUCT(r);
	r.in.handle = &parentkd->pol;
	r.in.name.name = path;
	r.in.keyclass.name = NULL;
	r.in.options = 0;
	r.in.access_mask = 0x02000000;
	r.in.secdesc = NULL;
	r.in.action_taken = NULL;
	r.out.new_handle = &rpck->pol;
	r.out.action_taken = NULL;

	status = dcerpc_winreg_CreateKey_r(parentkd->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		talloc_free(rpck);
		DEBUG(1, ("CreateKey failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	rpck->binding_handle = parentkd->binding_handle;
	*key = (struct registry_key *)rpck;

	return r.out.result;
}

static WERROR rpc_query_key(TALLOC_CTX *mem_ctx, const struct registry_key *k)
{
	struct winreg_QueryInfoKey r;
	struct rpc_key *mykeydata = talloc_get_type(k, struct rpc_key);
	struct winreg_String classname;
	NTSTATUS status;

	classname.name = NULL;

	ZERO_STRUCT(r);
	r.in.handle = &mykeydata->pol;
	r.in.classname = &classname;
	r.out.classname = &classname;
	r.out.num_subkeys = &mykeydata->num_subkeys;
	r.out.max_subkeylen = &mykeydata->max_subkeylen;
	r.out.max_classlen = &mykeydata->max_classlen;
	r.out.num_values = &mykeydata->num_values;
	r.out.max_valnamelen = &mykeydata->max_valnamelen;
	r.out.max_valbufsize = &mykeydata->max_valbufsize;
	r.out.secdescsize = &mykeydata->secdescsize;
	r.out.last_changed_time = &mykeydata->last_changed_time;

	status = dcerpc_winreg_QueryInfoKey_r(mykeydata->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("QueryInfoKey failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	mykeydata->classname = talloc_steal(mem_ctx, r.out.classname->name);

	return r.out.result;
}

static WERROR rpc_del_key(TALLOC_CTX *mem_ctx, struct registry_key *parent,
			  const char *name)
{
	NTSTATUS status;
	struct rpc_key *mykeydata = talloc_get_type(parent, struct rpc_key);
	struct winreg_DeleteKey r;

	ZERO_STRUCT(r);
	r.in.handle = &mykeydata->pol;
	r.in.key.name = name;

	status = dcerpc_winreg_DeleteKey_r(mykeydata->binding_handle, mem_ctx, &r);

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("DeleteKey failed - %s\n", nt_errstr(status)));
		return ntstatus_to_werror(status);
	}

	return r.out.result;
}

static WERROR rpc_get_info(TALLOC_CTX *mem_ctx, const struct registry_key *key,
						   const char **classname,
						   uint32_t *num_subkeys,
						   uint32_t *num_values,
						   NTTIME *last_changed_time,
						   uint32_t *max_subkeylen,
						   uint32_t *max_valnamelen,
						   uint32_t *max_valbufsize)
{
	struct rpc_key *mykeydata = talloc_get_type(key, struct rpc_key);
	WERROR error;

	if (mykeydata->num_values == -1) {
		error = rpc_query_key(mem_ctx, key);
		if(!W_ERROR_IS_OK(error)) return error;
	}

	if (classname != NULL)
		*classname = mykeydata->classname;

	if (num_subkeys != NULL)
		*num_subkeys = mykeydata->num_subkeys;

	if (num_values != NULL)
		*num_values = mykeydata->num_values;

	if (last_changed_time != NULL)
		*last_changed_time = mykeydata->last_changed_time;

	if (max_subkeylen != NULL)
		*max_subkeylen = mykeydata->max_subkeylen;

	if (max_valnamelen != NULL)
		*max_valnamelen = mykeydata->max_valnamelen;

	if (max_valbufsize != NULL)
		*max_valbufsize = mykeydata->max_valbufsize;

	return WERR_OK;
}

static struct registry_operations reg_backend_rpc = {
	.name = "rpc",
	.open_key = rpc_open_key,
	.get_predefined_key = rpc_get_predefined_key,
	.enum_key = rpc_get_subkey_by_index,
	.enum_value = rpc_get_value_by_index,
	.get_value = rpc_get_value_by_name,
	.create_key = rpc_add_key,
	.delete_key = rpc_del_key,
	.get_key_info = rpc_get_info,
};

_PUBLIC_ WERROR reg_open_remote(TALLOC_CTX *mem_ctx,
				struct registry_context **ctx,
				struct auth_session_info *session_info,
				struct cli_credentials *credentials,
				struct loadparm_context *lp_ctx,
				const char *location, struct tevent_context *ev)
{
	NTSTATUS status;
	struct dcerpc_pipe *p;
	struct rpc_registry_context *rctx;

	dcerpc_init();

	rctx = talloc(mem_ctx, struct rpc_registry_context);
	W_ERROR_HAVE_NO_MEMORY(rctx);

	/* Default to local smbd if no connection is specified */
	if (!location) {
		location = talloc_strdup(rctx, "ncalrpc:");
	}

	status = dcerpc_pipe_connect(rctx /* TALLOC_CTX */,
				     &p, location,
				     &ndr_table_winreg,
				     credentials, ev, lp_ctx);
	if(NT_STATUS_IS_ERR(status)) {
		DEBUG(1, ("Unable to open '%s': %s\n", location,
			nt_errstr(status)));
		talloc_free(rctx);
		*ctx = NULL;
		return ntstatus_to_werror(status);
	}

	rctx->pipe = p;
	rctx->binding_handle = p->binding_handle;

	*ctx = (struct registry_context *)rctx;
	(*ctx)->ops = &reg_backend_rpc;

	return WERR_OK;
}
s="hl kwd">BIGLO(num); num = BIGDN(num); } i = DIGSPERLONG; while (--i && !digits[i]) ; RBIGNUM(big)->len = i+1; return big; } VALUE rb_int2big(n) long n; { long neg = 0; VALUE big; if (n < 0) { n = -n; neg = 1; } big = rb_uint2big(n); if (neg) { RBIGNUM(big)->sign = 0; } return big; } VALUE rb_uint2inum(n) unsigned long n; { if (POSFIXABLE(n)) return LONG2FIX(n); return rb_uint2big(n); } VALUE rb_int2inum(n) long n; { if (FIXABLE(n)) return LONG2FIX(n); return rb_int2big(n); } #ifdef HAVE_LONG_LONG void rb_quad_pack(buf, val) char *buf; VALUE val; { LONG_LONG q; val = rb_to_int(val); if (FIXNUM_P(val)) { q = FIX2LONG(val); } else { long len = RBIGNUM(val)->len; BDIGIT *ds; ds = BDIGITS(val); q = 0; while (len--) { q = BIGUP(q); q += ds[len]; } if (!RBIGNUM(val)->sign) q = -q; } memcpy(buf, (char*)&q, SIZEOF_LONG_LONG); } VALUE rb_quad_unpack(buf, sign) const char *buf; int sign; { unsigned LONG_LONG q; long neg = 0; long i; BDIGIT *digits; VALUE big; memcpy(&q, buf, SIZEOF_LONG_LONG); if (sign) { if (FIXABLE((LONG_LONG)q)) return LONG2FIX((LONG_LONG)q); if ((LONG_LONG)q < 0) { q = -(LONG_LONG)q; neg = 1; } } else { if (POSFIXABLE(q)) return LONG2FIX(q); } i = 0; big = bignew(DIGSPERLL, 1); digits = BDIGITS(big); while (i < DIGSPERLL) { digits[i++] = BIGLO(q); q = BIGDN(q); } i = DIGSPERLL; while (i-- && !digits[i]) ; RBIGNUM(big)->len = i+1; if (neg) { RBIGNUM(big)->sign = 0; } return bignorm(big); } #else #define QUAD_SIZE 8 void rb_quad_pack(buf, val) char *buf; VALUE val; { long len; memset(buf, 0, QUAD_SIZE); val = rb_to_int(val); if (FIXNUM_P(val)) { val = rb_int2big(FIX2LONG(val)); } len = RBIGNUM(val)->len * SIZEOF_BDIGITS; if (len > QUAD_SIZE) len = QUAD_SIZE; memcpy(buf, (char*)BDIGITS(val), len); if (!RBIGNUM(val)->sign) { len = QUAD_SIZE; while (len--) { *buf = ~*buf; buf++; } } } #define BNEG(b) (RSHIFT(((BDIGIT*)b)[QUAD_SIZE/SIZEOF_BDIGITS-1],BITSPERDIG-1) != 0) VALUE rb_quad_unpack(buf, sign) const char *buf; int sign; { VALUE big = bignew(QUAD_SIZE/SIZEOF_BDIGITS, 1); memcpy((char*)BDIGITS(big), buf, QUAD_SIZE); if (sign && BNEG(buf)) { long len = QUAD_SIZE; char *tmp = (char*)BDIGITS(big); RBIGNUM(big)->sign = 0; while (len--) { *tmp = ~*tmp; tmp++; } } return bignorm(big); } #endif VALUE rb_cstr_to_inum(str, base, badcheck) const char *str; int base; int badcheck; { const char *s = str; char *end; char sign = 1, nondigit = 0; int c; BDIGIT_DBL num; long len, blen = 1; long i; VALUE z; BDIGIT *zds; if (!str) { if (badcheck) goto bad; return INT2FIX(0); } if (badcheck) { while (ISSPACE(*str)) str++; } else { while (ISSPACE(*str) || *str == '_') str++; } if (str[0] == '+') { str++; } else if (str[0] == '-') { str++; sign = 0; } if (str[0] == '+' || str[0] == '-') { if (badcheck) goto bad; return INT2FIX(0); } if (base <= 0) { if (str[0] == '0') { switch (str[1]) { case 'x': case 'X': base = 16; break; case 'b': case 'B': base = 2; break; case 'o': case 'O': base = 8; break; case 'd': case 'D': base = 10; break; default: base = 8; } } else if (base < -1) { base = -base; } else { base = 10; } } switch (base) { case 2: len = 1; if (str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) { str += 2; } break; case 3: len = 2; break; case 8: if (str[0] == '0' && (str[1] == 'o'||str[1] == 'O')) { str += 2; } case 4: case 5: case 6: case 7: len = 3; break; case 10: if (str[0] == '0' && (str[1] == 'd'||str[1] == 'D')) { str += 2; } case 9: case 11: case 12: case 13: case 14: case 15: len = 4; break; case 16: len = 4; if (str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) { str += 2; } break; default: if (base < 2 || 36 < base) { rb_raise(rb_eArgError, "illegal radix %d", base); } if (base <= 32) { len = 5; } else { len = 6; } break; } if (*str == '0') { /* squeeze preceeding 0s */ while (*++str == '0'); --str; } len *= strlen(str)*sizeof(char); if (len <= (sizeof(VALUE)*CHAR_BIT)) { unsigned long val = strtoul((char*)str, &end, base); if (*end == '_') goto bigparse; if (badcheck) { if (end == str) goto bad; /* no number */ while (*end && ISSPACE(*end)) end++; if (*end) goto bad; /* trailing garbage */ } if (POSFIXABLE(val)) { if (sign) return LONG2FIX(val); else { long result = -(long)val; return LONG2FIX(result); } } else { VALUE big = rb_uint2big(val); RBIGNUM(big)->sign = sign; return bignorm(big); } } bigparse: len = (len/BITSPERDIG)+1; if (badcheck && *str == '_') goto bad; z = bignew(len, sign); zds = BDIGITS(z); for (i=len;i--;) zds[i]=0; while (c = *str++) { if (c == '_') { if (badcheck) { if (nondigit) goto bad; nondigit = c; } continue; } else if (isdigit(c)) { c -= '0'; } else if (islower(c)) { c -= 'a' - 10; } else if (isupper(c)) { c -= 'A' - 10; } else { break; } if (c >= base) break; nondigit = 0; i = 0; num = c; for (;;) { while (i<blen) { num += (BDIGIT_DBL)zds[i]*base; zds[i++] = BIGLO(num); num = BIGDN(num); } if (num) { blen++; continue; } break; } } if (badcheck) { str--; if (s+1 < str && str[-1] == '_') goto bad; while (*str && ISSPACE(*str)) str++; if (*str) { bad: rb_invalid_str(s, "Integer"); } } return bignorm(z); } VALUE rb_str_to_inum(str, base, badcheck) VALUE str; int base; int badcheck; { char *s; long len; StringValue(str); if (badcheck) { s = StringValueCStr(str); } else { s = RSTRING(str)->ptr; } if (s) { len = RSTRING(str)->len; if (s[len]) { /* no sentinel somehow */ char *p = ALLOCA_N(char, len+1); MEMCPY(p, s, char, len); p[len] = '\0'; s = p; } } return rb_cstr_to_inum(s, base, badcheck); } #if HAVE_LONG_LONG VALUE rb_ull2big(n) unsigned LONG_LONG n; { BDIGIT_DBL num = n; long i = 0; BDIGIT *digits; VALUE big; big = bignew(DIGSPERLL, 1); digits = BDIGITS(big); while (i < DIGSPERLL) { digits[i++] = BIGLO(num); num = BIGDN(num); } i = DIGSPERLL; while (i-- && !digits[i]) ; RBIGNUM(big)->len = i+1; return big; } VALUE rb_ll2big(n) LONG_LONG n; { long neg = 0; VALUE big; if (n < 0) { n = -n; neg = 1; } big = rb_ull2big(n); if (neg) { RBIGNUM(big)->sign = 0; } return big; } VALUE rb_ull2inum(n) unsigned LONG_LONG n; { if (POSFIXABLE(n)) return LONG2FIX(n); return rb_ull2big(n); } VALUE rb_ll2inum(n) LONG_LONG n; { if (FIXABLE(n)) return LONG2FIX(n); return rb_ll2big(n); } #endif /* HAVE_LONG_LONG */ VALUE rb_cstr2inum(str, base) const char *str; int base; { return rb_cstr_to_inum(str, base, base==0); } VALUE rb_str2inum(str, base) VALUE str; int base; { return rb_str_to_inum(str, base, base==0); } const char ruby_digitmap[] = "0123456789abcdefghijklmnopqrstuvwxyz"; VALUE rb_big2str(x, base) VALUE x; int base; { volatile VALUE t; BDIGIT *ds; long i, j, hbase; VALUE ss; char *s, c; if (FIXNUM_P(x)) { return rb_fix2str(x, base); } i = RBIGNUM(x)->len; if (BIGZEROP(x)) { return rb_str_new2("0"); } j = SIZEOF_BDIGITS*CHAR_BIT*i; switch (base) { case 2: break; case 3: j = j * 647L / 1024; break; case 4: case 5: case 6: case 7: j /= 2; break; case 8: case 9: j /= 3; break; case 10: case 11: case 12: case 13: case 14: case 15: j = j * 241L / 800; break; case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: j /= 4; break; case 32: case 33: case 34: case 35: case 36: j /= 5; break; default: rb_raise(rb_eArgError, "illegal radix %d", base); break; } j += 2; hbase = base * base; #if SIZEOF_BDIGITS > 2 hbase *= hbase; #endif t = rb_big_clone(x); ds = BDIGITS(t); ss = rb_str_new(0, j); s = RSTRING(ss)->ptr; s[0] = RBIGNUM(x)->sign ? '+' : '-'; while (i && j) { long k = i; BDIGIT_DBL num = 0; while (k--) { num = BIGUP(num) + ds[k]; ds[k] = (BDIGIT)(num / hbase); num %= hbase; } if (ds[i-1] == 0) i--; k = SIZEOF_BDIGITS; while (k--) { c = (char)(num % base); s[--j] = ruby_digitmap[(int)c]; num /= base; if (i == 0 && num == 0) break; } } while (s[j] == '0') j++; RSTRING(ss)->len -= RBIGNUM(x)->sign?j:j-1; memmove(RBIGNUM(x)->sign?s:s+1, s+j, RSTRING(ss)->len); s[RSTRING(ss)->len] = '\0'; return ss; } static VALUE rb_big_to_s(argc, argv, x) int argc; VALUE *argv; VALUE x; { VALUE b; int base; rb_scan_args(argc, argv, "01", &b); if (argc == 0) base = 10; else base = NUM2INT(b); return rb_big2str(x, base); } static unsigned long big2ulong(x, type) VALUE x; char *type; { long len = RBIGNUM(x)->len; BDIGIT_DBL num; BDIGIT *ds; if (len > SIZEOF_LONG/SIZEOF_BDIGITS) rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type); ds = BDIGITS(x); num = 0; while (len--) { num = BIGUP(num); num += ds[len]; } return num; } unsigned long rb_big2ulong(x) VALUE x; { unsigned long num = big2ulong(x, "unsigned long"); if (!RBIGNUM(x)->sign) return -num; return num; } long rb_big2long(x) VALUE x; { unsigned long num = big2ulong(x, "int"); if ((long)num < 0 && (RBIGNUM(x)->sign || (long)num != LONG_MIN)) { rb_raise(rb_eRangeError, "bignum too big to convert into `int'"); } if (!RBIGNUM(x)->sign) return -(long)num; return num; } #if HAVE_LONG_LONG static unsigned LONG_LONG big2ull(x, type) VALUE x; char *type; { long len = RBIGNUM(x)->len; BDIGIT_DBL num; BDIGIT *ds; if (len > SIZEOF_LONG_LONG/SIZEOF_BDIGITS) rb_raise(rb_eRangeError, "bignum too big to convert into `%s'", type); ds = BDIGITS(x); num = 0; while (len--) { num = BIGUP(num); num += ds[len]; } return num; } unsigned LONG_LONG rb_big2ull(x) VALUE x; { unsigned LONG_LONG num = big2ull(x, "unsigned long long"); if (!RBIGNUM(x)->sign) return -num; return num; } LONG_LONG rb_big2ll(x) VALUE x; { unsigned LONG_LONG num = big2ull(x, "long long"); if ((LONG_LONG)num < 0 && (RBIGNUM(x)->sign || (LONG_LONG)num != LLONG_MIN)) { rb_raise(rb_eRangeError, "bignum too big to convert into `long long'"); } if (!RBIGNUM(x)->sign) return -(LONG_LONG)num; return num; } #endif /* HAVE_LONG_LONG */ static VALUE dbl2big(d) double d; { long i = 0; BDIGIT c; BDIGIT *digits; VALUE z; double u = (d < 0)?-d:d; if (isinf(d)) { rb_raise(rb_eFloatDomainError, d < 0 ? "-Infinity" : "Infinity"); } if (isnan(d)) { rb_raise(rb_eFloatDomainError, "NaN"); } while (!POSFIXABLE(u) || 0 != (long)u) { u /= (double)(BIGRAD); i++; } z = bignew(i, d>=0); digits = BDIGITS(z); while (i--) { u *= BIGRAD; c = (BDIGIT)u; u -= c; digits[i] = c; } return z; } VALUE rb_dbl2big(d) double d; { return bignorm(dbl2big(d)); } double rb_big2dbl(x) VALUE x; { double d = 0.0; long i = RBIGNUM(x)->len; BDIGIT *ds = BDIGITS(x); while (i--) { d = ds[i] + BIGRAD*d; } if (isinf(d)) { rb_warn("Bignum out of Float range"); d = HUGE_VAL; } if (!RBIGNUM(x)->sign) d = -d; return d; } static VALUE rb_big_to_f(x) VALUE x; { return rb_float_new(rb_big2dbl(x)); } static VALUE rb_big_cmp(x, y) VALUE x, y; { long xlen = RBIGNUM(x)->len; switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: return rb_dbl_cmp(rb_big2dbl(x), RFLOAT(y)->value); default: return rb_num_coerce_cmp(x, y); } if (RBIGNUM(x)->sign > RBIGNUM(y)->sign) return INT2FIX(1); if (RBIGNUM(x)->sign < RBIGNUM(y)->sign) return INT2FIX(-1); if (xlen < RBIGNUM(y)->len) return (RBIGNUM(x)->sign) ? INT2FIX(-1) : INT2FIX(1); if (xlen > RBIGNUM(y)->len) return (RBIGNUM(x)->sign) ? INT2FIX(1) : INT2FIX(-1); while(xlen-- && (BDIGITS(x)[xlen]==BDIGITS(y)[xlen])); if (-1 == xlen) return INT2FIX(0); return (BDIGITS(x)[xlen] > BDIGITS(y)[xlen]) ? (RBIGNUM(x)->sign ? INT2FIX(1) : INT2FIX(-1)) : (RBIGNUM(x)->sign ? INT2FIX(-1) : INT2FIX(1)); } static VALUE rb_big_eq(x, y) VALUE x, y; { switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: if (rb_big2dbl(x) == RFLOAT(y)->value) return Qtrue; else return Qfalse; default: return rb_equal(y, x); } if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse; if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse; if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse; return Qtrue; } static VALUE rb_big_eql(x, y) VALUE x, y; { if (TYPE(y) != T_BIGNUM) return Qfalse; if (RBIGNUM(x)->sign != RBIGNUM(y)->sign) return Qfalse; if (RBIGNUM(x)->len != RBIGNUM(y)->len) return Qfalse; if (MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,RBIGNUM(y)->len) != 0) return Qfalse; return Qtrue; } static VALUE rb_big_uminus(x) VALUE x; { VALUE z = rb_big_clone(x); RBIGNUM(z)->sign = !RBIGNUM(x)->sign; return bignorm(z); } static VALUE rb_big_neg(x) VALUE x; { VALUE z = rb_big_clone(x); long i = RBIGNUM(x)->len; BDIGIT *ds = BDIGITS(z); if (!RBIGNUM(x)->sign) get2comp(z, Qtrue); while (i--) ds[i] = ~ds[i]; if (RBIGNUM(x)->sign) get2comp(z, Qfalse); RBIGNUM(z)->sign = !RBIGNUM(z)->sign; return bignorm(z); } static VALUE bigsub(x, y) VALUE x, y; { VALUE z = 0; BDIGIT *zds; BDIGIT_DBL_SIGNED num; long i = RBIGNUM(x)->len; /* if x is larger than y, swap */ if (RBIGNUM(x)->len < RBIGNUM(y)->len) { z = x; x = y; y = z; /* swap x y */ } else if (RBIGNUM(x)->len == RBIGNUM(y)->len) { while (i > 0) { i--; if (BDIGITS(x)[i] > BDIGITS(y)[i]) { break; } if (BDIGITS(x)[i] < BDIGITS(y)[i]) { z = x; x = y; y = z; /* swap x y */ break; } } } z = bignew(RBIGNUM(x)->len, (z == 0)?1:0); zds = BDIGITS(z); for (i = 0, num = 0; i < RBIGNUM(y)->len; i++) { num += (BDIGIT_DBL_SIGNED)BDIGITS(x)[i] - BDIGITS(y)[i]; zds[i] = BIGLO(num); num = BIGDN(num); } while (num && i < RBIGNUM(x)->len) { num += BDIGITS(x)[i]; zds[i++] = BIGLO(num); num = BIGDN(num); } while (i < RBIGNUM(x)->len) { zds[i] = BDIGITS(x)[i]; i++; } return z; } static VALUE bigadd(x, y, sign) VALUE x, y; char sign; { VALUE z; BDIGIT_DBL num; long i, len; sign = (sign == RBIGNUM(y)->sign); if (RBIGNUM(x)->sign != sign) { if (sign) return bigsub(y, x); return bigsub(x, y); } if (RBIGNUM(x)->len > RBIGNUM(y)->len) { len = RBIGNUM(x)->len + 1; z = x; x = y; y = z; } else { len = RBIGNUM(y)->len + 1; } z = bignew(len, sign); len = RBIGNUM(x)->len; for (i = 0, num = 0; i < len; i++) { num += (BDIGIT_DBL)BDIGITS(x)[i] + BDIGITS(y)[i]; BDIGITS(z)[i] = BIGLO(num); num = BIGDN(num); } len = RBIGNUM(y)->len; while (num && i < len) { num += BDIGITS(y)[i]; BDIGITS(z)[i++] = BIGLO(num); num = BIGDN(num); } while (i < len) { BDIGITS(z)[i] = BDIGITS(y)[i]; i++; } BDIGITS(z)[i] = (BDIGIT)num; return z; } VALUE rb_big_plus(x, y) VALUE x, y; { switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); /* fall through */ case T_BIGNUM: return bignorm(bigadd(x, y, 1)); case T_FLOAT: return rb_float_new(rb_big2dbl(x) + RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } } VALUE rb_big_minus(x, y) VALUE x, y; { switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); /* fall through */ case T_BIGNUM: return bignorm(bigadd(x, y, 0)); case T_FLOAT: return rb_float_new(rb_big2dbl(x) - RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } } VALUE rb_big_mul(x, y) VALUE x, y; { long i, j; BDIGIT_DBL n = 0; VALUE z; BDIGIT *zds; if (FIXNUM_P(x)) x = rb_int2big(FIX2LONG(x)); switch (TYPE(y)) { case T_FIXNUM: y = rb_int2big(FIX2LONG(y)); break; case T_BIGNUM: break; case T_FLOAT: return rb_float_new(rb_big2dbl(x) * RFLOAT(y)->value); default: return rb_num_coerce_bin(x, y); } j = RBIGNUM(x)->len + RBIGNUM(y)->len + 1; z = bignew(j, RBIGNUM(x)->sign==RBIGNUM(y)->sign); zds = BDIGITS(z); while (j--) zds[j] = 0; for (i = 0; i < RBIGNUM(x)->len; i++) { BDIGIT_DBL dd = BDIGITS(x)[i]; if (dd == 0) continue; n = 0; for (j = 0; j < RBIGNUM(y)->len; j++) { BDIGIT_DBL ee = n + (BDIGIT_DBL)dd * BDIGITS(y)[j]; n = zds[i + j] + ee; if (ee) zds[i + j] = BIGLO(n); n = BIGDN(n); } if (n) { zds[i + j] = n; } } return bignorm(z); } static void bigdivrem(x, y, divp, modp) VALUE x, y; VALUE *divp, *modp; { long nx = RBIGNUM(x)->len, ny = RBIGNUM(y)->len; long i, j; VALUE yy, z; BDIGIT *xds, *yds, *zds, *tds; BDIGIT_DBL t2; BDIGIT_DBL_SIGNED num; BDIGIT dd, q; if (BIGZEROP(y)) rb_num_zerodiv(); yds = BDIGITS(y); if (nx < ny || (nx == ny && BDIGITS(x)[nx - 1] < BDIGITS(y)[ny - 1])) { if (divp) *divp = rb_int2big(0); if (modp) *modp = x; return; } xds = BDIGITS(x); if (ny == 1) { dd = yds[0]; z = rb_big_clone(x); zds = BDIGITS(z); t2 = 0; i = nx; while (i--) { t2 = BIGUP(t2) + zds[i]; zds[i] = (BDIGIT)(t2 / dd); t2 %= dd; } RBIGNUM(z)->sign = RBIGNUM(x)->sign==RBIGNUM(y)->sign; if (modp) { *modp = rb_uint2big((unsigned long)t2); RBIGNUM(*modp)->sign = RBIGNUM(x)->sign; } if (divp) *divp = z; return; } z = bignew(nx==ny?nx+2:nx+1, RBIGNUM(x)->sign==RBIGNUM(y)->sign); zds = BDIGITS(z); if (nx==ny) zds[nx+1] = 0; while (!yds[ny-1]) ny--; dd = 0; q = yds[ny-1]; while ((q & (1<<(BITSPERDIG-1))) == 0) { q <<= 1; dd++; } if (dd) { yy = rb_big_clone(y); tds = BDIGITS(yy); j = 0; t2 = 0; while (j<ny) { t2 += (BDIGIT_DBL)yds[j]<<dd; tds[j++] = BIGLO(t2); t2 = BIGDN(t2); } yds = tds; j = 0; t2 = 0; while (j<nx) { t2 += (BDIGIT_DBL)xds[j]<<dd; zds[j++] = BIGLO(t2); t2 = BIGDN(t2); } zds[j] = (BDIGIT)t2; } else { zds[nx] = 0; j = nx; while (j--) zds[j] = xds[j]; } j = nx==ny?nx+1:nx; do { if (zds[j] == yds[ny-1]) q = BIGRAD-1; else q = (BDIGIT)((BIGUP(zds[j]) + zds[j-1])/yds[ny-1]); if (q) { i = 0; num = 0; t2 = 0; do { /* multiply and subtract */ BDIGIT_DBL ee; t2 += (BDIGIT_DBL)yds[i] * q; ee = num - BIGLO(t2); num = (BDIGIT_DBL)zds[j - ny + i] + ee; if (ee) zds[j - ny + i] = BIGLO(num); num = BIGDN(num); t2 = BIGDN(t2); } while (++i < ny); num += zds[j - ny + i] - t2;/* borrow from high digit; don't update */ while (num) { /* "add back" required */