tree checksum vpatch file split hunks

all signers: asciilifeform

antecedents:

press order:

mpi-genesis~asciilifeform

patch:

-
+ 9225ACDFEE37D53F45669EAC0ABD4F4E8EBA5E9DBF39F49E9F182530A038A159934F8645E2BDC00783B4AF40743643C1B3256653B5D3A4DEA375ACE1613B72FC
mpi/COPYING
(0 . 0)(1 . 676)
5
6 GNU GENERAL PUBLIC LICENSE
7 Version 3, 29 June 2007
8
9 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
10 Everyone is permitted to copy and distribute verbatim copies
11 of this license document, but changing it is not allowed.
12
13 Preamble
14
15 The GNU General Public License is a free, copyleft license for
16 software and other kinds of works.
17
18 The licenses for most software and other practical works are designed
19 to take away your freedom to share and change the works. By contrast,
20 the GNU General Public License is intended to guarantee your freedom to
21 share and change all versions of a program--to make sure it remains free
22 software for all its users. We, the Free Software Foundation, use the
23 GNU General Public License for most of our software; it applies also to
24 any other work released this way by its authors. You can apply it to
25 your programs, too.
26
27 When we speak of free software, we are referring to freedom, not
28 price. Our General Public Licenses are designed to make sure that you
29 have the freedom to distribute copies of free software (and charge for
30 them if you wish), that you receive source code or can get it if you
31 want it, that you can change the software or use pieces of it in new
32 free programs, and that you know you can do these things.
33
34 To protect your rights, we need to prevent others from denying you
35 these rights or asking you to surrender the rights. Therefore, you have
36 certain responsibilities if you distribute copies of the software, or if
37 you modify it: responsibilities to respect the freedom of others.
38
39 For example, if you distribute copies of such a program, whether
40 gratis or for a fee, you must pass on to the recipients the same
41 freedoms that you received. You must make sure that they, too, receive
42 or can get the source code. And you must show them these terms so they
43 know their rights.
44
45 Developers that use the GNU GPL protect your rights with two steps:
46 (1) assert copyright on the software, and (2) offer you this License
47 giving you legal permission to copy, distribute and/or modify it.
48
49 For the developers' and authors' protection, the GPL clearly explains
50 that there is no warranty for this free software. For both users' and
51 authors' sake, the GPL requires that modified versions be marked as
52 changed, so that their problems will not be attributed erroneously to
53 authors of previous versions.
54
55 Some devices are designed to deny users access to install or run
56 modified versions of the software inside them, although the manufacturer
57 can do so. This is fundamentally incompatible with the aim of
58 protecting users' freedom to change the software. The systematic
59 pattern of such abuse occurs in the area of products for individuals to
60 use, which is precisely where it is most unacceptable. Therefore, we
61 have designed this version of the GPL to prohibit the practice for those
62 products. If such problems arise substantially in other domains, we
63 stand ready to extend this provision to those domains in future versions
64 of the GPL, as needed to protect the freedom of users.
65
66 Finally, every program is threatened constantly by software patents.
67 States should not allow patents to restrict development and use of
68 software on general-purpose computers, but in those that do, we wish to
69 avoid the special danger that patents applied to a free program could
70 make it effectively proprietary. To prevent this, the GPL assures that
71 patents cannot be used to render the program non-free.
72
73 The precise terms and conditions for copying, distribution and
74 modification follow.
75
76 TERMS AND CONDITIONS
77
78 0. Definitions.
79
80 "This License" refers to version 3 of the GNU General Public License.
81
82 "Copyright" also means copyright-like laws that apply to other kinds of
83 works, such as semiconductor masks.
84
85 "The Program" refers to any copyrightable work licensed under this
86 License. Each licensee is addressed as "you". "Licensees" and
87 "recipients" may be individuals or organizations.
88
89 To "modify" a work means to copy from or adapt all or part of the work
90 in a fashion requiring copyright permission, other than the making of an
91 exact copy. The resulting work is called a "modified version" of the
92 earlier work or a work "based on" the earlier work.
93
94 A "covered work" means either the unmodified Program or a work based
95 on the Program.
96
97 To "propagate" a work means to do anything with it that, without
98 permission, would make you directly or secondarily liable for
99 infringement under applicable copyright law, except executing it on a
100 computer or modifying a private copy. Propagation includes copying,
101 distribution (with or without modification), making available to the
102 public, and in some countries other activities as well.
103
104 To "convey" a work means any kind of propagation that enables other
105 parties to make or receive copies. Mere interaction with a user through
106 a computer network, with no transfer of a copy, is not conveying.
107
108 An interactive user interface displays "Appropriate Legal Notices"
109 to the extent that it includes a convenient and prominently visible
110 feature that (1) displays an appropriate copyright notice, and (2)
111 tells the user that there is no warranty for the work (except to the
112 extent that warranties are provided), that licensees may convey the
113 work under this License, and how to view a copy of this License. If
114 the interface presents a list of user commands or options, such as a
115 menu, a prominent item in the list meets this criterion.
116
117 1. Source Code.
118
119 The "source code" for a work means the preferred form of the work
120 for making modifications to it. "Object code" means any non-source
121 form of a work.
122
123 A "Standard Interface" means an interface that either is an official
124 standard defined by a recognized standards body, or, in the case of
125 interfaces specified for a particular programming language, one that
126 is widely used among developers working in that language.
127
128 The "System Libraries" of an executable work include anything, other
129 than the work as a whole, that (a) is included in the normal form of
130 packaging a Major Component, but which is not part of that Major
131 Component, and (b) serves only to enable use of the work with that
132 Major Component, or to implement a Standard Interface for which an
133 implementation is available to the public in source code form. A
134 "Major Component", in this context, means a major essential component
135 (kernel, window system, and so on) of the specific operating system
136 (if any) on which the executable work runs, or a compiler used to
137 produce the work, or an object code interpreter used to run it.
138
139 The "Corresponding Source" for a work in object code form means all
140 the source code needed to generate, install, and (for an executable
141 work) run the object code and to modify the work, including scripts to
142 control those activities. However, it does not include the work's
143 System Libraries, or general-purpose tools or generally available free
144 programs which are used unmodified in performing those activities but
145 which are not part of the work. For example, Corresponding Source
146 includes interface definition files associated with source files for
147 the work, and the source code for shared libraries and dynamically
148 linked subprograms that the work is specifically designed to require,
149 such as by intimate data communication or control flow between those
150 subprograms and other parts of the work.
151
152 The Corresponding Source need not include anything that users
153 can regenerate automatically from other parts of the Corresponding
154 Source.
155
156 The Corresponding Source for a work in source code form is that
157 same work.
158
159 2. Basic Permissions.
160
161 All rights granted under this License are granted for the term of
162 copyright on the Program, and are irrevocable provided the stated
163 conditions are met. This License explicitly affirms your unlimited
164 permission to run the unmodified Program. The output from running a
165 covered work is covered by this License only if the output, given its
166 content, constitutes a covered work. This License acknowledges your
167 rights of fair use or other equivalent, as provided by copyright law.
168
169 You may make, run and propagate covered works that you do not
170 convey, without conditions so long as your license otherwise remains
171 in force. You may convey covered works to others for the sole purpose
172 of having them make modifications exclusively for you, or provide you
173 with facilities for running those works, provided that you comply with
174 the terms of this License in conveying all material for which you do
175 not control copyright. Those thus making or running the covered works
176 for you must do so exclusively on your behalf, under your direction
177 and control, on terms that prohibit them from making any copies of
178 your copyrighted material outside their relationship with you.
179
180 Conveying under any other circumstances is permitted solely under
181 the conditions stated below. Sublicensing is not allowed; section 10
182 makes it unnecessary.
183
184 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185
186 No covered work shall be deemed part of an effective technological
187 measure under any applicable law fulfilling obligations under article
188 11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 similar laws prohibiting or restricting circumvention of such
190 measures.
191
192 When you convey a covered work, you waive any legal power to forbid
193 circumvention of technological measures to the extent such circumvention
194 is effected by exercising rights under this License with respect to
195 the covered work, and you disclaim any intention to limit operation or
196 modification of the work as a means of enforcing, against the work's
197 users, your or third parties' legal rights to forbid circumvention of
198 technological measures.
199
200 4. Conveying Verbatim Copies.
201
202 You may convey verbatim copies of the Program's source code as you
203 receive it, in any medium, provided that you conspicuously and
204 appropriately publish on each copy an appropriate copyright notice;
205 keep intact all notices stating that this License and any
206 non-permissive terms added in accord with section 7 apply to the code;
207 keep intact all notices of the absence of any warranty; and give all
208 recipients a copy of this License along with the Program.
209
210 You may charge any price or no price for each copy that you convey,
211 and you may offer support or warranty protection for a fee.
212
213 5. Conveying Modified Source Versions.
214
215 You may convey a work based on the Program, or the modifications to
216 produce it from the Program, in the form of source code under the
217 terms of section 4, provided that you also meet all of these conditions:
218
219 a) The work must carry prominent notices stating that you modified
220 it, and giving a relevant date.
221
222 b) The work must carry prominent notices stating that it is
223 released under this License and any conditions added under section
224 7. This requirement modifies the requirement in section 4 to
225 "keep intact all notices".
226
227 c) You must license the entire work, as a whole, under this
228 License to anyone who comes into possession of a copy. This
229 License will therefore apply, along with any applicable section 7
230 additional terms, to the whole of the work, and all its parts,
231 regardless of how they are packaged. This License gives no
232 permission to license the work in any other way, but it does not
233 invalidate such permission if you have separately received it.
234
235 d) If the work has interactive user interfaces, each must display
236 Appropriate Legal Notices; however, if the Program has interactive
237 interfaces that do not display Appropriate Legal Notices, your
238 work need not make them do so.
239
240 A compilation of a covered work with other separate and independent
241 works, which are not by their nature extensions of the covered work,
242 and which are not combined with it such as to form a larger program,
243 in or on a volume of a storage or distribution medium, is called an
244 "aggregate" if the compilation and its resulting copyright are not
245 used to limit the access or legal rights of the compilation's users
246 beyond what the individual works permit. Inclusion of a covered work
247 in an aggregate does not cause this License to apply to the other
248 parts of the aggregate.
249
250 6. Conveying Non-Source Forms.
251
252 You may convey a covered work in object code form under the terms
253 of sections 4 and 5, provided that you also convey the
254 machine-readable Corresponding Source under the terms of this License,
255 in one of these ways:
256
257 a) Convey the object code in, or embodied in, a physical product
258 (including a physical distribution medium), accompanied by the
259 Corresponding Source fixed on a durable physical medium
260 customarily used for software interchange.
261
262 b) Convey the object code in, or embodied in, a physical product
263 (including a physical distribution medium), accompanied by a
264 written offer, valid for at least three years and valid for as
265 long as you offer spare parts or customer support for that product
266 model, to give anyone who possesses the object code either (1) a
267 copy of the Corresponding Source for all the software in the
268 product that is covered by this License, on a durable physical
269 medium customarily used for software interchange, for a price no
270 more than your reasonable cost of physically performing this
271 conveying of source, or (2) access to copy the
272 Corresponding Source from a network server at no charge.
273
274 c) Convey individual copies of the object code with a copy of the
275 written offer to provide the Corresponding Source. This
276 alternative is allowed only occasionally and noncommercially, and
277 only if you received the object code with such an offer, in accord
278 with subsection 6b.
279
280 d) Convey the object code by offering access from a designated
281 place (gratis or for a charge), and offer equivalent access to the
282 Corresponding Source in the same way through the same place at no
283 further charge. You need not require recipients to copy the
284 Corresponding Source along with the object code. If the place to
285 copy the object code is a network server, the Corresponding Source
286 may be on a different server (operated by you or a third party)
287 that supports equivalent copying facilities, provided you maintain
288 clear directions next to the object code saying where to find the
289 Corresponding Source. Regardless of what server hosts the
290 Corresponding Source, you remain obligated to ensure that it is
291 available for as long as needed to satisfy these requirements.
292
293 e) Convey the object code using peer-to-peer transmission, provided
294 you inform other peers where the object code and Corresponding
295 Source of the work are being offered to the general public at no
296 charge under subsection 6d.
297
298 A separable portion of the object code, whose source code is excluded
299 from the Corresponding Source as a System Library, need not be
300 included in conveying the object code work.
301
302 A "User Product" is either (1) a "consumer product", which means any
303 tangible personal property which is normally used for personal, family,
304 or household purposes, or (2) anything designed or sold for incorporation
305 into a dwelling. In determining whether a product is a consumer product,
306 doubtful cases shall be resolved in favor of coverage. For a particular
307 product received by a particular user, "normally used" refers to a
308 typical or common use of that class of product, regardless of the status
309 of the particular user or of the way in which the particular user
310 actually uses, or expects or is expected to use, the product. A product
311 is a consumer product regardless of whether the product has substantial
312 commercial, industrial or non-consumer uses, unless such uses represent
313 the only significant mode of use of the product.
314
315 "Installation Information" for a User Product means any methods,
316 procedures, authorization keys, or other information required to install
317 and execute modified versions of a covered work in that User Product from
318 a modified version of its Corresponding Source. The information must
319 suffice to ensure that the continued functioning of the modified object
320 code is in no case prevented or interfered with solely because
321 modification has been made.
322
323 If you convey an object code work under this section in, or with, or
324 specifically for use in, a User Product, and the conveying occurs as
325 part of a transaction in which the right of possession and use of the
326 User Product is transferred to the recipient in perpetuity or for a
327 fixed term (regardless of how the transaction is characterized), the
328 Corresponding Source conveyed under this section must be accompanied
329 by the Installation Information. But this requirement does not apply
330 if neither you nor any third party retains the ability to install
331 modified object code on the User Product (for example, the work has
332 been installed in ROM).
333
334 The requirement to provide Installation Information does not include a
335 requirement to continue to provide support service, warranty, or updates
336 for a work that has been modified or installed by the recipient, or for
337 the User Product in which it has been modified or installed. Access to a
338 network may be denied when the modification itself materially and
339 adversely affects the operation of the network or violates the rules and
340 protocols for communication across the network.
341
342 Corresponding Source conveyed, and Installation Information provided,
343 in accord with this section must be in a format that is publicly
344 documented (and with an implementation available to the public in
345 source code form), and must require no special password or key for
346 unpacking, reading or copying.
347
348 7. Additional Terms.
349
350 "Additional permissions" are terms that supplement the terms of this
351 License by making exceptions from one or more of its conditions.
352 Additional permissions that are applicable to the entire Program shall
353 be treated as though they were included in this License, to the extent
354 that they are valid under applicable law. If additional permissions
355 apply only to part of the Program, that part may be used separately
356 under those permissions, but the entire Program remains governed by
357 this License without regard to the additional permissions.
358
359 When you convey a copy of a covered work, you may at your option
360 remove any additional permissions from that copy, or from any part of
361 it. (Additional permissions may be written to require their own
362 removal in certain cases when you modify the work.) You may place
363 additional permissions on material, added by you to a covered work,
364 for which you have or can give appropriate copyright permission.
365
366 Notwithstanding any other provision of this License, for material you
367 add to a covered work, you may (if authorized by the copyright holders of
368 that material) supplement the terms of this License with terms:
369
370 a) Disclaiming warranty or limiting liability differently from the
371 terms of sections 15 and 16 of this License; or
372
373 b) Requiring preservation of specified reasonable legal notices or
374 author attributions in that material or in the Appropriate Legal
375 Notices displayed by works containing it; or
376
377 c) Prohibiting misrepresentation of the origin of that material, or
378 requiring that modified versions of such material be marked in
379 reasonable ways as different from the original version; or
380
381 d) Limiting the use for publicity purposes of names of licensors or
382 authors of the material; or
383
384 e) Declining to grant rights under trademark law for use of some
385 trade names, trademarks, or service marks; or
386
387 f) Requiring indemnification of licensors and authors of that
388 material by anyone who conveys the material (or modified versions of
389 it) with contractual assumptions of liability to the recipient, for
390 any liability that these contractual assumptions directly impose on
391 those licensors and authors.
392
393 All other non-permissive additional terms are considered "further
394 restrictions" within the meaning of section 10. If the Program as you
395 received it, or any part of it, contains a notice stating that it is
396 governed by this License along with a term that is a further
397 restriction, you may remove that term. If a license document contains
398 a further restriction but permits relicensing or conveying under this
399 License, you may add to a covered work material governed by the terms
400 of that license document, provided that the further restriction does
401 not survive such relicensing or conveying.
402
403 If you add terms to a covered work in accord with this section, you
404 must place, in the relevant source files, a statement of the
405 additional terms that apply to those files, or a notice indicating
406 where to find the applicable terms.
407
408 Additional terms, permissive or non-permissive, may be stated in the
409 form of a separately written license, or stated as exceptions;
410 the above requirements apply either way.
411
412 8. Termination.
413
414 You may not propagate or modify a covered work except as expressly
415 provided under this License. Any attempt otherwise to propagate or
416 modify it is void, and will automatically terminate your rights under
417 this License (including any patent licenses granted under the third
418 paragraph of section 11).
419
420 However, if you cease all violation of this License, then your
421 license from a particular copyright holder is reinstated (a)
422 provisionally, unless and until the copyright holder explicitly and
423 finally terminates your license, and (b) permanently, if the copyright
424 holder fails to notify you of the violation by some reasonable means
425 prior to 60 days after the cessation.
426
427 Moreover, your license from a particular copyright holder is
428 reinstated permanently if the copyright holder notifies you of the
429 violation by some reasonable means, this is the first time you have
430 received notice of violation of this License (for any work) from that
431 copyright holder, and you cure the violation prior to 30 days after
432 your receipt of the notice.
433
434 Termination of your rights under this section does not terminate the
435 licenses of parties who have received copies or rights from you under
436 this License. If your rights have been terminated and not permanently
437 reinstated, you do not qualify to receive new licenses for the same
438 material under section 10.
439
440 9. Acceptance Not Required for Having Copies.
441
442 You are not required to accept this License in order to receive or
443 run a copy of the Program. Ancillary propagation of a covered work
444 occurring solely as a consequence of using peer-to-peer transmission
445 to receive a copy likewise does not require acceptance. However,
446 nothing other than this License grants you permission to propagate or
447 modify any covered work. These actions infringe copyright if you do
448 not accept this License. Therefore, by modifying or propagating a
449 covered work, you indicate your acceptance of this License to do so.
450
451 10. Automatic Licensing of Downstream Recipients.
452
453 Each time you convey a covered work, the recipient automatically
454 receives a license from the original licensors, to run, modify and
455 propagate that work, subject to this License. You are not responsible
456 for enforcing compliance by third parties with this License.
457
458 An "entity transaction" is a transaction transferring control of an
459 organization, or substantially all assets of one, or subdividing an
460 organization, or merging organizations. If propagation of a covered
461 work results from an entity transaction, each party to that
462 transaction who receives a copy of the work also receives whatever
463 licenses to the work the party's predecessor in interest had or could
464 give under the previous paragraph, plus a right to possession of the
465 Corresponding Source of the work from the predecessor in interest, if
466 the predecessor has it or can get it with reasonable efforts.
467
468 You may not impose any further restrictions on the exercise of the
469 rights granted or affirmed under this License. For example, you may
470 not impose a license fee, royalty, or other charge for exercise of
471 rights granted under this License, and you may not initiate litigation
472 (including a cross-claim or counterclaim in a lawsuit) alleging that
473 any patent claim is infringed by making, using, selling, offering for
474 sale, or importing the Program or any portion of it.
475
476 11. Patents.
477
478 A "contributor" is a copyright holder who authorizes use under this
479 License of the Program or a work on which the Program is based. The
480 work thus licensed is called the contributor's "contributor version".
481
482 A contributor's "essential patent claims" are all patent claims
483 owned or controlled by the contributor, whether already acquired or
484 hereafter acquired, that would be infringed by some manner, permitted
485 by this License, of making, using, or selling its contributor version,
486 but do not include claims that would be infringed only as a
487 consequence of further modification of the contributor version. For
488 purposes of this definition, "control" includes the right to grant
489 patent sublicenses in a manner consistent with the requirements of
490 this License.
491
492 Each contributor grants you a non-exclusive, worldwide, royalty-free
493 patent license under the contributor's essential patent claims, to
494 make, use, sell, offer for sale, import and otherwise run, modify and
495 propagate the contents of its contributor version.
496
497 In the following three paragraphs, a "patent license" is any express
498 agreement or commitment, however denominated, not to enforce a patent
499 (such as an express permission to practice a patent or covenant not to
500 sue for patent infringement). To "grant" such a patent license to a
501 party means to make such an agreement or commitment not to enforce a
502 patent against the party.
503
504 If you convey a covered work, knowingly relying on a patent license,
505 and the Corresponding Source of the work is not available for anyone
506 to copy, free of charge and under the terms of this License, through a
507 publicly available network server or other readily accessible means,
508 then you must either (1) cause the Corresponding Source to be so
509 available, or (2) arrange to deprive yourself of the benefit of the
510 patent license for this particular work, or (3) arrange, in a manner
511 consistent with the requirements of this License, to extend the patent
512 license to downstream recipients. "Knowingly relying" means you have
513 actual knowledge that, but for the patent license, your conveying the
514 covered work in a country, or your recipient's use of the covered work
515 in a country, would infringe one or more identifiable patents in that
516 country that you have reason to believe are valid.
517
518 If, pursuant to or in connection with a single transaction or
519 arrangement, you convey, or propagate by procuring conveyance of, a
520 covered work, and grant a patent license to some of the parties
521 receiving the covered work authorizing them to use, propagate, modify
522 or convey a specific copy of the covered work, then the patent license
523 you grant is automatically extended to all recipients of the covered
524 work and works based on it.
525
526 A patent license is "discriminatory" if it does not include within
527 the scope of its coverage, prohibits the exercise of, or is
528 conditioned on the non-exercise of one or more of the rights that are
529 specifically granted under this License. You may not convey a covered
530 work if you are a party to an arrangement with a third party that is
531 in the business of distributing software, under which you make payment
532 to the third party based on the extent of your activity of conveying
533 the work, and under which the third party grants, to any of the
534 parties who would receive the covered work from you, a discriminatory
535 patent license (a) in connection with copies of the covered work
536 conveyed by you (or copies made from those copies), or (b) primarily
537 for and in connection with specific products or compilations that
538 contain the covered work, unless you entered into that arrangement,
539 or that patent license was granted, prior to 28 March 2007.
540
541 Nothing in this License shall be construed as excluding or limiting
542 any implied license or other defenses to infringement that may
543 otherwise be available to you under applicable patent law.
544
545 12. No Surrender of Others' Freedom.
546
547 If conditions are imposed on you (whether by court order, agreement or
548 otherwise) that contradict the conditions of this License, they do not
549 excuse you from the conditions of this License. If you cannot convey a
550 covered work so as to satisfy simultaneously your obligations under this
551 License and any other pertinent obligations, then as a consequence you may
552 not convey it at all. For example, if you agree to terms that obligate you
553 to collect a royalty for further conveying from those to whom you convey
554 the Program, the only way you could satisfy both those terms and this
555 License would be to refrain entirely from conveying the Program.
556
557 13. Use with the GNU Affero General Public License.
558
559 Notwithstanding any other provision of this License, you have
560 permission to link or combine any covered work with a work licensed
561 under version 3 of the GNU Affero General Public License into a single
562 combined work, and to convey the resulting work. The terms of this
563 License will continue to apply to the part which is the covered work,
564 but the special requirements of the GNU Affero General Public License,
565 section 13, concerning interaction through a network will apply to the
566 combination as such.
567
568 14. Revised Versions of this License.
569
570 The Free Software Foundation may publish revised and/or new versions of
571 the GNU General Public License from time to time. Such new versions will
572 be similar in spirit to the present version, but may differ in detail to
573 address new problems or concerns.
574
575 Each version is given a distinguishing version number. If the
576 Program specifies that a certain numbered version of the GNU General
577 Public License "or any later version" applies to it, you have the
578 option of following the terms and conditions either of that numbered
579 version or of any later version published by the Free Software
580 Foundation. If the Program does not specify a version number of the
581 GNU General Public License, you may choose any version ever published
582 by the Free Software Foundation.
583
584 If the Program specifies that a proxy can decide which future
585 versions of the GNU General Public License can be used, that proxy's
586 public statement of acceptance of a version permanently authorizes you
587 to choose that version for the Program.
588
589 Later license versions may give you additional or different
590 permissions. However, no additional obligations are imposed on any
591 author or copyright holder as a result of your choosing to follow a
592 later version.
593
594 15. Disclaimer of Warranty.
595
596 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
597 APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
598 HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
599 OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
600 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
601 PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
602 IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
603 ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
604
605 16. Limitation of Liability.
606
607 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
608 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
609 THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
610 GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
611 USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
612 DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
613 PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
614 EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
615 SUCH DAMAGES.
616
617 17. Interpretation of Sections 15 and 16.
618
619 If the disclaimer of warranty and limitation of liability provided
620 above cannot be given local legal effect according to their terms,
621 reviewing courts shall apply local law that most closely approximates
622 an absolute waiver of all civil liability in connection with the
623 Program, unless a warranty or assumption of liability accompanies a
624 copy of the Program in return for a fee.
625
626 END OF TERMS AND CONDITIONS
627
628 How to Apply These Terms to Your New Programs
629
630 If you develop a new program, and you want it to be of the greatest
631 possible use to the public, the best way to achieve this is to make it
632 free software which everyone can redistribute and change under these terms.
633
634 To do so, attach the following notices to the program. It is safest
635 to attach them to the start of each source file to most effectively
636 state the exclusion of warranty; and each file should have at least
637 the "copyright" line and a pointer to where the full notice is found.
638
639 <one line to give the program's name and a brief idea of what it does.>
640 Copyright (C) <year> <name of author>
641
642 This program is free software: you can redistribute it and/or modify
643 it under the terms of the GNU General Public License as published by
644 the Free Software Foundation, either version 3 of the License, or
645 (at your option) any later version.
646
647 This program is distributed in the hope that it will be useful,
648 but WITHOUT ANY WARRANTY; without even the implied warranty of
649 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
650 GNU General Public License for more details.
651
652 You should have received a copy of the GNU General Public License
653 along with this program. If not, see <http://www.gnu.org/licenses/>.
654
655 Also add information on how to contact you by electronic and paper mail.
656
657 If the program does terminal interaction, make it output a short
658 notice like this when it starts in an interactive mode:
659
660 <program> Copyright (C) <year> <name of author>
661 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
662 This is free software, and you are welcome to redistribute it
663 under certain conditions; type `show c' for details.
664
665 The hypothetical commands `show w' and `show c' should show the appropriate
666 parts of the General Public License. Of course, your program's commands
667 might be different; for a GUI interface, you would use an "about box".
668
669 You should also get your employer (if you work as a programmer) or school,
670 if any, to sign a "copyright disclaimer" for the program, if necessary.
671 For more information on this, and how to apply and follow the GNU GPL, see
672 <http://www.gnu.org/licenses/>.
673
674 The GNU General Public License does not permit incorporating your program
675 into proprietary programs. If your program is a subroutine library, you
676 may consider it more useful to permit linking proprietary applications with
677 the library. If this is what you want to do, use the GNU Lesser General
678 Public License instead of this License. But first, please read
679 <http://www.gnu.org/philosophy/why-not-lgpl.html>.
680
-
+ D946187EDC8013ACEC997499092EB30464487922925230FBFE5D21EA6CD76320625E947B8F47CF19EC4C47987CC5DCD0C22E6DBFB4B40E4B0F93189C29B5BFC9
mpi/Makefile
(0 . 0)(1 . 25)
685 PROGRAM = mpi.a
686
687 BUILD=obj
688 DIST=bin
689
690 CXX = gcc
691 OBJECTS = $(addprefix $(BUILD)/, $(patsubst %.c,%.o,$(wildcard *.c)))
692 FLAGS = -g -Wall
693 INCLUDE = -I include
694
695 .SUFFIXES: .o .c
696
697 $(BUILD)/%.o:
698 $(CXX) $(FLAGS) $(INCLUDE) -c $*.c -o $@
699
700 all: $(PROGRAM)
701
702 $(PROGRAM): $(OBJECTS)
703 ar rcs $(DIST)/$(PROGRAM) $(OBJECTS)
704
705 clean :
706 rm -rf nul core *flymake* $(BUILD)/*.o $(DIST)/$(PROGRAM) *~ bin/*
707
708 check-syntax:
709 $(CXX) -c $(FLAGS) $(INCLUDE) -o nul -Wall -S $(CHK_SOURCES)
-
+ 198BBCC5578FD13DF9C2BD2EE55DBDD7328F24631553692248B963142212589777A37D88137C25DA5695A13024D4C0501FC1693599B04F50FEE5C646A1917B40
mpi/README
(0 . 0)(1 . 71)
714 -----BEGIN PGP SIGNED MESSAGE-----
715 Hash: SHA512
716
717 What you see here is a very classic version of the GNU MPI (bignum) library.
718 It has been surgically removed from GnuPG 1.4.10, specifically as found at:
719
720 http://trilema.com/wp-content/uploads/2015/10/gnupg-1.4.10.tar.gz.asc
721
722 SHA512(gnupg-1.4.10.tar.gz) :
723 d037041d2e6882fd3b999500b5a7b42be2c224836afc358e1f8a2465c1b74473d518f185b7c324b2c8dec4ffb70e9e34a03c94d1a54cc55d297f40c9745f6e1b
724
725 CHANGES FROM ORIGINAL:
726
727 1) Everything pertaining to Automake was nuked, and the earth where it stood -
728 salted.
729
730 Instead, we now have a conventional Makefile. It builds precisely
731 ONE THING - a single 'mpi.a' library suitable for static linking into
732 another project. This will turn up in 'bin'.
733
734 Among other things, this now means that all KNOBS now reside in a
735 MANUALLY-controlled 'config.h' found in 'include'. If you are building
736 on some very peculiar unix, please read it and adjust as appropriate.
737 It contains ONLY those knobs which actually pertain to the code.
738
739 The Makefile contains a 'check-syntax' - users of Emacs and Flymake
740 will see proper error-highlighting.
741
742 2) ALL chip-specific ASM optimizations (including those found in longlong.h)
743 have been nuked.
744
745 3) GPG-specific cruft has been amputated to the extent practical.
746
747 The logging system has been retained, but it can be easily torn out,
748 which I may choose to do in the near future.
749
750 The I/O buffering system has been retained. I may choose to remove it
751 in the near future.
752
753 The 'secure memory' (unpageable alloc) system has been retained.
754
755 'Localization' and all related idiocies have been nuked.
756 Write hieroglyphs at home, leave them there, civilized folk
757 don't need'em in their source code.
758
759 4) Other code has been altered solely to the extent required by items
760 (1) and (2).
761
762 Cruft which appears in dead #ifdefs may be removed in the future.
763 Don't get comfortable with it being there.
764
765 5) Readers who wish to know EXACTLY what I changed, should get a copy of the
766 original tarball and write a simple script involving 'find' and 'vdiff',
767 which sadly did not fit in the margins of this page.
768
769 6) To use the library, include 'include/mpi.h' in your project,
770 and statically link with 'bin/mpi.a'.
771
772 7) The original code was distributed under GPL 3, which may apply on
773 your planet and is therefore included. (See COPYING.)
774 -----BEGIN PGP SIGNATURE-----
775 Version: GnuPG v1.4.10 (GNU/Linux)
776
777 iQEcBAEBCgAGBQJWNP8uAAoJELmCKKABq//H0bIIAK2aw/wuV2Vxz0zWBT3foeVg
778 tecm7i2ar8GuEJUvNOnoo/r4gAIRloStIPH50YBlg9Ypuj5+CrkZXvRi8jEzz9aL
779 oT17/gjEoBc3c006i9ag08RvZz70r8WHc1z08vuNlDUfzSZ3T3dPA77y4jjc4EaM
780 Oag7rM9m3HYL0Gag8NLV//vL/WjeOGOd7jSlGfAq4hoYpEZspJhUO6ie+CHgVJRR
781 5NQBQNzbuzShUKG0RgyBbHM0WS7QkSnZLQtv9263e0g5QkhKccAh8MyfjdBPkatA
782 VCj3YABL/Ac+8TkBszUS5T4RBteNGCjN+lvaLVg18uS6//KnN7+3o5cn97q2Krc=
783 =+5hX
784 -----END PGP SIGNATURE-----
-
+ 2637E827D61AC5BE58C3CC88799EAF49DAED6C957ED6C6647B6D8D787E4F7FD731CDD16DB53CB1FA15E35230E918CD62DA33B4DD410CC073CA4092BC973F5AD1
mpi/errors.c
(0 . 0)(1 . 113)
789 /* errors.c - error strings
790 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
791 *
792 * This file is part of GnuPG.
793 *
794 * GnuPG is free software; you can redistribute it and/or modify
795 * it under the terms of the GNU General Public License as published by
796 * the Free Software Foundation; either version 3 of the License, or
797 * (at your option) any later version.
798 *
799 * GnuPG is distributed in the hope that it will be useful,
800 * but WITHOUT ANY WARRANTY; without even the implied warranty of
801 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
802 * GNU General Public License for more details.
803 *
804 * You should have received a copy of the GNU General Public License
805 * along with this program; if not, see <http://www.gnu.org/licenses/>.
806 */
807
808 #include <config.h>
809 #include <stdio.h>
810 #include <stdlib.h>
811 #include <stdarg.h>
812
813 #include "errors.h"
814
815 #ifndef HAVE_STRERROR
816 char *
817 strerror( int n )
818 {
819 extern char *sys_errlist[];
820 extern int sys_nerr;
821 static char buf[15];
822
823 if( n >= 0 && n < sys_nerr )
824 return sys_errlist[n];
825 strcpy( buf, "Unknown error" );
826 return buf;
827 }
828 #endif /* !HAVE_STRERROR */
829
830 const char *
831 g10_errstr( int err )
832 {
833 static char buf[50];
834 const char *p;
835
836 #define X(n,s) case G10ERR_##n : p = s; break;
837 switch( err ) {
838 case -1: p = "eof"; break;
839 case 0: p = "okay"; break;
840 X(GENERAL, N_("general error"))
841 X(UNKNOWN_PACKET, N_("unknown packet type"))
842 X(UNKNOWN_VERSION,N_("unknown version"))
843 X(PUBKEY_ALGO ,N_("unknown pubkey algorithm"))
844 X(DIGEST_ALGO ,N_("unknown digest algorithm"))
845 X(BAD_PUBKEY ,N_("bad public key"))
846 X(BAD_SECKEY ,N_("bad secret key"))
847 X(BAD_SIGN ,N_("bad signature"))
848 X(CHECKSUM , N_("checksum error"))
849 X(BAD_PASS , N_("bad passphrase"))
850 X(NO_PUBKEY ,N_("public key not found"))
851 X(CIPHER_ALGO ,N_("unknown cipher algorithm"))
852 X(KEYRING_OPEN ,N_("can't open the keyring"))
853 X(INVALID_PACKET ,N_("invalid packet"))
854 X(INVALID_ARMOR ,N_("invalid armor"))
855 X(NO_USER_ID ,N_("no such user id"))
856 X(NO_SECKEY ,N_("secret key not available"))
857 X(WRONG_SECKEY ,N_("wrong secret key used"))
858 X(UNSUPPORTED ,N_("not supported"))
859 X(BAD_KEY ,N_("bad key"))
860 X(READ_FILE ,N_("file read error"))
861 X(WRITE_FILE ,N_("file write error"))
862 X(COMPR_ALGO ,N_("unknown compress algorithm"))
863 X(OPEN_FILE ,N_("file open error"))
864 X(CREATE_FILE ,N_("file create error"))
865 X(PASSPHRASE ,N_("invalid passphrase"))
866 X(NI_PUBKEY ,N_("unimplemented pubkey algorithm"))
867 X(NI_CIPHER ,N_("unimplemented cipher algorithm"))
868 X(SIG_CLASS ,N_("unknown signature class"))
869 X(TRUSTDB ,N_("trust database error"))
870 X(BAD_MPI ,N_("bad MPI"))
871 X(RESOURCE_LIMIT ,N_("resource limit"))
872 X(INV_KEYRING ,N_("invalid keyring"))
873 X(BAD_CERT ,N_("bad certificate"))
874 X(INV_USER_ID ,N_("malformed user id"))
875 X(CLOSE_FILE ,N_("file close error"))
876 X(RENAME_FILE ,N_("file rename error"))
877 X(DELETE_FILE ,N_("file delete error"))
878 X(UNEXPECTED ,N_("unexpected data"))
879 X(TIME_CONFLICT ,N_("timestamp conflict"))
880 X(WR_PUBKEY_ALGO ,N_("unusable pubkey algorithm"))
881 X(FILE_EXISTS ,N_("file exists"))
882 X(WEAK_KEY ,N_("weak key"))
883 X(INV_ARG ,N_("invalid argument"))
884 X(BAD_URI ,N_("bad URI"))
885 X(INVALID_URI ,N_("unsupported URI"))
886 X(NETWORK ,N_("network error"))
887 X(SELFTEST_FAILED,"selftest failed")
888 X(NOT_ENCRYPTED ,N_("not encrypted"))
889 X(NOT_PROCESSED ,N_("not processed"))
890 /* the key cannot be used for a specific usage */
891 X(UNU_PUBKEY ,N_("unusable public key"))
892 X(UNU_SECKEY ,N_("unusable secret key"))
893 X(KEYSERVER ,N_("keyserver error"))
894 X(CANCELED ,N_("canceled"))
895 X(NO_CARD ,N_("no card"))
896 X(NO_DATA ,N_("no data"))
897 default: p = buf; sprintf(buf, "g10err=%d", err); break;
898 }
899 #undef X
900 return _(p);
901 }
-
+ CBB804CBF1D96718EEBC82ABDED7FB63514BA10EFD2EB136A606D85BD1896DBEAA0D631CD87BF01C8C1E014350F5664309EC9136A0D4C6EDF63C039227450926
mpi/include/compat.h
(0 . 0)(1 . 25)
906 #ifndef _COMPAT_H_
907 #define _COMPAT_H_
908
909 /* Note this isn't identical to a C locale isspace() without \f and
910 \v, but works for the purposes used here. */
911 #define ascii_isspace(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t')
912
913 int hextobyte( const char *s );
914 int ascii_toupper (int c);
915 int ascii_tolower (int c);
916 int ascii_strcasecmp( const char *a, const char *b );
917 int ascii_strncasecmp( const char *a, const char *b, size_t n);
918
919 #ifndef HAVE_STRSEP
920 char *strsep (char **stringp, const char *delim);
921 #endif
922
923 #if __GNUC__ >= 4
924 char *xstrconcat (const char *s1, ...) __attribute__ ((sentinel(0)));
925 #else
926 char *xstrconcat (const char *s1, ...);
927 #endif
928
929
930 #endif /* !_COMPAT_H_ */
-
+ F16ECF4FD4CFFB8CB4C97BEE3A486E8FEAAA6CE8C2D70FDF6AB80687847AE8700B2DC199476459401505048D1642B4D94FD2E4152D911E8B6D54065DA09EFE66
mpi/include/config.h
(0 . 0)(1 . 89)
935 /* config.h.
936 ORIGINALLY Generated from config.h.in by configure.
937 Cleaned up by hand. The price of this is that the knobs must
938 now be turned by hand.
939 */
940
941 #ifndef GNUPG_CONFIG_H_INCLUDED
942 #define GNUPG_CONFIG_H_INCLUDED
943
944 /* Define to 1 if you have the `atexit' function. */
945 #define HAVE_ATEXIT 1
946
947 /* Defined if the mlock() call does not work */
948 /* #undef HAVE_BROKEN_MLOCK */
949
950 /* Defined if a `byte' is typedef'd */
951 /* #undef HAVE_BYTE_TYPEDEF */
952
953 /* defined if we run on some of the PCDOS like systems (DOS, Windoze. OS/2)
954 with special properties like no file modes */
955 /* #undef HAVE_DOSISH_SYSTEM */
956
957 /* Define to 1 if fseeko (and presumably ftello) exists and is declared. */
958 #define HAVE_FSEEKO 1
959
960 /* Define to 1 if you have the `getpagesize' function. */
961 #define HAVE_GETPAGESIZE 1
962
963 /* Define to 1 if you have the <inttypes.h> header file. */
964 #define HAVE_INTTYPES_H 1
965
966 /* Define to 1 if you have the <limits.h> header file. */
967 #define HAVE_LIMITS_H 1
968
969 /* Define to 1 if you have the <locale.h> header file. */
970 // #undef HAVE_LOCALE_H
971
972 /* Define to 1 if you have the `memmove' function. */
973 #define HAVE_MEMMOVE 1
974
975 /* Defined if the system supports an mlock() call */
976 #define HAVE_MLOCK 1
977
978 /* Define to 1 if you have the `mmap' function. */
979 #define HAVE_MMAP 1
980
981 /* Define to 1 if you have the `plock' function. */
982 /* #undef HAVE_PLOCK */
983
984 /* Define to 1 if you have the `raise' function. */
985 #define HAVE_RAISE 1
986
987 /* Define to 1 if you have the `stpcpy' function. */
988 #define HAVE_STPCPY 1
989
990 /* Define to 1 if you have the `strcasecmp' function. */
991 #define HAVE_STRCASECMP 1
992
993 /* Define to 1 if you have the `strerror' function. */
994 #define HAVE_STRERROR 1
995
996 /* Define to 1 if you have the `strlwr' function. */
997 /* #undef HAVE_STRLWR */
998
999 /* Define to 1 if you have the `strncasecmp' function. */
1000 #define HAVE_STRNCASECMP 1
1001
1002 /* Define to 1 if you have the `strsep' function. */
1003 #define HAVE_STRSEP 1
1004
1005 /* Define to 1 if you have the `strtoul' function. */
1006 #define HAVE_STRTOUL 1
1007
1008 /* Define to 1 if you have the `sysconf' function. */
1009 #define HAVE_SYSCONF 1
1010
1011 /* Defined if a `u16' is typedef'd */
1012 /* #undef HAVE_U16_TYPEDEF */
1013
1014 /* Defined if a `u32' is typedef'd */
1015 /* #undef HAVE_U32_TYPEDEF */
1016
1017 /* Defined if a `ulong' is typedef'd */
1018 #define HAVE_ULONG_TYPEDEF 1
1019
1020 /* Defined if a `ushort' is typedef'd */
1021 #define HAVE_USHORT_TYPEDEF 1
1022
1023 #endif /*GNUPG_CONFIG_H_INCLUDED*/
-
+ 6C4FAB042DB987C280EA86471C8549A167903CB11073D0B74A426DC78CE9E65A1B66FB2815722ACB069DF807506181548960E60C33EE27C64246672A8457F752
mpi/include/errors.h
(0 . 0)(1 . 89)
1028 /* errors.h - erro code
1029 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
1030 *
1031 * This file is part of GNUPG.
1032 *
1033 * GNUPG is free software; you can redistribute it and/or modify
1034 * it under the terms of the GNU General Public License as published by
1035 * the Free Software Foundation; either version 3 of the License, or
1036 * (at your option) any later version.
1037 *
1038 * GNUPG is distributed in the hope that it will be useful,
1039 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1040 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1041 * GNU General Public License for more details.
1042 *
1043 * You should have received a copy of the GNU General Public License
1044 * along with this program; if not, see <http://www.gnu.org/licenses/>.
1045 */
1046 #ifndef G10_ERRORS_H
1047 #define G10_ERRORS_H
1048
1049 #define G10ERR_GENERAL 1
1050 #define G10ERR_UNKNOWN_PACKET 2
1051 #define G10ERR_UNKNOWN_VERSION 3 /* Unknown version (in packet) */
1052 #define G10ERR_PUBKEY_ALGO 4 /* Unknown pubkey algorithm */
1053 #define G10ERR_DIGEST_ALGO 5 /* Unknown digest algorithm */
1054 #define G10ERR_BAD_PUBKEY 6 /* Bad public key */
1055 #define G10ERR_BAD_SECKEY 7 /* Bad secret key */
1056 #define G10ERR_BAD_SIGN 8 /* Bad signature */
1057 #define G10ERR_NO_PUBKEY 9 /* public key not found */
1058 #define G10ERR_CHECKSUM 10 /* checksum error */
1059 #define G10ERR_BAD_PASS 11 /* Bad passphrase */
1060 #define G10ERR_CIPHER_ALGO 12 /* Unknown cipher algorithm */
1061 #define G10ERR_KEYRING_OPEN 13
1062 #define G10ERR_INVALID_PACKET 14
1063 #define G10ERR_INVALID_ARMOR 15
1064 #define G10ERR_NO_USER_ID 16
1065 #define G10ERR_NO_SECKEY 17 /* secret key not available */
1066 #define G10ERR_WRONG_SECKEY 18 /* wrong seckey used */
1067 #define G10ERR_UNSUPPORTED 19
1068 #define G10ERR_BAD_KEY 20 /* bad (session) key */
1069 #define G10ERR_READ_FILE 21
1070 #define G10ERR_WRITE_FILE 22
1071 #define G10ERR_COMPR_ALGO 23 /* Unknown compress algorithm */
1072 #define G10ERR_OPEN_FILE 24
1073 #define G10ERR_CREATE_FILE 25
1074 #define G10ERR_PASSPHRASE 26 /* invalid passphrase */
1075 #define G10ERR_NI_PUBKEY 27
1076 #define G10ERR_NI_CIPHER 28
1077 #define G10ERR_SIG_CLASS 29
1078 #define G10ERR_BAD_MPI 30
1079 #define G10ERR_RESOURCE_LIMIT 31
1080 #define G10ERR_INV_KEYRING 32
1081 #define G10ERR_TRUSTDB 33 /* a problem with the trustdb */
1082 #define G10ERR_BAD_CERT 34 /* bad certicate */
1083 #define G10ERR_INV_USER_ID 35
1084 #define G10ERR_CLOSE_FILE 36
1085 #define G10ERR_RENAME_FILE 37
1086 #define G10ERR_DELETE_FILE 38
1087 #define G10ERR_UNEXPECTED 39
1088 #define G10ERR_TIME_CONFLICT 40
1089 #define G10ERR_WR_PUBKEY_ALGO 41 /* unusabe pubkey algo */
1090 #define G10ERR_FILE_EXISTS 42
1091 #define G10ERR_WEAK_KEY 43 /* NOTE: hardcoded into the cipher modules */
1092 #define G10ERR_WRONG_KEYLEN 44 /* NOTE: hardcoded into the cipher modules */
1093 #define G10ERR_INV_ARG 45
1094 #define G10ERR_BAD_URI 46 /* syntax error in URI */
1095 #define G10ERR_INVALID_URI 47 /* e.g. unsupported scheme */
1096 #define G10ERR_NETWORK 48 /* general network error */
1097 #define G10ERR_UNKNOWN_HOST 49
1098 #define G10ERR_SELFTEST_FAILED 50
1099 #define G10ERR_NOT_ENCRYPTED 51
1100 #define G10ERR_NOT_PROCESSED 52
1101 #define G10ERR_UNU_PUBKEY 53
1102 #define G10ERR_UNU_SECKEY 54
1103 #define G10ERR_KEYSERVER 55
1104 #define G10ERR_CANCELED 56
1105 #define G10ERR_NO_CARD 57
1106 #define G10ERR_NO_DATA 58
1107
1108 #ifndef HAVE_STRERROR
1109 char *strerror (int n);
1110 #endif
1111
1112 #ifdef _WIN32
1113 const char * w32_strerror (int w32_errno);
1114 #endif
1115
1116 #endif /*G10_ERRORS_H*/
-
+ 42269E10B09731558FE6D6E4F8D52F3C3CE10AD1C67496E22F7EC0E19C6D6586F1491921486E90A468905A68D6414D7B7F68914582206CCC2CE2E3ED1E2D3F3D
mpi/include/iobuf.h
(0 . 0)(1 . 161)
1121 /* iobuf.h - I/O buffer
1122 * Copyright (C) 1998, 1999, 2000, 2001, 2004 Free Software Foundation, Inc.
1123 *
1124 * This file is part of GNUPG.
1125 *
1126 * GNUPG is free software; you can redistribute it and/or modify
1127 * it under the terms of the GNU General Public License as published by
1128 * the Free Software Foundation; either version 3 of the License, or
1129 * (at your option) any later version.
1130 *
1131 * GNUPG is distributed in the hope that it will be useful,
1132 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1133 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1134 * GNU General Public License for more details.
1135 *
1136 * You should have received a copy of the GNU General Public License
1137 * along with this program; if not, see <http://www.gnu.org/licenses/>.
1138 */
1139
1140 #ifndef G10_IOBUF_H
1141 #define G10_IOBUF_H
1142
1143 #include "types.h"
1144
1145
1146 #define DBG_IOBUF iobuf_debug_mode
1147
1148 #define IOBUFCTRL_INIT 1
1149 #define IOBUFCTRL_FREE 2
1150 #define IOBUFCTRL_UNDERFLOW 3
1151 #define IOBUFCTRL_FLUSH 4
1152 #define IOBUFCTRL_DESC 5
1153 #define IOBUFCTRL_CANCEL 6
1154 #define IOBUFCTRL_USER 16
1155
1156 typedef struct iobuf_struct *IOBUF;
1157 typedef struct iobuf_struct *iobuf_t;
1158
1159 /* fixme: we should hide most of this stuff */
1160 struct iobuf_struct {
1161 int use; /* 1 input , 2 output, 3 temp */
1162 off_t nlimit;
1163 off_t nbytes; /* used together with nlimit */
1164 off_t ntotal; /* total bytes read (position of stream) */
1165 int nofast; /* used by the iobuf_get() */
1166 void *directfp;
1167 struct {
1168 size_t size; /* allocated size */
1169 size_t start; /* number of invalid bytes at the begin of the buffer */
1170 size_t len; /* currently filled to this size */
1171 byte *buf;
1172 } d;
1173 int filter_eof;
1174 int error;
1175 int (*filter)( void *opaque, int control,
1176 IOBUF chain, byte *buf, size_t *len);
1177 void *filter_ov; /* value for opaque */
1178 int filter_ov_owner;
1179 char *real_fname;
1180 IOBUF chain; /* next iobuf used for i/o if any (passed to filter) */
1181 int no, subno;
1182 const char *desc;
1183 void *opaque; /* can be used to hold any information */
1184 /* this value is copied to all instances */
1185 struct {
1186 size_t size; /* allocated size */
1187 size_t start; /* number of invalid bytes at the begin of the buffer */
1188 size_t len; /* currently filled to this size */
1189 byte *buf;
1190 } unget;
1191 };
1192
1193 #ifndef EXTERN_UNLESS_MAIN_MODULE
1194 #if defined (__riscos__) && !defined (INCLUDED_BY_MAIN_MODULE)
1195 #define EXTERN_UNLESS_MAIN_MODULE extern
1196 #else
1197 #define EXTERN_UNLESS_MAIN_MODULE
1198 #endif
1199 #endif
1200 EXTERN_UNLESS_MAIN_MODULE int iobuf_debug_mode;
1201
1202 void iobuf_enable_special_filenames ( int yes );
1203 int iobuf_is_pipe_filename (const char *fname);
1204 IOBUF iobuf_alloc(int use, size_t bufsize);
1205 IOBUF iobuf_temp(void);
1206 IOBUF iobuf_temp_with_content( const char *buffer, size_t length );
1207 IOBUF iobuf_open( const char *fname );
1208 IOBUF iobuf_fdopen( int fd, const char *mode );
1209 IOBUF iobuf_sockopen( int fd, const char *mode );
1210 IOBUF iobuf_create( const char *fname );
1211 IOBUF iobuf_append( const char *fname );
1212 IOBUF iobuf_openrw( const char *fname );
1213 int iobuf_ioctl ( IOBUF a, int cmd, int intval, void *ptrval );
1214 int iobuf_close( IOBUF iobuf );
1215 int iobuf_cancel( IOBUF iobuf );
1216
1217 int iobuf_push_filter( IOBUF a, int (*f)(void *opaque, int control,
1218 IOBUF chain, byte *buf, size_t *len), void *ov );
1219 int iobuf_push_filter2( IOBUF a,
1220 int (*f)(void *opaque, int control,
1221 IOBUF chain, byte *buf, size_t *len),
1222 void *ov, int rel_ov );
1223 int iobuf_flush(IOBUF a);
1224 void iobuf_clear_eof(IOBUF a);
1225 #define iobuf_set_error(a) do { (a)->error = 1; } while(0)
1226 #define iobuf_error(a) ((a)->error)
1227
1228 void iobuf_set_limit( IOBUF a, off_t nlimit );
1229
1230 off_t iobuf_tell( IOBUF a );
1231 int iobuf_seek( IOBUF a, off_t newpos );
1232
1233 int iobuf_readbyte(IOBUF a);
1234 int iobuf_read(IOBUF a, byte *buf, unsigned buflen );
1235 unsigned iobuf_read_line( IOBUF a, byte **addr_of_buffer,
1236 unsigned *length_of_buffer, unsigned *max_length );
1237 int iobuf_peek(IOBUF a, byte *buf, unsigned buflen );
1238 int iobuf_writebyte(IOBUF a, unsigned c);
1239 int iobuf_write(IOBUF a, byte *buf, unsigned buflen );
1240 int iobuf_writestr(IOBUF a, const char *buf );
1241
1242 void iobuf_flush_temp( IOBUF temp );
1243 int iobuf_write_temp( IOBUF a, IOBUF temp );
1244 size_t iobuf_temp_to_buffer( IOBUF a, byte *buffer, size_t buflen );
1245 void iobuf_unget_and_close_temp( IOBUF a, IOBUF temp );
1246
1247 int iobuf_get_fd (IOBUF a);
1248 off_t iobuf_get_filelength (IOBUF a, int *overflow);
1249 #define IOBUF_FILELENGTH_LIMIT 0xffffffff
1250 const char *iobuf_get_real_fname( IOBUF a );
1251 const char *iobuf_get_fname( IOBUF a );
1252
1253 void iobuf_set_partial_block_mode( IOBUF a, size_t len );
1254
1255 int iobuf_translate_file_handle ( int fd, int for_write );
1256
1257 /* Get a byte form the iobuf; must check for eof prior to this function.
1258 * This function returns values in the range 0 .. 255 or -1 to indicate EOF
1259 * iobuf_get_noeof() does not return -1 to indicate EOF, but masks the
1260 * returned value to be in the range 0..255.
1261 */
1262 #define iobuf_get(a) \
1263 ( ((a)->nofast || (a)->d.start >= (a)->d.len )? \
1264 iobuf_readbyte((a)) : ( (a)->nbytes++, (a)->d.buf[(a)->d.start++] ) )
1265 #define iobuf_get_noeof(a) (iobuf_get((a))&0xff)
1266
1267 /* write a byte to the iobuf and return true on write error
1268 * This macro does only write the low order byte
1269 */
1270 #define iobuf_put(a,c) iobuf_writebyte(a,c)
1271
1272 #define iobuf_where(a) "[don't know]"
1273 #define iobuf_id(a) ((a)->no)
1274
1275 #define iobuf_get_temp_buffer(a) ( (a)->d.buf )
1276 #define iobuf_get_temp_length(a) ( (a)->d.len )
1277 #define iobuf_is_temp(a) ( (a)->use == 3 )
1278
1279 void iobuf_skip_rest (IOBUF a, unsigned long n, int partial);
1280
1281 #endif /*G10_IOBUF_H*/
-
+ 042BA62021E6A33FA5F28447D8D268D4FD9A66D49BD10B904AA5F5C9FB6A30345F5CFEA787FBA1145B328F56E77C39E4D7C3D6DF94CCD4B7696B9FE2C8AA7055
mpi/include/longlong.h
(0 . 0)(1 . 224)
1286 /* longlong.h -- definitions for mixed size 32/64 bit arithmetic.
1287 Note: I added some stuff for use with gnupg
1288
1289 Copyright (C) 1991, 1992, 1993, 1994, 1996, 1998,
1290 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
1291
1292 This file is free software; you can redistribute it and/or modify
1293 it under the terms of the GNU Lesser General Public License as published by
1294 the Free Software Foundation; either version 2.1 of the License, or (at your
1295 option) any later version.
1296
1297 This file is distributed in the hope that it will be useful, but
1298 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
1299 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
1300 License for more details.
1301
1302 You should have received a copy of the GNU Lesser General Public License
1303 along with this file; if not, see <http://www.gnu.org/licenses/>. */
1304
1305
1306 /* You have to define the following before including this file:
1307
1308 UWtype -- An unsigned type, default type for operations (typically a "word")
1309 UHWtype -- An unsigned type, at least half the size of UWtype.
1310 UDWtype -- An unsigned type, at least twice as large a UWtype
1311 W_TYPE_SIZE -- size in bits of UWtype
1312
1313 SItype, USItype -- Signed and unsigned 32 bit types.
1314 DItype, UDItype -- Signed and unsigned 64 bit types.
1315
1316 On a 32 bit machine UWtype should typically be USItype;
1317 on a 64 bit machine, UWtype should typically be UDItype.
1318 */
1319
1320 #define __BITS4 (W_TYPE_SIZE / 4)
1321 #define __ll_B ((UWtype) 1 << (W_TYPE_SIZE / 2))
1322 #define __ll_lowpart(t) ((UWtype) (t) & (__ll_B - 1))
1323 #define __ll_highpart(t) ((UWtype) (t) >> (W_TYPE_SIZE / 2))
1324
1325 /* This is used to make sure no undesirable sharing between different libraries
1326 that use this file takes place. */
1327 #ifndef __MPN
1328 #define __MPN(x) __##x
1329 #endif
1330
1331 /***************************************
1332 *********** Generic Versions ********
1333 ***************************************/
1334 #if !defined (umul_ppmm) && defined (__umulsidi3)
1335 #define umul_ppmm(ph, pl, m0, m1) \
1336 { \
1337 UDWtype __ll = __umulsidi3 (m0, m1); \
1338 ph = (UWtype) (__ll >> W_TYPE_SIZE); \
1339 pl = (UWtype) __ll; \
1340 }
1341 #endif
1342
1343 #if !defined (__umulsidi3)
1344 #define __umulsidi3(u, v) \
1345 ({UWtype __hi, __lo; \
1346 umul_ppmm (__hi, __lo, u, v); \
1347 ((UDWtype) __hi << W_TYPE_SIZE) | __lo; })
1348 #endif
1349
1350 /* If this machine has no inline assembler, use C macros. */
1351
1352 #if !defined (add_ssaaaa)
1353 #define add_ssaaaa(sh, sl, ah, al, bh, bl) \
1354 do { \
1355 UWtype __x; \
1356 __x = (al) + (bl); \
1357 (sh) = (ah) + (bh) + (__x < (al)); \
1358 (sl) = __x; \
1359 } while (0)
1360 #endif
1361
1362 #if !defined (sub_ddmmss)
1363 #define sub_ddmmss(sh, sl, ah, al, bh, bl) \
1364 do { \
1365 UWtype __x; \
1366 __x = (al) - (bl); \
1367 (sh) = (ah) - (bh) - (__x > (al)); \
1368 (sl) = __x; \
1369 } while (0)
1370 #endif
1371
1372 #if !defined (umul_ppmm)
1373 #define umul_ppmm(w1, w0, u, v) \
1374 do { \
1375 UWtype __x0, __x1, __x2, __x3; \
1376 UHWtype __ul, __vl, __uh, __vh; \
1377 UWtype __u = (u), __v = (v); \
1378 \
1379 __ul = __ll_lowpart (__u); \
1380 __uh = __ll_highpart (__u); \
1381 __vl = __ll_lowpart (__v); \
1382 __vh = __ll_highpart (__v); \
1383 \
1384 __x0 = (UWtype) __ul * __vl; \
1385 __x1 = (UWtype) __ul * __vh; \
1386 __x2 = (UWtype) __uh * __vl; \
1387 __x3 = (UWtype) __uh * __vh; \
1388 \
1389 __x1 += __ll_highpart (__x0);/* this can't give carry */ \
1390 __x1 += __x2; /* but this indeed can */ \
1391 if (__x1 < __x2) /* did we get it? */ \
1392 __x3 += __ll_B; /* yes, add it in the proper pos. */ \
1393 \
1394 (w1) = __x3 + __ll_highpart (__x1); \
1395 (w0) = (__ll_lowpart (__x1) << W_TYPE_SIZE/2) + __ll_lowpart (__x0);\
1396 } while (0)
1397 #endif
1398
1399 #if !defined (umul_ppmm)
1400 #define smul_ppmm(w1, w0, u, v) \
1401 do { \
1402 UWtype __w1; \
1403 UWtype __m0 = (u), __m1 = (v); \
1404 umul_ppmm (__w1, w0, __m0, __m1); \
1405 (w1) = __w1 - (-(__m0 >> (W_TYPE_SIZE - 1)) & __m1) \
1406 - (-(__m1 >> (W_TYPE_SIZE - 1)) & __m0); \
1407 } while (0)
1408 #endif
1409
1410 /* Define this unconditionally, so it can be used for debugging. */
1411 #define __udiv_qrnnd_c(q, r, n1, n0, d) \
1412 do { \
1413 UWtype __d1, __d0, __q1, __q0, __r1, __r0, __m; \
1414 __d1 = __ll_highpart (d); \
1415 __d0 = __ll_lowpart (d); \
1416 \
1417 __r1 = (n1) % __d1; \
1418 __q1 = (n1) / __d1; \
1419 __m = (UWtype) __q1 * __d0; \
1420 __r1 = __r1 * __ll_B | __ll_highpart (n0); \
1421 if (__r1 < __m) \
1422 { \
1423 __q1--, __r1 += (d); \
1424 if (__r1 >= (d)) /* i.e. we didn't get carry when adding to __r1 */\
1425 if (__r1 < __m) \
1426 __q1--, __r1 += (d); \
1427 } \
1428 __r1 -= __m; \
1429 \
1430 __r0 = __r1 % __d1; \
1431 __q0 = __r1 / __d1; \
1432 __m = (UWtype) __q0 * __d0; \
1433 __r0 = __r0 * __ll_B | __ll_lowpart (n0); \
1434 if (__r0 < __m) \
1435 { \
1436 __q0--, __r0 += (d); \
1437 if (__r0 >= (d)) \
1438 if (__r0 < __m) \
1439 __q0--, __r0 += (d); \
1440 } \
1441 __r0 -= __m; \
1442 \
1443 (q) = (UWtype) __q1 * __ll_B | __q0; \
1444 (r) = __r0; \
1445 } while (0)
1446
1447 /* If the processor has no udiv_qrnnd but sdiv_qrnnd, go through
1448 __udiv_w_sdiv (defined in libgcc or elsewhere). */
1449 #if !defined (udiv_qrnnd) && defined (sdiv_qrnnd)
1450 #define udiv_qrnnd(q, r, nh, nl, d) \
1451 do { \
1452 UWtype __r; \
1453 (q) = __MPN(udiv_w_sdiv) (&__r, nh, nl, d); \
1454 (r) = __r; \
1455 } while (0)
1456 #endif
1457
1458 /* If udiv_qrnnd was not defined for this processor, use __udiv_qrnnd_c. */
1459 #if !defined (udiv_qrnnd)
1460 #define UDIV_NEEDS_NORMALIZATION 1
1461 #define udiv_qrnnd __udiv_qrnnd_c
1462 #endif
1463
1464 #if !defined (count_leading_zeros)
1465 extern
1466 #ifdef __STDC__
1467 const
1468 #endif
1469 unsigned char __clz_tab[];
1470 #define MPI_INTERNAL_NEED_CLZ_TAB 1
1471 #define count_leading_zeros(count, x) \
1472 do { \
1473 UWtype __xr = (x); \
1474 UWtype __a; \
1475 \
1476 if (W_TYPE_SIZE <= 32) \
1477 { \
1478 __a = __xr < ((UWtype) 1 << 2*__BITS4) \
1479 ? (__xr < ((UWtype) 1 << __BITS4) ? 0 : __BITS4) \
1480 : (__xr < ((UWtype) 1 << 3*__BITS4) ? 2*__BITS4 : 3*__BITS4);\
1481 } \
1482 else \
1483 { \
1484 for (__a = W_TYPE_SIZE - 8; __a > 0; __a -= 8) \
1485 if (((__xr >> __a) & 0xff) != 0) \
1486 break; \
1487 } \
1488 \
1489 (count) = W_TYPE_SIZE - (__clz_tab[__xr >> __a] + __a); \
1490 } while (0)
1491 /* This version gives a well-defined value for zero. */
1492 #define COUNT_LEADING_ZEROS_0 W_TYPE_SIZE
1493 #endif
1494
1495 #if !defined (count_trailing_zeros)
1496 /* Define count_trailing_zeros using count_leading_zeros. The latter might be
1497 defined in asm, but if it is not, the C version above is good enough. */
1498 #define count_trailing_zeros(count, x) \
1499 do { \
1500 UWtype __ctz_x = (x); \
1501 UWtype __ctz_c; \
1502 count_leading_zeros (__ctz_c, __ctz_x & -__ctz_x); \
1503 (count) = W_TYPE_SIZE - 1 - __ctz_c; \
1504 } while (0)
1505 #endif
1506
1507 #ifndef UDIV_NEEDS_NORMALIZATION
1508 #define UDIV_NEEDS_NORMALIZATION 0
1509 #endif
-
+ B48416427E71FE46868283490813E4D0A22DA9F4B17EFF706673A9B05380AE2D85EC9B183DB47EAA8AA197B7C7629EB873E63E5F8A66208BF230A794B6967FAB
mpi/include/memory.h
(0 . 0)(1 . 105)
1514 /* memory.h - memory allocation
1515 * Copyright (C) 1998, 1999, 2000, 2001, 2005 Free Software Foundation, Inc.
1516 *
1517 * This file is part of GNUPG.
1518 *
1519 * GNUPG is free software; you can redistribute it and/or modify
1520 * it under the terms of the GNU General Public License as published by
1521 * the Free Software Foundation; either version 3 of the License, or
1522 * (at your option) any later version.
1523 *
1524 * GNUPG is distributed in the hope that it will be useful,
1525 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1526 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1527 * GNU General Public License for more details.
1528 *
1529 * You should have received a copy of the GNU General Public License
1530 * along with this program; if not, see <http://www.gnu.org/licenses/>.
1531 */
1532
1533 #ifndef G10_MEMORY_H
1534 #define G10_MEMORY_H
1535
1536 #ifdef M_DEBUG
1537 #ifndef STR
1538 #define STR(v) #v
1539 #endif
1540 #ifndef __riscos__
1541 #define M_DBGINFO(a) __FUNCTION__ "["__FILE__ ":" STR(a) "]"
1542 #else /* __riscos__ */
1543 #define M_DBGINFO(a) "["__FILE__ ":" STR(a) "]"
1544 #endif /* __riscos__ */
1545 #define xmalloc(n) m_debug_alloc((n), M_DBGINFO( __LINE__ ) )
1546 #define xtrymalloc(n) m_debug_trymalloc ((n), M_DBGINFO( __LINE__ ))
1547 #define xmalloc_clear(n) m_debug_alloc_clear((n), M_DBGINFO(__LINE__) )
1548 #define xmalloc_secure(n) m_debug_alloc_secure(n), M_DBGINFO(__LINE__) )
1549 #define xmalloc_secure_clear(n) m_debug_alloc_secure_clear((n), M_DBGINFO(__LINE__) )
1550 #define xrealloc(n,m) m_debug_realloc((n),(m), M_DBGINFO(__LINE__) )
1551 #define xfree(n) m_debug_free((n), M_DBGINFO(__LINE__) )
1552 #define m_check(n) m_debug_check((n), M_DBGINFO(__LINE__) )
1553 /*#define m_copy(a) m_debug_copy((a), M_DBGINFO(__LINE__) )*/
1554 #define xstrdup(a) m_debug_strdup((a), M_DBGINFO(__LINE__) )
1555 #define xtrystrdup(a) m_debug_trystrdup((a), M_DBGINFO(__LINE__) )
1556
1557 void *m_debug_alloc( size_t n, const char *info );
1558 void *m_debug_trymalloc (size_t n, const char *info);
1559 void *m_debug_alloc_clear( size_t n, const char *info );
1560 void *m_debug_alloc_secure( size_t n, const char *info );
1561 void *m_debug_alloc_secure_clear( size_t n, const char *info );
1562 void *m_debug_realloc( void *a, size_t n, const char *info );
1563 void m_debug_free( void *p, const char *info );
1564 void m_debug_check( const void *a, const char *info );
1565 /*void *m_debug_copy( const void *a, const char *info );*/
1566 char *m_debug_strdup( const char *a, const char *info );
1567 char *m_debug_trystrdup (const char *a, const char *info);
1568
1569 #else
1570 void *xmalloc( size_t n );
1571 void *xtrymalloc (size_t n);
1572 void *xmalloc_clear( size_t n );
1573 void *xmalloc_secure( size_t n );
1574 void *xmalloc_secure_clear( size_t n );
1575 void *xrealloc( void *a, size_t n );
1576 void xfree( void *p );
1577 void m_check( const void *a );
1578 /*void *m_copy( const void *a );*/
1579 char *xstrdup( const char * a);
1580 char *xtrystrdup (const char *a);
1581 #endif
1582
1583 size_t m_size( const void *a );
1584 void m_print_stats(const char *prefix);
1585
1586 /* The follwing functions should be preferred over xmalloc_clear. */
1587 void *xcalloc (size_t n, size_t m);
1588 void *xcalloc_secure (size_t n, size_t m);
1589
1590
1591 /*-- secmem.c --*/
1592 int secmem_init( size_t npool );
1593 void secmem_term( void );
1594 void *secmem_malloc( size_t size );
1595 void *secmexrealloc( void *a, size_t newsize );
1596 void secmem_free( void *a );
1597 int m_is_secure( const void *p );
1598 void secmem_dump_stats(void);
1599 void secmem_set_flags( unsigned flags );
1600 unsigned secmem_get_flags(void);
1601
1602
1603 #define DBG_MEMORY memory_debug_mode
1604 #define DBG_MEMSTAT memory_stat_debug_mode
1605
1606 #ifndef EXTERN_UNLESS_MAIN_MODULE
1607 #if defined (__riscos__) && !defined (INCLUDED_BY_MAIN_MODULE)
1608 #define EXTERN_UNLESS_MAIN_MODULE extern
1609 #else
1610 #define EXTERN_UNLESS_MAIN_MODULE
1611 #endif
1612 #endif
1613 EXTERN_UNLESS_MAIN_MODULE int memory_debug_mode;
1614 EXTERN_UNLESS_MAIN_MODULE int memory_stat_debug_mode;
1615
1616
1617
1618 #endif /*G10_MEMORY_H*/
-
+ FB2AFC7686790FA12E3143E79C4728DAC3E43C4056C647650D216B7EC7350F7651F6C44C4393858E8BAB02719B7674AD7F29E1FCB10511DE0A5AE4A2C12AF5A6
mpi/include/mpi-asm-defs.h
(0 . 0)(1 . 10)
1623 /* This file defines some basic constants for the MPI machinery. We
1624 * need to define the types on a per-CPU basis, so it is done with
1625 * this file here. */
1626 #define BYTES_PER_MPI_LIMB (SIZEOF_UNSIGNED_LONG)
1627
1628
1629
1630
1631
1632
-
+ DF6064B02A11C90FB20945DAD1ECC4753A231F894D6CF60E133D6196D924442E0FA08C1D38421A97511F4007A9545C6A980960A20817E6EAECF4CE36E920F151
mpi/include/mpi-inline.h
(0 . 0)(1 . 126)
1637 /* mpi-inline.h - Internal to the Multi Precision Integers
1638 * Copyright (C) 1994, 1996, 1998, 1999 Free Software Foundation, Inc.
1639 *
1640 * This file is part of GnuPG.
1641 *
1642 * GnuPG is free software; you can redistribute it and/or modify
1643 * it under the terms of the GNU General Public License as published by
1644 * the Free Software Foundation; either version 3 of the License, or
1645 * (at your option) any later version.
1646 *
1647 * GnuPG is distributed in the hope that it will be useful,
1648 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1649 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1650 * GNU General Public License for more details.
1651 *
1652 * You should have received a copy of the GNU General Public License
1653 * along with this program; if not, see <http://www.gnu.org/licenses/>.
1654 *
1655 * Note: This code is heavily based on the GNU MP Library.
1656 * Actually it's the same code with only minor changes in the
1657 * way the data is stored; this is to support the abstraction
1658 * of an optional secure memory allocation which may be used
1659 * to avoid revealing of sensitive data due to paging etc.
1660 * The GNU MP Library itself is published under the LGPL;
1661 * however I decided to publish this code under the plain GPL.
1662 */
1663
1664 #ifndef G10_MPI_INLINE_H
1665 #define G10_MPI_INLINE_H
1666
1667 #ifndef G10_MPI_INLINE_DECL
1668 #define G10_MPI_INLINE_DECL extern __inline__
1669 #endif
1670
1671 G10_MPI_INLINE_DECL mpi_limb_t
1672 mpihelp_add_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1673 mpi_size_t s1_size, mpi_limb_t s2_limb)
1674 {
1675 mpi_limb_t x;
1676
1677 x = *s1_ptr++;
1678 s2_limb += x;
1679 *res_ptr++ = s2_limb;
1680 if( s2_limb < x ) { /* sum is less than the left operand: handle carry */
1681 while( --s1_size ) {
1682 x = *s1_ptr++ + 1; /* add carry */
1683 *res_ptr++ = x; /* and store */
1684 if( x ) /* not 0 (no overflow): we can stop */
1685 goto leave;
1686 }
1687 return 1; /* return carry (size of s1 to small) */
1688 }
1689
1690 leave:
1691 if( res_ptr != s1_ptr ) { /* not the same variable */
1692 mpi_size_t i; /* copy the rest */
1693 for( i=0; i < s1_size-1; i++ )
1694 res_ptr[i] = s1_ptr[i];
1695 }
1696 return 0; /* no carry */
1697 }
1698
1699
1700
1701 G10_MPI_INLINE_DECL mpi_limb_t
1702 mpihelp_add(mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr, mpi_size_t s1_size,
1703 mpi_ptr_t s2_ptr, mpi_size_t s2_size)
1704 {
1705 mpi_limb_t cy = 0;
1706
1707 if( s2_size )
1708 cy = mpihelp_add_n( res_ptr, s1_ptr, s2_ptr, s2_size );
1709
1710 if( s1_size - s2_size )
1711 cy = mpihelp_add_1( res_ptr + s2_size, s1_ptr + s2_size,
1712 s1_size - s2_size, cy);
1713 return cy;
1714 }
1715
1716
1717 G10_MPI_INLINE_DECL mpi_limb_t
1718 mpihelp_sub_1(mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1719 mpi_size_t s1_size, mpi_limb_t s2_limb )
1720 {
1721 mpi_limb_t x;
1722
1723 x = *s1_ptr++;
1724 s2_limb = x - s2_limb;
1725 *res_ptr++ = s2_limb;
1726 if( s2_limb > x ) {
1727 while( --s1_size ) {
1728 x = *s1_ptr++;
1729 *res_ptr++ = x - 1;
1730 if( x )
1731 goto leave;
1732 }
1733 return 1;
1734 }
1735
1736 leave:
1737 if( res_ptr != s1_ptr ) {
1738 mpi_size_t i;
1739 for( i=0; i < s1_size-1; i++ )
1740 res_ptr[i] = s1_ptr[i];
1741 }
1742 return 0;
1743 }
1744
1745
1746
1747 G10_MPI_INLINE_DECL mpi_limb_t
1748 mpihelp_sub( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr, mpi_size_t s1_size,
1749 mpi_ptr_t s2_ptr, mpi_size_t s2_size)
1750 {
1751 mpi_limb_t cy = 0;
1752
1753 if( s2_size )
1754 cy = mpihelp_sub_n(res_ptr, s1_ptr, s2_ptr, s2_size);
1755
1756 if( s1_size - s2_size )
1757 cy = mpihelp_sub_1(res_ptr + s2_size, s1_ptr + s2_size,
1758 s1_size - s2_size, cy);
1759 return cy;
1760 }
1761
1762 #endif /*G10_MPI_INLINE_H*/
-
+ 98C4253D69C7531F96DC7631D3D26C5733D5104A3DDBD9EAFD622F8AACD8619E71ABB55D0C951B148E9D33887DAB0EDF2CBD9C9B38CA908BC8E04ED930943FDE
mpi/include/mpi-internal.h
(0 . 0)(1 . 290)
1767 /* mpi-internal.h - Internal to the Multi Precision Integers
1768 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
1769 * Copyright (C) 1998, 2000 Free Software Foundation, Inc.
1770 *
1771 * This file is part of GnuPG.
1772 *
1773 * GnuPG is free software; you can redistribute it and/or modify
1774 * it under the terms of the GNU General Public License as published by
1775 * the Free Software Foundation; either version 3 of the License, or
1776 * (at your option) any later version.
1777 *
1778 * GnuPG is distributed in the hope that it will be useful,
1779 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1780 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1781 * GNU General Public License for more details.
1782 *
1783 * You should have received a copy of the GNU General Public License
1784 * along with this program; if not, see <http://www.gnu.org/licenses/>.
1785 *
1786 * Note: This code is heavily based on the GNU MP Library.
1787 * Actually it's the same code with only minor changes in the
1788 * way the data is stored; this is to support the abstraction
1789 * of an optional secure memory allocation which may be used
1790 * to avoid revealing of sensitive data due to paging etc.
1791 * The GNU MP Library itself is published under the LGPL;
1792 * however I decided to publish this code under the plain GPL.
1793 */
1794
1795 #ifndef G10_MPI_INTERNAL_H
1796 #define G10_MPI_INTERNAL_H
1797
1798 #include "mpi.h"
1799 #include "mpi-asm-defs.h"
1800
1801 #if BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_INT
1802 typedef unsigned int mpi_limb_t;
1803 typedef signed int mpi_limb_signed_t;
1804 #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG
1805 typedef unsigned long int mpi_limb_t;
1806 typedef signed long int mpi_limb_signed_t;
1807 #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG_LONG
1808 typedef unsigned long long int mpi_limb_t;
1809 typedef signed long long int mpi_limb_signed_t;
1810 #elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_SHORT
1811 typedef unsigned short int mpi_limb_t;
1812 typedef signed short int mpi_limb_signed_t;
1813 #else
1814 #error BYTES_PER_MPI_LIMB does not match any C type
1815 #endif
1816 #define BITS_PER_MPI_LIMB (8*BYTES_PER_MPI_LIMB)
1817
1818
1819 struct gcry_mpi {
1820 int alloced; /* array size (# of allocated limbs) */
1821 int nlimbs; /* number of valid limbs */
1822 unsigned int nbits; /* the real number of valid bits (info only) */
1823 int sign; /* indicates a negative number */
1824 unsigned flags; /* bit 0: array must be allocated in secure memory space */
1825 /* bit 1: not used */
1826 /* bit 2: the limb is a pointer to some xmalloced data */
1827 mpi_limb_t *d; /* array with the limbs */
1828 };
1829
1830
1831
1832 /* If KARATSUBA_THRESHOLD is not already defined, define it to a
1833 * value which is good on most machines. */
1834
1835 /* tested 4, 16, 32 and 64, where 16 gave the best performance when
1836 * checking a 768 and a 1024 bit ElGamal signature.
1837 * (wk 22.12.97) */
1838 #ifndef KARATSUBA_THRESHOLD
1839 #define KARATSUBA_THRESHOLD 16
1840 #endif
1841
1842 /* The code can't handle KARATSUBA_THRESHOLD smaller than 2. */
1843 #if KARATSUBA_THRESHOLD < 2
1844 #undef KARATSUBA_THRESHOLD
1845 #define KARATSUBA_THRESHOLD 2
1846 #endif
1847
1848
1849 typedef mpi_limb_t *mpi_ptr_t; /* pointer to a limb */
1850 typedef int mpi_size_t; /* (must be a signed type) */
1851
1852 #define ABS(x) (x >= 0 ? x : -x)
1853 #define MIN(l,o) ((l) < (o) ? (l) : (o))
1854 #define MAX(h,i) ((h) > (i) ? (h) : (i))
1855 #define RESIZE_IF_NEEDED(a,b) \
1856 do { \
1857 if( (a)->alloced < (b) ) \
1858 mpi_resize((a), (b)); \
1859 } while(0)
1860
1861 /* Copy N limbs from S to D. */
1862 #define MPN_COPY( d, s, n) \
1863 do { \
1864 mpi_size_t _i; \
1865 for( _i = 0; _i < (n); _i++ ) \
1866 (d)[_i] = (s)[_i]; \
1867 } while(0)
1868
1869 #define MPN_COPY_INCR( d, s, n) \
1870 do { \
1871 mpi_size_t _i; \
1872 for( _i = 0; _i < (n); _i++ ) \
1873 (d)[_i] = (d)[_i]; \
1874 } while (0)
1875
1876 #define MPN_COPY_DECR( d, s, n ) \
1877 do { \
1878 mpi_size_t _i; \
1879 for( _i = (n)-1; _i >= 0; _i--) \
1880 (d)[_i] = (s)[_i]; \
1881 } while(0)
1882
1883 /* Zero N limbs at D */
1884 #define MPN_ZERO(d, n) \
1885 do { \
1886 int _i; \
1887 for( _i = 0; _i < (n); _i++ ) \
1888 (d)[_i] = 0; \
1889 } while (0)
1890
1891 #define MPN_NORMALIZE(d, n) \
1892 do { \
1893 while( (n) > 0 ) { \
1894 if( (d)[(n)-1] ) \
1895 break; \
1896 (n)--; \
1897 } \
1898 } while(0)
1899
1900 #define MPN_NORMALIZE_NOT_ZERO(d, n) \
1901 do { \
1902 for(;;) { \
1903 if( (d)[(n)-1] ) \
1904 break; \
1905 (n)--; \
1906 } \
1907 } while(0)
1908
1909 #define MPN_MUL_N_RECURSE(prodp, up, vp, size, tspace) \
1910 do { \
1911 if( (size) < KARATSUBA_THRESHOLD ) \
1912 mul_n_basecase (prodp, up, vp, size); \
1913 else \
1914 mul_n (prodp, up, vp, size, tspace); \
1915 } while (0);
1916
1917
1918 /* Divide the two-limb number in (NH,,NL) by D, with DI being the largest
1919 * limb not larger than (2**(2*BITS_PER_MP_LIMB))/D - (2**BITS_PER_MP_LIMB).
1920 * If this would yield overflow, DI should be the largest possible number
1921 * (i.e., only ones). For correct operation, the most significant bit of D
1922 * has to be set. Put the quotient in Q and the remainder in R.
1923 */
1924 #define UDIV_QRNND_PREINV(q, r, nh, nl, d, di) \
1925 do { \
1926 mpi_limb_t _q, _ql, _r; \
1927 mpi_limb_t _xh, _xl; \
1928 umul_ppmm (_q, _ql, (nh), (di)); \
1929 _q += (nh); /* DI is 2**BITS_PER_MPI_LIMB too small */ \
1930 umul_ppmm (_xh, _xl, _q, (d)); \
1931 sub_ddmmss (_xh, _r, (nh), (nl), _xh, _xl); \
1932 if( _xh ) { \
1933 sub_ddmmss (_xh, _r, _xh, _r, 0, (d)); \
1934 _q++; \
1935 if( _xh) { \
1936 sub_ddmmss (_xh, _r, _xh, _r, 0, (d)); \
1937 _q++; \
1938 } \
1939 } \
1940 if( _r >= (d) ) { \
1941 _r -= (d); \
1942 _q++; \
1943 } \
1944 (r) = _r; \
1945 (q) = _q; \
1946 } while (0)
1947
1948
1949 /*-- mpiutil.c --*/
1950 #ifdef M_DEBUG
1951 #define mpi_alloc_limb_space(n,f) mpi_debug_alloc_limb_space((n),(f), M_DBGINFO( __LINE__ ) )
1952 #define mpi_free_limb_space(n) mpi_debug_free_limb_space((n), M_DBGINFO( __LINE__ ) )
1953 mpi_ptr_t mpi_debug_alloc_limb_space( unsigned nlimbs, int sec, const char *info );
1954 void mpi_debug_free_limb_space( mpi_ptr_t a, const char *info );
1955 #else
1956 mpi_ptr_t mpi_alloc_limb_space( unsigned nlimbs, int sec );
1957 void mpi_free_limb_space( mpi_ptr_t a );
1958 #endif
1959 void mpi_assign_limb_space( MPI a, mpi_ptr_t ap, unsigned nlimbs );
1960
1961 /*-- mpi-bit.c --*/
1962 void mpi_rshift_limbs( MPI a, unsigned int count );
1963 void mpi_lshift_limbs( MPI a, unsigned int count );
1964
1965
1966 /*-- mpihelp-add.c --*/
1967 mpi_limb_t mpihelp_add_1(mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1968 mpi_size_t s1_size, mpi_limb_t s2_limb );
1969 mpi_limb_t mpihelp_add_n( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1970 mpi_ptr_t s2_ptr, mpi_size_t size);
1971 mpi_limb_t mpihelp_add(mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr, mpi_size_t s1_size,
1972 mpi_ptr_t s2_ptr, mpi_size_t s2_size);
1973
1974 /*-- mpihelp-sub.c --*/
1975 mpi_limb_t mpihelp_sub_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1976 mpi_size_t s1_size, mpi_limb_t s2_limb );
1977 mpi_limb_t mpihelp_sub_n( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1978 mpi_ptr_t s2_ptr, mpi_size_t size);
1979 mpi_limb_t mpihelp_sub(mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr, mpi_size_t s1_size,
1980 mpi_ptr_t s2_ptr, mpi_size_t s2_size);
1981
1982 /*-- mpihelp-cmp.c --*/
1983 int mpihelp_cmp( mpi_ptr_t op1_ptr, mpi_ptr_t op2_ptr, mpi_size_t size );
1984
1985 /*-- mpihelp-mul.c --*/
1986
1987 struct karatsuba_ctx {
1988 struct karatsuba_ctx *next;
1989 mpi_ptr_t tspace;
1990 mpi_size_t tspace_size;
1991 mpi_ptr_t tp;
1992 mpi_size_t tp_size;
1993 };
1994
1995 void mpihelp_release_karatsuba_ctx( struct karatsuba_ctx *ctx );
1996
1997 mpi_limb_t mpihelp_addmul_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
1998 mpi_size_t s1_size, mpi_limb_t s2_limb);
1999 mpi_limb_t mpihelp_submul_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
2000 mpi_size_t s1_size, mpi_limb_t s2_limb);
2001 void mpihelp_mul_n( mpi_ptr_t prodp, mpi_ptr_t up, mpi_ptr_t vp,
2002 mpi_size_t size);
2003 mpi_limb_t mpihelp_mul( mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t usize,
2004 mpi_ptr_t vp, mpi_size_t vsize);
2005 void mpih_sqr_n_basecase( mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t size );
2006 void mpih_sqr_n( mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t size,
2007 mpi_ptr_t tspace);
2008
2009 void mpihelp_mul_karatsuba_case( mpi_ptr_t prodp,
2010 mpi_ptr_t up, mpi_size_t usize,
2011 mpi_ptr_t vp, mpi_size_t vsize,
2012 struct karatsuba_ctx *ctx );
2013
2014
2015 /*-- mpihelp-mul_1.c (or xxx/cpu/ *.S) --*/
2016 mpi_limb_t mpihelp_mul_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
2017 mpi_size_t s1_size, mpi_limb_t s2_limb);
2018
2019 /*-- mpihelp-div.c --*/
2020 mpi_limb_t mpihelp_mod_1(mpi_ptr_t dividend_ptr, mpi_size_t dividend_size,
2021 mpi_limb_t divisor_limb);
2022 mpi_limb_t mpihelp_divrem( mpi_ptr_t qp, mpi_size_t qextra_limbs,
2023 mpi_ptr_t np, mpi_size_t nsize,
2024 mpi_ptr_t dp, mpi_size_t dsize);
2025 mpi_limb_t mpihelp_divmod_1( mpi_ptr_t quot_ptr,
2026 mpi_ptr_t dividend_ptr, mpi_size_t dividend_size,
2027 mpi_limb_t divisor_limb);
2028
2029 /*-- mpihelp-shift.c --*/
2030 mpi_limb_t mpihelp_lshift( mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize,
2031 unsigned cnt);
2032 mpi_limb_t mpihelp_rshift( mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize,
2033 unsigned cnt);
2034
2035
2036 /* Define stuff for longlong.h. */
2037 #define W_TYPE_SIZE BITS_PER_MPI_LIMB
2038 typedef mpi_limb_t UWtype;
2039 typedef unsigned int UHWtype;
2040 #if defined (__GNUC__)
2041 typedef unsigned int UQItype __attribute__ ((mode (QI)));
2042 typedef int SItype __attribute__ ((mode (SI)));
2043 typedef unsigned int USItype __attribute__ ((mode (SI)));
2044 typedef int DItype __attribute__ ((mode (DI)));
2045 typedef unsigned int UDItype __attribute__ ((mode (DI)));
2046 #else
2047 typedef unsigned char UQItype;
2048 typedef long SItype;
2049 typedef unsigned long USItype;
2050 #endif
2051
2052 #ifdef __GNUC__
2053 #include "mpi-inline.h"
2054 #endif
2055
2056 #endif /*G10_MPI_INTERNAL_H*/
-
+ E539EF777487B66317CD23B7D19F883A9BAB67A9CB984DFB5D1A5DF4575A66CB44B7EC199AC0829B1270EDFA68F182D646CE944C14F5C401654E1E0F68271BAF
mpi/include/mpi.h
(0 . 0)(1 . 169)
2061 /* mpi.h - Multi Precision Integers
2062 * Copyright (C) 1994, 1996, 1998, 1999,
2063 * 2000, 2001 Free Software Foundation, Inc.
2064 *
2065 * This file is part of GNUPG.
2066 *
2067 * GNUPG is free software; you can redistribute it and/or modify
2068 * it under the terms of the GNU General Public License as published by
2069 * the Free Software Foundation; either version 3 of the License, or
2070 * (at your option) any later version.
2071 *
2072 * GNUPG is distributed in the hope that it will be useful,
2073 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2074 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2075 * GNU General Public License for more details.
2076 *
2077 * You should have received a copy of the GNU General Public License
2078 * along with this program; if not, see <http://www.gnu.org/licenses/>.
2079 *
2080 * Note: This code is heavily based on the GNU MP Library.
2081 * Actually it's the same code with only minor changes in the
2082 * way the data is stored; this is to support the abstraction
2083 * of an optional secure memory allocation which may be used
2084 * to avoid revealing of sensitive data due to paging etc.
2085 * The GNU MP Library itself is published under the LGPL;
2086 * however I decided to publish this code under the plain GPL.
2087 */
2088
2089 #ifndef G10_MPI_H
2090 #define G10_MPI_H
2091
2092 #include <config.h>
2093 #include <stdio.h>
2094 #include "iobuf.h"
2095 #include "types.h"
2096 #include "memory.h"
2097
2098 #ifndef EXTERN_UNLESS_MAIN_MODULE
2099 #if defined (__riscos__) && !defined (INCLUDED_BY_MAIN_MODULE)
2100 #define EXTERN_UNLESS_MAIN_MODULE extern
2101 #else
2102 #define EXTERN_UNLESS_MAIN_MODULE
2103 #endif
2104 #endif
2105
2106 #define DBG_MPI mpi_debug_mode
2107 EXTERN_UNLESS_MAIN_MODULE int mpi_debug_mode;
2108
2109
2110 struct gcry_mpi;
2111 typedef struct gcry_mpi *MPI;
2112
2113
2114 /*-- mpiutil.c --*/
2115
2116 #ifdef M_DEBUG
2117 #define mpi_alloc(n) mpi_debug_alloc((n), M_DBGINFO( __LINE__ ) )
2118 #define mpi_alloc_secure(n) mpi_debug_alloc_secure((n), M_DBGINFO( __LINE__ ) )
2119 #define mpi_alloc_like(n) mpi_debug_alloc_like((n), M_DBGINFO( __LINE__ ) )
2120 #define mpi_free(a) mpi_debug_free((a), M_DBGINFO(__LINE__) )
2121 #define mpi_resize(a,b) mpi_debug_resize((a),(b), M_DBGINFO(__LINE__) )
2122 #define mpi_copy(a) mpi_debug_copy((a), M_DBGINFO(__LINE__) )
2123 MPI mpi_debug_alloc( unsigned nlimbs, const char *info );
2124 MPI mpi_debug_alloc_secure( unsigned nlimbs, const char *info );
2125 MPI mpi_debug_alloc_like( MPI a, const char *info );
2126 void mpi_debug_free( MPI a, const char *info );
2127 void mpi_debug_resize( MPI a, unsigned nlimbs, const char *info );
2128 MPI mpi_debug_copy( MPI a, const char *info );
2129 #else
2130 MPI mpi_alloc( unsigned nlimbs );
2131 MPI mpi_alloc_secure( unsigned nlimbs );
2132 MPI mpi_alloc_like( MPI a );
2133 void mpi_free( MPI a );
2134 void mpi_resize( MPI a, unsigned nlimbs );
2135 MPI mpi_copy( MPI a );
2136 #endif
2137 #define mpi_is_opaque(a) ((a) && (mpi_get_flags (a)&4))
2138 MPI mpi_set_opaque( MPI a, void *p, unsigned int len );
2139 void *mpi_get_opaque( MPI a, unsigned int *len );
2140 #define mpi_is_secure(a) ((a) && (mpi_get_flags (a)&1))
2141 void mpi_set_secure( MPI a );
2142 void mpi_clear( MPI a );
2143 void mpi_set( MPI w, MPI u);
2144 void mpi_set_ui( MPI w, ulong u);
2145 MPI mpi_alloc_set_ui( unsigned long u);
2146 void mpi_m_check( MPI a );
2147 void mpi_swap( MPI a, MPI b);
2148 int mpi_get_nlimbs (MPI a);
2149 int mpi_is_neg (MPI a);
2150 unsigned int mpi_nlimb_hint_from_nbytes (unsigned int nbytes);
2151 unsigned int mpi_nlimb_hint_from_nbits (unsigned int nbits);
2152 unsigned int mpi_get_flags (MPI a);
2153
2154 /*-- mpicoder.c --*/
2155 int mpi_write( IOBUF out, MPI a );
2156 #ifdef M_DEBUG
2157 #define mpi_read(a,b,c) mpi_debug_read((a),(b),(c), M_DBGINFO( __LINE__ ) )
2158 MPI mpi_debug_read(IOBUF inp, unsigned *nread, int secure, const char *info);
2159 #else
2160 MPI mpi_read(IOBUF inp, unsigned *nread, int secure);
2161 #endif
2162 MPI mpi_read_from_buffer(byte *buffer, unsigned *ret_nread, int secure);
2163 int mpi_fromstr(MPI val, const char *str);
2164 int mpi_print( FILE *fp, MPI a, int mode );
2165 void g10_log_mpidump( const char *text, MPI a );
2166 u32 mpi_get_keyid( MPI a, u32 *keyid );
2167 byte *mpi_get_buffer( MPI a, unsigned *nbytes, int *sign );
2168 byte *mpi_get_secure_buffer( MPI a, unsigned *nbytes, int *sign );
2169 void mpi_set_buffer( MPI a, const byte *buffer, unsigned nbytes, int sign );
2170
2171 #define log_mpidump g10_log_mpidump
2172
2173 /*-- mpi-add.c --*/
2174 void mpi_add_ui(MPI w, MPI u, ulong v );
2175 void mpi_add(MPI w, MPI u, MPI v);
2176 void mpi_addm(MPI w, MPI u, MPI v, MPI m);
2177 void mpi_sub_ui(MPI w, MPI u, ulong v );
2178 void mpi_sub( MPI w, MPI u, MPI v);
2179 void mpi_subm( MPI w, MPI u, MPI v, MPI m);
2180
2181 /*-- mpi-mul.c --*/
2182 void mpi_mul_ui(MPI w, MPI u, ulong v );
2183 void mpi_mul_2exp( MPI w, MPI u, ulong cnt);
2184 void mpi_mul( MPI w, MPI u, MPI v);
2185 void mpi_mulm( MPI w, MPI u, MPI v, MPI m);
2186
2187 /*-- mpi-div.c --*/
2188 ulong mpi_fdiv_r_ui( MPI rem, MPI dividend, ulong divisor );
2189 void mpi_fdiv_r( MPI rem, MPI dividend, MPI divisor );
2190 void mpi_fdiv_q( MPI quot, MPI dividend, MPI divisor );
2191 void mpi_fdiv_qr( MPI quot, MPI rem, MPI dividend, MPI divisor );
2192 void mpi_tdiv_r( MPI rem, MPI num, MPI den);
2193 void mpi_tdiv_qr( MPI quot, MPI rem, MPI num, MPI den);
2194 void mpi_tdiv_q_2exp( MPI w, MPI u, unsigned count );
2195 int mpi_divisible_ui(MPI dividend, ulong divisor );
2196
2197 /*-- mpi-gcd.c --*/
2198 int mpi_gcd( MPI g, MPI a, MPI b );
2199
2200 /*-- mpi-pow.c --*/
2201 void mpi_pow( MPI w, MPI u, MPI v);
2202 void mpi_powm( MPI res, MPI base, MPI exponent, MPI mod);
2203
2204 /*-- mpi-mpow.c --*/
2205 void mpi_mulpowm( MPI res, MPI *basearray, MPI *exparray, MPI mod);
2206
2207 /*-- mpi-cmp.c --*/
2208 int mpi_cmp_ui( MPI u, ulong v );
2209 int mpi_cmp( MPI u, MPI v );
2210
2211 /*-- mpi-scan.c --*/
2212 int mpi_getbyte( MPI a, unsigned idx );
2213 void mpi_putbyte( MPI a, unsigned idx, int value );
2214 unsigned mpi_trailing_zeros( MPI a );
2215
2216 /*-- mpi-bit.c --*/
2217 void mpi_normalize( MPI a );
2218 unsigned mpi_get_nbits( MPI a );
2219 int mpi_test_bit( MPI a, unsigned n );
2220 void mpi_set_bit( MPI a, unsigned n );
2221 void mpi_set_highbit( MPI a, unsigned n );
2222 void mpi_clear_highbit( MPI a, unsigned n );
2223 void mpi_clear_bit( MPI a, unsigned n );
2224 void mpi_rshift( MPI x, MPI a, unsigned n );
2225
2226 /*-- mpi-inv.c --*/
2227 void mpi_invm( MPI x, MPI u, MPI v );
2228
2229 #endif /*G10_MPI_H*/
-
+ 85D1DE1E79681B0CECE4CAEA7CA324374FB41317C449585E8CD4D23FAE4EF10923285545645FAC2921D3C53A0C897E33DA32D895B9BD0B761F696D0D8E036479
mpi/include/ttyio.h
(0 . 0)(1 . 58)
2234 /* ttyio.h
2235 * Copyright (C) 1998, 1999, 2000, 2001, 2005 Free Software Foundation, Inc.
2236 *
2237 * This file is part of GNUPG.
2238 *
2239 * GNUPG is free software; you can redistribute it and/or modify
2240 * it under the terms of the GNU General Public License as published by
2241 * the Free Software Foundation; either version 3 of the License, or
2242 * (at your option) any later version.
2243 *
2244 * GNUPG is distributed in the hope that it will be useful,
2245 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2246 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2247 * GNU General Public License for more details.
2248 *
2249 * You should have received a copy of the GNU General Public License
2250 * along with this program; if not, see <http://www.gnu.org/licenses/>.
2251 */
2252 #ifndef G10_TTYIO_H
2253 #define G10_TTYIO_H
2254
2255 #ifdef HAVE_LIBREADLINE
2256 #include <stdio.h>
2257 #include <readline/readline.h>
2258 #endif
2259
2260 const char *tty_get_ttyname (void);
2261 int tty_batchmode( int onoff );
2262 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 )
2263 void tty_printf (const char *fmt, ... ) __attribute__ ((format (printf,1,2)));
2264 void tty_fprintf (FILE *fp, const char *fmt, ... )
2265 __attribute__ ((format (printf,2,3)));
2266 #else
2267 void tty_printf (const char *fmt, ... );
2268 void tty_fprintf (FILE *fp, const char *fmt, ... );
2269 #endif
2270 void tty_print_string( const byte *p, size_t n );
2271 void tty_print_utf8_string( const byte *p, size_t n );
2272 void tty_print_utf8_string2( const byte *p, size_t n, size_t max_n );
2273 char *tty_get( const char *prompt );
2274 char *tty_get_hidden( const char *prompt );
2275 void tty_kill_prompt(void);
2276 int tty_get_answer_is_yes( const char *prompt );
2277 int tty_no_terminal(int onoff);
2278
2279 #ifdef HAVE_LIBREADLINE
2280 void tty_enable_completion(rl_completion_func_t *completer);
2281 void tty_disable_completion(void);
2282 #else
2283 /* Use a macro to stub out these functions since a macro has no need
2284 to typedef a "rl_completion_func_t" which would be undefined
2285 without readline. */
2286 #define tty_enable_completion(x)
2287 #define tty_disable_completion()
2288 #endif
2289 void tty_cleanup_after_signal (void);
2290
2291 #endif /*G10_TTYIO_H*/
-
+ D355F8BB711647E95451CF2D53F8C496013D9C797ACC81560FAE155C5850823C880D647347426A4562DA568A6CDE708FDCCBD1E881568816156C0801C7E47FD7
mpi/include/types.h
(0 . 0)(1 . 142)
2296 /* types.h - some common typedefs
2297 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
2298 *
2299 * This file is part of GNUPG.
2300 *
2301 * GNUPG is free software; you can redistribute it and/or modify
2302 * it under the terms of the GNU General Public License as published by
2303 * the Free Software Foundation; either version 3 of the License, or
2304 * (at your option) any later version.
2305 *
2306 * GNUPG is distributed in the hope that it will be useful,
2307 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2308 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2309 * GNU General Public License for more details.
2310 *
2311 * You should have received a copy of the GNU General Public License
2312 * along with this program; if not, see <http://www.gnu.org/licenses/>.
2313 */
2314
2315 #ifndef G10_TYPES_H
2316 #define G10_TYPES_H
2317
2318 #ifdef HAVE_INTTYPES_H
2319 /* For uint64_t */
2320 #include <inttypes.h>
2321 #endif
2322
2323 /* The AC_CHECK_SIZEOF() in configure fails for some machines.
2324 * we provide some fallback values here */
2325 #if !SIZEOF_UNSIGNED_SHORT
2326 #undef SIZEOF_UNSIGNED_SHORT
2327 #define SIZEOF_UNSIGNED_SHORT 2
2328 #endif
2329 #if !SIZEOF_UNSIGNED_INT
2330 #undef SIZEOF_UNSIGNED_INT
2331 #define SIZEOF_UNSIGNED_INT 4
2332 #endif
2333 #if !SIZEOF_UNSIGNED_LONG
2334 #undef SIZEOF_UNSIGNED_LONG
2335 #define SIZEOF_UNSIGNED_LONG 4
2336 #endif
2337
2338
2339 #include <sys/types.h>
2340
2341
2342 #ifndef HAVE_BYTE_TYPEDEF
2343 #undef byte /* maybe there is a macro with this name */
2344 #ifndef __riscos__
2345 typedef unsigned char byte;
2346 #else
2347 /* Norcroft treats char = unsigned char as legal assignment
2348 but char* = unsigned char* as illegal assignment
2349 and the same applies to the signed variants as well */
2350 typedef char byte;
2351 #endif
2352 #define HAVE_BYTE_TYPEDEF
2353 #endif
2354
2355 #ifndef HAVE_USHORT_TYPEDEF
2356 #undef ushort /* maybe there is a macro with this name */
2357 typedef unsigned short ushort;
2358 #define HAVE_USHORT_TYPEDEF
2359 #endif
2360
2361 #ifndef HAVE_ULONG_TYPEDEF
2362 #undef ulong /* maybe there is a macro with this name */
2363 typedef unsigned long ulong;
2364 #define HAVE_ULONG_TYPEDEF
2365 #endif
2366
2367 #ifndef HAVE_U16_TYPEDEF
2368 #undef u16 /* maybe there is a macro with this name */
2369 #if SIZEOF_UNSIGNED_INT == 2
2370 typedef unsigned int u16;
2371 #elif SIZEOF_UNSIGNED_SHORT == 2
2372 typedef unsigned short u16;
2373 #else
2374 #error no typedef for u16
2375 #endif
2376 #define HAVE_U16_TYPEDEF
2377 #endif
2378
2379 #ifndef HAVE_U32_TYPEDEF
2380 #undef u32 /* maybe there is a macro with this name */
2381 #if SIZEOF_UNSIGNED_INT == 4
2382 typedef unsigned int u32;
2383 #elif SIZEOF_UNSIGNED_LONG == 4
2384 typedef unsigned long u32;
2385 #else
2386 #error no typedef for u32
2387 #endif
2388 #define HAVE_U32_TYPEDEF
2389 #endif
2390
2391 /****************
2392 * Warning: Some systems segfault when this u64 typedef and
2393 * the dummy code in cipher/md.c is not available. Examples are
2394 * Solaris and IRIX.
2395 */
2396 #ifndef HAVE_U64_TYPEDEF
2397 #undef u64 /* maybe there is a macro with this name */
2398 #if SIZEOF_UINT64_T == 8
2399 typedef uint64_t u64;
2400 #define U64_C(c) (UINT64_C(c))
2401 #define HAVE_U64_TYPEDEF
2402 #elif SIZEOF_UNSIGNED_INT == 8
2403 typedef unsigned int u64;
2404 #define U64_C(c) (c ## U)
2405 #define HAVE_U64_TYPEDEF
2406 #elif SIZEOF_UNSIGNED_LONG == 8
2407 typedef unsigned long u64;
2408 #define U64_C(c) (c ## UL)
2409 #define HAVE_U64_TYPEDEF
2410 #elif SIZEOF_UNSIGNED_LONG_LONG == 8
2411 typedef unsigned long long u64;
2412 #define U64_C(c) (c ## ULL)
2413 #define HAVE_U64_TYPEDEF
2414 #endif
2415 #endif
2416
2417 typedef union {
2418 int a;
2419 short b;
2420 char c[1];
2421 long d;
2422 #ifdef HAVE_U64_TYPEDEF
2423 u64 e;
2424 #endif
2425 float f;
2426 double g;
2427 } PROPERLY_ALIGNED_TYPE;
2428
2429 struct string_list {
2430 struct string_list *next;
2431 unsigned int flags;
2432 char d[1];
2433 };
2434 typedef struct string_list *STRLIST;
2435 typedef struct string_list *strlist_t;
2436
2437 #endif /*G10_TYPES_H*/
-
+ 5B4ADEDB0DDA25D37413FD81037EF2D94722CEE3B58B5A5314DA3816308540588319A280819E272845D154B6F2FDBDCECE3A73C15B2802F33BC6BFE484F0B4A5
mpi/include/util.h
(0 . 0)(1 . 334)
2442 /* util.h
2443 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
2444 * 2006 Free Software Foundation, Inc.
2445 *
2446 * This file is part of GNUPG.
2447 *
2448 * GNUPG is free software; you can redistribute it and/or modify
2449 * it under the terms of the GNU General Public License as published by
2450 * the Free Software Foundation; either version 3 of the License, or
2451 * (at your option) any later version.
2452 *
2453 * GNUPG is distributed in the hope that it will be useful,
2454 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2455 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2456 * GNU General Public License for more details.
2457 *
2458 * You should have received a copy of the GNU General Public License
2459 * along with this program; if not, see <http://www.gnu.org/licenses/>.
2460 */
2461 #ifndef G10_UTIL_H
2462 #define G10_UTIL_H
2463
2464 #if defined (_WIN32) || defined (__CYGWIN32__)
2465 #include <stdarg.h>
2466 #endif
2467
2468 #include "types.h"
2469 #include "errors.h"
2470 #include "types.h"
2471 #include "mpi.h"
2472 #include "compat.h"
2473
2474 typedef struct {
2475 int *argc; /* pointer to argc (value subject to change) */
2476 char ***argv; /* pointer to argv (value subject to change) */
2477 unsigned flags; /* Global flags (DO NOT CHANGE) */
2478 int err; /* print error about last option */
2479 /* 1 = warning, 2 = abort */
2480 int r_opt; /* return option */
2481 int r_type; /* type of return value (0 = no argument found)*/
2482 union {
2483 int ret_int;
2484 long ret_long;
2485 ulong ret_ulong;
2486 char *ret_str;
2487 } r; /* Return values */
2488 struct {
2489 int idx;
2490 int inarg;
2491 int stopped;
2492 const char *last;
2493 void *aliases;
2494 const void *cur_alias;
2495 } internal; /* DO NOT CHANGE */
2496 } ARGPARSE_ARGS;
2497
2498 typedef struct {
2499 int short_opt;
2500 const char *long_opt;
2501 unsigned flags;
2502 const char *description; /* optional option description */
2503 } ARGPARSE_OPTS;
2504
2505 /*-- logger.c --*/
2506 void log_set_logfile( const char *name, int fd );
2507 FILE *log_stream(void);
2508 void g10_log_print_prefix(const char *text);
2509 void log_set_name( const char *name );
2510 const char *log_get_name(void);
2511 void log_set_pid( int pid );
2512 int log_get_errorcount( int clear );
2513 void log_inc_errorcount(void);
2514 int log_set_strict(int val);
2515 void g10_log_hexdump( const char *text, const char *buf, size_t len );
2516
2517 #if defined (__riscos__) \
2518 || (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ))
2519 void g10_log_bug( const char *fmt, ... )
2520 __attribute__ ((noreturn, format (printf,1,2)));
2521 void g10_log_bug0( const char *, int, const char * ) __attribute__ ((noreturn));
2522 void g10_log_fatal( const char *fmt, ... )
2523 __attribute__ ((noreturn, format (printf,1,2)));
2524 void g10_log_error( const char *fmt, ... ) __attribute__ ((format (printf,1,2)));
2525 void g10_log_info( const char *fmt, ... ) __attribute__ ((format (printf,1,2)));
2526 void g10_log_warning( const char *fmt, ... ) __attribute__ ((format (printf,1,2)));
2527 void g10_log_debug( const char *fmt, ... ) __attribute__ ((format (printf,1,2)));
2528 #ifndef __riscos__
2529 #define BUG() g10_log_bug0( __FILE__ , __LINE__, __FUNCTION__ )
2530 #else
2531 #define BUG() g10_log_bug0( __FILE__ , __LINE__, __func__ )
2532 #endif
2533 #else
2534 void g10_log_bug( const char *fmt, ... );
2535 void g10_log_bug0( const char *, int );
2536 void g10_log_fatal( const char *fmt, ... );
2537 void g10_log_error( const char *fmt, ... );
2538 void g10_log_info( const char *fmt, ... );
2539 void g10_log_warning( const char *fmt, ... );
2540 void g10_log_debug( const char *fmt, ... );
2541 #define BUG() g10_log_bug0( __FILE__ , __LINE__ )
2542 #endif
2543
2544 #define log_hexdump g10_log_hexdump
2545 #define log_bug g10_log_bug
2546 #define log_bug0 g10_log_bug0
2547 #define log_fatal g10_log_fatal
2548 #define log_error g10_log_error
2549 #define log_info g10_log_info
2550 #define log_warning g10_log_warning
2551 #define log_debug g10_log_debug
2552
2553
2554 /*-- errors.c --*/
2555 const char * g10_errstr( int no );
2556
2557 /*-- argparse.c --*/
2558 int arg_parse( ARGPARSE_ARGS *arg, ARGPARSE_OPTS *opts);
2559 int optfile_parse( FILE *fp, const char *filename, unsigned *lineno,
2560 ARGPARSE_ARGS *arg, ARGPARSE_OPTS *opts);
2561 void usage( int level );
2562 const char *default_strusage( int level );
2563
2564
2565 /*-- (main program) --*/
2566 const char *strusage( int level );
2567
2568
2569 /*-- dotlock.c --*/
2570 struct dotlock_handle;
2571 typedef struct dotlock_handle *DOTLOCK;
2572
2573 void disable_dotlock(void);
2574 DOTLOCK create_dotlock( const char *file_to_lock );
2575 void destroy_dotlock ( DOTLOCK h );
2576 int make_dotlock( DOTLOCK h, long timeout );
2577 int release_dotlock( DOTLOCK h );
2578 void remove_lockfiles (void);
2579
2580 /*-- fileutil.c --*/
2581 char * make_basename(const char *filepath, const char *inputpath);
2582 char * make_dirname(const char *filepath);
2583 char *make_filename( const char *first_part, ... );
2584 int compare_filenames( const char *a, const char *b );
2585 int same_file_p (const char *name1, const char *name2);
2586 const char *print_fname_stdin( const char *s );
2587 const char *print_fname_stdout( const char *s );
2588 int is_file_compressed(const char *s, int *r_status);
2589
2590 /*-- miscutil.c --*/
2591 u32 make_timestamp(void);
2592 u32 scan_isodatestr( const char *string );
2593 u32 isotime2seconds (const char *string);
2594 const char *strtimevalue( u32 stamp );
2595 const char *strtimestamp( u32 stamp ); /* GMT */
2596 const char *isotimestamp( u32 stamp ); /* GMT with hh:mm:ss */
2597 const char *asctimestamp( u32 stamp ); /* localized */
2598 void print_string( FILE *fp, const byte *p, size_t n, int delim );
2599 void print_string2( FILE *fp, const byte *p, size_t n, int delim, int delim2 );
2600 void print_utf8_string( FILE *fp, const byte *p, size_t n );
2601 void print_utf8_string2( FILE *fp, const byte *p, size_t n, int delim);
2602 char *make_printable_string( const byte *p, size_t n, int delim );
2603 int answer_is_yes_no_default( const char *s, int def_answer );
2604 int answer_is_yes( const char *s );
2605 int answer_is_yes_no_quit( const char *s );
2606 int answer_is_okay_cancel (const char *s, int def_answer);
2607 int match_multistr(const char *multistr,const char *match);
2608
2609 /*-- strgutil.c --*/
2610 void free_strlist( STRLIST sl );
2611 #define FREE_STRLIST(a) do { free_strlist((a)); (a) = NULL ; } while(0)
2612 STRLIST add_to_strlist( STRLIST *list, const char *string );
2613 STRLIST add_to_strlist2( STRLIST *list, const char *string, int is_utf8 );
2614 STRLIST append_to_strlist( STRLIST *list, const char *string );
2615 STRLIST append_to_strlist2( STRLIST *list, const char *string, int is_utf8 );
2616 STRLIST strlist_prev( STRLIST head, STRLIST node );
2617 STRLIST strlist_last( STRLIST node );
2618 char *pop_strlist( STRLIST *list );
2619 const char *memistr( const char *buf, size_t buflen, const char *sub );
2620 const char *ascii_memistr( const char *buf, size_t buflen, const char *sub );
2621 char *mem2str( char *, const void *, size_t);
2622 char *trim_spaces( char *string );
2623 unsigned int trim_trailing_chars( byte *line, unsigned int len,
2624 const char *trimchars);
2625 unsigned int trim_trailing_ws( byte *line, unsigned len );
2626 unsigned int check_trailing_chars( const byte *line, unsigned int len,
2627 const char *trimchars );
2628 unsigned int check_trailing_ws( const byte *line, unsigned int len );
2629 int string_count_chr( const char *string, int c );
2630 int set_native_charset( const char *newset );
2631 const char* get_native_charset(void);
2632 char *native_to_utf8( const char *string );
2633 char *utf8_to_native( const char *string, size_t length, int delim);
2634 char *string_to_utf8 (const char *string);
2635
2636 int ascii_isupper (int c);
2637 int ascii_islower (int c);
2638 int ascii_memcasecmp( const char *a, const char *b, size_t n);
2639
2640 #ifndef HAVE_STPCPY
2641 char *stpcpy(char *a,const char *b);
2642 #endif
2643 #ifndef HAVE_STRLWR
2644 char *strlwr(char *a);
2645 #endif
2646 #ifndef HAVE_STRCASECMP
2647 int strcasecmp( const char *, const char *b);
2648 #endif
2649 #ifndef HAVE_STRNCASECMP
2650 int strncasecmp (const char *, const char *b, size_t n);
2651 #endif
2652 #ifndef HAVE_STRTOUL
2653 #define strtoul(a,b,c) ((unsigned long)strtol((a),(b),(c)))
2654 #endif
2655 #ifndef HAVE_MEMMOVE
2656 #define memmove(d, s, n) bcopy((s), (d), (n))
2657 #endif
2658
2659 /*-- membuf.c --*/
2660 /* The definition of the structure is private, we only need it here,
2661 so it can be allocated on the stack. */
2662 struct private_membuf_s {
2663 size_t len;
2664 size_t size;
2665 char *buf;
2666 int out_of_core;
2667 };
2668
2669 typedef struct private_membuf_s membuf_t;
2670
2671 void init_membuf (membuf_t *mb, int initiallen);
2672 void put_membuf (membuf_t *mb, const void *buf, size_t len);
2673 void *get_membuf (membuf_t *mb, size_t *len);
2674
2675
2676
2677 #if defined (_WIN32)
2678 /*-- w32reg.c --*/
2679 char *read_w32_registry_string( const char *root,
2680 const char *dir, const char *name );
2681 int write_w32_registry_string(const char *root, const char *dir,
2682 const char *name, const char *value);
2683
2684 #endif /*_WIN32*/
2685
2686 /*-- strgutil.c --*/
2687 char *xasprintf (const char *fmt, ...);
2688 char *xtryasprintf (const char *fmt, ...);
2689
2690
2691 /*-- pka.c --*/
2692 char *get_pka_info (const char *address, unsigned char *fpr);
2693
2694 /*-- cert.c --*/
2695 int get_cert(const char *name,size_t max_size,IOBUF *iobuf,
2696 unsigned char **fpr,size_t *fpr_len,char **url);
2697
2698 /*-- convert.c --*/
2699 int hex2bin (const char *string, void *buffer, size_t length);
2700 int hexcolon2bin (const char *string, void *buffer, size_t length);
2701 char *bin2hex (const void *buffer, size_t length, char *stringbuf);
2702 char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf);
2703 const char *hex2str (const char *hexstring,
2704 char *buffer, size_t bufsize, size_t *buflen);
2705 char *hex2str_alloc (const char *hexstring, size_t *r_count);
2706
2707
2708 /**** other missing stuff ****/
2709 #ifndef HAVE_ATEXIT /* For SunOS */
2710 #define atexit(a) (on_exit((a),0))
2711 #endif
2712
2713 #ifndef HAVE_RAISE
2714 #define raise(a) kill(getpid(), (a))
2715 #endif
2716
2717 /*-- Replacement functions from funcname.c --*/
2718
2719
2720
2721 /******** some macros ************/
2722 #ifndef STR
2723 #define STR(v) #v
2724 #endif
2725 #define STR2(v) STR(v)
2726 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
2727 #define DIMof(type,member) DIM(((type *)0)->member)
2728
2729 #define wipememory2(_ptr,_set,_len) do { volatile char *_vptr=(volatile char *)(_ptr); size_t _vlen=(_len); while(_vlen) { *_vptr=(_set); _vptr++; _vlen--; } } while(0)
2730 #define wipememory(_ptr,_len) wipememory2(_ptr,0,_len)
2731
2732 /*-- macros to replace ctype ones and avoid locale problems --*/
2733 #define spacep(p) (*(p) == ' ' || *(p) == '\t')
2734 #define digitp(p) (*(p) >= '0' && *(p) <= '9')
2735 #define hexdigitp(a) (digitp (a) \
2736 || (*(a) >= 'A' && *(a) <= 'F') \
2737 || (*(a) >= 'a' && *(a) <= 'f'))
2738 /* the atoi macros assume that the buffer has only valid digits */
2739 #define atoi_1(p) (*(p) - '0' )
2740 #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1))
2741 #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2))
2742 #define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
2743 *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
2744 #define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
2745
2746 /******* RISC OS stuff ***********/
2747 #ifdef __riscos__
2748 int riscos_load_module(const char *name, const char * const path[], int fatal);
2749 int riscos_get_filetype_from_string(const char *string, int len);
2750 int riscos_get_filetype(const char *filename);
2751 void riscos_set_filetype_by_number(const char *filename, int type);
2752 void riscos_set_filetype_by_mimetype(const char *filename, const char *mimetype);
2753 pid_t riscos_getpid(void);
2754 int riscos_kill(pid_t pid, int sig);
2755 int riscos_access(const char *path, int amode);
2756 int riscos_getchar(void);
2757 char *riscos_make_basename(const char *filepath, const char *inputpath);
2758 int riscos_check_regexp(const char *exp, const char *string, int debug);
2759 int riscos_fdopenfile(const char *filename, const int allow_write);
2760 void riscos_close_fds(void);
2761 int riscos_renamefile(const char *old, const char *new);
2762 char *riscos_gstrans(const char *old);
2763 void riscos_not_implemented(const char *feature);
2764 #ifdef DEBUG
2765 void riscos_dump_fdlist(void);
2766 void riscos_list_openfiles(void);
2767 #endif
2768 #ifndef __RISCOS__C__
2769 #define getpid riscos_getpid
2770 #define kill(a,b) riscos_kill((a),(b))
2771 #define access(a,b) riscos_access((a),(b))
2772 #endif /* !__RISCOS__C__ */
2773 #endif /* __riscos__ */
2774
2775 #endif /*G10_UTIL_H*/
-
+ C5DDDD9D52900BA3D847422F9DBA2799BE2954AD9CCA3B9AA6FB1654DD89EE00575C52D15BD65E98D3054D4646943372CA8AD591F610EA7761D21FE4C3AE6187
mpi/iobuf.c
(0 . 0)(1 . 2326)
2780 /* iobuf.c - file handling
2781 * Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2008,
2782 * 2009 Free Software Foundation, Inc.
2783 *
2784 * This file is part of GnuPG.
2785 *
2786 * GnuPG is free software; you can redistribute it and/or modify
2787 * it under the terms of the GNU General Public License as published by
2788 * the Free Software Foundation; either version 3 of the License, or
2789 * (at your option) any later version.
2790 *
2791 * GnuPG is distributed in the hope that it will be useful,
2792 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2793 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2794 * GNU General Public License for more details.
2795 *
2796 * You should have received a copy of the GNU General Public License
2797 * along with this program; if not, see <http://www.gnu.org/licenses/>.
2798 */
2799
2800 #include <config.h>
2801 #include <stdio.h>
2802 #include <stdlib.h>
2803 #include <string.h>
2804 #include <errno.h>
2805 #include <ctype.h>
2806 #include <assert.h>
2807 #include <sys/types.h>
2808 #include <sys/stat.h>
2809 #include <fcntl.h>
2810 #include <unistd.h>
2811 #ifdef HAVE_DOSISH_SYSTEM
2812 #include <windows.h>
2813 #endif
2814 #ifdef __riscos__
2815 #include <kernel.h>
2816 #include <swis.h>
2817 #endif /* __riscos__ */
2818
2819 #include "memory.h"
2820 #include "util.h"
2821 #include "iobuf.h"
2822
2823 /* The size of the internal buffers.
2824 NOTE: If you change this value you MUST also adjust the regression
2825 test "armored_key_8192" in armor.test! */
2826 #define IOBUF_BUFFER_SIZE 8192
2827
2828
2829 #undef FILE_FILTER_USES_STDIO
2830
2831 #ifdef HAVE_DOSISH_SYSTEM
2832 #define USE_SETMODE 1
2833 #endif
2834
2835 #ifdef FILE_FILTER_USES_STDIO
2836 #define my_fileno(a) fileno ((a))
2837 #define my_fopen_ro(a,b) fopen ((a),(b))
2838 #define my_fopen(a,b) fopen ((a),(b))
2839 typedef FILE *FILEP_OR_FD;
2840 #define INVALID_FP NULL
2841 #define FILEP_OR_FD_FOR_STDIN (stdin)
2842 #define FILEP_OR_FD_FOR_STDOUT (stdout)
2843 typedef struct {
2844 FILE *fp; /* open file handle */
2845 int keep_open;
2846 int no_cache;
2847 int print_only_name; /* flags indicating that fname is not a real file*/
2848 char fname[1]; /* name of the file */
2849 } file_filter_ctx_t ;
2850 #else
2851 #define my_fileno(a) (a)
2852 #define my_fopen_ro(a,b) fd_cache_open ((a),(b))
2853 #define my_fopen(a,b) direct_open ((a),(b))
2854 #ifdef HAVE_DOSISH_SYSTEM
2855 typedef HANDLE FILEP_OR_FD;
2856 #define INVALID_FP ((HANDLE)-1)
2857 #define FILEP_OR_FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE))
2858 #define FILEP_OR_FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE))
2859 #undef USE_SETMODE
2860 #else
2861 typedef int FILEP_OR_FD;
2862 #define INVALID_FP (-1)
2863 #define FILEP_OR_FD_FOR_STDIN (0)
2864 #define FILEP_OR_FD_FOR_STDOUT (1)
2865 #endif
2866 typedef struct {
2867 FILEP_OR_FD fp; /* open file handle */
2868 int keep_open;
2869 int no_cache;
2870 int eof_seen;
2871 int print_only_name; /* flags indicating that fname is not a real file*/
2872 char fname[1]; /* name of the file */
2873 } file_filter_ctx_t ;
2874
2875 struct close_cache_s {
2876 struct close_cache_s *next;
2877 FILEP_OR_FD fp;
2878 char fname[1];
2879 };
2880 typedef struct close_cache_s *CLOSE_CACHE;
2881 static CLOSE_CACHE close_cache;
2882 #endif
2883
2884 #ifdef _WIN32
2885 typedef struct {
2886 int sock;
2887 int keep_open;
2888 int no_cache;
2889 int eof_seen;
2890 int print_only_name; /* flags indicating that fname is not a real file*/
2891 char fname[1]; /* name of the file */
2892 } sock_filter_ctx_t ;
2893 #endif /*_WIN32*/
2894
2895 /* The first partial length header block must be of size 512
2896 * to make it easier (and efficienter) we use a min. block size of 512
2897 * for all chunks (but the last one) */
2898 #define OP_MIN_PARTIAL_CHUNK 512
2899 #define OP_MIN_PARTIAL_CHUNK_2POW 9
2900
2901 typedef struct {
2902 int use;
2903 size_t size;
2904 size_t count;
2905 int partial; /* 1 = partial header, 2 in last partial packet */
2906 char *buffer; /* used for partial header */
2907 size_t buflen; /* used size of buffer */
2908 int first_c; /* of partial header (which is > 0)*/
2909 int eof;
2910 } block_filter_ctx_t;
2911
2912 static int special_names_enabled;
2913
2914 static int underflow(IOBUF a);
2915 static int translate_file_handle ( int fd, int for_write );
2916
2917
2918
2919 #ifndef FILE_FILTER_USES_STDIO
2920
2921 /* This is a replacement for strcmp. Under W32 it does not
2922 distinguish between backslash and slash. */
2923 static int
2924 fd_cache_strcmp (const char *a, const char *b)
2925 {
2926 #ifdef HAVE_DOSISH_SYSTEM
2927 for (; *a && *b; a++, b++)
2928 {
2929 if (*a != *b && !((*a == '/' && *b == '\\')
2930 || (*a == '\\' && *b == '/')) )
2931 break;
2932 }
2933 return *(const unsigned char *)a - *(const unsigned char *)b;
2934 #else
2935 return strcmp (a, b);
2936 #endif
2937 }
2938
2939 /*
2940 * Invalidate (i.e. close) a cached iobuf or all iobufs if NULL is
2941 * used for FNAME.
2942 */
2943 static int
2944 fd_cache_invalidate (const char *fname)
2945 {
2946 CLOSE_CACHE cc;
2947 int err=0;
2948
2949 if (!fname) {
2950 if( DBG_IOBUF )
2951 log_debug ("fd_cache_invalidate (all)\n");
2952
2953 for (cc=close_cache; cc; cc = cc->next ) {
2954 if ( cc->fp != INVALID_FP ) {
2955 #ifdef HAVE_DOSISH_SYSTEM
2956 CloseHandle (cc->fp);
2957 #else
2958 close(cc->fp);
2959 #endif
2960 cc->fp = INVALID_FP;
2961 }
2962 }
2963 return err;
2964 }
2965
2966 if( DBG_IOBUF )
2967 log_debug ("fd_cache_invalidate (%s)\n", fname);
2968
2969 for (cc=close_cache; cc; cc = cc->next ) {
2970 if ( cc->fp != INVALID_FP && !fd_cache_strcmp (cc->fname, fname) ) {
2971 if( DBG_IOBUF )
2972 log_debug (" did (%s)\n", cc->fname);
2973 #ifdef HAVE_DOSISH_SYSTEM
2974 if(CloseHandle (cc->fp)==0)
2975 err=-1;
2976 #else
2977 err=close(cc->fp);
2978 #endif
2979 cc->fp = INVALID_FP;
2980 }
2981 }
2982
2983 return err;
2984 }
2985
2986 static int
2987 fd_cache_synchronize(const char *fname)
2988 {
2989 int err=0;
2990
2991 #ifndef HAVE_DOSISH_SYSTEM
2992 CLOSE_CACHE cc;
2993
2994 if( DBG_IOBUF )
2995 log_debug ("fd_cache_synchronize (%s)\n", fname);
2996
2997 for (cc=close_cache; cc; cc = cc->next )
2998 {
2999 if ( cc->fp != INVALID_FP && !fd_cache_strcmp (cc->fname, fname) )
3000 {
3001 if( DBG_IOBUF )
3002 log_debug (" did (%s)\n", cc->fname);
3003
3004 err=fsync(cc->fp);
3005 }
3006 }
3007 #endif
3008
3009 return err;
3010 }
3011
3012 static FILEP_OR_FD
3013 direct_open (const char *fname, const char *mode)
3014 {
3015 #ifdef HAVE_DOSISH_SYSTEM
3016 unsigned long da, cd, sm;
3017 HANDLE hfile;
3018
3019 /* Note, that we do not handle all mode combinations */
3020
3021 /* According to the ReactOS source it seems that open() of the
3022 * standard MSW32 crt does open the file in share mode which is
3023 * something new for MS applications ;-)
3024 */
3025 if ( strchr (mode, '+') ) {
3026 fd_cache_invalidate (fname);
3027 da = GENERIC_READ|GENERIC_WRITE;
3028 cd = OPEN_EXISTING;
3029 sm = FILE_SHARE_READ | FILE_SHARE_WRITE;
3030 }
3031 else if ( strchr (mode, 'w') ) {
3032 fd_cache_invalidate (fname);
3033 da = GENERIC_WRITE;
3034 cd = CREATE_ALWAYS;
3035 sm = FILE_SHARE_WRITE;
3036 }
3037 else {
3038 da = GENERIC_READ;
3039 cd = OPEN_EXISTING;
3040 sm = FILE_SHARE_READ;
3041 }
3042
3043 hfile = CreateFile (fname, da, sm, NULL, cd, FILE_ATTRIBUTE_NORMAL, NULL);
3044 return hfile;
3045 #else
3046 int oflag;
3047 int cflag = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
3048
3049 /* Note, that we do not handle all mode combinations */
3050 if ( strchr (mode, '+') ) {
3051 fd_cache_invalidate (fname);
3052 oflag = O_RDWR;
3053 }
3054 else if ( strchr (mode, 'w') ) {
3055 fd_cache_invalidate (fname);
3056 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3057 }
3058 else {
3059 oflag = O_RDONLY;
3060 }
3061 #ifdef O_BINARY
3062 if (strchr (mode, 'b'))
3063 oflag |= O_BINARY;
3064 #endif
3065 #ifndef __riscos__
3066 return open (fname, oflag, cflag );
3067 #else
3068 {
3069 struct stat buf;
3070 int rc = stat( fname, &buf );
3071
3072 /* Don't allow iobufs on directories */
3073 if( !rc && S_ISDIR(buf.st_mode) && !S_ISREG(buf.st_mode) )
3074 return __set_errno( EISDIR );
3075 else
3076 return open( fname, oflag, cflag );
3077 }
3078 #endif
3079 #endif
3080 }
3081
3082
3083 /*
3084 * Instead of closing an FD we keep it open and cache it for later reuse
3085 * Note that this caching strategy only works if the process does not chdir.
3086 */
3087 static void
3088 fd_cache_close (const char *fname, FILEP_OR_FD fp)
3089 {
3090 CLOSE_CACHE cc;
3091
3092 assert (fp);
3093 if ( !fname || !*fname ) {
3094 #ifdef HAVE_DOSISH_SYSTEM
3095 CloseHandle (fp);
3096 #else
3097 close(fp);
3098 #endif
3099 if( DBG_IOBUF )
3100 log_debug ("fd_cache_close (%d) real\n", (int)fp);
3101 return;
3102 }
3103 /* try to reuse a slot */
3104 for (cc=close_cache; cc; cc = cc->next ) {
3105 if ( cc->fp == INVALID_FP && !fd_cache_strcmp (cc->fname, fname) ) {
3106 cc->fp = fp;
3107 if( DBG_IOBUF )
3108 log_debug ("fd_cache_close (%s) used existing slot\n", fname);
3109 return;
3110 }
3111 }
3112 /* add a new one */
3113 if( DBG_IOBUF )
3114 log_debug ("fd_cache_close (%s) new slot created\n", fname);
3115 cc = xmalloc_clear (sizeof *cc + strlen (fname));
3116 strcpy (cc->fname, fname);
3117 cc->fp = fp;
3118 cc->next = close_cache;
3119 close_cache = cc;
3120 }
3121
3122 /*
3123 * Do an direct_open on FNAME but first try to reuse one from the fd_cache
3124 */
3125 static FILEP_OR_FD
3126 fd_cache_open (const char *fname, const char *mode)
3127 {
3128 CLOSE_CACHE cc;
3129
3130 assert (fname);
3131 for (cc=close_cache; cc; cc = cc->next ) {
3132 if ( cc->fp != INVALID_FP && !fd_cache_strcmp (cc->fname, fname) ) {
3133 FILEP_OR_FD fp = cc->fp;
3134 cc->fp = INVALID_FP;
3135 if( DBG_IOBUF )
3136 log_debug ("fd_cache_open (%s) using cached fp\n", fname);
3137 #ifdef HAVE_DOSISH_SYSTEM
3138 if (SetFilePointer (fp, 0, NULL, FILE_BEGIN) == 0xffffffff ) {
3139 log_error ("rewind file failed on handle %p: %s\n",
3140 fp, w32_strerror (errno));
3141 fp = INVALID_FP;
3142 }
3143 #else
3144 if ( lseek (fp, 0, SEEK_SET) == (off_t)-1 ) {
3145 log_error("can't rewind fd %d: %s\n", fp, strerror(errno) );
3146 fp = INVALID_FP;
3147 }
3148 #endif
3149 return fp;
3150 }
3151 }
3152 if( DBG_IOBUF )
3153 log_debug ("fd_cache_open (%s) not cached\n", fname);
3154 return direct_open (fname, mode);
3155 }
3156
3157
3158 #endif /*FILE_FILTER_USES_STDIO*/
3159
3160
3161 /****************
3162 * Read data from a file into buf which has an allocated length of *LEN.
3163 * return the number of read bytes in *LEN. OPAQUE is the FILE * of
3164 * the stream. A is not used.
3165 * control may be:
3166 * IOBUFCTRL_INIT: called just before the function is linked into the
3167 * list of function. This can be used to prepare internal
3168 * data structures of the function.
3169 * IOBUFCTRL_FREE: called just before the function is removed from the
3170 * list of functions and can be used to release internal
3171 * data structures or close a file etc.
3172 * IOBUFCTRL_UNDERFLOW: called by iobuf_underflow to fill the buffer
3173 * with new stuff. *RET_LEN is the available size of the
3174 * buffer, and should be set to the number of bytes
3175 * which were put into the buffer. The function
3176 * returns 0 to indicate success, -1 on EOF and
3177 * G10ERR_xxxxx for other errors.
3178 *
3179 * IOBUFCTRL_FLUSH: called by iobuf_flush() to write out the collected stuff.
3180 * *RET_LAN is the number of bytes in BUF.
3181 *
3182 * IOBUFCTRL_CANCEL: send to all filters on behalf of iobuf_cancel. The
3183 * filter may take appropriate action on this message.
3184 */
3185 static int
3186 file_filter(void *opaque, int control, IOBUF chain, byte *buf, size_t *ret_len)
3187 {
3188 file_filter_ctx_t *a = opaque;
3189 FILEP_OR_FD f = a->fp;
3190 size_t size = *ret_len;
3191 size_t nbytes = 0;
3192 int rc = 0;
3193
3194 #ifdef FILE_FILTER_USES_STDIO
3195 if( control == IOBUFCTRL_UNDERFLOW ) {
3196 assert( size ); /* need a buffer */
3197 if ( feof(f)) { /* On terminals you could easiely read as many EOFs as you call */
3198 rc = -1; /* fread() or fgetc() repeatly. Every call will block until you press */
3199 *ret_len = 0; /* CTRL-D. So we catch this case before we call fread() again. */
3200 }
3201 else {
3202 clearerr( f );
3203 nbytes = fread( buf, 1, size, f );
3204 if( feof(f) && !nbytes ) {
3205 rc = -1; /* okay: we can return EOF now. */
3206 }
3207 else if( ferror(f) && errno != EPIPE ) {
3208 log_error("%s: read error: %s\n",
3209 a->fname, strerror(errno));
3210 rc = G10ERR_READ_FILE;
3211 }
3212 *ret_len = nbytes;
3213 }
3214 }
3215 else if( control == IOBUFCTRL_FLUSH ) {
3216 if( size ) {
3217 clearerr( f );
3218 nbytes = fwrite( buf, 1, size, f );
3219 if( ferror(f) ) {
3220 log_error("%s: write error: %s\n", a->fname, strerror(errno));
3221 rc = G10ERR_WRITE_FILE;
3222 }
3223 }
3224 *ret_len = nbytes;
3225 }
3226 else if( control == IOBUFCTRL_INIT ) {
3227 a->keep_open = a->no_cache = 0;
3228 }
3229 else if( control == IOBUFCTRL_DESC ) {
3230 *(char**)buf = "file_filter";
3231 }
3232 else if( control == IOBUFCTRL_FREE ) {
3233 if( f != stdin && f != stdout ) {
3234 if( DBG_IOBUF )
3235 log_debug("%s: close fd %d\n", a->fname, fileno(f) );
3236 if (!a->keep_open)
3237 fclose(f);
3238 }
3239 f = NULL;
3240 xfree(a); /* we can free our context now */
3241 }
3242 #else /* !stdio implementation */
3243
3244 if( control == IOBUFCTRL_UNDERFLOW ) {
3245 assert( size ); /* need a buffer */
3246 if ( a->eof_seen) {
3247 rc = -1;
3248 *ret_len = 0;
3249 }
3250 else {
3251 #ifdef HAVE_DOSISH_SYSTEM
3252 unsigned long nread;
3253
3254 nbytes = 0;
3255 if ( !ReadFile ( f, buf, size, &nread, NULL ) ) {
3256 if ((int)GetLastError () != ERROR_BROKEN_PIPE) {
3257 log_error ("%s: read error: %s\n", a->fname,
3258 w32_strerror (0));
3259 rc = G10ERR_READ_FILE;
3260 }
3261 }
3262 else if ( !nread ) {
3263 a->eof_seen = 1;
3264 rc = -1;
3265 }
3266 else {
3267 nbytes = nread;
3268 }
3269
3270 #else
3271
3272 int n;
3273
3274 nbytes = 0;
3275 do {
3276 n = read ( f, buf, size );
3277 } while (n == -1 && errno == EINTR );
3278 if ( n == -1 ) { /* error */
3279 if (errno != EPIPE) {
3280 log_error("%s: read error: %s\n",
3281 a->fname, strerror(errno));
3282 rc = G10ERR_READ_FILE;
3283 }
3284 }
3285 else if ( !n ) { /* eof */
3286 a->eof_seen = 1;
3287 rc = -1;
3288 }
3289 else {
3290 nbytes = n;
3291 }
3292 #endif
3293 *ret_len = nbytes;
3294 }
3295 }
3296 else if( control == IOBUFCTRL_FLUSH ) {
3297 if( size ) {
3298 #ifdef HAVE_DOSISH_SYSTEM
3299 byte *p = buf;
3300 unsigned long n;
3301
3302 nbytes = size;
3303 do {
3304 if (size && !WriteFile (f, p, nbytes, &n, NULL)) {
3305 log_error ("%s: write error: %s\n", a->fname,
3306 w32_strerror (0));
3307 rc = G10ERR_WRITE_FILE;
3308 break;
3309 }
3310 p += n;
3311 nbytes -= n;
3312 } while ( nbytes );
3313 nbytes = p - buf;
3314 #else
3315 byte *p = buf;
3316 int n;
3317
3318 nbytes = size;
3319 do {
3320 do {
3321 n = write ( f, p, nbytes );
3322 } while ( n == -1 && errno == EINTR );
3323 if ( n > 0 ) {
3324 p += n;
3325 nbytes -= n;
3326 }
3327 } while ( n != -1 && nbytes );
3328 if( n == -1 ) {
3329 log_error("%s: write error: %s\n", a->fname, strerror(errno));
3330 rc = G10ERR_WRITE_FILE;
3331 }
3332 nbytes = p - buf;
3333 #endif
3334 }
3335 *ret_len = nbytes;
3336 }
3337 else if ( control == IOBUFCTRL_INIT ) {
3338 a->eof_seen = 0;
3339 a->keep_open = 0;
3340 a->no_cache = 0;
3341 }
3342 else if ( control == IOBUFCTRL_DESC ) {
3343 *(char**)buf = "file_filter(fd)";
3344 }
3345 else if ( control == IOBUFCTRL_FREE ) {
3346 #ifdef HAVE_DOSISH_SYSTEM
3347 if ( f != FILEP_OR_FD_FOR_STDIN && f != FILEP_OR_FD_FOR_STDOUT ) {
3348 if( DBG_IOBUF )
3349 log_debug("%s: close handle %p\n", a->fname, f );
3350 if (!a->keep_open)
3351 fd_cache_close (a->no_cache?NULL:a->fname, f);
3352 }
3353 #else
3354 if ( (int)f != 0 && (int)f != 1 ) {
3355 if( DBG_IOBUF )
3356 log_debug("%s: close fd %d\n", a->fname, f );
3357 if (!a->keep_open)
3358 fd_cache_close (a->no_cache?NULL:a->fname, f);
3359 }
3360 f = INVALID_FP;
3361 #endif
3362 xfree (a); /* we can free our context now */
3363 }
3364 #endif /* !stdio implementation */
3365 return rc;
3366 }
3367
3368 #ifdef _WIN32
3369 /* Becuase sockets are an special object under Lose32 we have to
3370 * use a special filter */
3371 static int
3372 sock_filter (void *opaque, int control, IOBUF chain, byte *buf, size_t *ret_len)
3373 {
3374 sock_filter_ctx_t *a = opaque;
3375 size_t size = *ret_len;
3376 size_t nbytes = 0;
3377 int rc = 0;
3378
3379 if( control == IOBUFCTRL_UNDERFLOW ) {
3380 assert( size ); /* need a buffer */
3381 if ( a->eof_seen) {
3382 rc = -1;
3383 *ret_len = 0;
3384 }
3385 else {
3386 int nread;
3387
3388 nread = recv ( a->sock, buf, size, 0 );
3389 if ( nread == SOCKET_ERROR ) {
3390 int ec = (int)WSAGetLastError ();
3391 log_error("socket read error: ec=%d\n", ec);
3392 rc = G10ERR_READ_FILE;
3393 }
3394 else if ( !nread ) {
3395 a->eof_seen = 1;
3396 rc = -1;
3397 }
3398 else {
3399 nbytes = nread;
3400 }
3401 *ret_len = nbytes;
3402 }
3403 }
3404 else if( control == IOBUFCTRL_FLUSH ) {
3405 if( size ) {
3406 byte *p = buf;
3407 int n;
3408
3409 nbytes = size;
3410 do {
3411 n = send (a->sock, p, nbytes, 0);
3412 if ( n == SOCKET_ERROR ) {
3413 int ec = (int)WSAGetLastError ();
3414 log_error("socket write error: ec=%d\n", ec);
3415 rc = G10ERR_WRITE_FILE;
3416 break;
3417 }
3418 p += n;
3419 nbytes -= n;
3420 } while ( nbytes );
3421 nbytes = p - buf;
3422 }
3423 *ret_len = nbytes;
3424 }
3425 else if ( control == IOBUFCTRL_INIT ) {
3426 a->eof_seen = 0;
3427 a->keep_open = 0;
3428 a->no_cache = 0;
3429 }
3430 else if ( control == IOBUFCTRL_DESC ) {
3431 *(char**)buf = "sock_filter";
3432 }
3433 else if ( control == IOBUFCTRL_FREE ) {
3434 if (!a->keep_open)
3435 closesocket (a->sock);
3436 xfree (a); /* we can free our context now */
3437 }
3438 return rc;
3439 }
3440 #endif /*_WIN32*/
3441
3442 /****************
3443 * This is used to implement the block write mode.
3444 * Block reading is done on a byte by byte basis in readbyte(),
3445 * without a filter
3446 */
3447 static int
3448 block_filter(void *opaque, int control, IOBUF chain, byte *buf, size_t *ret_len)
3449 {
3450 block_filter_ctx_t *a = opaque;
3451 size_t size = *ret_len;
3452 int c, needed, rc = 0;
3453 char *p;
3454
3455 if( control == IOBUFCTRL_UNDERFLOW ) {
3456 size_t n=0;
3457
3458 p = buf;
3459 assert( size ); /* need a buffer */
3460 if( a->eof ) /* don't read any further */
3461 rc = -1;
3462 while( !rc && size ) {
3463 if( !a->size ) { /* get the length bytes */
3464 if( a->partial == 2 ) {
3465 a->eof = 1;
3466 if( !n )
3467 rc = -1;
3468 break;
3469 }
3470 else if( a->partial ) {
3471 /* These OpenPGP introduced huffman like encoded length
3472 * bytes are really a mess :-( */
3473 if( a->first_c ) {
3474 c = a->first_c;
3475 a->first_c = 0;
3476 }
3477 else if( (c = iobuf_get(chain)) == -1 ) {
3478 log_error("block_filter: 1st length byte missing\n");
3479 rc = G10ERR_READ_FILE;
3480 break;
3481 }
3482 if( c < 192 ) {
3483 a->size = c;
3484 a->partial = 2;
3485 if( !a->size ) {
3486 a->eof = 1;
3487 if( !n )
3488 rc = -1;
3489 break;
3490 }
3491 }
3492 else if( c < 224 ) {
3493 a->size = (c - 192) * 256;
3494 if( (c = iobuf_get(chain)) == -1 ) {
3495 log_error("block_filter: 2nd length byte missing\n");
3496 rc = G10ERR_READ_FILE;
3497 break;
3498 }
3499 a->size += c + 192;
3500 a->partial = 2;
3501 if( !a->size ) {
3502 a->eof = 1;
3503 if( !n )
3504 rc = -1;
3505 break;
3506 }
3507 }
3508 else if( c == 255 ) {
3509 a->size = iobuf_get(chain) << 24;
3510 a->size |= iobuf_get(chain) << 16;
3511 a->size |= iobuf_get(chain) << 8;
3512 if( (c = iobuf_get(chain)) == -1 ) {
3513 log_error("block_filter: invalid 4 byte length\n");
3514 rc = G10ERR_READ_FILE;
3515 break;
3516 }
3517 a->size |= c;
3518 a->partial = 2;
3519 if( !a->size ) {
3520 a->eof = 1;
3521 if( !n )
3522 rc = -1;
3523 break;
3524 }
3525 }
3526 else { /* next partial body length */
3527 a->size = 1 << (c & 0x1f);
3528 }
3529 /* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size);*/
3530 }
3531 else
3532 BUG();
3533 }
3534
3535 while( !rc && size && a->size ) {
3536 needed = size < a->size ? size : a->size;
3537 c = iobuf_read( chain, p, needed );
3538 if( c < needed ) {
3539 if( c == -1 ) c = 0;
3540 log_error("block_filter %p: read error (size=%lu,a->size=%lu)\n",
3541 a, (ulong)size+c, (ulong)a->size+c);
3542 rc = G10ERR_READ_FILE;
3543 }
3544 else {
3545 size -= c;
3546 a->size -= c;
3547 p += c;
3548 n += c;
3549 }
3550 }
3551 }
3552 *ret_len = n;
3553 }
3554 else if( control == IOBUFCTRL_FLUSH ) {
3555 if( a->partial ) { /* the complicated openpgp scheme */
3556 size_t blen, n, nbytes = size + a->buflen;
3557
3558 assert( a->buflen <= OP_MIN_PARTIAL_CHUNK );
3559 if( nbytes < OP_MIN_PARTIAL_CHUNK ) {
3560 /* not enough to write a partial block out; so we store it*/
3561 if( !a->buffer )
3562 a->buffer = xmalloc( OP_MIN_PARTIAL_CHUNK );
3563 memcpy( a->buffer + a->buflen, buf, size );
3564 a->buflen += size;
3565 }
3566 else { /* okay, we can write out something */
3567 /* do this in a loop to use the most efficient block lengths */
3568 p = buf;
3569 do {
3570 /* find the best matching block length - this is limited
3571 * by the size of the internal buffering */
3572 for( blen=OP_MIN_PARTIAL_CHUNK*2,
3573 c=OP_MIN_PARTIAL_CHUNK_2POW+1; blen <= nbytes;
3574 blen *=2, c++ )
3575 ;
3576 blen /= 2; c--;
3577 /* write the partial length header */
3578 assert( c <= 0x1f ); /*;-)*/
3579 c |= 0xe0;
3580 iobuf_put( chain, c );
3581 if( (n=a->buflen) ) { /* write stuff from the buffer */
3582 assert( n == OP_MIN_PARTIAL_CHUNK);
3583 if( iobuf_write(chain, a->buffer, n ) )
3584 rc = G10ERR_WRITE_FILE;
3585 a->buflen = 0;
3586 nbytes -= n;
3587 }
3588 if( (n = nbytes) > blen )
3589 n = blen;
3590 if( n && iobuf_write(chain, p, n ) )
3591 rc = G10ERR_WRITE_FILE;
3592 p += n;
3593 nbytes -= n;
3594 } while( !rc && nbytes >= OP_MIN_PARTIAL_CHUNK );
3595 /* store the rest in the buffer */
3596 if( !rc && nbytes ) {
3597 assert( !a->buflen );
3598 assert( nbytes < OP_MIN_PARTIAL_CHUNK );
3599 if( !a->buffer )
3600 a->buffer = xmalloc( OP_MIN_PARTIAL_CHUNK );
3601 memcpy( a->buffer, p, nbytes );
3602 a->buflen = nbytes;
3603 }
3604 }
3605 }
3606 else
3607 BUG();
3608 }
3609 else if( control == IOBUFCTRL_INIT ) {
3610 if( DBG_IOBUF )
3611 log_debug("init block_filter %p\n", a );
3612 if( a->partial )
3613 a->count = 0;
3614 else if( a->use == 1 )
3615 a->count = a->size = 0;
3616 else
3617 a->count = a->size; /* force first length bytes */
3618 a->eof = 0;
3619 a->buffer = NULL;
3620 a->buflen = 0;
3621 }
3622 else if( control == IOBUFCTRL_DESC ) {
3623 *(char**)buf = "block_filter";
3624 }
3625 else if( control == IOBUFCTRL_FREE ) {
3626 if( a->use == 2 ) { /* write the end markers */
3627 if( a->partial ) {
3628 u32 len;
3629 /* write out the remaining bytes without a partial header
3630 * the length of this header may be 0 - but if it is
3631 * the first block we are not allowed to use a partial header
3632 * and frankly we can't do so, because this length must be
3633 * a power of 2. This is _really_ complicated because we
3634 * have to check the possible length of a packet prior
3635 * to it's creation: a chain of filters becomes complicated
3636 * and we need a lot of code to handle compressed packets etc.
3637 * :-(((((((
3638 */
3639 /* construct header */
3640 len = a->buflen;
3641 /*log_debug("partial: remaining length=%u\n", len );*/
3642 if( len < 192 )
3643 rc = iobuf_put(chain, len );
3644 else if( len < 8384 ) {
3645 if( !(rc=iobuf_put( chain, ((len-192) / 256) + 192)) )
3646 rc = iobuf_put( chain, ((len-192) % 256));
3647 }
3648 else { /* use a 4 byte header */
3649 if( !(rc=iobuf_put( chain, 0xff )) )
3650 if( !(rc=iobuf_put( chain, (len >> 24)&0xff )) )
3651 if( !(rc=iobuf_put( chain, (len >> 16)&0xff )) )
3652 if( !(rc=iobuf_put( chain, (len >> 8)&0xff )))
3653 rc=iobuf_put( chain, len & 0xff );
3654 }
3655 if( !rc && len )
3656 rc = iobuf_write(chain, a->buffer, len );
3657 if( rc ) {
3658 log_error("block_filter: write error: %s\n",strerror(errno));
3659 rc = G10ERR_WRITE_FILE;
3660 }
3661 xfree( a->buffer ); a->buffer = NULL; a->buflen = 0;
3662 }
3663 else
3664 BUG();
3665 }
3666 else if( a->size ) {
3667 log_error("block_filter: pending bytes!\n");
3668 }
3669 if( DBG_IOBUF )
3670 log_debug("free block_filter %p\n", a );
3671 xfree(a); /* we can free our context now */
3672 }
3673
3674 return rc;
3675 }
3676
3677
3678 static void
3679 print_chain( IOBUF a )
3680 {
3681 if( !DBG_IOBUF )
3682 return;
3683 for(; a; a = a->chain ) {
3684 size_t dummy_len = 0;
3685 const char *desc = "[none]";
3686
3687 if( a->filter )
3688 a->filter( a->filter_ov, IOBUFCTRL_DESC, NULL,
3689 (byte*)&desc, &dummy_len );
3690
3691 log_debug("iobuf chain: %d.%d `%s' filter_eof=%d start=%d len=%d\n",
3692 a->no, a->subno, desc?desc:"?", a->filter_eof,
3693 (int)a->d.start, (int)a->d.len );
3694 }
3695 }
3696
3697 int
3698 iobuf_print_chain( IOBUF a )
3699 {
3700 print_chain(a);
3701 return 0;
3702 }
3703
3704 /****************
3705 * Allocate a new io buffer, with no function assigned.
3706 * Use is the desired usage: 1 for input, 2 for output, 3 for temp buffer
3707 * BUFSIZE is a suggested buffer size.
3708 */
3709 IOBUF
3710 iobuf_alloc(int use, size_t bufsize)
3711 {
3712 IOBUF a;
3713 static int number=0;
3714
3715 a = xmalloc_clear(sizeof *a);
3716 a->use = use;
3717 a->d.buf = xmalloc( bufsize );
3718 a->d.size = bufsize;
3719 a->no = ++number;
3720 a->subno = 0;
3721 a->opaque = NULL;
3722 a->real_fname = NULL;
3723 return a;
3724 }
3725
3726 int
3727 iobuf_close ( IOBUF a )
3728 {
3729 IOBUF a2;
3730 size_t dummy_len=0;
3731 int rc=0;
3732
3733 if( a && a->directfp ) {
3734 fclose( a->directfp );
3735 xfree( a->real_fname );
3736 if( DBG_IOBUF )
3737 log_debug("iobuf_close -> %p\n", a->directfp );
3738 return 0;
3739 }
3740
3741 for( ; a && !rc ; a = a2 ) {
3742 a2 = a->chain;
3743 if( a->use == 2 && (rc=iobuf_flush(a)) )
3744 log_error("iobuf_flush failed on close: %s\n", g10_errstr(rc));
3745
3746 if( DBG_IOBUF )
3747 log_debug("iobuf-%d.%d: close `%s'\n", a->no, a->subno,
3748 a->desc?a->desc:"?");
3749 if( a->filter && (rc = a->filter(a->filter_ov, IOBUFCTRL_FREE,
3750 a->chain, NULL, &dummy_len)) )
3751 log_error("IOBUFCTRL_FREE failed on close: %s\n", g10_errstr(rc) );
3752 xfree(a->real_fname);
3753 if (a->d.buf) {
3754 memset (a->d.buf, 0, a->d.size); /* erase the buffer */
3755 xfree(a->d.buf);
3756 }
3757 xfree(a);
3758 }
3759 return rc;
3760 }
3761
3762 int
3763 iobuf_cancel( IOBUF a )
3764 {
3765 const char *s;
3766 IOBUF a2;
3767 int rc;
3768 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
3769 char *remove_name = NULL;
3770 #endif
3771
3772 if( a && a->use == 2 ) {
3773 s = iobuf_get_real_fname(a);
3774 if( s && *s ) {
3775 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
3776 remove_name = xstrdup ( s );
3777 #else
3778 remove(s);
3779 #endif
3780 }
3781 }
3782
3783 /* send a cancel message to all filters */
3784 for( a2 = a; a2 ; a2 = a2->chain ) {
3785 size_t dummy;
3786 if( a2->filter )
3787 a2->filter( a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain,
3788 NULL, &dummy );
3789 }
3790
3791 rc = iobuf_close(a);
3792 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
3793 if ( remove_name ) {
3794 /* Argg, MSDOS does not allow to remove open files. So
3795 * we have to do it here */
3796 remove ( remove_name );
3797 xfree ( remove_name );
3798 }
3799 #endif
3800 return rc;
3801 }
3802
3803
3804 /****************
3805 * create a temporary iobuf, which can be used to collect stuff
3806 * in an iobuf and later be written by iobuf_write_temp() to another
3807 * iobuf.
3808 */
3809 IOBUF
3810 iobuf_temp()
3811 {
3812 IOBUF a;
3813
3814 a = iobuf_alloc(3, IOBUF_BUFFER_SIZE );
3815
3816 return a;
3817 }
3818
3819 IOBUF
3820 iobuf_temp_with_content( const char *buffer, size_t length )
3821 {
3822 IOBUF a;
3823
3824 a = iobuf_alloc(3, length );
3825 memcpy( a->d.buf, buffer, length );
3826 a->d.len = length;
3827
3828 return a;
3829 }
3830
3831 void
3832 iobuf_enable_special_filenames ( int yes )
3833 {
3834 special_names_enabled = yes;
3835 }
3836
3837 /*
3838 * see whether the filename has the for "-&nnnn", where n is a
3839 * non-zero number.
3840 * Returns this number or -1 if it is not the case.
3841 */
3842 static int
3843 check_special_filename ( const char *fname )
3844 {
3845 if ( special_names_enabled
3846 && fname && *fname == '-' && fname[1] == '&' ) {
3847 int i;
3848
3849 fname += 2;
3850 for (i=0; digitp (fname+i); i++ )
3851 ;
3852 if ( !fname[i] )
3853 return atoi (fname);
3854 }
3855 return -1;
3856 }
3857
3858 /* This fucntion returns true if FNAME indicates a PIPE (stdout or
3859 stderr) or a special file name if those are enabled. */
3860 int
3861 iobuf_is_pipe_filename (const char *fname)
3862 {
3863 if (!fname || (*fname=='-' && !fname[1]) )
3864 return 1;
3865 return check_special_filename (fname) != -1;
3866 }
3867
3868 /****************
3869 * Create a head iobuf for reading from a file
3870 * returns: NULL if an error occures and sets errno
3871 */
3872 IOBUF
3873 iobuf_open( const char *fname )
3874 {
3875 IOBUF a;
3876 FILEP_OR_FD fp;
3877 file_filter_ctx_t *fcx;
3878 size_t len;
3879 int print_only = 0;
3880 int fd;
3881
3882 if( !fname || (*fname=='-' && !fname[1]) ) {
3883 fp = FILEP_OR_FD_FOR_STDIN;
3884 #ifdef USE_SETMODE
3885 setmode ( my_fileno(fp) , O_BINARY );
3886 #endif
3887 fname = "[stdin]";
3888 print_only = 1;
3889 }
3890 else if ( (fd = check_special_filename ( fname )) != -1 )
3891 return iobuf_fdopen ( translate_file_handle (fd,0), "rb" );
3892 else if( (fp = my_fopen_ro(fname, "rb")) == INVALID_FP )
3893 return NULL;
3894 a = iobuf_alloc(1, IOBUF_BUFFER_SIZE );
3895 fcx = xmalloc( sizeof *fcx + strlen(fname) );
3896 fcx->fp = fp;
3897 fcx->print_only_name = print_only;
3898 strcpy(fcx->fname, fname );
3899 if( !print_only )
3900 a->real_fname = xstrdup( fname );
3901 a->filter = file_filter;
3902 a->filter_ov = fcx;
3903 file_filter( fcx, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &len );
3904 file_filter( fcx, IOBUFCTRL_INIT, NULL, NULL, &len );
3905 if( DBG_IOBUF )
3906 log_debug("iobuf-%d.%d: open `%s' fd=%d\n",
3907 a->no, a->subno, fname, (int)my_fileno(fcx->fp) );
3908
3909 return a;
3910 }
3911
3912 /****************
3913 * Create a head iobuf for reading from a file
3914 * returns: NULL if an error occures and sets errno
3915 */
3916 IOBUF
3917 iobuf_fdopen( int fd, const char *mode )
3918 {
3919 IOBUF a;
3920 FILEP_OR_FD fp;
3921 file_filter_ctx_t *fcx;
3922 size_t len;
3923
3924 #ifdef FILE_FILTER_USES_STDIO
3925 if( !(fp = fdopen(fd, mode)) )
3926 return NULL;
3927 #else
3928 fp = (FILEP_OR_FD)fd;
3929 #endif
3930 a = iobuf_alloc( strchr( mode, 'w')? 2:1, IOBUF_BUFFER_SIZE );
3931 fcx = xmalloc( sizeof *fcx + 20 );
3932 fcx->fp = fp;
3933 fcx->print_only_name = 1;
3934 sprintf(fcx->fname, "[fd %d]", fd );
3935 a->filter = file_filter;
3936 a->filter_ov = fcx;
3937 file_filter( fcx, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &len );
3938 file_filter( fcx, IOBUFCTRL_INIT, NULL, NULL, &len );
3939 if( DBG_IOBUF )
3940 log_debug("iobuf-%d.%d: fdopen `%s'\n", a->no, a->subno, fcx->fname );
3941 iobuf_ioctl (a,3,1,NULL); /* disable fd caching */
3942 return a;
3943 }
3944
3945
3946 IOBUF
3947 iobuf_sockopen ( int fd, const char *mode )
3948 {
3949 IOBUF a;
3950 #ifdef _WIN32
3951 sock_filter_ctx_t *scx;
3952 size_t len;
3953
3954 a = iobuf_alloc( strchr( mode, 'w')? 2:1, IOBUF_BUFFER_SIZE );
3955 scx = xmalloc( sizeof *scx + 25 );
3956 scx->sock = fd;
3957 scx->print_only_name = 1;
3958 sprintf(scx->fname, "[sock %d]", fd );
3959 a->filter = sock_filter;
3960 a->filter_ov = scx;
3961 sock_filter( scx, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &len );
3962 sock_filter( scx, IOBUFCTRL_INIT, NULL, NULL, &len );
3963 if( DBG_IOBUF )
3964 log_debug("iobuf-%d.%d: sockopen `%s'\n", a->no, a->subno, scx->fname);
3965 iobuf_ioctl (a,3,1,NULL); /* disable fd caching */
3966 #else
3967 a = iobuf_fdopen (fd, mode);
3968 #endif
3969 return a;
3970 }
3971
3972 /****************
3973 * create an iobuf for writing to a file; the file will be created.
3974 */
3975 IOBUF
3976 iobuf_create( const char *fname )
3977 {
3978 IOBUF a;
3979 FILEP_OR_FD fp;
3980 file_filter_ctx_t *fcx;
3981 size_t len;
3982 int print_only = 0;
3983 int fd;
3984
3985 if( !fname || (*fname=='-' && !fname[1]) ) {
3986 fp = FILEP_OR_FD_FOR_STDOUT;
3987 #ifdef USE_SETMODE
3988 setmode ( my_fileno(fp) , O_BINARY );
3989 #endif
3990 fname = "[stdout]";
3991 print_only = 1;
3992 }
3993 else if ( (fd = check_special_filename ( fname )) != -1 )
3994 return iobuf_fdopen ( translate_file_handle (fd, 1), "wb" );
3995 else if( (fp = my_fopen(fname, "wb")) == INVALID_FP )
3996 return NULL;
3997 a = iobuf_alloc(2, IOBUF_BUFFER_SIZE );
3998 fcx = xmalloc( sizeof *fcx + strlen(fname) );
3999 fcx->fp = fp;
4000 fcx->print_only_name = print_only;
4001 strcpy(fcx->fname, fname );
4002 if( !print_only )
4003 a->real_fname = xstrdup( fname );
4004 a->filter = file_filter;
4005 a->filter_ov = fcx;
4006 file_filter( fcx, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &len );
4007 file_filter( fcx, IOBUFCTRL_INIT, NULL, NULL, &len );
4008 if( DBG_IOBUF )
4009 log_debug("iobuf-%d.%d: create `%s'\n", a->no, a->subno,
4010 a->desc?a->desc:"?" );
4011
4012 return a;
4013 }
4014
4015 /****************
4016 * append to an iobuf; if the file does not exist, create it.
4017 * cannot be used for stdout.
4018 * Note: This is not used.
4019 */
4020 #if 0 /* not used */
4021 IOBUF
4022 iobuf_append( const char *fname )
4023 {
4024 IOBUF a;
4025 FILE *fp;
4026 file_filter_ctx_t *fcx;
4027 size_t len;
4028
4029 if( !fname )
4030 return NULL;
4031 else if( !(fp = my_fopen(fname, "ab")) )
4032 return NULL;
4033 a = iobuf_alloc(2, IOBUF_BUFFER_SIZE );
4034 fcx = xmalloc( sizeof *fcx + strlen(fname) );
4035 fcx->fp = fp;
4036 strcpy(fcx->fname, fname );
4037 a->real_fname = xstrdup( fname );
4038 a->filter = file_filter;
4039 a->filter_ov = fcx;
4040 file_filter( fcx, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &len );
4041 file_filter( fcx, IOBUFCTRL_INIT, NULL, NULL, &len );
4042 if( DBG_IOBUF )
4043 log_debug("iobuf-%d.%d: append `%s'\n", a->no, a->subno,
4044 a->desc?a->desc:"?" );
4045
4046 return a;
4047 }
4048 #endif
4049
4050 IOBUF
4051 iobuf_openrw( const char *fname )
4052 {
4053 IOBUF a;
4054 FILEP_OR_FD fp;
4055 file_filter_ctx_t *fcx;
4056 size_t len;
4057
4058 if( !fname )
4059 return NULL;
4060 else if( (fp = my_fopen(fname, "r+b")) == INVALID_FP )
4061 return NULL;
4062 a = iobuf_alloc(2, IOBUF_BUFFER_SIZE );
4063 fcx = xmalloc( sizeof *fcx + strlen(fname) );
4064 fcx->fp = fp;
4065 strcpy(fcx->fname, fname );
4066 a->real_fname = xstrdup( fname );
4067 a->filter = file_filter;
4068 a->filter_ov = fcx;
4069 file_filter( fcx, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &len );
4070 file_filter( fcx, IOBUFCTRL_INIT, NULL, NULL, &len );
4071 if( DBG_IOBUF )
4072 log_debug("iobuf-%d.%d: openrw `%s'\n", a->no, a->subno,
4073 a->desc?a->desc:"?");
4074
4075 return a;
4076 }
4077
4078
4079 int
4080 iobuf_ioctl ( IOBUF a, int cmd, int intval, void *ptrval )
4081 {
4082 if ( cmd == 1 ) { /* keep system filepointer/descriptor open */
4083 if( DBG_IOBUF )
4084 log_debug("iobuf-%d.%d: ioctl `%s' keep=%d\n",
4085 a? a->no:-1, a?a->subno:-1,
4086 a&&a->desc?a->desc:"?", intval );
4087 for( ; a; a = a->chain )
4088 if( !a->chain && a->filter == file_filter ) {
4089 file_filter_ctx_t *b = a->filter_ov;
4090 b->keep_open = intval;
4091 return 0;
4092 }
4093 #ifdef _WIN32
4094 else if( !a->chain && a->filter == sock_filter ) {
4095 sock_filter_ctx_t *b = a->filter_ov;
4096 b->keep_open = intval;
4097 return 0;
4098 }
4099 #endif
4100 }
4101 else if ( cmd == 2 ) { /* invalidate cache */
4102 if( DBG_IOBUF )
4103 log_debug("iobuf-*.*: ioctl `%s' invalidate\n",
4104 ptrval? (char*)ptrval:"[all]");
4105 if ( !a && !intval ) {
4106 #ifndef FILE_FILTER_USES_STDIO
4107 return fd_cache_invalidate (ptrval);
4108 #endif
4109 return 0;
4110 }
4111 }
4112 else if ( cmd == 3 ) { /* disallow/allow caching */
4113 if( DBG_IOBUF )
4114 log_debug("iobuf-%d.%d: ioctl `%s' no_cache=%d\n",
4115 a? a->no:-1, a?a->subno:-1,
4116 a&&a->desc?a->desc:"?", intval );
4117 for( ; a; a = a->chain )
4118 if( !a->chain && a->filter == file_filter ) {
4119 file_filter_ctx_t *b = a->filter_ov;
4120 b->no_cache = intval;
4121 return 0;
4122 }
4123 #ifdef _WIN32
4124 else if( !a->chain && a->filter == sock_filter ) {
4125 sock_filter_ctx_t *b = a->filter_ov;
4126 b->no_cache = intval;
4127 return 0;
4128 }
4129 #endif
4130 }
4131 else if(cmd==4)
4132 {
4133 /* Do a fsync on the open fd and return any errors to the
4134 caller of iobuf_ioctl */
4135 if( DBG_IOBUF )
4136 log_debug("iobuf-*.*: ioctl `%s' fsync\n",
4137 ptrval? (char*)ptrval:"<null>");
4138
4139 if(!a && !intval && ptrval)
4140 {
4141 #ifndef FILE_FILTER_USES_STDIO
4142 return fd_cache_synchronize (ptrval);
4143 #else
4144 return 0;
4145 #endif
4146 }
4147 }
4148
4149 return -1;
4150 }
4151
4152
4153 /****************
4154 * Register an i/o filter.
4155 */
4156 int
4157 iobuf_push_filter( IOBUF a,
4158 int (*f)(void *opaque, int control,
4159 IOBUF chain, byte *buf, size_t *len), void *ov )
4160 {
4161 return iobuf_push_filter2( a, f, ov, 0 );
4162 }
4163
4164 int
4165 iobuf_push_filter2( IOBUF a,
4166 int (*f)(void *opaque, int control,
4167 IOBUF chain, byte *buf, size_t *len),
4168 void *ov, int rel_ov )
4169 {
4170 IOBUF b;
4171 size_t dummy_len=0;
4172 int rc=0;
4173
4174 if( a->directfp )
4175 BUG();
4176
4177 if( a->use == 2 && (rc=iobuf_flush(a)) )
4178 return rc;
4179 /* make a copy of the current stream, so that
4180 * A is the new stream and B the original one.
4181 * The contents of the buffers are transferred to the
4182 * new stream.
4183 */
4184 b = xmalloc(sizeof *b);
4185 memcpy(b, a, sizeof *b );
4186 /* fixme: it is stupid to keep a copy of the name at every level
4187 * but we need the name somewhere because the name known by file_filter
4188 * may have been released when we need the name of the file */
4189 b->real_fname = a->real_fname? xstrdup(a->real_fname):NULL;
4190 /* remove the filter stuff from the new stream */
4191 a->filter = NULL;
4192 a->filter_ov = NULL;
4193 a->filter_ov_owner = 0;
4194 a->filter_eof = 0;
4195 if( a->use == 3 )
4196 a->use = 2; /* make a write stream from a temp stream */
4197
4198 if( a->use == 2 ) { /* allocate a fresh buffer for the original stream */
4199 b->d.buf = xmalloc( a->d.size );
4200 b->d.len = 0;
4201 b->d.start = 0;
4202 }
4203 else { /* allocate a fresh buffer for the new stream */
4204 a->d.buf = xmalloc( a->d.size );
4205 a->d.len = 0;
4206 a->d.start = 0;
4207 }
4208 /* disable nlimit for the new stream */
4209 a->ntotal = b->ntotal + b->nbytes;
4210 a->nlimit = a->nbytes = 0;
4211 a->nofast &= ~1;
4212 /* make a link from the new stream to the original stream */
4213 a->chain = b;
4214 a->opaque = b->opaque;
4215
4216 /* setup the function on the new stream */
4217 a->filter = f;
4218 a->filter_ov = ov;
4219 a->filter_ov_owner = rel_ov;
4220
4221 a->subno = b->subno + 1;
4222 f( ov, IOBUFCTRL_DESC, NULL, (byte*)&a->desc, &dummy_len );
4223
4224 if( DBG_IOBUF ) {
4225 log_debug("iobuf-%d.%d: push `%s'\n", a->no, a->subno,
4226 a->desc?a->desc:"?" );
4227 print_chain( a );
4228 }
4229
4230 /* now we can initialize the new function if we have one */
4231 if( a->filter && (rc = a->filter(a->filter_ov, IOBUFCTRL_INIT, a->chain,
4232 NULL, &dummy_len)) )
4233 log_error("IOBUFCTRL_INIT failed: %s\n", g10_errstr(rc) );
4234 return rc;
4235 }
4236
4237 /****************
4238 * Remove an i/o filter.
4239 */
4240 static int
4241 pop_filter( IOBUF a, int (*f)(void *opaque, int control,
4242 IOBUF chain, byte *buf, size_t *len), void *ov )
4243 {
4244 IOBUF b;
4245 size_t dummy_len=0;
4246 int rc=0;
4247
4248 if( a->directfp )
4249 BUG();
4250
4251 if( DBG_IOBUF )
4252 log_debug("iobuf-%d.%d: pop `%s'\n", a->no, a->subno,
4253 a->desc?a->desc:"?" );
4254 if( !a->filter ) { /* this is simple */
4255 b = a->chain;
4256 assert(b);
4257 xfree(a->d.buf);
4258 xfree(a->real_fname);
4259 memcpy(a,b, sizeof *a);
4260 xfree(b);
4261 return 0;
4262 }
4263 for(b=a ; b; b = b->chain )
4264 if( b->filter == f && (!ov || b->filter_ov == ov) )
4265 break;
4266 if( !b )
4267 log_bug("pop_filter(): filter function not found\n");
4268
4269 /* flush this stream if it is an output stream */
4270 if( a->use == 2 && (rc=iobuf_flush(b)) ) {
4271 log_error("iobuf_flush failed in pop_filter: %s\n", g10_errstr(rc));
4272 return rc;
4273 }
4274 /* and tell the filter to free it self */
4275 if( b->filter && (rc = b->filter(b->filter_ov, IOBUFCTRL_FREE, b->chain,
4276 NULL, &dummy_len)) ) {
4277 log_error("IOBUFCTRL_FREE failed: %s\n", g10_errstr(rc) );
4278 return rc;
4279 }
4280 if( b->filter_ov && b->filter_ov_owner ) {
4281 xfree( b->filter_ov );
4282 b->filter_ov = NULL;
4283 }
4284
4285
4286 /* and see how to remove it */
4287 if( a == b && !b->chain )
4288 log_bug("can't remove the last filter from the chain\n");
4289 else if( a == b ) { /* remove the first iobuf from the chain */
4290 /* everything from b is copied to a. This is save because
4291 * a flush has been done on the to be removed entry
4292 */
4293 b = a->chain;
4294 xfree(a->d.buf);
4295 xfree(a->real_fname);
4296 memcpy(a,b, sizeof *a);
4297 xfree(b);
4298 if( DBG_IOBUF )
4299 log_debug("iobuf-%d.%d: popped filter\n", a->no, a->subno );
4300 }
4301 else if( !b->chain ) { /* remove the last iobuf from the chain */
4302 log_bug("Ohh jeee, trying to remove a head filter\n");
4303 }
4304 else { /* remove an intermediate iobuf from the chain */
4305 log_bug("Ohh jeee, trying to remove an intermediate filter\n");
4306 }
4307
4308 return rc;
4309 }
4310
4311
4312 /****************
4313 * read underflow: read more bytes into the buffer and return
4314 * the first byte or -1 on EOF.
4315 */
4316 static int
4317 underflow(IOBUF a)
4318 {
4319 size_t len;
4320 int rc;
4321
4322 assert( a->d.start == a->d.len );
4323 if( a->use == 3 )
4324 return -1; /* EOF because a temp buffer can't do an underflow */
4325
4326 if( a->filter_eof ) {
4327 if( a->chain ) {
4328 IOBUF b = a->chain;
4329 if( DBG_IOBUF )
4330 log_debug("iobuf-%d.%d: pop `%s' in underflow\n",
4331 a->no, a->subno, a->desc?a->desc:"?" );
4332 xfree(a->d.buf);
4333 xfree(a->real_fname);
4334 memcpy(a, b, sizeof *a);
4335 xfree(b);
4336 print_chain(a);
4337 }
4338 else
4339 a->filter_eof = 0; /* for the top level filter */
4340 if( DBG_IOBUF )
4341 log_debug("iobuf-%d.%d: underflow: eof (due to filter eof)\n",
4342 a->no, a->subno );
4343 return -1; /* return one(!) EOF */
4344 }
4345 if( a->error ) {
4346 if( DBG_IOBUF )
4347 log_debug("iobuf-%d.%d: error\n", a->no, a->subno );
4348 return -1;
4349 }
4350
4351 if( a->directfp ) {
4352 FILE *fp = a->directfp;
4353
4354 len = fread( a->d.buf, 1, a->d.size, fp);
4355 if( len < a->d.size ) {
4356 if( ferror(fp) )
4357 a->error = 1;
4358 }
4359 a->d.len = len;
4360 a->d.start = 0;
4361 return len? a->d.buf[a->d.start++] : -1;
4362 }
4363
4364
4365 if( a->filter ) {
4366 len = a->d.size;
4367 if( DBG_IOBUF )
4368 log_debug("iobuf-%d.%d: underflow: req=%lu\n",
4369 a->no, a->subno, (ulong)len );
4370 rc = a->filter( a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
4371 a->d.buf, &len );
4372 if( DBG_IOBUF ) {
4373 log_debug("iobuf-%d.%d: underflow: got=%lu rc=%d\n",
4374 a->no, a->subno, (ulong)len, rc );
4375 /* if( a->no == 1 ) */
4376 /* log_hexdump (" data:", a->d.buf, len); */
4377 }
4378 if( a->use == 1 && rc == -1 ) { /* EOF: we can remove the filter */
4379 size_t dummy_len=0;
4380
4381 /* and tell the filter to free itself */
4382 if( (rc = a->filter(a->filter_ov, IOBUFCTRL_FREE, a->chain,
4383 NULL, &dummy_len)) )
4384 log_error("IOBUFCTRL_FREE failed: %s\n", g10_errstr(rc) );
4385 if( a->filter_ov && a->filter_ov_owner ) {
4386 xfree( a->filter_ov );
4387 a->filter_ov = NULL;
4388 }
4389 a->filter = NULL;
4390 a->desc = NULL;
4391 a->filter_ov = NULL;
4392 a->filter_eof = 1;
4393 if( !len && a->chain ) {
4394 IOBUF b = a->chain;
4395 if( DBG_IOBUF )
4396 log_debug("iobuf-%d.%d: pop in underflow (!len)\n",
4397 a->no, a->subno);
4398 xfree(a->d.buf);
4399 xfree(a->real_fname);
4400 memcpy(a,b, sizeof *a);
4401 xfree(b);
4402 print_chain(a);
4403 }
4404 }
4405 else if( rc )
4406 a->error = 1;
4407
4408 if( !len ) {
4409 if( DBG_IOBUF )
4410 log_debug("iobuf-%d.%d: underflow: eof\n", a->no, a->subno );
4411 return -1;
4412 }
4413 a->d.len = len;
4414 a->d.start = 0;
4415 return a->d.buf[a->d.start++];
4416 }
4417 else {
4418 if( DBG_IOBUF )
4419 log_debug("iobuf-%d.%d: underflow: eof (no filter)\n",
4420 a->no, a->subno );
4421 return -1; /* no filter; return EOF */
4422 }
4423 }
4424
4425
4426 int
4427 iobuf_flush(IOBUF a)
4428 {
4429 size_t len;
4430 int rc;
4431
4432 if( a->directfp )
4433 return 0;
4434
4435 if( a->use == 3 ) { /* increase the temp buffer */
4436 char *newbuf;
4437 size_t newsize = a->d.size + IOBUF_BUFFER_SIZE;
4438
4439 if( DBG_IOBUF )
4440 log_debug("increasing temp iobuf from %lu to %lu\n",
4441 (ulong)a->d.size, (ulong)newsize );
4442 newbuf = xmalloc( newsize );
4443 memcpy( newbuf, a->d.buf, a->d.len );
4444 xfree(a->d.buf);
4445 a->d.buf = newbuf;
4446 a->d.size = newsize;
4447 return 0;
4448 }
4449 else if( a->use != 2 )
4450 log_bug("flush on non-output iobuf\n");
4451 else if( !a->filter )
4452 log_bug("iobuf_flush: no filter\n");
4453 len = a->d.len;
4454 rc = a->filter( a->filter_ov, IOBUFCTRL_FLUSH, a->chain, a->d.buf, &len );
4455 if( !rc && len != a->d.len ) {
4456 log_info("iobuf_flush did not write all!\n");
4457 rc = G10ERR_WRITE_FILE;
4458 }
4459 else if( rc )
4460 a->error = 1;
4461 a->d.len = 0;
4462
4463 return rc;
4464 }
4465
4466
4467 /****************
4468 * Read a byte from the iobuf; returns -1 on EOF
4469 */
4470 int
4471 iobuf_readbyte(IOBUF a)
4472 {
4473 int c;
4474
4475 /* nlimit does not work together with unget */
4476 /* nbytes is also not valid! */
4477 if( a->unget.buf ) {
4478 if( a->unget.start < a->unget.len )
4479 return a->unget.buf[a->unget.start++];
4480 xfree(a->unget.buf);
4481 a->unget.buf = NULL;
4482 a->nofast &= ~2;
4483 }
4484
4485 if( a->nlimit && a->nbytes >= a->nlimit )
4486 return -1; /* forced EOF */
4487
4488 if( a->d.start < a->d.len ) {
4489 c = a->d.buf[a->d.start++];
4490 }
4491 else if( (c=underflow(a)) == -1 )
4492 return -1; /* EOF */
4493
4494 a->nbytes++;
4495 return c;
4496 }
4497
4498
4499 int
4500 iobuf_read(IOBUF a, byte *buf, unsigned buflen )
4501 {
4502 int c, n;
4503
4504 if( a->unget.buf || a->nlimit ) {
4505 /* handle special cases */
4506 for(n=0 ; n < buflen; n++ ) {
4507 if( (c = iobuf_readbyte(a)) == -1 ) {
4508 if( !n )
4509 return -1; /* eof */
4510 break;
4511 }
4512 else
4513 if( buf ) *buf = c;
4514 if( buf ) buf++;
4515 }
4516 return n;
4517 }
4518
4519 n = 0;
4520 do {
4521 if( n < buflen && a->d.start < a->d.len ) {
4522 unsigned size = a->d.len - a->d.start;
4523 if( size > buflen - n )
4524 size = buflen - n;
4525 if( buf )
4526 memcpy( buf, a->d.buf + a->d.start, size );
4527 n += size;
4528 a->d.start += size;
4529 if( buf )
4530 buf += size;
4531 }
4532 if( n < buflen ) {
4533 if( (c=underflow(a)) == -1 ) {
4534 a->nbytes += n;
4535 return n? n : -1/*EOF*/;
4536 }
4537 if( buf )
4538 *buf++ = c;
4539 n++;
4540 }
4541 } while( n < buflen );
4542 a->nbytes += n;
4543 return n;
4544 }
4545
4546
4547 /****************
4548 * Have a look at the iobuf.
4549 * NOTE: This only works in special cases.
4550 */
4551 int
4552 iobuf_peek(IOBUF a, byte *buf, unsigned buflen )
4553 {
4554 int n=0;
4555
4556 if( a->filter_eof )
4557 return -1;
4558
4559 if( !(a->d.start < a->d.len) ) {
4560 if( underflow(a) == -1 )
4561 return -1;
4562 /* and unget this character */
4563 assert(a->d.start == 1);
4564 a->d.start = 0;
4565 }
4566
4567 for(n=0 ; n < buflen && (a->d.start+n) < a->d.len ; n++, buf++ )
4568 *buf = a->d.buf[n];
4569 return n;
4570 }
4571
4572
4573
4574
4575 int
4576 iobuf_writebyte(IOBUF a, unsigned c)
4577 {
4578
4579 if( a->directfp )
4580 BUG();
4581
4582 if( a->d.len == a->d.size )
4583 if( iobuf_flush(a) )
4584 return -1;
4585
4586 assert( a->d.len < a->d.size );
4587 a->d.buf[a->d.len++] = c;
4588 return 0;
4589 }
4590
4591
4592 int
4593 iobuf_write(IOBUF a, byte *buf, unsigned buflen )
4594 {
4595
4596 if( a->directfp )
4597 BUG();
4598
4599 do {
4600 if( buflen && a->d.len < a->d.size ) {
4601 unsigned size = a->d.size - a->d.len;
4602 if( size > buflen ) size = buflen;
4603 memcpy( a->d.buf + a->d.len, buf, size );
4604 buflen -= size;
4605 buf += size;
4606 a->d.len += size;
4607 }
4608 if( buflen ) {
4609 if( iobuf_flush(a) )
4610 return -1;
4611 }
4612 } while( buflen );
4613 return 0;
4614 }
4615
4616
4617 int
4618 iobuf_writestr(IOBUF a, const char *buf )
4619 {
4620 for( ; *buf; buf++ )
4621 if( iobuf_writebyte(a, *buf) )
4622 return -1;
4623 return 0;
4624 }
4625
4626
4627
4628 /****************
4629 * copy the contents of TEMP to A.
4630 */
4631 int
4632 iobuf_write_temp( IOBUF a, IOBUF temp )
4633 {
4634 while( temp->chain )
4635 pop_filter( temp, temp->filter, NULL );
4636 return iobuf_write(a, temp->d.buf, temp->d.len );
4637 }
4638
4639 /****************
4640 * copy the contents of the temp io stream to BUFFER.
4641 */
4642 size_t
4643 iobuf_temp_to_buffer( IOBUF a, byte *buffer, size_t buflen )
4644 {
4645 size_t n = a->d.len;
4646
4647 if( n > buflen )
4648 n = buflen;
4649 memcpy( buffer, a->d.buf, n );
4650 return n;
4651 }
4652
4653
4654 /****************
4655 * Call this function to terminate processing of the temp stream
4656 * without closing it. This removes all filters from the stream
4657 * makes sure that iobuf_get_temp_{buffer,length}() returns correct
4658 * values.
4659 */
4660 void
4661 iobuf_flush_temp( IOBUF temp )
4662 {
4663 while( temp->chain )
4664 pop_filter( temp, temp->filter, NULL );
4665 }
4666
4667
4668 /****************
4669 * Set a limit on how many bytes may be read from the input stream A.
4670 * Setting the limit to 0 disables this feature.
4671 */
4672 void
4673 iobuf_set_limit( IOBUF a, off_t nlimit )
4674 {
4675 if( nlimit )
4676 a->nofast |= 1;
4677 else
4678 a->nofast &= ~1;
4679 a->nlimit = nlimit;
4680 a->ntotal += a->nbytes;
4681 a->nbytes = 0;
4682 }
4683
4684
4685
4686 /* Return the length of an open file A. IF OVERFLOW is not NULL it
4687 will be set to true if the file is larger than what off_t can cope
4688 with. The function return 0 on error or on overflow condition. */
4689 off_t
4690 iobuf_get_filelength (IOBUF a, int *overflow )
4691 {
4692 struct stat st;
4693
4694 if (overflow)
4695 *overflow = 0;
4696
4697 if( a->directfp ) {
4698 FILE *fp = a->directfp;
4699
4700 if( !fstat(fileno(fp), &st) )
4701 return st.st_size;
4702 log_error("fstat() failed: %s\n", strerror(errno) );
4703 return 0;
4704 }
4705
4706 /* Hmmm: file_filter may have already been removed */
4707 for( ; a; a = a->chain )
4708 if( !a->chain && a->filter == file_filter ) {
4709 file_filter_ctx_t *b = a->filter_ov;
4710 FILEP_OR_FD fp = b->fp;
4711
4712 #if defined(HAVE_DOSISH_SYSTEM) && !defined(FILE_FILTER_USES_STDIO)
4713 ulong size;
4714 static int (* __stdcall get_file_size_ex)
4715 (void *handle, LARGE_INTEGER *size);
4716 static int get_file_size_ex_initialized;
4717
4718 if (!get_file_size_ex_initialized)
4719 {
4720 void *handle;
4721
4722 handle = dlopen ("kernel32.dll", RTLD_LAZY);
4723 if (handle)
4724 {
4725 get_file_size_ex = dlsym (handle, "GetFileSizeEx");
4726 if (!get_file_size_ex)
4727 dlclose (handle);
4728 }
4729 get_file_size_ex_initialized = 1;
4730 }
4731
4732 if (get_file_size_ex)
4733 {
4734 /* This is a newer system with GetFileSizeEx; we use
4735 this then becuase it seem that GetFileSize won't
4736 return a proper error in case a file is larger than
4737 4GB. */
4738 LARGE_INTEGER size;
4739
4740 if (get_file_size_ex (fp, &size))
4741 {
4742 if (!size.u.HighPart)
4743 return size.u.LowPart;
4744 if (overflow)
4745 *overflow = 1;
4746 return 0;
4747 }
4748 }
4749 else
4750 {
4751 if ((size=GetFileSize (fp, NULL)) != 0xffffffff)
4752 return size;
4753 }
4754 log_error ("GetFileSize for handle %p failed: %s\n",
4755 fp, w32_strerror (0));
4756 #else
4757 if( !fstat(my_fileno(fp), &st) )
4758 return st.st_size;
4759 log_error("fstat() failed: %s\n", strerror(errno) );
4760 #endif
4761 break;
4762 }
4763
4764 return 0;
4765 }
4766
4767
4768 /* Return the file descriptor of the underlying file or -1 if it is
4769 not available. */
4770 int
4771 iobuf_get_fd (IOBUF a)
4772 {
4773 if (a->directfp)
4774 return fileno ( (FILE*)a->directfp );
4775
4776 for ( ; a; a = a->chain )
4777 if (!a->chain && a->filter == file_filter)
4778 {
4779 file_filter_ctx_t *b = a->filter_ov;
4780 FILEP_OR_FD fp = b->fp;
4781
4782 return my_fileno (fp);
4783 }
4784
4785 return -1;
4786 }
4787
4788
4789 /****************
4790 * Tell the file position, where the next read will take place
4791 */
4792 off_t
4793 iobuf_tell( IOBUF a )
4794 {
4795 return a->ntotal + a->nbytes;
4796 }
4797
4798
4799 #if !defined(HAVE_FSEEKO) && !defined(fseeko)
4800
4801 #ifdef HAVE_LIMITS_H
4802 # include <limits.h>
4803 #endif
4804 #ifndef LONG_MAX
4805 # define LONG_MAX ((long) ((unsigned long) -1 >> 1))
4806 #endif
4807 #ifndef LONG_MIN
4808 # define LONG_MIN (-1 - LONG_MAX)
4809 #endif
4810
4811 /****************
4812 * A substitute for fseeko, for hosts that don't have it.
4813 */
4814 static int
4815 fseeko( FILE *stream, off_t newpos, int whence )
4816 {
4817 while( newpos != (long) newpos ) {
4818 long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
4819 if( fseek( stream, pos, whence ) != 0 )
4820 return -1;
4821 newpos -= pos;
4822 whence = SEEK_CUR;
4823 }
4824 return fseek( stream, (long)newpos, whence );
4825 }
4826 #endif
4827
4828 /****************
4829 * This is a very limited implementation. It simply discards all internal
4830 * buffering and removes all filters but the first one.
4831 */
4832 int
4833 iobuf_seek( IOBUF a, off_t newpos )
4834 {
4835 file_filter_ctx_t *b = NULL;
4836
4837 if( a->directfp ) {
4838 FILE *fp = a->directfp;
4839 if( fseeko( fp, newpos, SEEK_SET ) ) {
4840 log_error("can't seek: %s\n", strerror(errno) );
4841 return -1;
4842 }
4843 clearerr(fp);
4844 }
4845 else {
4846 for( ; a; a = a->chain ) {
4847 if( !a->chain && a->filter == file_filter ) {
4848 b = a->filter_ov;
4849 break;
4850 }
4851 }
4852 if( !a )
4853 return -1;
4854 #ifdef FILE_FILTER_USES_STDIO
4855 if( fseeko( b->fp, newpos, SEEK_SET ) ) {
4856 log_error("can't fseek: %s\n", strerror(errno) );
4857 return -1;
4858 }
4859 #else
4860 #ifdef HAVE_DOSISH_SYSTEM
4861 if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff ) {
4862 log_error ("SetFilePointer failed on handle %p: %s\n",
4863 b->fp, w32_strerror (0));
4864 return -1;
4865 }
4866 #else
4867 if ( lseek (b->fp, newpos, SEEK_SET) == (off_t)-1 ) {
4868 log_error("can't lseek: %s\n", strerror(errno) );
4869 return -1;
4870 }
4871 #endif
4872 #endif
4873 }
4874 a->d.len = 0; /* discard buffer */
4875 a->d.start = 0;
4876 a->nbytes = 0;
4877 a->nlimit = 0;
4878 a->nofast &= ~1;
4879 a->ntotal = newpos;
4880 a->error = 0;
4881 /* remove filters, but the last */
4882 if( a->chain )
4883 log_debug("pop_filter called in iobuf_seek - please report\n");
4884 while( a->chain )
4885 pop_filter( a, a->filter, NULL );
4886
4887 return 0;
4888 }
4889
4890
4891
4892
4893
4894
4895 /****************
4896 * Retrieve the real filename
4897 */
4898 const char *
4899 iobuf_get_real_fname( IOBUF a )
4900 {
4901 if( a->real_fname )
4902 return a->real_fname;
4903
4904 /* the old solution */
4905 for( ; a; a = a->chain )
4906 if( !a->chain && a->filter == file_filter ) {
4907 file_filter_ctx_t *b = a->filter_ov;
4908 return b->print_only_name? NULL : b->fname;
4909 }
4910
4911 return NULL;
4912 }
4913
4914
4915 /****************
4916 * Retrieve the filename
4917 */
4918 const char *
4919 iobuf_get_fname( IOBUF a )
4920 {
4921 for( ; a; a = a->chain )
4922 if( !a->chain && a->filter == file_filter ) {
4923 file_filter_ctx_t *b = a->filter_ov;
4924 return b->fname;
4925 }
4926
4927 return NULL;
4928 }
4929
4930
4931 /****************
4932 * enable partial block mode as described in the OpenPGP draft.
4933 * LEN is the first length byte on read, but ignored on writes.
4934 */
4935 void
4936 iobuf_set_partial_block_mode( IOBUF a, size_t len )
4937 {
4938 block_filter_ctx_t *ctx = xmalloc_clear( sizeof *ctx );
4939
4940 assert( a->use == 1 || a->use == 2 );
4941 ctx->use = a->use;
4942 if( !len ) {
4943 if( a->use == 1 )
4944 log_debug("pop_filter called in set_partial_block_mode"
4945 " - please report\n");
4946 pop_filter(a, block_filter, NULL );
4947 }
4948 else {
4949 ctx->partial = 1;
4950 ctx->size = 0;
4951 ctx->first_c = len;
4952 iobuf_push_filter(a, block_filter, ctx );
4953 }
4954 }
4955
4956
4957 /****************
4958 * Same as fgets() but if the buffer is too short a larger one will
4959 * be allocated up to some limit *max_length.
4960 * A line is considered a byte stream ending in a LF.
4961 * Returns the length of the line. EOF is indicated by a line of
4962 * length zero. The last LF may be missing due to an EOF.
4963 * is max_length is zero on return, the line has been truncated.
4964 *
4965 * Note: The buffer is allocated with enough space to append a CR,LF,EOL
4966 */
4967 unsigned
4968 iobuf_read_line( IOBUF a, byte **addr_of_buffer,
4969 unsigned *length_of_buffer, unsigned *max_length )
4970 {
4971 int c;
4972 char *buffer = *addr_of_buffer;
4973 unsigned length = *length_of_buffer;
4974 unsigned nbytes = 0;
4975 unsigned maxlen = *max_length;
4976 char *p;
4977
4978 if( !buffer ) { /* must allocate a new buffer */
4979 length = 256;
4980 buffer = xmalloc( length );
4981 *addr_of_buffer = buffer;
4982 *length_of_buffer = length;
4983 }
4984
4985 length -= 3; /* reserve 3 bytes (cr,lf,eol) */
4986 p = buffer;
4987 while( (c=iobuf_get(a)) != -1 ) {
4988 if( nbytes == length ) { /* increase the buffer */
4989 if( length > maxlen ) { /* this is out limit */
4990 /* skip the rest of the line */
4991 while( c != '\n' && (c=iobuf_get(a)) != -1 )
4992 ;
4993 *p++ = '\n'; /* always append a LF (we have reserved space) */
4994 nbytes++;
4995 *max_length = 0; /* indicate truncation */
4996 break;
4997 }
4998 length += 3; /* correct for the reserved byte */
4999 length += length < 1024? 256 : 1024;
5000 buffer = xrealloc( buffer, length );
5001 *addr_of_buffer = buffer;
5002 *length_of_buffer = length;
5003 length -= 3; /* and reserve again */
5004 p = buffer + nbytes;
5005 }
5006 *p++ = c;
5007 nbytes++;
5008 if( c == '\n' )
5009 break;
5010 }
5011 *p = 0; /* make sure the line is a string */
5012
5013 return nbytes;
5014 }
5015
5016 /* This is the non iobuf specific function */
5017 int
5018 iobuf_translate_file_handle ( int fd, int for_write )
5019 {
5020 #ifdef _WIN32
5021 {
5022 int x;
5023
5024 if ( fd <= 2 )
5025 return fd; /* do not do this for error, stdin, stdout, stderr */
5026
5027 x = _open_osfhandle ( fd, for_write? 1:0 );
5028 if (x==-1 )
5029 log_error ("failed to translate osfhandle %p\n", (void*)fd );
5030 else {
5031 /*log_info ("_open_osfhandle %p yields %d%s\n",
5032 (void*)fd, x, for_write? " for writing":"" );*/
5033 fd = x;
5034 }
5035 }
5036 #endif
5037 return fd;
5038 }
5039
5040 static int
5041 translate_file_handle ( int fd, int for_write )
5042 {
5043 #ifdef _WIN32
5044 #ifdef FILE_FILTER_USES_STDIO
5045 fd = iobuf_translate_file_handle (fd, for_write);
5046 #else
5047 {
5048 int x;
5049
5050 if ( fd == 0 )
5051 x = (int)GetStdHandle (STD_INPUT_HANDLE);
5052 else if (fd == 1)
5053 x = (int)GetStdHandle (STD_OUTPUT_HANDLE);
5054 else if (fd == 2)
5055 x = (int)GetStdHandle (STD_ERROR_HANDLE);
5056 else
5057 x = fd;
5058
5059 if (x == -1)
5060 log_debug ("GetStdHandle(%d) failed: %s\n",
5061 fd, w32_strerror (0));
5062
5063 fd = x;
5064 }
5065 #endif
5066 #endif
5067 return fd;
5068 }
5069
5070
5071 void
5072 iobuf_skip_rest(IOBUF a, unsigned long n, int partial)
5073 {
5074 if ( partial ) {
5075 for (;;) {
5076 if (a->nofast || a->d.start >= a->d.len) {
5077 if (iobuf_readbyte (a) == -1) {
5078 break;
5079 }
5080 } else {
5081 unsigned long count = a->d.len - a->d.start;
5082 a->nbytes += count;
5083 a->d.start = a->d.len;
5084 }
5085 }
5086 } else {
5087 unsigned long remaining = n;
5088 while (remaining > 0) {
5089 if (a->nofast || a->d.start >= a->d.len) {
5090 if (iobuf_readbyte (a) == -1) {
5091 break;
5092 }
5093 --remaining;
5094 } else {
5095 unsigned long count = a->d.len - a->d.start;
5096 if (count > remaining) {
5097 count = remaining;
5098 }
5099 a->nbytes += count;
5100 a->d.start += count;
5101 remaining -= count;
5102 }
5103 }
5104 }
5105 }
-
+ A4CA272E00EBA069786CB1EDFB3F7054C5B31630A22AE66C012878D4BCEE96B11298141730589F0A0DDB04EEFF1C2F4EEF5A25D88447226F32EAA5346595EA96
mpi/logger.c
(0 . 0)(1 . 262)
5110 /* logger.c - log functions
5111 * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
5112 *
5113 * This file is part of GnuPG.
5114 *
5115 * GnuPG is free software; you can redistribute it and/or modify
5116 * it under the terms of the GNU General Public License as published by
5117 * the Free Software Foundation; either version 3 of the License, or
5118 * (at your option) any later version.
5119 *
5120 * GnuPG is distributed in the hope that it will be useful,
5121 * but WITHOUT ANY WARRANTY; without even the implied warranty of
5122 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5123 * GNU General Public License for more details.
5124 *
5125 * You should have received a copy of the GNU General Public License
5126 * along with this program; if not, see <http://www.gnu.org/licenses/>.
5127 */
5128
5129 #include <config.h>
5130 #include <stdio.h>
5131 #include <stdlib.h>
5132 #include <stdarg.h>
5133 #include <string.h>
5134 #include <errno.h>
5135
5136 #include "util.h"
5137
5138 static char pidstring[15];
5139 static char *pgm_name;
5140 static int errorcount;
5141 static int strict;
5142 static FILE *logfp;
5143
5144 /****************
5145 * Set the logfile to use (not yet implemneted) or, if logfile is NULL,
5146 * the Fd where logoutputs should go.
5147 */
5148 void
5149 log_set_logfile( const char *name, int fd )
5150 {
5151 if( name )
5152 BUG();
5153
5154 if( logfp && logfp != stderr && logfp != stdout )
5155 fclose( logfp );
5156 if( fd == 1 )
5157 logfp = stdout;
5158 else if( fd == 2 )
5159 logfp = stderr;
5160 else
5161 logfp = fdopen( fd, "a" );
5162 if( !logfp ) {
5163 logfp = stderr;
5164 log_fatal("can't open fd %d for logging: %s\n", fd, strerror(errno));
5165 }
5166 }
5167
5168 FILE *
5169 log_stream()
5170 {
5171 if( !logfp )
5172 logfp = stderr;
5173 return logfp;
5174 }
5175
5176
5177 void
5178 log_set_name( const char *name )
5179 {
5180 xfree(pgm_name);
5181 if( name )
5182 pgm_name = xstrdup(name);
5183 else
5184 pgm_name = NULL;
5185 }
5186
5187 const char *
5188 log_get_name(void)
5189 {
5190 return pgm_name? pgm_name : "";
5191 }
5192
5193
5194 void
5195 log_set_pid( int pid )
5196 {
5197 if( pid )
5198 sprintf(pidstring,"[%u]", (unsigned)pid );
5199 else
5200 *pidstring = 0;
5201 }
5202
5203 int
5204 log_get_errorcount( int clear)
5205 {
5206 int n = errorcount;
5207 if( clear )
5208 errorcount = 0;
5209 return n;
5210 }
5211
5212 void
5213 log_inc_errorcount()
5214 {
5215 errorcount++;
5216 }
5217
5218 int
5219 log_set_strict(int val)
5220 {
5221 int old=strict;
5222 strict=val;
5223 return old;
5224 }
5225
5226 void
5227 g10_log_print_prefix(const char *text)
5228 {
5229 if( !logfp )
5230 logfp = stderr;
5231 if( pgm_name )
5232 fprintf(logfp, "%s%s: %s", pgm_name, pidstring, text );
5233 else
5234 fprintf(logfp, "?%s: %s", pidstring, text );
5235 #ifdef __riscos__
5236 fflush( logfp );
5237 #endif /* __riscos__ */
5238 }
5239
5240
5241 void
5242 g10_log_info( const char *fmt, ... )
5243 {
5244 va_list arg_ptr ;
5245
5246 g10_log_print_prefix("");
5247 va_start( arg_ptr, fmt ) ;
5248 vfprintf(logfp,fmt,arg_ptr) ;
5249 va_end(arg_ptr);
5250 #ifdef __riscos__
5251 fflush( logfp );
5252 #endif /* __riscos__ */
5253 }
5254
5255
5256 void
5257 g10_log_warning( const char *fmt, ... )
5258 {
5259 va_list arg_ptr ;
5260
5261 if(strict)
5262 {
5263 errorcount++;
5264 g10_log_print_prefix(_("ERROR: "));
5265 }
5266 else
5267 g10_log_print_prefix(_("WARNING: "));
5268
5269 va_start( arg_ptr, fmt ) ;
5270 vfprintf(logfp,fmt,arg_ptr) ;
5271 va_end(arg_ptr);
5272 #ifdef __riscos__
5273 fflush( logfp );
5274 #endif /* __riscos__ */
5275 }
5276
5277
5278 void
5279 g10_log_error( const char *fmt, ... )
5280 {
5281 va_list arg_ptr ;
5282
5283 g10_log_print_prefix("");
5284 va_start( arg_ptr, fmt ) ;
5285 vfprintf(logfp,fmt,arg_ptr) ;
5286 va_end(arg_ptr);
5287 errorcount++;
5288 #ifdef __riscos__
5289 fflush( logfp );
5290 #endif /* __riscos__ */
5291 }
5292
5293
5294 void
5295 g10_log_fatal( const char *fmt, ... )
5296 {
5297 va_list arg_ptr ;
5298
5299 g10_log_print_prefix("fatal: ");
5300 va_start( arg_ptr, fmt ) ;
5301 vfprintf(logfp,fmt,arg_ptr) ;
5302 va_end(arg_ptr);
5303 secmem_dump_stats();
5304 #ifdef __riscos__
5305 fflush( logfp );
5306 #endif /* __riscos__ */
5307 exit(2);
5308 }
5309
5310 void
5311 g10_log_bug( const char *fmt, ... )
5312 {
5313 va_list arg_ptr ;
5314
5315 putc('\n', stderr );
5316 g10_log_print_prefix("Ohhhh jeeee: ");
5317 va_start( arg_ptr, fmt ) ;
5318 vfprintf(stderr,fmt,arg_ptr) ;
5319 va_end(arg_ptr);
5320 fflush(stderr);
5321 secmem_dump_stats();
5322 abort();
5323 }
5324
5325 #if defined (__riscos__) \
5326 || ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ))
5327 void
5328 g10_log_bug0( const char *file, int line, const char *func )
5329 {
5330 log_bug(_("... this is a bug (%s:%d:%s)\n"), file, line, func );
5331 }
5332 #else
5333 void
5334 g10_log_bug0( const char *file, int line )
5335 {
5336 log_bug(_("you found a bug ... (%s:%d)\n"), file, line);
5337 }
5338 #endif
5339
5340 void
5341 g10_log_debug( const char *fmt, ... )
5342 {
5343 va_list arg_ptr ;
5344
5345 g10_log_print_prefix("DBG: ");
5346 va_start( arg_ptr, fmt ) ;
5347 vfprintf(logfp,fmt,arg_ptr) ;
5348 va_end(arg_ptr);
5349 #ifdef __riscos__
5350 fflush( logfp );
5351 #endif /* __riscos__ */
5352 }
5353
5354
5355
5356 void
5357 g10_log_hexdump( const char *text, const char *buf, size_t len )
5358 {
5359 int i;
5360
5361 g10_log_print_prefix(text);
5362 for(i=0; i < len; i++ )
5363 fprintf(logfp, " %02X", ((const byte*)buf)[i] );
5364 fputc('\n', logfp);
5365 #ifdef __riscos__
5366 fflush( logfp );
5367 #endif /* __riscos__ */
5368 }
5369
5370
5371
-
+ 9DEA2170DE57AC92123D3DAC0FD5930BC5C1A5AC88CA1C2FDA88C8555091A38E5862FD7AC5BCED9393349F66AB970707B27D759FE0041F358A0D205E066ECDE0
mpi/memory.c
(0 . 0)(1 . 681)
5376 /* memory.c - memory allocation
5377 * Copyright (C) 1998, 1999, 2001, 2005 Free Software Foundation, Inc.
5378 *
5379 * This file is part of GnuPG.
5380 *
5381 * GnuPG is free software; you can redistribute it and/or modify
5382 * it under the terms of the GNU General Public License as published by
5383 * the Free Software Foundation; either version 3 of the License, or
5384 * (at your option) any later version.
5385 *
5386 * GnuPG is distributed in the hope that it will be useful,
5387 * but WITHOUT ANY WARRANTY; without even the implied warranty of
5388 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5389 * GNU General Public License for more details.
5390 *
5391 * You should have received a copy of the GNU General Public License
5392 * along with this program; if not, see <http://www.gnu.org/licenses/>.
5393 *
5394 *
5395 * We use our own memory allocation functions instead of plain malloc(),
5396 * so that we can provide some special enhancements:
5397 * a) functions to provide memory from a secure memory.
5398 * b) by looking at the requested allocation size we
5399 * can reuse memory very quickly (e.g. MPI storage)
5400 * (really needed?)
5401 * c) memory usage reporting if compiled with M_DEBUG
5402 * d) memory checking if compiled with M_GUARD
5403 */
5404
5405 #include <config.h>
5406 #include <stdio.h>
5407 #include <stdlib.h>
5408 #include <string.h>
5409 #include <stdarg.h>
5410
5411 #include "types.h"
5412 #include "memory.h"
5413 #include "util.h"
5414
5415
5416 #define MAGIC_NOR_BYTE 0x55
5417 #define MAGIC_SEC_BYTE 0xcc
5418 #define MAGIC_END_BYTE 0xaa
5419
5420 /* This is a very crude alignment check which does not work on all CPUs
5421 * IIRC, I once introduced it for testing on an Alpha. We should better
5422 * replace this guard stuff with one provided by a modern malloc library
5423 */
5424 #if SIZEOF_UNSIGNED_LONG == 8
5425 #define EXTRA_ALIGN 4
5426 #else
5427 #define EXTRA_ALIGN 0
5428 #endif
5429
5430 #if defined(M_DEBUG) || defined(M_GUARD)
5431 static void membug( const char *fmt, ... );
5432 #endif
5433
5434 #ifdef M_DEBUG
5435
5436 #ifndef M_GUARD
5437 #define M_GUARD 1
5438 #endif
5439 #undef xmalloc
5440 #undef xtrymalloc
5441 #undef xmalloc_clear
5442 #undef xmalloc_secure
5443 #undef xmalloc_secure_clear
5444 #undef xrealloc
5445 #undef xfree
5446 #undef m_check
5447 #undef xstrdup
5448 #undef xtrystrdup
5449 #define FNAME(a) m_debug_ ##a
5450 #define FNAMEX(a) m_debug_ ##a
5451 #define FNAMEXM(a) m_debug_ ##a
5452 #define FNAMEPRT , const char *info
5453 #define FNAMEARG , info
5454 #ifndef __riscos__
5455 #define store_len(p,n,m) do { add_entry(p,n,m, \
5456 info, __FUNCTION__); } while(0)
5457 #else
5458 #define store_len(p,n,m) do { add_entry(p,n,m, \
5459 info, __func__ ); } while(0)
5460 #endif
5461 #else
5462 #define FNAME(a) m_ ##a
5463 #define FNAMEX(a) x ##a
5464 #define FNAMEXM(a) xm ##a
5465 #define FNAMEPRT
5466 #define FNAMEARG
5467 #define store_len(p,n,m) do { ((byte*)p)[EXTRA_ALIGN+0] = n; \
5468 ((byte*)p)[EXTRA_ALIGN+1] = n >> 8 ; \
5469 ((byte*)p)[EXTRA_ALIGN+2] = n >> 16 ; \
5470 ((byte*)p)[EXTRA_ALIGN+3] = m? MAGIC_SEC_BYTE \
5471 : MAGIC_NOR_BYTE; \
5472 } while(0)
5473 #endif
5474
5475
5476 #ifdef M_GUARD
5477 static long used_memory;
5478 #endif
5479
5480 #ifdef M_DEBUG /* stuff used for memory debuging */
5481
5482 struct info_entry {
5483 struct info_entry *next;
5484 unsigned count; /* call count */
5485 const char *info; /* the reference to the info string */
5486 };
5487
5488 struct memtbl_entry {
5489 const void *user_p; /* for reference: the pointer given to the user */
5490 size_t user_n; /* length requested by the user */
5491 struct memtbl_entry *next; /* to build a list of unused entries */
5492 const struct info_entry *info; /* points into the table with */
5493 /* the info strings */
5494 unsigned inuse:1; /* this entry is in use */
5495 unsigned count:31;
5496 };
5497
5498
5499 #define INFO_BUCKETS 53
5500 #define info_hash(p) ( *(u32*)((p)) % INFO_BUCKETS )
5501 static struct info_entry *info_strings[INFO_BUCKETS]; /* hash table */
5502
5503 static struct memtbl_entry *memtbl; /* the table with the memory info */
5504 static unsigned memtbl_size; /* number of allocated entries */
5505 static unsigned memtbl_len; /* number of used entries */
5506 static struct memtbl_entry *memtbl_unused;/* to keep track of unused entries */
5507
5508 static void dump_table_at_exit(void);
5509 static void dump_table(void);
5510 static void check_allmem( const char *info );
5511
5512 /****************
5513 * Put the new P into the debug table and return a pointer to the table entry.
5514 * mode is true for security. BY is the name of the function which called us.
5515 */
5516 static void
5517 add_entry( byte *p, unsigned n, int mode, const char *info, const char *by )
5518 {
5519 unsigned index;
5520 struct memtbl_entry *e;
5521 struct info_entry *ie;
5522
5523 if( memtbl_len < memtbl_size )
5524 index = memtbl_len++;
5525 else {
5526 struct memtbl_entry *e;
5527 /* look for a used entry in the table. We take the first one,
5528 * so that freed entries remain as long as possible in the table
5529 * (free appends a new one)
5530 */
5531 if( (e = memtbl_unused) ) {
5532 index = e - memtbl;
5533 memtbl_unused = e->next;
5534 e->next = NULL;
5535 }
5536 else { /* no free entries in the table: extend the table */
5537 if( !memtbl_size ) { /* first time */
5538 memtbl_size = 100;
5539 if( !(memtbl = calloc( memtbl_size, sizeof *memtbl )) )
5540 membug("memory debug table malloc failed\n");
5541 index = 0;
5542 memtbl_len = 1;
5543 atexit( dump_table_at_exit );
5544 }
5545 else { /* realloc */
5546 unsigned n = memtbl_size / 4; /* enlarge by 25% */
5547 if(!(memtbl = realloc(memtbl, (memtbl_size+n)*sizeof *memtbl)))
5548 membug("memory debug table realloc failed\n");
5549 memset(memtbl+memtbl_size, 0, n*sizeof *memtbl );
5550 memtbl_size += n;
5551 index = memtbl_len++;
5552 }
5553 }
5554 }
5555 e = memtbl+index;
5556 if( e->inuse )
5557 membug("Ooops: entry %u is flagged as in use\n", index);
5558 e->user_p = p + EXTRA_ALIGN + 4;
5559 e->user_n = n;
5560 e->count++;
5561 if( e->next )
5562 membug("Ooops: entry is in free entry list\n");
5563 /* do we already have this info string */
5564 for( ie = info_strings[info_hash(info)]; ie; ie = ie->next )
5565 if( ie->info == info )
5566 break;
5567 if( !ie ) { /* no: make a new entry */
5568 if( !(ie = malloc( sizeof *ie )) )
5569 membug("can't allocate info entry\n");
5570 ie->next = info_strings[info_hash(info)];
5571 info_strings[info_hash(info)] = ie;
5572 ie->info = info;
5573 ie->count = 0;
5574 }
5575 ie->count++;
5576 e->info = ie;
5577 e->inuse = 1;
5578
5579 /* put the index at the start of the memory */
5580 p[EXTRA_ALIGN+0] = index;
5581 p[EXTRA_ALIGN+1] = index >> 8 ;
5582 p[EXTRA_ALIGN+2] = index >> 16 ;
5583 p[EXTRA_ALIGN+3] = mode? MAGIC_SEC_BYTE : MAGIC_NOR_BYTE ;
5584 if( DBG_MEMORY )
5585 log_debug( "%s allocates %u bytes using %s\n", info, e->user_n, by );
5586 }
5587
5588
5589
5590 /****************
5591 * Check that the memory block is correct. The magic byte has already been
5592 * checked. Checks which are done here:
5593 * - see whether the index points into our memory table
5594 * - see whether P is the same as the one stored in the table
5595 * - see whether we have already freed this block.
5596 */
5597 struct memtbl_entry *
5598 check_mem( const byte *p, const char *info )
5599 {
5600 unsigned n;
5601 struct memtbl_entry *e;
5602
5603 n = p[EXTRA_ALIGN+0];
5604 n |= p[EXTRA_ALIGN+1] << 8;
5605 n |= p[EXTRA_ALIGN+2] << 16;
5606
5607 if( n >= memtbl_len )
5608 membug("memory at %p corrupted: index=%u table_len=%u (%s)\n",
5609 p+EXTRA_ALIGN+4, n, memtbl_len, info );
5610 e = memtbl+n;
5611
5612 if( e->user_p != p+EXTRA_ALIGN+4 )
5613 membug("memory at %p corrupted: reference mismatch (%s)\n",
5614 p+EXTRA_ALIGN+4, info );
5615 if( !e->inuse )
5616 membug("memory at %p corrupted: marked as free (%s)\n",
5617 p+EXTRA_ALIGN+4, info );
5618
5619 if( !(p[EXTRA_ALIGN+3] == MAGIC_NOR_BYTE
5620 || p[EXTRA_ALIGN+3] == MAGIC_SEC_BYTE) )
5621 membug("memory at %p corrupted: underflow=%02x (%s)\n",
5622 p+EXTRA_ALIGN+4, p[EXTRA_ALIGN+3], info );
5623 if( p[EXTRA_ALIGN+4+e->user_n] != MAGIC_END_BYTE )
5624 membug("memory at %p corrupted: overflow=%02x (%s)\n",
5625 p+EXTRA_ALIGN+4, p[EXTRA_ALIGN+4+e->user_n], info );
5626 return e;
5627 }
5628
5629
5630 /****************
5631 * free the entry and the memory (replaces free)
5632 */
5633 static void
5634 free_entry( byte *p, const char *info )
5635 {
5636 struct memtbl_entry *e, *e2;
5637
5638 check_allmem("add_entry");
5639
5640 e = check_mem(p, info);
5641 if( DBG_MEMORY )
5642 log_debug( "%s frees %u bytes alloced by %s\n",
5643 info, e->user_n, e->info->info );
5644 if( !e->inuse ) {
5645 if( e->user_p == p + EXTRA_ALIGN+ 4 )
5646 membug("freeing an already freed pointer at %p\n", p+EXTRA_ALIGN+4 );
5647 else
5648 membug("freeing pointer %p which is flagged as freed\n", p+EXTRA_ALIGN+4 );
5649 }
5650
5651 e->inuse = 0;
5652 e->next = NULL;
5653 if( !memtbl_unused )
5654 memtbl_unused = e;
5655 else {
5656 for(e2=memtbl_unused; e2->next; e2 = e2->next )
5657 ;
5658 e2->next = e;
5659 }
5660 if( m_is_secure(p+EXTRA_ALIGN+4) )
5661 secmem_free(p);
5662 else {
5663 memset(p,'f', e->user_n+5);
5664 free(p);
5665 }
5666 }
5667
5668 static void
5669 dump_entry(struct memtbl_entry *e )
5670 {
5671 unsigned n = e - memtbl;
5672
5673 fprintf(stderr, "mem %4u%c %5u %p %5u %s (%u)\n",
5674 n, e->inuse?'a':'u', e->count, e->user_p, e->user_n,
5675 e->info->info, e->info->count );
5676
5677
5678 }
5679
5680
5681 static void
5682 dump_table_at_exit( void)
5683 {
5684 if( DBG_MEMSTAT )
5685 dump_table();
5686 }
5687
5688 static void
5689 dump_table( void)
5690 {
5691 unsigned n;
5692 struct memtbl_entry *e;
5693 ulong sum = 0, chunks =0;
5694
5695 for( e = memtbl, n = 0; n < memtbl_len; n++, e++ ) {
5696 if(e->inuse) {
5697 dump_entry(e);
5698 sum += e->user_n;
5699 chunks++;
5700 }
5701 }
5702 fprintf(stderr, " memory used: %8lu bytes in %ld chunks\n",
5703 sum, chunks );
5704 }
5705
5706
5707 static void
5708 check_allmem( const char *info )
5709 {
5710 unsigned n;
5711 struct memtbl_entry *e;
5712
5713 for( e = memtbl, n = 0; n < memtbl_len; n++, e++ ) {
5714 if( e->inuse ) {
5715 #ifndef __riscos__
5716 check_mem(e->user_p-4-EXTRA_ALIGN, info);
5717 #else
5718 check_mem((const byte *) e->user_p-4-EXTRA_ALIGN, info);
5719 #endif
5720 }
5721 }
5722 }
5723
5724 #endif /* M_DEBUG */
5725
5726 #if defined(M_DEBUG) || defined(M_GUARD)
5727 static void
5728 membug( const char *fmt, ... )
5729 {
5730 va_list arg_ptr ;
5731
5732 fprintf(stderr, "\nMemory Error: " ) ;
5733 va_start( arg_ptr, fmt ) ;
5734 vfprintf(stderr,fmt,arg_ptr) ;
5735 va_end(arg_ptr);
5736 fflush(stderr);
5737 #ifdef M_DEBUG
5738 if( DBG_MEMSTAT )
5739 dump_table();
5740 #endif
5741 abort();
5742 }
5743 #endif
5744
5745 void
5746 m_print_stats( const char *prefix )
5747 {
5748 #ifdef M_DEBUG
5749 unsigned n;
5750 struct memtbl_entry *e;
5751 ulong sum = 0, chunks =0;
5752
5753 for( e = memtbl, n = 0; n < memtbl_len; n++, e++ ) {
5754 if(e->inuse) {
5755 sum += e->user_n;
5756 chunks++;
5757 }
5758 }
5759
5760 log_debug( "%s%smemstat: %8lu bytes in %ld chunks used\n",
5761 prefix? prefix:"", prefix? ": ":"", sum, chunks );
5762 #elif defined(M_GUARD)
5763 log_debug( "%s%smemstat: %8ld bytes\n",
5764 prefix? prefix:"", prefix? ": ":"", used_memory );
5765 #endif
5766 }
5767
5768 void
5769 m_dump_table( const char *prefix )
5770 {
5771 #ifdef M_DEBUG
5772 fprintf(stderr,"Memory-Table-Dump: %s\n", prefix);
5773 dump_table();
5774 #endif
5775 m_print_stats( prefix );
5776 }
5777
5778
5779 static void
5780 out_of_core(size_t n, int secure)
5781 {
5782 log_error ("out of %s memory while allocating %u bytes\n",
5783 secure? "secure":"" ,(unsigned)n );
5784 if (secure) {
5785 /*secmem_dump_stats ();*/
5786 log_info ("(this may be caused by too many secret keys used "
5787 "simultaneously or due to excessive large key sizes)\n");
5788 }
5789 #if defined(M_GUARD) && defined(__riscos__)
5790 abort();
5791 #endif
5792 exit (2);
5793 }
5794
5795 /****************
5796 * Allocate memory of size n.
5797 * This function gives up if we do not have enough memory
5798 */
5799 void *
5800 FNAMEXM(alloc)( size_t n FNAMEPRT )
5801 {
5802 char *p;
5803
5804 #ifdef M_GUARD
5805 if(!n)
5806 out_of_core(n,0); /* should never happen */
5807 if( !(p = malloc( n + EXTRA_ALIGN+5 )) )
5808 out_of_core(n,0);
5809 store_len(p,n,0);
5810 used_memory += n;
5811 p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE;
5812 return p+EXTRA_ALIGN+4;
5813 #else
5814 /* mallocing zero bytes is undefined by ISO-C, so we better make
5815 sure that it won't happen */
5816 if (!n)
5817 n = 1;
5818 if( !(p = malloc( n )) )
5819 out_of_core(n,0);
5820 return p;
5821 #endif
5822 }
5823
5824 /* Allocate memory of size n. This function returns NULL if we do not
5825 have enough memory. */
5826 void *
5827 FNAMEX(trymalloc)(size_t n FNAMEPRT)
5828 {
5829 #ifdef M_GUARD
5830 char *p;
5831
5832 if (!n)
5833 n = 1;
5834 p = malloc (n + EXTRA_ALIGN+5);
5835 if (!p)
5836 return NULL;
5837 store_len(p,n,0);
5838 used_memory += n;
5839 p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE;
5840 return p+EXTRA_ALIGN+4;
5841 #else
5842 /* Mallocing zero bytes is undefined by ISO-C, so we better make
5843 sure that it won't happen. */
5844 return malloc (n? n: 1);
5845 #endif
5846 }
5847
5848 /****************
5849 * Allocate memory of size n from the secure memory pool.
5850 * This function gives up if we do not have enough memory
5851 */
5852 void *
5853 FNAMEXM(alloc_secure)( size_t n FNAMEPRT )
5854 {
5855 char *p;
5856
5857 #ifdef M_GUARD
5858 if(!n)
5859 out_of_core(n,1); /* should never happen */
5860 if( !(p = secmem_malloc( n +EXTRA_ALIGN+ 5 )) )
5861 out_of_core(n,1);
5862 store_len(p,n,1);
5863 p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE;
5864 return p+EXTRA_ALIGN+4;
5865 #else
5866 /* mallocing zero bytes is undefined by ISO-C, so we better make
5867 sure that it won't happen */
5868 if (!n)
5869 n = 1;
5870 if( !(p = secmem_malloc( n )) )
5871 out_of_core(n,1);
5872 return p;
5873 #endif
5874 }
5875
5876 void *
5877 FNAMEXM(alloc_clear)( size_t n FNAMEPRT )
5878 {
5879 void *p;
5880 p = FNAMEXM(alloc)( n FNAMEARG );
5881 memset(p, 0, n );
5882 return p;
5883 }
5884
5885 void *
5886 FNAMEXM(alloc_secure_clear)( size_t n FNAMEPRT)
5887 {
5888 void *p;
5889 p = FNAMEXM(alloc_secure)( n FNAMEARG );
5890 memset(p, 0, n );
5891 return p;
5892 }
5893
5894
5895 /****************
5896 * realloc and clear the old space
5897 */
5898 void *
5899 FNAMEX(realloc)( void *a, size_t n FNAMEPRT )
5900 {
5901 void *b;
5902
5903 #ifdef M_GUARD
5904 if( a ) {
5905 #error "--enable-m-guard does not currently work"
5906 unsigned char *p = a;
5907 size_t len = m_size(a);
5908
5909 if( len >= n ) /* we don't shrink for now */
5910 return a;
5911 if( p[-1] == MAGIC_SEC_BYTE )
5912 b = FNAME(alloc_secure_clear)(n FNAMEARG);
5913 else
5914 b = FNAME(alloc_clear)(n FNAMEARG);
5915 FNAME(check)(NULL FNAMEARG);
5916 memcpy(b, a, len );
5917 FNAME(free)(p FNAMEARG);
5918 }
5919 else
5920 b = FNAME(alloc)(n FNAMEARG);
5921 #else
5922 if( m_is_secure(a) ) {
5923 if( !(b = secmexrealloc( a, n )) )
5924 out_of_core(n,1);
5925 }
5926 else {
5927 if( !(b = realloc( a, n )) )
5928 out_of_core(n,0);
5929 }
5930 #endif
5931
5932 return b;
5933 }
5934
5935
5936
5937 /****************
5938 * Free a pointer
5939 */
5940 void
5941 FNAMEX(free)( void *a FNAMEPRT )
5942 {
5943 byte *p = a;
5944
5945 if( !p )
5946 return;
5947 #ifdef M_DEBUG
5948 free_entry(p-EXTRA_ALIGN-4, info);
5949 #elif defined M_GUARD
5950 m_check(p);
5951 if( m_is_secure(a) )
5952 secmem_free(p-EXTRA_ALIGN-4);
5953 else {
5954 used_memory -= m_size(a);
5955 free(p-EXTRA_ALIGN-4);
5956 }
5957 #else
5958 if( m_is_secure(a) )
5959 secmem_free(p);
5960 else
5961 free(p);
5962 #endif
5963 }
5964
5965
5966 void
5967 FNAME(check)( const void *a FNAMEPRT )
5968 {
5969 #ifdef M_GUARD
5970 const byte *p = a;
5971
5972 #ifdef M_DEBUG
5973 if( p )
5974 check_mem(p-EXTRA_ALIGN-4, info);
5975 else
5976 check_allmem(info);
5977 #else
5978 if( !p )
5979 return;
5980 if( !(p[-1] == MAGIC_NOR_BYTE || p[-1] == MAGIC_SEC_BYTE) )
5981 membug("memory at %p corrupted (underflow=%02x)\n", p, p[-1] );
5982 else if( p[m_size(p)] != MAGIC_END_BYTE )
5983 membug("memory at %p corrupted (overflow=%02x)\n", p, p[-1] );
5984 #endif
5985 #endif
5986 }
5987
5988
5989 size_t
5990 m_size( const void *a )
5991 {
5992 #ifndef M_GUARD
5993 log_debug("dummy m_size called\n");
5994 return 0;
5995 #else
5996 const byte *p = a;
5997 size_t n;
5998
5999 #ifdef M_DEBUG
6000 n = check_mem(p-EXTRA_ALIGN-4, "m_size")->user_n;
6001 #else
6002 n = ((byte*)p)[-4];
6003 n |= ((byte*)p)[-3] << 8;
6004 n |= ((byte*)p)[-2] << 16;
6005 #endif
6006 return n;
6007 #endif
6008 }
6009
6010
6011 char *
6012 FNAMEX(strdup)( const char *a FNAMEPRT )
6013 {
6014 size_t n = strlen(a);
6015 char *p = FNAMEXM(alloc)(n+1 FNAMEARG);
6016 strcpy(p, a);
6017 return p;
6018 }
6019
6020 char *
6021 FNAMEX(trystrdup)(const char *a FNAMEPRT)
6022 {
6023 size_t n = strlen (a);
6024 char *p = FNAMEX(trymalloc)(n+1 FNAMEARG);
6025 if (p)
6026 strcpy (p, a);
6027 return p;
6028 }
6029
6030
6031 /* Wrapper around xmalloc_clear to take the usual 2 arguments of a
6032 calloc style function. */
6033 void *
6034 xcalloc (size_t n, size_t m)
6035 {
6036 size_t nbytes;
6037
6038 nbytes = n * m;
6039 if (m && nbytes / m != n)
6040 out_of_core (nbytes, 0);
6041 return xmalloc_clear (nbytes);
6042 }
6043
6044 /* Wrapper around xmalloc_csecure_lear to take the usual 2 arguments
6045 of a calloc style function. */
6046 void *
6047 xcalloc_secure (size_t n, size_t m)
6048 {
6049 size_t nbytes;
6050
6051 nbytes = n * m;
6052 if (m && nbytes / m != n)
6053 out_of_core (nbytes, 1);
6054 return xmalloc_secure_clear (nbytes);
6055 }
6056
-
+ FFCEA4F2389EB4919DF50FC60423606D2835E4BE6A853FA885754CF04C397FE96D4A688ECCD591C60BC687846AE1E230304D3554B3E504E2E53662270342C591
mpi/mpi-add.c
(0 . 0)(1 . 246)
6061 /* mpi-add.c - MPI functions
6062 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
6063 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
6064 *
6065 * This file is part of GnuPG.
6066 *
6067 * GnuPG is free software; you can redistribute it and/or modify
6068 * it under the terms of the GNU General Public License as published by
6069 * the Free Software Foundation; either version 3 of the License, or
6070 * (at your option) any later version.
6071 *
6072 * GnuPG is distributed in the hope that it will be useful,
6073 * but WITHOUT ANY WARRANTY; without even the implied warranty of
6074 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6075 * GNU General Public License for more details.
6076 *
6077 * You should have received a copy of the GNU General Public License
6078 * along with this program; if not, see <http://www.gnu.org/licenses/>.
6079 *
6080 * Note: This code is heavily based on the GNU MP Library.
6081 * Actually it's the same code with only minor changes in the
6082 * way the data is stored; this is to support the abstraction
6083 * of an optional secure memory allocation which may be used
6084 * to avoid revealing of sensitive data due to paging etc.
6085 * The GNU MP Library itself is published under the LGPL;
6086 * however I decided to publish this code under the plain GPL.
6087 */
6088
6089 #include <config.h>
6090 #include <stdio.h>
6091 #include <stdlib.h>
6092
6093 #include "mpi-internal.h"
6094
6095
6096 /****************
6097 * Add the unsigned integer V to the mpi-integer U and store the
6098 * result in W. U and V may be the same.
6099 */
6100 void
6101 mpi_add_ui(MPI w, MPI u, unsigned long v )
6102 {
6103 mpi_ptr_t wp, up;
6104 mpi_size_t usize, wsize;
6105 int usign, wsign;
6106
6107 usize = u->nlimbs;
6108 usign = u->sign;
6109 wsign = 0;
6110
6111 /* If not space for W (and possible carry), increase space. */
6112 wsize = usize + 1;
6113 if( w->alloced < wsize )
6114 mpi_resize(w, wsize);
6115
6116 /* These must be after realloc (U may be the same as W). */
6117 up = u->d;
6118 wp = w->d;
6119
6120 if( !usize ) { /* simple */
6121 wp[0] = v;
6122 wsize = v? 1:0;
6123 }
6124 else if( !usign ) { /* mpi is not negative */
6125 mpi_limb_t cy;
6126 cy = mpihelp_add_1(wp, up, usize, v);
6127 wp[usize] = cy;
6128 wsize = usize + cy;
6129 }
6130 else { /* The signs are different. Need exact comparison to determine
6131 * which operand to subtract from which. */
6132 if( usize == 1 && up[0] < v ) {
6133 wp[0] = v - up[0];
6134 wsize = 1;
6135 }
6136 else {
6137 mpihelp_sub_1(wp, up, usize, v);
6138 /* Size can decrease with at most one limb. */
6139 wsize = usize - (wp[usize-1]==0);
6140 wsign = 1;
6141 }
6142 }
6143
6144 w->nlimbs = wsize;
6145 w->sign = wsign;
6146 }
6147
6148
6149 void
6150 mpi_add(MPI w, MPI u, MPI v)
6151 {
6152 mpi_ptr_t wp, up, vp;
6153 mpi_size_t usize, vsize, wsize;
6154 int usign, vsign, wsign;
6155
6156 if( u->nlimbs < v->nlimbs ) { /* Swap U and V. */
6157 usize = v->nlimbs;
6158 usign = v->sign;
6159 vsize = u->nlimbs;
6160 vsign = u->sign;
6161 wsize = usize + 1;
6162 RESIZE_IF_NEEDED(w, wsize);
6163 /* These must be after realloc (u or v may be the same as w). */
6164 up = v->d;
6165 vp = u->d;
6166 }
6167 else {
6168 usize = u->nlimbs;
6169 usign = u->sign;
6170 vsize = v->nlimbs;
6171 vsign = v->sign;
6172 wsize = usize + 1;
6173 RESIZE_IF_NEEDED(w, wsize);
6174 /* These must be after realloc (u or v may be the same as w). */
6175 up = u->d;
6176 vp = v->d;
6177 }
6178 wp = w->d;
6179 wsign = 0;
6180
6181 if( !vsize ) { /* simple */
6182 MPN_COPY(wp, up, usize );
6183 wsize = usize;
6184 wsign = usign;
6185 }
6186 else if( usign != vsign ) { /* different sign */
6187 /* This test is right since USIZE >= VSIZE */
6188 if( usize != vsize ) {
6189 mpihelp_sub(wp, up, usize, vp, vsize);
6190 wsize = usize;
6191 MPN_NORMALIZE(wp, wsize);
6192 wsign = usign;
6193 }
6194 else if( mpihelp_cmp(up, vp, usize) < 0 ) {
6195 mpihelp_sub_n(wp, vp, up, usize);
6196 wsize = usize;
6197 MPN_NORMALIZE(wp, wsize);
6198 if( !usign )
6199 wsign = 1;
6200 }
6201 else {
6202 mpihelp_sub_n(wp, up, vp, usize);
6203 wsize = usize;
6204 MPN_NORMALIZE(wp, wsize);
6205 if( usign )
6206 wsign = 1;
6207 }
6208 }
6209 else { /* U and V have same sign. Add them. */
6210 mpi_limb_t cy = mpihelp_add(wp, up, usize, vp, vsize);
6211 wp[usize] = cy;
6212 wsize = usize + cy;
6213 if( usign )
6214 wsign = 1;
6215 }
6216
6217 w->nlimbs = wsize;
6218 w->sign = wsign;
6219 }
6220
6221
6222 /****************
6223 * Subtract the unsigned integer V from the mpi-integer U and store the
6224 * result in W.
6225 */
6226 void
6227 mpi_sub_ui(MPI w, MPI u, unsigned long v )
6228 {
6229 mpi_ptr_t wp, up;
6230 mpi_size_t usize, wsize;
6231 int usign, wsign;
6232
6233 usize = u->nlimbs;
6234 usign = u->sign;
6235 wsign = 0;
6236
6237 /* If not space for W (and possible carry), increase space. */
6238 wsize = usize + 1;
6239 if( w->alloced < wsize )
6240 mpi_resize(w, wsize);
6241
6242 /* These must be after realloc (U may be the same as W). */
6243 up = u->d;
6244 wp = w->d;
6245
6246 if( !usize ) { /* simple */
6247 wp[0] = v;
6248 wsize = v? 1:0;
6249 wsign = 1;
6250 }
6251 else if( usign ) { /* mpi and v are negative */
6252 mpi_limb_t cy;
6253 cy = mpihelp_add_1(wp, up, usize, v);
6254 wp[usize] = cy;
6255 wsize = usize + cy;
6256 }
6257 else { /* The signs are different. Need exact comparison to determine
6258 * which operand to subtract from which. */
6259 if( usize == 1 && up[0] < v ) {
6260 wp[0] = v - up[0];
6261 wsize = 1;
6262 wsign = 1;
6263 }
6264 else {
6265 mpihelp_sub_1(wp, up, usize, v);
6266 /* Size can decrease with at most one limb. */
6267 wsize = usize - (wp[usize-1]==0);
6268 }
6269 }
6270
6271 w->nlimbs = wsize;
6272 w->sign = wsign;
6273 }
6274
6275 void
6276 mpi_sub(MPI w, MPI u, MPI v)
6277 {
6278 if( w == v ) {
6279 MPI vv = mpi_copy(v);
6280 vv->sign = !vv->sign;
6281 mpi_add( w, u, vv );
6282 mpi_free(vv);
6283 }
6284 else {
6285 /* fixme: this is not thread-save (we temp. modify v) */
6286 v->sign = !v->sign;
6287 mpi_add( w, u, v );
6288 v->sign = !v->sign;
6289 }
6290 }
6291
6292
6293 void
6294 mpi_addm( MPI w, MPI u, MPI v, MPI m)
6295 {
6296 mpi_add(w, u, v);
6297 mpi_fdiv_r( w, w, m );
6298 }
6299
6300 void
6301 mpi_subm( MPI w, MPI u, MPI v, MPI m)
6302 {
6303 mpi_sub(w, u, v);
6304 mpi_fdiv_r( w, w, m );
6305 }
6306
-
+ A48F6DCD95712D600A89EFAE6DC7425B5CADE2869B48AA49D6D6FC5C42D63EC462E2A1FCB08CB1DF5468A9A5AD8C8DD419DC7FB8F5758AD0D93007960B19A153
mpi/mpi-bit.c
(0 . 0)(1 . 254)
6311 /* mpi-bit.c - MPI bit level fucntions
6312 * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
6313 *
6314 * This file is part of GnuPG.
6315 *
6316 * GnuPG is free software; you can redistribute it and/or modify
6317 * it under the terms of the GNU General Public License as published by
6318 * the Free Software Foundation; either version 3 of the License, or
6319 * (at your option) any later version.
6320 *
6321 * GnuPG is distributed in the hope that it will be useful,
6322 * but WITHOUT ANY WARRANTY; without even the implied warranty of
6323 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6324 * GNU General Public License for more details.
6325 *
6326 * You should have received a copy of the GNU General Public License
6327 * along with this program; if not, see <http://www.gnu.org/licenses/>.
6328 */
6329
6330 #include <config.h>
6331 #include <stdio.h>
6332 #include <stdlib.h>
6333 #include <assert.h>
6334 #include "mpi-internal.h"
6335 #include "longlong.h"
6336
6337
6338 #ifdef MPI_INTERNAL_NEED_CLZ_TAB
6339 #ifdef __STDC__
6340 const
6341 #endif
6342 unsigned char
6343 __clz_tab[] =
6344 {
6345 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6346 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6347 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
6348 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
6349 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6350 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6351 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6352 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
6353 };
6354 #endif
6355
6356
6357 #define A_LIMB_1 ((mpi_limb_t)1)
6358
6359
6360 /****************
6361 * Sometimes we have MSL (most significant limbs) which are 0;
6362 * this is for some reasons not good, so this function removes them.
6363 */
6364 void
6365 mpi_normalize( MPI a )
6366 {
6367 if( mpi_is_opaque (a) )
6368 return;
6369
6370 for( ; a->nlimbs && !a->d[a->nlimbs-1]; a->nlimbs-- )
6371 ;
6372 }
6373
6374
6375
6376 /****************
6377 * Return the number of bits in A.
6378 */
6379 unsigned
6380 mpi_get_nbits( MPI a )
6381 {
6382 unsigned n;
6383
6384 mpi_normalize( a );
6385 if( a->nlimbs ) {
6386 mpi_limb_t alimb = a->d[a->nlimbs-1];
6387 if( alimb )
6388 count_leading_zeros( n, alimb );
6389 else
6390 n = BITS_PER_MPI_LIMB;
6391 n = BITS_PER_MPI_LIMB - n + (a->nlimbs-1) * BITS_PER_MPI_LIMB;
6392 }
6393 else
6394 n = 0;
6395 return n;
6396 }
6397
6398
6399 /****************
6400 * Test whether bit N is set.
6401 */
6402 int
6403 mpi_test_bit( MPI a, unsigned n )
6404 {
6405 unsigned limbno, bitno;
6406 mpi_limb_t limb;
6407
6408 limbno = n / BITS_PER_MPI_LIMB;
6409 bitno = n % BITS_PER_MPI_LIMB;
6410
6411 if( limbno >= a->nlimbs )
6412 return 0; /* too far left: this is a 0 */
6413 limb = a->d[limbno];
6414 return (limb & (A_LIMB_1 << bitno))? 1: 0;
6415 }
6416
6417
6418 /****************
6419 * Set bit N of A.
6420 */
6421 void
6422 mpi_set_bit( MPI a, unsigned n )
6423 {
6424 unsigned limbno, bitno;
6425
6426 limbno = n / BITS_PER_MPI_LIMB;
6427 bitno = n % BITS_PER_MPI_LIMB;
6428
6429 if( limbno >= a->nlimbs ) { /* resize */
6430 if( a->alloced >= limbno )
6431 mpi_resize(a, limbno+1 );
6432 a->nlimbs = limbno+1;
6433 }
6434 a->d[limbno] |= (A_LIMB_1<<bitno);
6435 }
6436
6437 /****************
6438 * Set bit N of A. and clear all bits above
6439 */
6440 void
6441 mpi_set_highbit( MPI a, unsigned n )
6442 {
6443 unsigned limbno, bitno;
6444
6445 limbno = n / BITS_PER_MPI_LIMB;
6446 bitno = n % BITS_PER_MPI_LIMB;
6447
6448 if( limbno >= a->nlimbs ) { /* resize */
6449 if( a->alloced >= limbno )
6450 mpi_resize(a, limbno+1 );
6451 a->nlimbs = limbno+1;
6452 }
6453 a->d[limbno] |= (A_LIMB_1<<bitno);
6454 for( bitno++; bitno < BITS_PER_MPI_LIMB; bitno++ )
6455 a->d[limbno] &= ~(A_LIMB_1 << bitno);
6456 a->nlimbs = limbno+1;
6457 }
6458
6459 /****************
6460 * clear bit N of A and all bits above
6461 */
6462 void
6463 mpi_clear_highbit( MPI a, unsigned n )
6464 {
6465 unsigned limbno, bitno;
6466
6467 limbno = n / BITS_PER_MPI_LIMB;
6468 bitno = n % BITS_PER_MPI_LIMB;
6469
6470 if( limbno >= a->nlimbs )
6471 return; /* not allocated, so need to clear bits :-) */
6472
6473 for( ; bitno < BITS_PER_MPI_LIMB; bitno++ )
6474 a->d[limbno] &= ~(A_LIMB_1 << bitno);
6475 a->nlimbs = limbno+1;
6476 }
6477
6478 /****************
6479 * Clear bit N of A.
6480 */
6481 void
6482 mpi_clear_bit( MPI a, unsigned n )
6483 {
6484 unsigned limbno, bitno;
6485
6486 limbno = n / BITS_PER_MPI_LIMB;
6487 bitno = n % BITS_PER_MPI_LIMB;
6488
6489 if( limbno >= a->nlimbs )
6490 return; /* don't need to clear this bit, it's to far to left */
6491 a->d[limbno] &= ~(A_LIMB_1 << bitno);
6492 }
6493
6494
6495 /****************
6496 * Shift A by N bits to the right
6497 * FIXME: should use alloc_limb if X and A are same.
6498 */
6499 void
6500 mpi_rshift( MPI x, MPI a, unsigned n )
6501 {
6502 mpi_ptr_t xp;
6503 mpi_size_t xsize;
6504
6505 xsize = a->nlimbs;
6506 x->sign = a->sign;
6507 RESIZE_IF_NEEDED(x, xsize);
6508 xp = x->d;
6509
6510 if( xsize ) {
6511 mpihelp_rshift( xp, a->d, xsize, n);
6512 MPN_NORMALIZE( xp, xsize);
6513 }
6514 x->nlimbs = xsize;
6515 }
6516
6517
6518 /****************
6519 * Shift A by COUNT limbs to the left
6520 * This is used only within the MPI library
6521 */
6522 void
6523 mpi_lshift_limbs( MPI a, unsigned int count )
6524 {
6525 mpi_ptr_t ap = a->d;
6526 int n = a->nlimbs;
6527 int i;
6528
6529 if( !count || !n )
6530 return;
6531
6532 RESIZE_IF_NEEDED( a, n+count );
6533
6534 for( i = n-1; i >= 0; i-- )
6535 ap[i+count] = ap[i];
6536 for(i=0; i < count; i++ )
6537 ap[i] = 0;
6538 a->nlimbs += count;
6539 }
6540
6541
6542 /****************
6543 * Shift A by COUNT limbs to the right
6544 * This is used only within the MPI library
6545 */
6546 void
6547 mpi_rshift_limbs( MPI a, unsigned int count )
6548 {
6549 mpi_ptr_t ap = a->d;
6550 mpi_size_t n = a->nlimbs;
6551 unsigned int i;
6552
6553 if( count >= n ) {
6554 a->nlimbs = 0;
6555 return;
6556 }
6557
6558 for( i = 0; i < n - count; i++ )
6559 ap[i] = ap[i+count];
6560 ap[i] = 0;
6561 a->nlimbs -= count;
6562 }
6563
6564
-
+ 83C978461CA2FC606EAB05035DB9A67D600396F013E5CE0DB8CC110D8881E9BE513D540B27DAECC8B0293178D7AB27EE52F5C947A0B9976863B9094F82EBD522
mpi/mpi-cmp.c
(0 . 0)(1 . 73)
6569 /* mpi-cmp.c - MPI functions
6570 * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
6571 *
6572 * This file is part of GnuPG.
6573 *
6574 * GnuPG is free software; you can redistribute it and/or modify
6575 * it under the terms of the GNU General Public License as published by
6576 * the Free Software Foundation; either version 3 of the License, or
6577 * (at your option) any later version.
6578 *
6579 * GnuPG is distributed in the hope that it will be useful,
6580 * but WITHOUT ANY WARRANTY; without even the implied warranty of
6581 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6582 * GNU General Public License for more details.
6583 *
6584 * You should have received a copy of the GNU General Public License
6585 * along with this program; if not, see <http://www.gnu.org/licenses/>.
6586 */
6587
6588 #include <config.h>
6589 #include <stdio.h>
6590 #include <stdlib.h>
6591 #include "mpi-internal.h"
6592
6593 int
6594 mpi_cmp_ui( MPI u, unsigned long v )
6595 {
6596 mpi_limb_t limb = v;
6597
6598 mpi_normalize( u );
6599 if( !u->nlimbs && !limb )
6600 return 0;
6601 if( u->sign )
6602 return -1;
6603 if( u->nlimbs > 1 )
6604 return 1;
6605
6606 if( u->d[0] == limb )
6607 return 0;
6608 else if( u->d[0] > limb )
6609 return 1;
6610 else
6611 return -1;
6612 }
6613
6614 int
6615 mpi_cmp( MPI u, MPI v )
6616 {
6617 mpi_size_t usize, vsize;
6618 int cmp;
6619
6620 mpi_normalize( u );
6621 mpi_normalize( v );
6622 usize = u->nlimbs;
6623 vsize = v->nlimbs;
6624 if( !u->sign && v->sign )
6625 return 1;
6626 if( u->sign && !v->sign )
6627 return -1;
6628 if( usize != vsize && !u->sign && !v->sign )
6629 return usize - vsize;
6630 if( usize != vsize && u->sign && v->sign )
6631 return vsize + usize;
6632 if( !usize )
6633 return 0;
6634 if( !(cmp=mpihelp_cmp( u->d, v->d, usize )) )
6635 return 0;
6636 if( (cmp < 0?1:0) == (u->sign?1:0))
6637 return 1;
6638 return -1;
6639 }
6640
6641
-
+ B320709B57B3CF0C00BC98277B037494C62FED93FD99BCA0412EA633F8662844D35ED62990CBE1FC02A47DEE5795D3A7B6B401440F6E80A8A00243868815C06A
mpi/mpi-div.c
(0 . 0)(1 . 321)
6646 /* mpi-div.c - MPI functions
6647 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
6648 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
6649 *
6650 * This file is part of GnuPG.
6651 *
6652 * GnuPG is free software; you can redistribute it and/or modify
6653 * it under the terms of the GNU General Public License as published by
6654 * the Free Software Foundation; either version 3 of the License, or
6655 * (at your option) any later version.
6656 *
6657 * GnuPG is distributed in the hope that it will be useful,
6658 * but WITHOUT ANY WARRANTY; without even the implied warranty of
6659 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6660 * GNU General Public License for more details.
6661 *
6662 * You should have received a copy of the GNU General Public License
6663 * along with this program; if not, see <http://www.gnu.org/licenses/>.
6664 *
6665 * Note: This code is heavily based on the GNU MP Library.
6666 * Actually it's the same code with only minor changes in the
6667 * way the data is stored; this is to support the abstraction
6668 * of an optional secure memory allocation which may be used
6669 * to avoid revealing of sensitive data due to paging etc.
6670 * The GNU MP Library itself is published under the LGPL;
6671 * however I decided to publish this code under the plain GPL.
6672 */
6673
6674 #include <config.h>
6675 #include <stdio.h>
6676 #include <stdlib.h>
6677 #include "mpi-internal.h"
6678 #include "longlong.h"
6679
6680
6681
6682 void
6683 mpi_fdiv_r( MPI rem, MPI dividend, MPI divisor )
6684 {
6685 int divisor_sign = divisor->sign;
6686 MPI temp_divisor = NULL;
6687
6688 /* We need the original value of the divisor after the remainder has been
6689 * preliminary calculated. We have to copy it to temporary space if it's
6690 * the same variable as REM. */
6691 if( rem == divisor ) {
6692 temp_divisor = mpi_copy( divisor );
6693 divisor = temp_divisor;
6694 }
6695
6696 mpi_tdiv_r( rem, dividend, divisor );
6697
6698 if( ((divisor_sign?1:0) ^ (dividend->sign?1:0)) && rem->nlimbs )
6699 mpi_add( rem, rem, divisor);
6700
6701 if( temp_divisor )
6702 mpi_free(temp_divisor);
6703 }
6704
6705
6706
6707 /****************
6708 * Division rounding the quotient towards -infinity.
6709 * The remainder gets the same sign as the denominator.
6710 * rem is optional
6711 */
6712
6713 ulong
6714 mpi_fdiv_r_ui( MPI rem, MPI dividend, ulong divisor )
6715 {
6716 mpi_limb_t rlimb;
6717
6718 rlimb = mpihelp_mod_1( dividend->d, dividend->nlimbs, divisor );
6719 if( rlimb && dividend->sign )
6720 rlimb = divisor - rlimb;
6721
6722 if( rem ) {
6723 rem->d[0] = rlimb;
6724 rem->nlimbs = rlimb? 1:0;
6725 }
6726 return rlimb;
6727 }
6728
6729
6730 void
6731 mpi_fdiv_q( MPI quot, MPI dividend, MPI divisor )
6732 {
6733 MPI tmp = mpi_alloc( mpi_get_nlimbs(quot) );
6734 mpi_fdiv_qr( quot, tmp, dividend, divisor);
6735 mpi_free(tmp);
6736 }
6737
6738 void
6739 mpi_fdiv_qr( MPI quot, MPI rem, MPI dividend, MPI divisor )
6740 {
6741 int divisor_sign = divisor->sign;
6742 MPI temp_divisor = NULL;
6743
6744 if( quot == divisor || rem == divisor ) {
6745 temp_divisor = mpi_copy( divisor );
6746 divisor = temp_divisor;
6747 }
6748
6749 mpi_tdiv_qr( quot, rem, dividend, divisor );
6750
6751 if( (divisor_sign ^ dividend->sign) && rem->nlimbs ) {
6752 mpi_sub_ui( quot, quot, 1 );
6753 mpi_add( rem, rem, divisor);
6754 }
6755
6756 if( temp_divisor )
6757 mpi_free(temp_divisor);
6758 }
6759
6760
6761 /* If den == quot, den needs temporary storage.
6762 * If den == rem, den needs temporary storage.
6763 * If num == quot, num needs temporary storage.
6764 * If den has temporary storage, it can be normalized while being copied,
6765 * i.e no extra storage should be allocated.
6766 */
6767
6768 void
6769 mpi_tdiv_r( MPI rem, MPI num, MPI den)
6770 {
6771 mpi_tdiv_qr(NULL, rem, num, den );
6772 }
6773
6774 void
6775 mpi_tdiv_qr( MPI quot, MPI rem, MPI num, MPI den)
6776 {
6777 mpi_ptr_t np, dp;
6778 mpi_ptr_t qp, rp;
6779 mpi_size_t nsize = num->nlimbs;
6780 mpi_size_t dsize = den->nlimbs;
6781 mpi_size_t qsize, rsize;
6782 mpi_size_t sign_remainder = num->sign;
6783 mpi_size_t sign_quotient = num->sign ^ den->sign;
6784 unsigned normalization_steps;
6785 mpi_limb_t q_limb;
6786 mpi_ptr_t marker[5];
6787 int markidx=0;
6788
6789 /* Ensure space is enough for quotient and remainder.
6790 * We need space for an extra limb in the remainder, because it's
6791 * up-shifted (normalized) below. */
6792 rsize = nsize + 1;
6793 mpi_resize( rem, rsize);
6794
6795 qsize = rsize - dsize; /* qsize cannot be bigger than this. */
6796 if( qsize <= 0 ) {
6797 if( num != rem ) {
6798 rem->nlimbs = num->nlimbs;
6799 rem->sign = num->sign;
6800 MPN_COPY(rem->d, num->d, nsize);
6801 }
6802 if( quot ) {
6803 /* This needs to follow the assignment to rem, in case the
6804 * numerator and quotient are the same. */
6805 quot->nlimbs = 0;
6806 quot->sign = 0;
6807 }
6808 return;
6809 }
6810
6811 if( quot )
6812 mpi_resize( quot, qsize);
6813
6814 /* Read pointers here, when reallocation is finished. */
6815 np = num->d;
6816 dp = den->d;
6817 rp = rem->d;
6818
6819 /* Optimize division by a single-limb divisor. */
6820 if( dsize == 1 ) {
6821 mpi_limb_t rlimb;
6822 if( quot ) {
6823 qp = quot->d;
6824 rlimb = mpihelp_divmod_1( qp, np, nsize, dp[0] );
6825 qsize -= qp[qsize - 1] == 0;
6826 quot->nlimbs = qsize;
6827 quot->sign = sign_quotient;
6828 }
6829 else
6830 rlimb = mpihelp_mod_1( np, nsize, dp[0] );
6831 rp[0] = rlimb;
6832 rsize = rlimb != 0?1:0;
6833 rem->nlimbs = rsize;
6834 rem->sign = sign_remainder;
6835 return;
6836 }
6837
6838
6839 if( quot ) {
6840 qp = quot->d;
6841 /* Make sure QP and NP point to different objects. Otherwise the
6842 * numerator would be gradually overwritten by the quotient limbs. */
6843 if(qp == np) { /* Copy NP object to temporary space. */
6844 np = marker[markidx++] = mpi_alloc_limb_space(nsize,
6845 mpi_is_secure(quot));
6846 MPN_COPY(np, qp, nsize);
6847 }
6848 }
6849 else /* Put quotient at top of remainder. */
6850 qp = rp + dsize;
6851
6852 count_leading_zeros( normalization_steps, dp[dsize - 1] );
6853
6854 /* Normalize the denominator, i.e. make its most significant bit set by
6855 * shifting it NORMALIZATION_STEPS bits to the left. Also shift the
6856 * numerator the same number of steps (to keep the quotient the same!).
6857 */
6858 if( normalization_steps ) {
6859 mpi_ptr_t tp;
6860 mpi_limb_t nlimb;
6861
6862 /* Shift up the denominator setting the most significant bit of
6863 * the most significant word. Use temporary storage not to clobber
6864 * the original contents of the denominator. */
6865 tp = marker[markidx++] = mpi_alloc_limb_space(dsize,mpi_is_secure(den));
6866 mpihelp_lshift( tp, dp, dsize, normalization_steps );
6867 dp = tp;
6868
6869 /* Shift up the numerator, possibly introducing a new most
6870 * significant word. Move the shifted numerator in the remainder
6871 * meanwhile. */
6872 nlimb = mpihelp_lshift(rp, np, nsize, normalization_steps);
6873 if( nlimb ) {
6874 rp[nsize] = nlimb;
6875 rsize = nsize + 1;
6876 }
6877 else
6878 rsize = nsize;
6879 }
6880 else {
6881 /* The denominator is already normalized, as required. Copy it to
6882 * temporary space if it overlaps with the quotient or remainder. */
6883 if( dp == rp || (quot && (dp == qp))) {
6884 mpi_ptr_t tp;
6885
6886 tp = marker[markidx++] = mpi_alloc_limb_space(dsize, mpi_is_secure(den));
6887 MPN_COPY( tp, dp, dsize );
6888 dp = tp;
6889 }
6890
6891 /* Move the numerator to the remainder. */
6892 if( rp != np )
6893 MPN_COPY(rp, np, nsize);
6894
6895 rsize = nsize;
6896 }
6897
6898 q_limb = mpihelp_divrem( qp, 0, rp, rsize, dp, dsize );
6899
6900 if( quot ) {
6901 qsize = rsize - dsize;
6902 if(q_limb) {
6903 qp[qsize] = q_limb;
6904 qsize += 1;
6905 }
6906
6907 quot->nlimbs = qsize;
6908 quot->sign = sign_quotient;
6909 }
6910
6911 rsize = dsize;
6912 MPN_NORMALIZE (rp, rsize);
6913
6914 if( normalization_steps && rsize ) {
6915 mpihelp_rshift(rp, rp, rsize, normalization_steps);
6916 rsize -= rp[rsize - 1] == 0?1:0;
6917 }
6918
6919 rem->nlimbs = rsize;
6920 rem->sign = sign_remainder;
6921 while( markidx )
6922 mpi_free_limb_space(marker[--markidx]);
6923 }
6924
6925 void
6926 mpi_tdiv_q_2exp( MPI w, MPI u, unsigned count )
6927 {
6928 mpi_size_t usize, wsize;
6929 mpi_size_t limb_cnt;
6930
6931 usize = u->nlimbs;
6932 limb_cnt = count / BITS_PER_MPI_LIMB;
6933 wsize = usize - limb_cnt;
6934 if( limb_cnt >= usize )
6935 w->nlimbs = 0;
6936 else {
6937 mpi_ptr_t wp;
6938 mpi_ptr_t up;
6939
6940 RESIZE_IF_NEEDED( w, wsize );
6941 wp = w->d;
6942 up = u->d;
6943
6944 count %= BITS_PER_MPI_LIMB;
6945 if( count ) {
6946 mpihelp_rshift( wp, up + limb_cnt, wsize, count );
6947 wsize -= !wp[wsize - 1];
6948 }
6949 else {
6950 MPN_COPY_INCR( wp, up + limb_cnt, wsize);
6951 }
6952
6953 w->nlimbs = wsize;
6954 }
6955 }
6956
6957 /****************
6958 * Check whether dividend is divisible by divisor
6959 * (note: divisor must fit into a limb)
6960 */
6961 int
6962 mpi_divisible_ui(MPI dividend, ulong divisor )
6963 {
6964 return !mpihelp_mod_1( dividend->d, dividend->nlimbs, divisor );
6965 }
6966
-
+ F582DE56EE9BC1D4CF2EEA35BDABDCD61E0CC93DD186950709E32FC707D2F769669BAFDCFBF2AD074596BA474BF1E7AF5E29EA81CFF2316ACBFCD27A0F93F185
mpi/mpi-gcd.c
(0 . 0)(1 . 53)
6971 /* mpi-gcd.c - MPI functions
6972 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
6973 *
6974 * This file is part of GnuPG.
6975 *
6976 * GnuPG is free software; you can redistribute it and/or modify
6977 * it under the terms of the GNU General Public License as published by
6978 * the Free Software Foundation; either version 3 of the License, or
6979 * (at your option) any later version.
6980 *
6981 * GnuPG is distributed in the hope that it will be useful,
6982 * but WITHOUT ANY WARRANTY; without even the implied warranty of
6983 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
6984 * GNU General Public License for more details.
6985 *
6986 * You should have received a copy of the GNU General Public License
6987 * along with this program; if not, see <http://www.gnu.org/licenses/>.
6988 */
6989
6990 #include <config.h>
6991 #include <stdio.h>
6992 #include <stdlib.h>
6993 #include "mpi-internal.h"
6994
6995 /****************
6996 * Find the greatest common divisor G of A and B.
6997 * Return: true if this 1, false in all other cases
6998 */
6999 int
7000 mpi_gcd( MPI g, MPI xa, MPI xb )
7001 {
7002 MPI a, b;
7003
7004 a = mpi_copy(xa);
7005 b = mpi_copy(xb);
7006
7007 /* TAOCP Vol II, 4.5.2, Algorithm A */
7008 a->sign = 0;
7009 b->sign = 0;
7010 while( mpi_cmp_ui( b, 0 ) ) {
7011 mpi_fdiv_r( g, a, b ); /* g used as temorary variable */
7012 mpi_set(a,b);
7013 mpi_set(b,g);
7014 }
7015 mpi_set(g, a);
7016
7017 mpi_free(a);
7018 mpi_free(b);
7019 return !mpi_cmp_ui( g, 1);
7020 }
7021
7022
7023
-
+ 22B8E75D35ABC0449E048A2B18461B17D7EF5A6A00A56FE1A16BD89B526B8F6F19DEA196A258D6E3760F84B1124D7D40FA28D1B6C5BC4932BE11B9D91C7077EC
mpi/mpi-inline.c
(0 . 0)(1 . 35)
7028 /* mpi-inline.c
7029 * Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
7030 *
7031 * This file is part of GnuPG.
7032 *
7033 * GnuPG is free software; you can redistribute it and/or modify
7034 * it under the terms of the GNU General Public License as published by
7035 * the Free Software Foundation; either version 3 of the License, or
7036 * (at your option) any later version.
7037 *
7038 * GnuPG is distributed in the hope that it will be useful,
7039 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7040 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7041 * GNU General Public License for more details.
7042 *
7043 * You should have received a copy of the GNU General Public License
7044 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7045 */
7046
7047 #include <config.h>
7048 #include <stdio.h>
7049 #include <stdlib.h>
7050
7051 /* put the inline functions as real functions into the lib */
7052 #define G10_MPI_INLINE_DECL
7053
7054 #include "mpi-internal.h"
7055
7056 /* always include the header becuase it is only
7057 * included by mpi-internal if __GCC__ is defined but we
7058 * need it here in all cases and the above definition of
7059 * of the macro allows us to do so
7060 */
7061 #include "mpi-inline.h"
7062
-
+ 66EDF48A07BB672B7D9329150436A40AB2F1628F1F289B4C52B2E4BDB987B9105F36C441FB21A141346406A675D34B6265A4A0BC00D3C4DE471F461D0ACC5765
mpi/mpi-inv.c
(0 . 0)(1 . 266)
7067 /* mpi-inv.c - MPI functions
7068 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
7069 *
7070 * This file is part of GnuPG.
7071 *
7072 * GnuPG is free software; you can redistribute it and/or modify
7073 * it under the terms of the GNU General Public License as published by
7074 * the Free Software Foundation; either version 3 of the License, or
7075 * (at your option) any later version.
7076 *
7077 * GnuPG is distributed in the hope that it will be useful,
7078 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7079 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7080 * GNU General Public License for more details.
7081 *
7082 * You should have received a copy of the GNU General Public License
7083 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7084 */
7085
7086 #include <config.h>
7087 #include <stdio.h>
7088 #include <stdlib.h>
7089 #include "mpi-internal.h"
7090
7091
7092 /****************
7093 * Calculate the multiplicative inverse X of A mod N
7094 * That is: Find the solution x for
7095 * 1 = (a*x) mod n
7096 */
7097 void
7098 mpi_invm( MPI x, MPI a, MPI n )
7099 {
7100 #if 0
7101 MPI u, v, u1, u2, u3, v1, v2, v3, q, t1, t2, t3;
7102 MPI ta, tb, tc;
7103
7104 u = mpi_copy(a);
7105 v = mpi_copy(n);
7106 u1 = mpi_alloc_set_ui(1);
7107 u2 = mpi_alloc_set_ui(0);
7108 u3 = mpi_copy(u);
7109 v1 = mpi_alloc_set_ui(0);
7110 v2 = mpi_alloc_set_ui(1);
7111 v3 = mpi_copy(v);
7112 q = mpi_alloc( mpi_get_nlimbs(u)+1 );
7113 t1 = mpi_alloc( mpi_get_nlimbs(u)+1 );
7114 t2 = mpi_alloc( mpi_get_nlimbs(u)+1 );
7115 t3 = mpi_alloc( mpi_get_nlimbs(u)+1 );
7116 while( mpi_cmp_ui( v3, 0 ) ) {
7117 mpi_fdiv_q( q, u3, v3 );
7118 mpi_mul(t1, v1, q); mpi_mul(t2, v2, q); mpi_mul(t3, v3, q);
7119 mpi_sub(t1, u1, t1); mpi_sub(t2, u2, t2); mpi_sub(t3, u3, t3);
7120 mpi_set(u1, v1); mpi_set(u2, v2); mpi_set(u3, v3);
7121 mpi_set(v1, t1); mpi_set(v2, t2); mpi_set(v3, t3);
7122 }
7123 /* log_debug("result:\n");
7124 log_mpidump("q =", q );
7125 log_mpidump("u1=", u1);
7126 log_mpidump("u2=", u2);
7127 log_mpidump("u3=", u3);
7128 log_mpidump("v1=", v1);
7129 log_mpidump("v2=", v2); */
7130 mpi_set(x, u1);
7131
7132 mpi_free(u1);
7133 mpi_free(u2);
7134 mpi_free(u3);
7135 mpi_free(v1);
7136 mpi_free(v2);
7137 mpi_free(v3);
7138 mpi_free(q);
7139 mpi_free(t1);
7140 mpi_free(t2);
7141 mpi_free(t3);
7142 mpi_free(u);
7143 mpi_free(v);
7144 #elif 0
7145 /* Extended Euclid's algorithm (See TAOPC Vol II, 4.5.2, Alg X)
7146 * modified according to Michael Penk's solution for Exercice 35 */
7147
7148 /* FIXME: we can simplify this in most cases (see Knuth) */
7149 MPI u, v, u1, u2, u3, v1, v2, v3, t1, t2, t3;
7150 unsigned k;
7151 int sign;
7152
7153 u = mpi_copy(a);
7154 v = mpi_copy(n);
7155 for(k=0; !mpi_test_bit(u,0) && !mpi_test_bit(v,0); k++ ) {
7156 mpi_rshift(u, u, 1);
7157 mpi_rshift(v, v, 1);
7158 }
7159
7160
7161 u1 = mpi_alloc_set_ui(1);
7162 u2 = mpi_alloc_set_ui(0);
7163 u3 = mpi_copy(u);
7164 v1 = mpi_copy(v); /* !-- used as const 1 */
7165 v2 = mpi_alloc( mpi_get_nlimbs(u) ); mpi_sub( v2, u1, u );
7166 v3 = mpi_copy(v);
7167 if( mpi_test_bit(u, 0) ) { /* u is odd */
7168 t1 = mpi_alloc_set_ui(0);
7169 t2 = mpi_alloc_set_ui(1); t2->sign = 1;
7170 t3 = mpi_copy(v); t3->sign = !t3->sign;
7171 goto Y4;
7172 }
7173 else {
7174 t1 = mpi_alloc_set_ui(1);
7175 t2 = mpi_alloc_set_ui(0);
7176 t3 = mpi_copy(u);
7177 }
7178 do {
7179 do {
7180 if( mpi_test_bit(t1, 0) || mpi_test_bit(t2, 0) ) { /* one is odd */
7181 mpi_add(t1, t1, v);
7182 mpi_sub(t2, t2, u);
7183 }
7184 mpi_rshift(t1, t1, 1);
7185 mpi_rshift(t2, t2, 1);
7186 mpi_rshift(t3, t3, 1);
7187 Y4:
7188 ;
7189 } while( !mpi_test_bit( t3, 0 ) ); /* while t3 is even */
7190
7191 if( !t3->sign ) {
7192 mpi_set(u1, t1);
7193 mpi_set(u2, t2);
7194 mpi_set(u3, t3);
7195 }
7196 else {
7197 mpi_sub(v1, v, t1);
7198 sign = u->sign; u->sign = !u->sign;
7199 mpi_sub(v2, u, t2);
7200 u->sign = sign;
7201 sign = t3->sign; t3->sign = !t3->sign;
7202 mpi_set(v3, t3);
7203 t3->sign = sign;
7204 }
7205 mpi_sub(t1, u1, v1);
7206 mpi_sub(t2, u2, v2);
7207 mpi_sub(t3, u3, v3);
7208 if( t1->sign ) {
7209 mpi_add(t1, t1, v);
7210 mpi_sub(t2, t2, u);
7211 }
7212 } while( mpi_cmp_ui( t3, 0 ) ); /* while t3 != 0 */
7213 /* mpi_lshift( u3, k ); */
7214 mpi_set(x, u1);
7215
7216 mpi_free(u1);
7217 mpi_free(u2);
7218 mpi_free(u3);
7219 mpi_free(v1);
7220 mpi_free(v2);
7221 mpi_free(v3);
7222 mpi_free(t1);
7223 mpi_free(t2);
7224 mpi_free(t3);
7225 #else
7226 /* Extended Euclid's algorithm (See TAOPC Vol II, 4.5.2, Alg X)
7227 * modified according to Michael Penk's solution for Exercice 35
7228 * with further enhancement */
7229 MPI u, v, u1, u2=NULL, u3, v1, v2=NULL, v3, t1, t2=NULL, t3;
7230 unsigned k;
7231 int sign;
7232 int odd ;
7233
7234 u = mpi_copy(a);
7235 v = mpi_copy(n);
7236
7237 for(k=0; !mpi_test_bit(u,0) && !mpi_test_bit(v,0); k++ ) {
7238 mpi_rshift(u, u, 1);
7239 mpi_rshift(v, v, 1);
7240 }
7241 odd = mpi_test_bit(v,0);
7242
7243 u1 = mpi_alloc_set_ui(1);
7244 if( !odd )
7245 u2 = mpi_alloc_set_ui(0);
7246 u3 = mpi_copy(u);
7247 v1 = mpi_copy(v);
7248 if( !odd ) {
7249 v2 = mpi_alloc( mpi_get_nlimbs(u) );
7250 mpi_sub( v2, u1, u ); /* U is used as const 1 */
7251 }
7252 v3 = mpi_copy(v);
7253 if( mpi_test_bit(u, 0) ) { /* u is odd */
7254 t1 = mpi_alloc_set_ui(0);
7255 if( !odd ) {
7256 t2 = mpi_alloc_set_ui(1); t2->sign = 1;
7257 }
7258 t3 = mpi_copy(v); t3->sign = !t3->sign;
7259 goto Y4;
7260 }
7261 else {
7262 t1 = mpi_alloc_set_ui(1);
7263 if( !odd )
7264 t2 = mpi_alloc_set_ui(0);
7265 t3 = mpi_copy(u);
7266 }
7267 do {
7268 do {
7269 if( !odd ) {
7270 if( mpi_test_bit(t1, 0) || mpi_test_bit(t2, 0) ) { /* one is odd */
7271 mpi_add(t1, t1, v);
7272 mpi_sub(t2, t2, u);
7273 }
7274 mpi_rshift(t1, t1, 1);
7275 mpi_rshift(t2, t2, 1);
7276 mpi_rshift(t3, t3, 1);
7277 }
7278 else {
7279 if( mpi_test_bit(t1, 0) )
7280 mpi_add(t1, t1, v);
7281 mpi_rshift(t1, t1, 1);
7282 mpi_rshift(t3, t3, 1);
7283 }
7284 Y4:
7285 ;
7286 } while( !mpi_test_bit( t3, 0 ) ); /* while t3 is even */
7287
7288 if( !t3->sign ) {
7289 mpi_set(u1, t1);
7290 if( !odd )
7291 mpi_set(u2, t2);
7292 mpi_set(u3, t3);
7293 }
7294 else {
7295 mpi_sub(v1, v, t1);
7296 sign = u->sign; u->sign = !u->sign;
7297 if( !odd )
7298 mpi_sub(v2, u, t2);
7299 u->sign = sign;
7300 sign = t3->sign; t3->sign = !t3->sign;
7301 mpi_set(v3, t3);
7302 t3->sign = sign;
7303 }
7304 mpi_sub(t1, u1, v1);
7305 if( !odd )
7306 mpi_sub(t2, u2, v2);
7307 mpi_sub(t3, u3, v3);
7308 if( t1->sign ) {
7309 mpi_add(t1, t1, v);
7310 if( !odd )
7311 mpi_sub(t2, t2, u);
7312 }
7313 } while( mpi_cmp_ui( t3, 0 ) ); /* while t3 != 0 */
7314 /* mpi_lshift( u3, k ); */
7315 mpi_set(x, u1);
7316
7317 mpi_free(u1);
7318 mpi_free(v1);
7319 mpi_free(t1);
7320 if( !odd ) {
7321 mpi_free(u2);
7322 mpi_free(v2);
7323 mpi_free(t2);
7324 }
7325 mpi_free(u3);
7326 mpi_free(v3);
7327 mpi_free(t3);
7328
7329 mpi_free(u);
7330 mpi_free(v);
7331 #endif
7332 }
-
+ A87EBB2E2397F5903EAA0066A9ADF8F977BF7A67866CD181D0699B6D6A029880D86F349BE9CB9E6901D35B052BD871380E18AB19EFCF319C8A3662A93691856E
mpi/mpi-mpow.c
(0 . 0)(1 . 98)
7337 /* mpi-mpow.c - MPI functions
7338 * Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
7339 *
7340 * This file is part of GnuPG.
7341 *
7342 * GnuPG is free software; you can redistribute it and/or modify
7343 * it under the terms of the GNU General Public License as published by
7344 * the Free Software Foundation; either version 3 of the License, or
7345 * (at your option) any later version.
7346 *
7347 * GnuPG is distributed in the hope that it will be useful,
7348 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7349 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7350 * GNU General Public License for more details.
7351 *
7352 * You should have received a copy of the GNU General Public License
7353 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7354 */
7355
7356 #include <config.h>
7357 #include <stdio.h>
7358 #include <stdlib.h>
7359 #include "mpi-internal.h"
7360 #include "longlong.h"
7361 #include <assert.h>
7362
7363 static int
7364 build_index( MPI *exparray, int k, int i, int t )
7365 {
7366 int j, bitno;
7367 int idx = 0;
7368
7369 bitno = t-i;
7370 for(j=k-1; j >= 0; j-- ) {
7371 idx <<= 1;
7372 if( mpi_test_bit( exparray[j], bitno ) )
7373 idx |= 1;
7374 }
7375 return idx;
7376 }
7377
7378 /****************
7379 * RES = (BASE[0] ^ EXP[0]) * (BASE[1] ^ EXP[1]) * ... * mod M
7380 */
7381 void
7382 mpi_mulpowm( MPI res, MPI *basearray, MPI *exparray, MPI m)
7383 {
7384 int k; /* number of elements */
7385 int t; /* bit size of largest exponent */
7386 int i, j, idx;
7387 MPI *G; /* table with precomputed values of size 2^k */
7388 MPI tmp;
7389
7390 for(k=0; basearray[k]; k++ )
7391 ;
7392 assert(k);
7393 for(t=0, i=0; (tmp=exparray[i]); i++ ) {
7394 j = mpi_get_nbits(tmp);
7395 if( j > t )
7396 t = j;
7397 }
7398 assert(i==k);
7399 assert(t);
7400 assert( k < 10 );
7401
7402 G = xmalloc_clear( (1<<k) * sizeof *G );
7403 /* and calculate */
7404 tmp = mpi_alloc( mpi_get_nlimbs(m)+1 );
7405 mpi_set_ui( res, 1 );
7406 for(i = 1; i <= t; i++ ) {
7407 mpi_mulm(tmp, res, res, m );
7408 idx = build_index( exparray, k, i, t );
7409 assert( idx >= 0 && idx < (1<<k) );
7410 if( !G[idx] ) {
7411 if( !idx )
7412 G[0] = mpi_alloc_set_ui( 1 );
7413 else {
7414 for(j=0; j < k; j++ ) {
7415 if( (idx & (1<<j) ) ) {
7416 if( !G[idx] )
7417 G[idx] = mpi_copy( basearray[j] );
7418 else
7419 mpi_mulm( G[idx], G[idx], basearray[j], m );
7420 }
7421 }
7422 if( !G[idx] )
7423 G[idx] = mpi_alloc(0);
7424 }
7425 }
7426 mpi_mulm(res, tmp, G[idx], m );
7427 }
7428
7429 /* cleanup */
7430 mpi_free(tmp);
7431 for(i=0; i < (1<<k); i++ )
7432 mpi_free(G[i]);
7433 xfree(G);
7434 }
-
+ 8A56ADB14BCAC8D72E4454562A0455C241756EDE576D2CD4E8A42CFDFF5ABE7C803A5F1523945EE81D5A149B88D969739443D00165FDAAB7041BAC9BE10DC8CF
mpi/mpi-mul.c
(0 . 0)(1 . 214)
7439 /* mpi-mul.c - MPI functions
7440 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
7441 * Copyright (C) 1998, 2001 Free Software Foundation, Inc.
7442 *
7443 * This file is part of GnuPG.
7444 *
7445 * GnuPG is free software; you can redistribute it and/or modify
7446 * it under the terms of the GNU General Public License as published by
7447 * the Free Software Foundation; either version 3 of the License, or
7448 * (at your option) any later version.
7449 *
7450 * GnuPG is distributed in the hope that it will be useful,
7451 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7452 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7453 * GNU General Public License for more details.
7454 *
7455 * You should have received a copy of the GNU General Public License
7456 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7457 *
7458 * Note: This code is heavily based on the GNU MP Library.
7459 * Actually it's the same code with only minor changes in the
7460 * way the data is stored; this is to support the abstraction
7461 * of an optional secure memory allocation which may be used
7462 * to avoid revealing of sensitive data due to paging etc.
7463 * The GNU MP Library itself is published under the LGPL;
7464 * however I decided to publish this code under the plain GPL.
7465 */
7466
7467 #include <config.h>
7468 #include <stdio.h>
7469 #include <stdlib.h>
7470 #include "mpi-internal.h"
7471
7472
7473 void
7474 mpi_mul_ui( MPI prod, MPI mult, unsigned long small_mult )
7475 {
7476 mpi_size_t size, prod_size;
7477 mpi_ptr_t prod_ptr;
7478 mpi_limb_t cy;
7479 int sign;
7480
7481 size = mult->nlimbs;
7482 sign = mult->sign;
7483
7484 if( !size || !small_mult ) {
7485 prod->nlimbs = 0;
7486 prod->sign = 0;
7487 return;
7488 }
7489
7490 prod_size = size + 1;
7491 if( prod->alloced < prod_size )
7492 mpi_resize( prod, prod_size );
7493 prod_ptr = prod->d;
7494
7495 cy = mpihelp_mul_1( prod_ptr, mult->d, size, (mpi_limb_t)small_mult );
7496 if( cy )
7497 prod_ptr[size++] = cy;
7498 prod->nlimbs = size;
7499 prod->sign = sign;
7500 }
7501
7502
7503 void
7504 mpi_mul_2exp( MPI w, MPI u, unsigned long cnt)
7505 {
7506 mpi_size_t usize, wsize, limb_cnt;
7507 mpi_ptr_t wp;
7508 mpi_limb_t wlimb;
7509 int usign, wsign;
7510
7511 usize = u->nlimbs;
7512 usign = u->sign;
7513
7514 if( !usize ) {
7515 w->nlimbs = 0;
7516 w->sign = 0;
7517 return;
7518 }
7519
7520 limb_cnt = cnt / BITS_PER_MPI_LIMB;
7521 wsize = usize + limb_cnt + 1;
7522 if( w->alloced < wsize )
7523 mpi_resize(w, wsize );
7524 wp = w->d;
7525 wsize = usize + limb_cnt;
7526 wsign = usign;
7527
7528 cnt %= BITS_PER_MPI_LIMB;
7529 if( cnt ) {
7530 wlimb = mpihelp_lshift( wp + limb_cnt, u->d, usize, cnt );
7531 if( wlimb ) {
7532 wp[wsize] = wlimb;
7533 wsize++;
7534 }
7535 }
7536 else {
7537 MPN_COPY_DECR( wp + limb_cnt, u->d, usize );
7538 }
7539
7540 /* Zero all whole limbs at low end. Do it here and not before calling
7541 * mpn_lshift, not to lose for U == W. */
7542 MPN_ZERO( wp, limb_cnt );
7543
7544 w->nlimbs = wsize;
7545 w->sign = wsign;
7546 }
7547
7548
7549
7550 void
7551 mpi_mul( MPI w, MPI u, MPI v)
7552 {
7553 mpi_size_t usize, vsize, wsize;
7554 mpi_ptr_t up, vp, wp;
7555 mpi_limb_t cy;
7556 int usign, vsign, usecure, vsecure, sign_product;
7557 int assign_wp=0;
7558 mpi_ptr_t tmp_limb=NULL;
7559
7560
7561 if( u->nlimbs < v->nlimbs ) { /* Swap U and V. */
7562 usize = v->nlimbs;
7563 usign = v->sign;
7564 usecure = mpi_is_secure(v);
7565 up = v->d;
7566 vsize = u->nlimbs;
7567 vsign = u->sign;
7568 vsecure = mpi_is_secure(u);
7569 vp = u->d;
7570 }
7571 else {
7572 usize = u->nlimbs;
7573 usign = u->sign;
7574 usecure = mpi_is_secure(u);
7575 up = u->d;
7576 vsize = v->nlimbs;
7577 vsign = v->sign;
7578 vsecure = mpi_is_secure(v);
7579 vp = v->d;
7580 }
7581 sign_product = usign ^ vsign;
7582 wp = w->d;
7583
7584 /* Ensure W has space enough to store the result. */
7585 wsize = usize + vsize;
7586 if ( !mpi_is_secure (w) && (mpi_is_secure (u) || mpi_is_secure (v)) ) {
7587 /* w is not allocated in secure space but u or v is. To make sure
7588 * that no temporray results are stored in w, we temporary use
7589 * a newly allocated limb space for w */
7590 wp = mpi_alloc_limb_space( wsize, 1 );
7591 assign_wp = 2; /* mark it as 2 so that we can later copy it back to
7592 * mormal memory */
7593 }
7594 else if( w->alloced < wsize ) {
7595 if( wp == up || wp == vp ) {
7596 wp = mpi_alloc_limb_space( wsize, mpi_is_secure(w) );
7597 assign_wp = 1;
7598 }
7599 else {
7600 mpi_resize(w, wsize );
7601 wp = w->d;
7602 }
7603 }
7604 else { /* Make U and V not overlap with W. */
7605 if( wp == up ) {
7606 /* W and U are identical. Allocate temporary space for U. */
7607 up = tmp_limb = mpi_alloc_limb_space( usize, usecure );
7608 /* Is V identical too? Keep it identical with U. */
7609 if( wp == vp )
7610 vp = up;
7611 /* Copy to the temporary space. */
7612 MPN_COPY( up, wp, usize );
7613 }
7614 else if( wp == vp ) {
7615 /* W and V are identical. Allocate temporary space for V. */
7616 vp = tmp_limb = mpi_alloc_limb_space( vsize, vsecure );
7617 /* Copy to the temporary space. */
7618 MPN_COPY( vp, wp, vsize );
7619 }
7620 }
7621
7622 if( !vsize )
7623 wsize = 0;
7624 else {
7625 cy = mpihelp_mul( wp, up, usize, vp, vsize );
7626 wsize -= cy? 0:1;
7627 }
7628
7629 if( assign_wp ) {
7630 if (assign_wp == 2) {
7631 /* copy the temp wp from secure memory back to normal memory */
7632 mpi_ptr_t tmp_wp = mpi_alloc_limb_space (wsize, 0);
7633 MPN_COPY (tmp_wp, wp, wsize);
7634 mpi_free_limb_space (wp);
7635 wp = tmp_wp;
7636 }
7637 mpi_assign_limb_space( w, wp, wsize );
7638 }
7639 w->nlimbs = wsize;
7640 w->sign = sign_product;
7641 if( tmp_limb )
7642 mpi_free_limb_space( tmp_limb );
7643 }
7644
7645
7646 void
7647 mpi_mulm( MPI w, MPI u, MPI v, MPI m)
7648 {
7649 mpi_mul(w, u, v);
7650 mpi_fdiv_r( w, w, m );
7651 }
7652
-
+ 8341923461226EC55DE5B29209CC03051587DE11885CB49433FF4C0EBA2160798B7DC27573B9BC363EE0954A8FC08CBD21AF3F655A9C0BC8AA294A74F80EB2C9
mpi/mpi-pow.c
(0 . 0)(1 . 294)
7657 /* mpi-pow.c - MPI functions
7658 * Copyright (C) 1994, 1996, 1998, 2000 Free Software Foundation, Inc.
7659 *
7660 * This file is part of GnuPG.
7661 *
7662 * GnuPG is free software; you can redistribute it and/or modify
7663 * it under the terms of the GNU General Public License as published by
7664 * the Free Software Foundation; either version 3 of the License, or
7665 * (at your option) any later version.
7666 *
7667 * GnuPG is distributed in the hope that it will be useful,
7668 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7669 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7670 * GNU General Public License for more details.
7671 *
7672 * You should have received a copy of the GNU General Public License
7673 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7674 *
7675 * Note: This code is heavily based on the GNU MP Library.
7676 * Actually it's the same code with only minor changes in the
7677 * way the data is stored; this is to support the abstraction
7678 * of an optional secure memory allocation which may be used
7679 * to avoid revealing of sensitive data due to paging etc.
7680 * The GNU MP Library itself is published under the LGPL;
7681 * however I decided to publish this code under the plain GPL.
7682 */
7683
7684 #include <config.h>
7685 #include <stdio.h>
7686 #include <stdlib.h>
7687 #include <string.h>
7688 #include "mpi-internal.h"
7689 #include "longlong.h"
7690 #include <assert.h>
7691
7692
7693 /****************
7694 * RES = BASE ^ EXP mod MOD
7695 */
7696 void
7697 mpi_powm( MPI res, MPI base, MPI exponent, MPI mod)
7698 {
7699 mpi_ptr_t rp, ep, mp, bp;
7700 mpi_size_t esize, msize, bsize, rsize;
7701 int esign, msign, bsign, rsign;
7702 int esec, msec, bsec, rsec;
7703 mpi_size_t size;
7704 int mod_shift_cnt;
7705 int negative_result;
7706 mpi_ptr_t mp_marker=NULL, bp_marker=NULL, ep_marker=NULL;
7707 mpi_ptr_t xp_marker=NULL;
7708 int assign_rp=0;
7709 mpi_ptr_t tspace = NULL;
7710 mpi_size_t tsize=0; /* to avoid compiler warning */
7711 /* fixme: we should check that the warning is void*/
7712
7713 esize = exponent->nlimbs;
7714 msize = mod->nlimbs;
7715 size = 2 * msize;
7716 esign = exponent->sign;
7717 msign = mod->sign;
7718
7719 esec = mpi_is_secure(exponent);
7720 msec = mpi_is_secure(mod);
7721 bsec = mpi_is_secure(base);
7722 rsec = mpi_is_secure(res);
7723
7724 rp = res->d;
7725 ep = exponent->d;
7726
7727 if( !msize )
7728 msize = 1 / msize; /* provoke a signal */
7729
7730 if( !esize ) {
7731 /* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0
7732 * depending on if MOD equals 1. */
7733 rp[0] = 1;
7734 res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;
7735 res->sign = 0;
7736 goto leave;
7737 }
7738
7739 /* Normalize MOD (i.e. make its most significant bit set) as required by
7740 * mpn_divrem. This will make the intermediate values in the calculation
7741 * slightly larger, but the correct result is obtained after a final
7742 * reduction using the original MOD value. */
7743 mp = mp_marker = mpi_alloc_limb_space(msize, msec);
7744 count_leading_zeros( mod_shift_cnt, mod->d[msize-1] );
7745 if( mod_shift_cnt )
7746 mpihelp_lshift( mp, mod->d, msize, mod_shift_cnt );
7747 else
7748 MPN_COPY( mp, mod->d, msize );
7749
7750 bsize = base->nlimbs;
7751 bsign = base->sign;
7752 if( bsize > msize ) { /* The base is larger than the module. Reduce it. */
7753 /* Allocate (BSIZE + 1) with space for remainder and quotient.
7754 * (The quotient is (bsize - msize + 1) limbs.) */
7755 bp = bp_marker = mpi_alloc_limb_space( bsize + 1, bsec );
7756 MPN_COPY( bp, base->d, bsize );
7757 /* We don't care about the quotient, store it above the remainder,
7758 * at BP + MSIZE. */
7759 mpihelp_divrem( bp + msize, 0, bp, bsize, mp, msize );
7760 bsize = msize;
7761 /* Canonicalize the base, since we are going to multiply with it
7762 * quite a few times. */
7763 MPN_NORMALIZE( bp, bsize );
7764 }
7765 else
7766 bp = base->d;
7767
7768 if( !bsize ) {
7769 res->nlimbs = 0;
7770 res->sign = 0;
7771 goto leave;
7772 }
7773
7774 if( res->alloced < size ) {
7775 /* We have to allocate more space for RES. If any of the input
7776 * parameters are identical to RES, defer deallocation of the old
7777 * space. */
7778 if( rp == ep || rp == mp || rp == bp ) {
7779 rp = mpi_alloc_limb_space( size, rsec );
7780 assign_rp = 1;
7781 }
7782 else {
7783 mpi_resize( res, size );
7784 rp = res->d;
7785 }
7786 }
7787 else { /* Make BASE, EXPONENT and MOD not overlap with RES. */
7788 if( rp == bp ) {
7789 /* RES and BASE are identical. Allocate temp. space for BASE. */
7790 assert( !bp_marker );
7791 bp = bp_marker = mpi_alloc_limb_space( bsize, bsec );
7792 MPN_COPY(bp, rp, bsize);
7793 }
7794 if( rp == ep ) {
7795 /* RES and EXPONENT are identical.
7796 Allocate temp. space for EXPONENT. */
7797 ep = ep_marker = mpi_alloc_limb_space( esize, esec );
7798 MPN_COPY(ep, rp, esize);
7799 }
7800 if( rp == mp ) {
7801 /* RES and MOD are identical. Allocate temporary space for MOD.*/
7802 assert( !mp_marker );
7803 mp = mp_marker = mpi_alloc_limb_space( msize, msec );
7804 MPN_COPY(mp, rp, msize);
7805 }
7806 }
7807
7808 MPN_COPY( rp, bp, bsize );
7809 rsize = bsize;
7810 rsign = bsign;
7811
7812 {
7813 mpi_size_t i;
7814 mpi_ptr_t xp = xp_marker = mpi_alloc_limb_space( 2 * (msize + 1), msec );
7815 int c;
7816 mpi_limb_t e;
7817 mpi_limb_t carry_limb;
7818 struct karatsuba_ctx karactx;
7819
7820 memset( &karactx, 0, sizeof karactx );
7821 negative_result = (ep[0] & 1) && base->sign;
7822
7823 i = esize - 1;
7824 e = ep[i];
7825 count_leading_zeros (c, e);
7826 e = (e << c) << 1; /* shift the exp bits to the left, lose msb */
7827 c = BITS_PER_MPI_LIMB - 1 - c;
7828
7829 /* Main loop.
7830 *
7831 * Make the result be pointed to alternately by XP and RP. This
7832 * helps us avoid block copying, which would otherwise be necessary
7833 * with the overlap restrictions of mpihelp_divmod. With 50% probability
7834 * the result after this loop will be in the area originally pointed
7835 * by RP (==RES->d), and with 50% probability in the area originally
7836 * pointed to by XP.
7837 */
7838
7839 for(;;) {
7840 while( c ) {
7841 mpi_ptr_t tp;
7842 mpi_size_t xsize;
7843
7844 /*mpihelp_mul_n(xp, rp, rp, rsize);*/
7845 if( rsize < KARATSUBA_THRESHOLD )
7846 mpih_sqr_n_basecase( xp, rp, rsize );
7847 else {
7848 if( !tspace ) {
7849 tsize = 2 * rsize;
7850 tspace = mpi_alloc_limb_space( tsize, 0 );
7851 }
7852 else if( tsize < (2*rsize) ) {
7853 mpi_free_limb_space( tspace );
7854 tsize = 2 * rsize;
7855 tspace = mpi_alloc_limb_space( tsize, 0 );
7856 }
7857 mpih_sqr_n( xp, rp, rsize, tspace );
7858 }
7859
7860 xsize = 2 * rsize;
7861 if( xsize > msize ) {
7862 mpihelp_divrem(xp + msize, 0, xp, xsize, mp, msize);
7863 xsize = msize;
7864 }
7865
7866 tp = rp; rp = xp; xp = tp;
7867 rsize = xsize;
7868
7869 if( (mpi_limb_signed_t)e < 0 ) {
7870 /*mpihelp_mul( xp, rp, rsize, bp, bsize );*/
7871 if( bsize < KARATSUBA_THRESHOLD ) {
7872 mpihelp_mul( xp, rp, rsize, bp, bsize );
7873 }
7874 else {
7875 mpihelp_mul_karatsuba_case(
7876 xp, rp, rsize, bp, bsize, &karactx );
7877 }
7878
7879 xsize = rsize + bsize;
7880 if( xsize > msize ) {
7881 mpihelp_divrem(xp + msize, 0, xp, xsize, mp, msize);
7882 xsize = msize;
7883 }
7884
7885 tp = rp; rp = xp; xp = tp;
7886 rsize = xsize;
7887 }
7888 e <<= 1;
7889 c--;
7890 }
7891
7892 i--;
7893 if( i < 0 )
7894 break;
7895 e = ep[i];
7896 c = BITS_PER_MPI_LIMB;
7897 }
7898
7899 /* We shifted MOD, the modulo reduction argument, left MOD_SHIFT_CNT
7900 * steps. Adjust the result by reducing it with the original MOD.
7901 *
7902 * Also make sure the result is put in RES->d (where it already
7903 * might be, see above).
7904 */
7905 if( mod_shift_cnt ) {
7906 carry_limb = mpihelp_lshift( res->d, rp, rsize, mod_shift_cnt);
7907 rp = res->d;
7908 if( carry_limb ) {
7909 rp[rsize] = carry_limb;
7910 rsize++;
7911 }
7912 }
7913 else {
7914 MPN_COPY( res->d, rp, rsize);
7915 rp = res->d;
7916 }
7917
7918 if( rsize >= msize ) {
7919 mpihelp_divrem(rp + msize, 0, rp, rsize, mp, msize);
7920 rsize = msize;
7921 }
7922
7923 /* Remove any leading zero words from the result. */
7924 if( mod_shift_cnt )
7925 mpihelp_rshift( rp, rp, rsize, mod_shift_cnt);
7926 MPN_NORMALIZE (rp, rsize);
7927
7928 mpihelp_release_karatsuba_ctx( &karactx );
7929 }
7930
7931 if( negative_result && rsize ) {
7932 if( mod_shift_cnt )
7933 mpihelp_rshift( mp, mp, msize, mod_shift_cnt);
7934 mpihelp_sub( rp, mp, msize, rp, rsize);
7935 rsize = msize;
7936 rsign = msign;
7937 MPN_NORMALIZE(rp, rsize);
7938 }
7939 res->nlimbs = rsize;
7940 res->sign = rsign;
7941
7942 leave:
7943 if( assign_rp ) mpi_assign_limb_space( res, rp, size );
7944 if( mp_marker ) mpi_free_limb_space( mp_marker );
7945 if( bp_marker ) mpi_free_limb_space( bp_marker );
7946 if( ep_marker ) mpi_free_limb_space( ep_marker );
7947 if( xp_marker ) mpi_free_limb_space( xp_marker );
7948 if( tspace ) mpi_free_limb_space( tspace );
7949 }
7950
-
+ AFFA0E93E6625CAD75CD10C454B493CBEBF061AECA3185E45B6571A26AE10F03947A1EF363C0898609F95CC737053E45A73926B22F14F4EC6A800410915D3FF9
mpi/mpi-scan.c
(0 . 0)(1 . 138)
7955 /* mpi-scan.c - MPI functions
7956 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
7957 *
7958 * This file is part of GnuPG.
7959 *
7960 * GnuPG is free software; you can redistribute it and/or modify
7961 * it under the terms of the GNU General Public License as published by
7962 * the Free Software Foundation; either version 3 of the License, or
7963 * (at your option) any later version.
7964 *
7965 * GnuPG is distributed in the hope that it will be useful,
7966 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7967 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
7968 * GNU General Public License for more details.
7969 *
7970 * You should have received a copy of the GNU General Public License
7971 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7972 */
7973
7974 #include <config.h>
7975 #include <stdio.h>
7976 #include <stdlib.h>
7977 #include "mpi-internal.h"
7978 #include "longlong.h"
7979
7980 /****************
7981 * Scan through an mpi and return byte for byte. a -1 is returned to indicate
7982 * the end of the mpi. Scanning is done from the lsb to the msb, returned
7983 * values are in the range of 0 .. 255.
7984 *
7985 * FIXME: This code is VERY ugly!
7986 */
7987 #if 0 /* Code is not used */
7988 int
7989 mpi_getbyte( MPI a, unsigned idx )
7990 {
7991 int i, j;
7992 unsigned n;
7993 mpi_ptr_t ap;
7994 mpi_limb_t limb;
7995
7996 ap = a->d;
7997 for(n=0,i=0; i < a->nlimbs; i++ ) {
7998 limb = ap[i];
7999 for( j=0; j < BYTES_PER_MPI_LIMB; j++, n++ )
8000 if( n == idx )
8001 return (limb >> j*8) & 0xff;
8002 }
8003 return -1;
8004 }
8005 #endif /* Code is not used */
8006
8007
8008 /****************
8009 * Put a value at position IDX into A. idx counts from lsb to msb
8010 */
8011 /* FIXME: There is a problem with the long constants which should have
8012 a LL prefix or better the macros we use at other places. */
8013 #if 0 /* Code is not used */
8014 void
8015 mpi_putbyte( MPI a, unsigned idx, int xc )
8016 {
8017
8018 int i, j;
8019 unsigned n;
8020 mpi_ptr_t ap;
8021 mpi_limb_t limb, c;
8022
8023 c = xc & 0xff;
8024 ap = a->d;
8025 for(n=0,i=0; i < a->alloced; i++ ) {
8026 limb = ap[i];
8027 for( j=0; j < BYTES_PER_MPI_LIMB; j++, n++ )
8028 if( n == idx ) {
8029 #if BYTES_PER_MPI_LIMB == 4
8030 if( j == 0 )
8031 limb = (limb & 0xffffff00) | c;
8032 else if( j == 1 )
8033 limb = (limb & 0xffff00ff) | (c<<8);
8034 else if( j == 2 )
8035 limb = (limb & 0xff00ffff) | (c<<16);
8036 else
8037 limb = (limb & 0x00ffffff) | (c<<24);
8038 #elif BYTES_PER_MPI_LIMB == 8
8039 if( j == 0 )
8040 limb = (limb & 0xffffffffffffff00) | c;
8041 else if( j == 1 )
8042 limb = (limb & 0xffffffffffff00ff) | (c<<8);
8043 else if( j == 2 )
8044 limb = (limb & 0xffffffffff00ffff) | (c<<16);
8045 else if( j == 3 )
8046 limb = (limb & 0xffffffff00ffffff) | (c<<24);
8047 else if( j == 4 )
8048 limb = (limb & 0xffffff00ffffffff) | (c<<32);
8049 else if( j == 5 )
8050 limb = (limb & 0xffff00ffffffffff) | (c<<40);
8051 else if( j == 6 )
8052 limb = (limb & 0xff00ffffffffffff) | (c<<48);
8053 else
8054 limb = (limb & 0x00ffffffffffffff) | (c<<56);
8055 #else
8056 #error please enhance this function, its ugly - i know.
8057 #endif
8058 if( a->nlimbs <= i )
8059 a->nlimbs = i+1;
8060 ap[i] = limb;
8061 return;
8062 }
8063 }
8064 abort(); /* index out of range */
8065 }
8066 #endif /* Code is not used */
8067
8068
8069 /****************
8070 * Count the number of zerobits at the low end of A
8071 */
8072 unsigned int
8073 mpi_trailing_zeros( MPI a )
8074 {
8075 unsigned n, count = 0;
8076
8077 for(n=0; n < a->nlimbs; n++ ) {
8078 if( a->d[n] ) {
8079 unsigned nn;
8080 mpi_limb_t alimb = a->d[n];
8081
8082 count_trailing_zeros( nn, alimb );
8083 count += nn;
8084 break;
8085 }
8086 count += BITS_PER_MPI_LIMB;
8087 }
8088 return count;
8089
8090 }
8091
8092
-
+ 6A4860EA723098A2E2BA703D8748F6D26C22D1AE72647A5CCCA67AB93976390B0D992BA870796BE3DA3B736B1A11B36F700A93214AE5926EC2652D1EDEE390A3
mpi/mpicoder.c
(0 . 0)(1 . 472)
8097 /* mpicoder.c - Coder for the external representation of MPIs
8098 * Copyright (C) 1998, 1999, 2005 Free Software Foundation, Inc.
8099 *
8100 * This file is part of GnuPG.
8101 *
8102 * GnuPG is free software; you can redistribute it and/or modify
8103 * it under the terms of the GNU General Public License as published by
8104 * the Free Software Foundation; either version 3 of the License, or
8105 * (at your option) any later version.
8106 *
8107 * GnuPG is distributed in the hope that it will be useful,
8108 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8109 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8110 * GNU General Public License for more details.
8111 *
8112 * You should have received a copy of the GNU General Public License
8113 * along with this program; if not, see <http://www.gnu.org/licenses/>.
8114 */
8115
8116 #include <config.h>
8117 #include <stdio.h>
8118 #include <string.h>
8119 #include <stdlib.h>
8120 #include <assert.h>
8121
8122 #include "mpi.h"
8123 #include "mpi-internal.h"
8124 #include "iobuf.h"
8125 #include "memory.h"
8126 #include "util.h"
8127
8128 #ifdef M_DEBUG
8129 #undef mpi_read
8130 #endif
8131
8132 #define MAX_EXTERN_MPI_BITS 16384
8133
8134 /****************
8135 * write an mpi to out.
8136 */
8137 int
8138 mpi_write( IOBUF out, MPI a )
8139 {
8140 int rc;
8141 unsigned nbits = mpi_get_nbits(a);
8142 byte *p, *buf;
8143 unsigned n;
8144
8145 if( nbits > MAX_EXTERN_MPI_BITS )
8146 log_bug("mpi_encode: mpi too large (%u bits)\n", nbits);
8147
8148 iobuf_put(out, (nbits >>8) );
8149 iobuf_put(out, (nbits) );
8150
8151 p = buf = mpi_get_buffer( a, &n, NULL );
8152 rc = iobuf_write( out, p, n );
8153 xfree(buf);
8154 return rc;
8155 }
8156
8157
8158 /****************
8159 * Read an external representation of an mpi and return the MPI
8160 * The external format is a 16 bit unsigned value stored in network byte order,
8161 * giving the number of bits for the following integer. The integer is stored
8162 * with MSB first (left padded with zeroes to align on a byte boundary).
8163 */
8164 MPI
8165 #ifdef M_DEBUG
8166 mpi_debug_read(IOBUF inp, unsigned *ret_nread, int secure, const char *info)
8167 #else
8168 mpi_read(IOBUF inp, unsigned *ret_nread, int secure)
8169 #endif
8170 {
8171 int c, i, j;
8172 unsigned int nmax = *ret_nread;
8173 unsigned nbits, nbytes, nlimbs, nread=0;
8174 mpi_limb_t a;
8175 MPI val = NULL;
8176
8177 if (nread == nmax)
8178 goto overflow;
8179 if( (c = iobuf_get(inp)) == -1 )
8180 goto leave;
8181 nread++;
8182 nbits = c << 8;
8183
8184 if (nread == nmax)
8185 goto overflow;
8186 if( (c = iobuf_get(inp)) == -1 )
8187 goto leave;
8188 nread++;
8189 nbits |= c;
8190
8191 if( nbits > MAX_EXTERN_MPI_BITS ) {
8192 log_error("mpi too large for this implementation (%u bits)\n", nbits);
8193 goto leave;
8194 }
8195
8196 nbytes = (nbits+7) / 8;
8197 nlimbs = (nbytes+BYTES_PER_MPI_LIMB-1) / BYTES_PER_MPI_LIMB;
8198 #ifdef M_DEBUG
8199 val = secure? mpi_debug_alloc_secure( nlimbs, info )
8200 : mpi_debug_alloc( nlimbs, info );
8201 #else
8202 val = secure? mpi_alloc_secure( nlimbs )
8203 : mpi_alloc( nlimbs );
8204 #endif
8205 i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
8206 i %= BYTES_PER_MPI_LIMB;
8207 val->nbits = nbits;
8208 j= val->nlimbs = nlimbs;
8209 val->sign = 0;
8210 for( ; j > 0; j-- ) {
8211 a = 0;
8212 for(; i < BYTES_PER_MPI_LIMB; i++ ) {
8213 if (nread == nmax) {
8214 #ifdef M_DEBUG
8215 mpi_debug_free (val);
8216 #else
8217 mpi_free (val);
8218 #endif
8219 val = NULL;
8220 goto overflow;
8221 }
8222 a <<= 8;
8223 a |= iobuf_get(inp) & 0xff; nread++;
8224 }
8225 i = 0;
8226 val->d[j-1] = a;
8227 }
8228
8229 leave:
8230 *ret_nread = nread;
8231 return val;
8232 overflow:
8233 log_error ("mpi larger than indicated length (%u bytes)\n", nmax);
8234 *ret_nread = nread;
8235 return val;
8236 }
8237
8238
8239 MPI
8240 mpi_read_from_buffer(byte *buffer, unsigned int *ret_nread, int secure)
8241 {
8242 int i, j;
8243 unsigned nbits, nbytes, nlimbs, nread=0;
8244 mpi_limb_t a;
8245 MPI val = NULL;
8246
8247 if( *ret_nread < 2 )
8248 goto leave;
8249 nbits = buffer[0] << 8 | buffer[1];
8250 if( nbits > MAX_EXTERN_MPI_BITS ) {
8251 log_info ("mpi too large (%u bits)\n", nbits);
8252 goto leave;
8253 }
8254 buffer += 2;
8255 nread = 2;
8256
8257 nbytes = (nbits+7) / 8;
8258 nlimbs = (nbytes+BYTES_PER_MPI_LIMB-1) / BYTES_PER_MPI_LIMB;
8259 val = secure? mpi_alloc_secure( nlimbs )
8260 : mpi_alloc( nlimbs );
8261 i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
8262 i %= BYTES_PER_MPI_LIMB;
8263 val->nbits = nbits;
8264 j= val->nlimbs = nlimbs;
8265 val->sign = 0;
8266 for( ; j > 0; j-- ) {
8267 a = 0;
8268 for(; i < BYTES_PER_MPI_LIMB; i++ ) {
8269 if( ++nread > *ret_nread ) {
8270 /* This (as well as the above error condition) may
8271 happen if we use this function to parse a decrypted
8272 MPI which didn't turn out to be a real MPI - possible
8273 because the supplied key was wrong but the OpenPGP
8274 checksum didn't caught it. */
8275 log_info ("mpi larger than buffer\n");
8276 mpi_free (val);
8277 val = NULL;
8278 goto leave;
8279 }
8280 a <<= 8;
8281 a |= *buffer++;
8282 }
8283 i = 0;
8284 val->d[j-1] = a;
8285 }
8286
8287 leave:
8288 *ret_nread = nread;
8289 return val;
8290 }
8291
8292
8293 /****************
8294 * Make an mpi from a character string.
8295 */
8296 int
8297 mpi_fromstr(MPI val, const char *str)
8298 {
8299 int hexmode=0, sign=0, prepend_zero=0, i, j, c, c1, c2;
8300 unsigned nbits, nbytes, nlimbs;
8301 mpi_limb_t a;
8302
8303 if( *str == '-' ) {
8304 sign = 1;
8305 str++;
8306 }
8307 if( *str == '0' && str[1] == 'x' )
8308 hexmode = 1;
8309 else
8310 return 1; /* other bases are not yet supported */
8311 str += 2;
8312
8313 nbits = strlen(str)*4;
8314 if( nbits % 8 )
8315 prepend_zero = 1;
8316 nbytes = (nbits+7) / 8;
8317 nlimbs = (nbytes+BYTES_PER_MPI_LIMB-1) / BYTES_PER_MPI_LIMB;
8318 if( val->alloced < nlimbs )
8319 mpi_resize(val, nlimbs );
8320 i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
8321 i %= BYTES_PER_MPI_LIMB;
8322 j= val->nlimbs = nlimbs;
8323 val->sign = sign;
8324 for( ; j > 0; j-- ) {
8325 a = 0;
8326 for(; i < BYTES_PER_MPI_LIMB; i++ ) {
8327 if( prepend_zero ) {
8328 c1 = '0';
8329 prepend_zero = 0;
8330 }
8331 else
8332 c1 = *str++;
8333 assert(c1);
8334 c2 = *str++;
8335 assert(c2);
8336 if( c1 >= '0' && c1 <= '9' )
8337 c = c1 - '0';
8338 else if( c1 >= 'a' && c1 <= 'f' )
8339 c = c1 - 'a' + 10;
8340 else if( c1 >= 'A' && c1 <= 'F' )
8341 c = c1 - 'A' + 10;
8342 else {
8343 mpi_clear(val);
8344 return 1;
8345 }
8346 c <<= 4;
8347 if( c2 >= '0' && c2 <= '9' )
8348 c |= c2 - '0';
8349 else if( c2 >= 'a' && c2 <= 'f' )
8350 c |= c2 - 'a' + 10;
8351 else if( c2 >= 'A' && c2 <= 'F' )
8352 c |= c2 - 'A' + 10;
8353 else {
8354 mpi_clear(val);
8355 return 1;
8356 }
8357 a <<= 8;
8358 a |= c;
8359 }
8360 i = 0;
8361 val->d[j-1] = a;
8362 }
8363
8364 return 0;
8365 }
8366
8367
8368 /****************
8369 * print an MPI to the given stream and return the number of characters
8370 * printed.
8371 */
8372 int
8373 mpi_print( FILE *fp, MPI a, int mode )
8374 {
8375 int i, n=0;
8376
8377 if( a == NULL )
8378 return fprintf(fp, "[MPI_NULL]");
8379 if( !mode ) {
8380 unsigned int n1;
8381
8382 n1 = mpi_get_nbits(a);
8383 n += fprintf(fp, "[%u bits]", n1);
8384 }
8385 else {
8386 if( a->sign )
8387 putc('-', fp);
8388 #if BYTES_PER_MPI_LIMB == 2
8389 #define X "4"
8390 #elif BYTES_PER_MPI_LIMB == 4
8391 #define X "8"
8392 #elif BYTES_PER_MPI_LIMB == 8
8393 #define X "16"
8394 #else
8395 #error please define the format here
8396 #endif
8397 for(i=a->nlimbs; i > 0 ; i-- ) {
8398 n += fprintf(fp, i!=a->nlimbs? "%0" X "lX":"%lX", (ulong)a->d[i-1]);
8399 #undef X
8400 }
8401 if( !a->nlimbs )
8402 putc('0', fp );
8403 }
8404 return n;
8405 }
8406
8407
8408 void
8409 g10_log_mpidump( const char *text, MPI a )
8410 {
8411 FILE *fp = log_stream();
8412
8413 g10_log_print_prefix(text);
8414 mpi_print(fp, a, 1 );
8415 fputc('\n', fp);
8416 }
8417
8418 /****************
8419 * Special function to get the low 8 bytes from an mpi.
8420 * This can be used as a keyid; KEYID is an 2 element array.
8421 * Return the low 4 bytes.
8422 */
8423 u32
8424 mpi_get_keyid( MPI a, u32 *keyid )
8425 {
8426 #if BYTES_PER_MPI_LIMB == 4
8427 if( keyid ) {
8428 keyid[0] = a->nlimbs >= 2? a->d[1] : 0;
8429 keyid[1] = a->nlimbs >= 1? a->d[0] : 0;
8430 }
8431 return a->nlimbs >= 1? a->d[0] : 0;
8432 #elif BYTES_PER_MPI_LIMB == 8
8433 if( keyid ) {
8434 keyid[0] = a->nlimbs? (u32)(a->d[0] >> 32) : 0;
8435 keyid[1] = a->nlimbs? (u32)(a->d[0] & 0xffffffff) : 0;
8436 }
8437 return a->nlimbs? (u32)(a->d[0] & 0xffffffff) : 0;
8438 #else
8439 #error Make this function work with other LIMB sizes
8440 #endif
8441 }
8442
8443
8444 /****************
8445 * Return an xmalloced buffer with the MPI (msb first).
8446 * NBYTES receives the length of this buffer. Caller must free the
8447 * return string (This function does return a 0 byte buffer with NBYTES
8448 * set to zero if the value of A is zero. If sign is not NULL, it will
8449 * be set to the sign of the A.
8450 */
8451 static byte *
8452 do_get_buffer( MPI a, unsigned *nbytes, int *sign, int force_secure )
8453 {
8454 byte *p, *buffer;
8455 mpi_limb_t alimb;
8456 int i;
8457 unsigned int n;
8458
8459 if( sign )
8460 *sign = a->sign;
8461 *nbytes = n = a->nlimbs * BYTES_PER_MPI_LIMB;
8462 if (!n)
8463 n++; /* avoid zero length allocation */
8464 p = buffer = force_secure || mpi_is_secure(a) ? xmalloc_secure(n)
8465 : xmalloc(n);
8466
8467 for(i=a->nlimbs-1; i >= 0; i-- ) {
8468 alimb = a->d[i];
8469 #if BYTES_PER_MPI_LIMB == 4
8470 *p++ = alimb >> 24;
8471 *p++ = alimb >> 16;
8472 *p++ = alimb >> 8;
8473 *p++ = alimb ;
8474 #elif BYTES_PER_MPI_LIMB == 8
8475 *p++ = alimb >> 56;
8476 *p++ = alimb >> 48;
8477 *p++ = alimb >> 40;
8478 *p++ = alimb >> 32;
8479 *p++ = alimb >> 24;
8480 *p++ = alimb >> 16;
8481 *p++ = alimb >> 8;
8482 *p++ = alimb ;
8483 #else
8484 #error please implement for this limb size.
8485 #endif
8486 }
8487
8488 /* this is sub-optimal but we need to do the shift operation
8489 * because the caller has to free the returned buffer */
8490 for(p=buffer; !*p && *nbytes; p++, --*nbytes )
8491 ;
8492 if( p != buffer )
8493 memmove(buffer,p, *nbytes);
8494
8495 return buffer;
8496 }
8497
8498
8499 byte *
8500 mpi_get_buffer( MPI a, unsigned *nbytes, int *sign )
8501 {
8502 return do_get_buffer( a, nbytes, sign, 0 );
8503 }
8504
8505 byte *
8506 mpi_get_secure_buffer( MPI a, unsigned *nbytes, int *sign )
8507 {
8508 return do_get_buffer( a, nbytes, sign, 1 );
8509 }
8510
8511 /****************
8512 * Use BUFFER to update MPI.
8513 */
8514 void
8515 mpi_set_buffer( MPI a, const byte *buffer, unsigned nbytes, int sign )
8516 {
8517 const byte *p;
8518 mpi_limb_t alimb;
8519 int nlimbs;
8520 int i;
8521
8522 nlimbs = (nbytes + BYTES_PER_MPI_LIMB - 1) / BYTES_PER_MPI_LIMB;
8523 RESIZE_IF_NEEDED(a, nlimbs);
8524 a->sign = sign;
8525
8526 for(i=0, p = buffer+nbytes-1; p >= buffer+BYTES_PER_MPI_LIMB; ) {
8527 #if BYTES_PER_MPI_LIMB == 4
8528 alimb = (mpi_limb_t)*p-- ;
8529 alimb |= (mpi_limb_t)*p-- << 8 ;
8530 alimb |= (mpi_limb_t)*p-- << 16 ;
8531 alimb |= (mpi_limb_t)*p-- << 24 ;
8532 #elif BYTES_PER_MPI_LIMB == 8
8533 alimb = (mpi_limb_t)*p-- ;
8534 alimb |= (mpi_limb_t)*p-- << 8 ;
8535 alimb |= (mpi_limb_t)*p-- << 16 ;
8536 alimb |= (mpi_limb_t)*p-- << 24 ;
8537 alimb |= (mpi_limb_t)*p-- << 32 ;
8538 alimb |= (mpi_limb_t)*p-- << 40 ;
8539 alimb |= (mpi_limb_t)*p-- << 48 ;
8540 alimb |= (mpi_limb_t)*p-- << 56 ;
8541 #else
8542 #error please implement for this limb size.
8543 #endif
8544 a->d[i++] = alimb;
8545 }
8546 if( p >= buffer ) {
8547 #if BYTES_PER_MPI_LIMB == 4
8548 alimb = *p-- ;
8549 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 8 ;
8550 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 16 ;
8551 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 24 ;
8552 #elif BYTES_PER_MPI_LIMB == 8
8553 alimb = (mpi_limb_t)*p-- ;
8554 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 8 ;
8555 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 16 ;
8556 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 24 ;
8557 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 32 ;
8558 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 40 ;
8559 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 48 ;
8560 if( p >= buffer ) alimb |= (mpi_limb_t)*p-- << 56 ;
8561 #else
8562 #error please implement for this limb size.
8563 #endif
8564 a->d[i++] = alimb;
8565 }
8566 a->nlimbs = i;
8567 assert( i == nlimbs );
8568 }
-
+ FB06EA790BD2B2C18013B3FB51F05A5C1577F45FDD67644E7745C3373FA26FA90DE8F30FD9221E978BA9676423ED1C4C27C0407F22A50E10F216AE9BBF4AC3F3
mpi/mpih-add1.c
(0 . 0)(1 . 64)
8573 /* mpihelp-add_1.c - MPI helper functions
8574 * Copyright (C) 1994, 1996, 1997, 1998,
8575 * 2000 Free Software Foundation, Inc.
8576 *
8577 * This file is part of GnuPG.
8578 *
8579 * GnuPG is free software; you can redistribute it and/or modify
8580 * it under the terms of the GNU General Public License as published by
8581 * the Free Software Foundation; either version 3 of the License, or
8582 * (at your option) any later version.
8583 *
8584 * GnuPG is distributed in the hope that it will be useful,
8585 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8586 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8587 * GNU General Public License for more details.
8588 *
8589 * You should have received a copy of the GNU General Public License
8590 * along with this program; if not, see <http://www.gnu.org/licenses/>.
8591 *
8592 * Note: This code is heavily based on the GNU MP Library.
8593 * Actually it's the same code with only minor changes in the
8594 * way the data is stored; this is to support the abstraction
8595 * of an optional secure memory allocation which may be used
8596 * to avoid revealing of sensitive data due to paging etc.
8597 * The GNU MP Library itself is published under the LGPL;
8598 * however I decided to publish this code under the plain GPL.
8599 */
8600
8601 #include <config.h>
8602 #include <stdio.h>
8603 #include <stdlib.h>
8604 #include "mpi-internal.h"
8605 #include "longlong.h"
8606
8607 mpi_limb_t
8608 mpihelp_add_n( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
8609 mpi_ptr_t s2_ptr, mpi_size_t size)
8610 {
8611 mpi_limb_t x, y, cy;
8612 mpi_size_t j;
8613
8614 /* The loop counter and index J goes from -SIZE to -1. This way
8615 the loop becomes faster. */
8616 j = -size;
8617
8618 /* Offset the base pointers to compensate for the negative indices. */
8619 s1_ptr -= j;
8620 s2_ptr -= j;
8621 res_ptr -= j;
8622
8623 cy = 0;
8624 do {
8625 y = s2_ptr[j];
8626 x = s1_ptr[j];
8627 y += cy; /* add previous carry to one addend */
8628 cy = y < cy; /* get out carry from that addition */
8629 y += x; /* add other addend */
8630 cy += y < x; /* get out carry from that add, combine */
8631 res_ptr[j] = y;
8632 } while( ++j );
8633
8634 return cy;
8635 }
8636
-
+ 88A21583524C37A7FEBB2EEDAF38F0942183A201EE8DF8B9E04A8098E892DD88B7F8566E40CC8BF042D5713E2F78886526CC23DE79C61463E7763685F280C37E
mpi/mpih-cmp.c
(0 . 0)(1 . 61)
8641 /* mpihelp-sub.c - MPI helper functions
8642 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
8643 * Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
8644 *
8645 * This file is part of GnuPG.
8646 *
8647 * GnuPG is free software; you can redistribute it and/or modify
8648 * it under the terms of the GNU General Public License as published by
8649 * the Free Software Foundation; either version 3 of the License, or
8650 * (at your option) any later version.
8651 *
8652 * GnuPG is distributed in the hope that it will be useful,
8653 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8654 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8655 * GNU General Public License for more details.
8656 *
8657 * You should have received a copy of the GNU General Public License
8658 * along with this program; if not, see <http://www.gnu.org/licenses/>.
8659 *
8660 * Note: This code is heavily based on the GNU MP Library.
8661 * Actually it's the same code with only minor changes in the
8662 * way the data is stored; this is to support the abstraction
8663 * of an optional secure memory allocation which may be used
8664 * to avoid revealing of sensitive data due to paging etc.
8665 * The GNU MP Library itself is published under the LGPL;
8666 * however I decided to publish this code under the plain GPL.
8667 */
8668
8669 #include <config.h>
8670 #include <stdio.h>
8671 #include <stdlib.h>
8672
8673 #include "mpi-internal.h"
8674
8675 /****************
8676 * Compare OP1_PTR/OP1_SIZE with OP2_PTR/OP2_SIZE.
8677 * There are no restrictions on the relative sizes of
8678 * the two arguments.
8679 * Return 1 if OP1 > OP2, 0 if they are equal, and -1 if OP1 < OP2.
8680 */
8681 int
8682 mpihelp_cmp( mpi_ptr_t op1_ptr, mpi_ptr_t op2_ptr, mpi_size_t size )
8683 {
8684 mpi_size_t i;
8685 mpi_limb_t op1_word, op2_word;
8686
8687 for( i = size - 1; i >= 0 ; i--) {
8688 op1_word = op1_ptr[i];
8689 op2_word = op2_ptr[i];
8690 if( op1_word != op2_word )
8691 goto diff;
8692 }
8693 return 0;
8694
8695 diff:
8696 /* This can *not* be simplified to
8697 * op2_word - op2_word
8698 * since that expression might give signed overflow. */
8699 return (op1_word > op2_word) ? 1 : -1;
8700 }
8701
-
+ AA4E2EFA1E53416AEDF9CBF7A73A00FBDE7A8266F532002DC046B0B995CF49D060496C45C74944EC3F41CF0DD441884FF6230260978FCBF227903EB7213B074A
mpi/mpih-div.c
(0 . 0)(1 . 534)
8706 /* mpihelp-div.c - MPI helper functions
8707 * Copyright (C) 1994, 1996 Free Software Foundation, Inc.
8708 * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
8709 *
8710 * This file is part of GnuPG.
8711 *
8712 * GnuPG is free software; you can redistribute it and/or modify
8713 * it under the terms of the GNU General Public License as published by
8714 * the Free Software Foundation; either version 3 of the License, or
8715 * (at your option) any later version.
8716 *
8717 * GnuPG is distributed in the hope that it will be useful,
8718 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8719 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8720 * GNU General Public License for more details.
8721 *
8722 * You should have received a copy of the GNU General Public License
8723 * along with this program; if not, see <http://www.gnu.org/licenses/>.
8724 *
8725 * Note: This code is heavily based on the GNU MP Library.
8726 * Actually it's the same code with only minor changes in the
8727 * way the data is stored; this is to support the abstraction
8728 * of an optional secure memory allocation which may be used
8729 * to avoid revealing of sensitive data due to paging etc.
8730 * The GNU MP Library itself is published under the LGPL;
8731 * however I decided to publish this code under the plain GPL.
8732 */
8733
8734 #include <config.h>
8735 #include <stdio.h>
8736 #include <stdlib.h>
8737 #include "mpi-internal.h"
8738 #include "longlong.h"
8739
8740 #ifndef UMUL_TIME
8741 #define UMUL_TIME 1
8742 #endif
8743 #ifndef UDIV_TIME
8744 #define UDIV_TIME UMUL_TIME
8745 #endif
8746
8747 /* FIXME: We should be using invert_limb (or invert_normalized_limb)
8748 * here (not udiv_qrnnd).
8749 */
8750
8751 mpi_limb_t
8752 mpihelp_mod_1(mpi_ptr_t dividend_ptr, mpi_size_t dividend_size,
8753 mpi_limb_t divisor_limb)
8754 {
8755 mpi_size_t i;
8756 mpi_limb_t n1, n0, r;
8757 int dummy;
8758
8759 /* Botch: Should this be handled at all? Rely on callers? */
8760 if( !dividend_size )
8761 return 0;
8762
8763 /* If multiplication is much faster than division, and the
8764 * dividend is large, pre-invert the divisor, and use
8765 * only multiplications in the inner loop.
8766 *
8767 * This test should be read:
8768 * Does it ever help to use udiv_qrnnd_preinv?
8769 * && Does what we save compensate for the inversion overhead?
8770 */
8771 if( UDIV_TIME > (2 * UMUL_TIME + 6)
8772 && (UDIV_TIME - (2 * UMUL_TIME + 6)) * dividend_size > UDIV_TIME ) {
8773 int normalization_steps;
8774
8775 count_leading_zeros( normalization_steps, divisor_limb );
8776 if( normalization_steps ) {
8777 mpi_limb_t divisor_limb_inverted;
8778
8779 divisor_limb <<= normalization_steps;
8780
8781 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
8782 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
8783 * most significant bit (with weight 2**N) implicit.
8784 *
8785 * Special case for DIVISOR_LIMB == 100...000.
8786 */
8787 if( !(divisor_limb << 1) )
8788 divisor_limb_inverted = ~(mpi_limb_t)0;
8789 else
8790 udiv_qrnnd(divisor_limb_inverted, dummy,
8791 -divisor_limb, 0, divisor_limb);
8792
8793 n1 = dividend_ptr[dividend_size - 1];
8794 r = n1 >> (BITS_PER_MPI_LIMB - normalization_steps);
8795
8796 /* Possible optimization:
8797 * if (r == 0
8798 * && divisor_limb > ((n1 << normalization_steps)
8799 * | (dividend_ptr[dividend_size - 2] >> ...)))
8800 * ...one division less...
8801 */
8802 for( i = dividend_size - 2; i >= 0; i--) {
8803 n0 = dividend_ptr[i];
8804 UDIV_QRNND_PREINV(dummy, r, r,
8805 ((n1 << normalization_steps)
8806 | (n0 >> (BITS_PER_MPI_LIMB - normalization_steps))),
8807 divisor_limb, divisor_limb_inverted);
8808 n1 = n0;
8809 }
8810 UDIV_QRNND_PREINV(dummy, r, r,
8811 n1 << normalization_steps,
8812 divisor_limb, divisor_limb_inverted);
8813 return r >> normalization_steps;
8814 }
8815 else {
8816 mpi_limb_t divisor_limb_inverted;
8817
8818 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
8819 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
8820 * most significant bit (with weight 2**N) implicit.
8821 *
8822 * Special case for DIVISOR_LIMB == 100...000.
8823 */
8824 if( !(divisor_limb << 1) )
8825 divisor_limb_inverted = ~(mpi_limb_t)0;
8826 else
8827 udiv_qrnnd(divisor_limb_inverted, dummy,
8828 -divisor_limb, 0, divisor_limb);
8829
8830 i = dividend_size - 1;
8831 r = dividend_ptr[i];
8832
8833 if( r >= divisor_limb )
8834 r = 0;
8835 else
8836 i--;
8837
8838 for( ; i >= 0; i--) {
8839 n0 = dividend_ptr[i];
8840 UDIV_QRNND_PREINV(dummy, r, r,
8841 n0, divisor_limb, divisor_limb_inverted);
8842 }
8843 return r;
8844 }
8845 }
8846 else {
8847 if( UDIV_NEEDS_NORMALIZATION ) {
8848 int normalization_steps;
8849
8850 count_leading_zeros(normalization_steps, divisor_limb);
8851 if( normalization_steps ) {
8852 divisor_limb <<= normalization_steps;
8853
8854 n1 = dividend_ptr[dividend_size - 1];
8855 r = n1 >> (BITS_PER_MPI_LIMB - normalization_steps);
8856
8857 /* Possible optimization:
8858 * if (r == 0
8859 * && divisor_limb > ((n1 << normalization_steps)
8860 * | (dividend_ptr[dividend_size - 2] >> ...)))
8861 * ...one division less...
8862 */
8863 for(i = dividend_size - 2; i >= 0; i--) {
8864 n0 = dividend_ptr[i];
8865 udiv_qrnnd (dummy, r, r,
8866 ((n1 << normalization_steps)
8867 | (n0 >> (BITS_PER_MPI_LIMB - normalization_steps))),
8868 divisor_limb);
8869 n1 = n0;
8870 }
8871 udiv_qrnnd (dummy, r, r,
8872 n1 << normalization_steps,
8873 divisor_limb);
8874 return r >> normalization_steps;
8875 }
8876 }
8877 /* No normalization needed, either because udiv_qrnnd doesn't require
8878 * it, or because DIVISOR_LIMB is already normalized. */
8879 i = dividend_size - 1;
8880 r = dividend_ptr[i];
8881
8882 if(r >= divisor_limb)
8883 r = 0;
8884 else
8885 i--;
8886
8887 for(; i >= 0; i--) {
8888 n0 = dividend_ptr[i];
8889 udiv_qrnnd (dummy, r, r, n0, divisor_limb);
8890 }
8891 return r;
8892 }
8893 }
8894
8895 /* Divide num (NP/NSIZE) by den (DP/DSIZE) and write
8896 * the NSIZE-DSIZE least significant quotient limbs at QP
8897 * and the DSIZE long remainder at NP. If QEXTRA_LIMBS is
8898 * non-zero, generate that many fraction bits and append them after the
8899 * other quotient limbs.
8900 * Return the most significant limb of the quotient, this is always 0 or 1.
8901 *
8902 * Preconditions:
8903 * 0. NSIZE >= DSIZE.
8904 * 1. The most significant bit of the divisor must be set.
8905 * 2. QP must either not overlap with the input operands at all, or
8906 * QP + DSIZE >= NP must hold true. (This means that it's
8907 * possible to put the quotient in the high part of NUM, right after the
8908 * remainder in NUM.
8909 * 3. NSIZE >= DSIZE, even if QEXTRA_LIMBS is non-zero.
8910 */
8911
8912 mpi_limb_t
8913 mpihelp_divrem( mpi_ptr_t qp, mpi_size_t qextra_limbs,
8914 mpi_ptr_t np, mpi_size_t nsize,
8915 mpi_ptr_t dp, mpi_size_t dsize)
8916 {
8917 mpi_limb_t most_significant_q_limb = 0;
8918
8919 switch(dsize) {
8920 case 0:
8921 /* We are asked to divide by zero, so go ahead and do it! (To make
8922 the compiler not remove this statement, return the value.) */
8923 return 1 / dsize;
8924
8925 case 1:
8926 {
8927 mpi_size_t i;
8928 mpi_limb_t n1;
8929 mpi_limb_t d;
8930
8931 d = dp[0];
8932 n1 = np[nsize - 1];
8933
8934 if( n1 >= d ) {
8935 n1 -= d;
8936 most_significant_q_limb = 1;
8937 }
8938
8939 qp += qextra_limbs;
8940 for( i = nsize - 2; i >= 0; i--)
8941 udiv_qrnnd( qp[i], n1, n1, np[i], d );
8942 qp -= qextra_limbs;
8943
8944 for( i = qextra_limbs - 1; i >= 0; i-- )
8945 udiv_qrnnd (qp[i], n1, n1, 0, d);
8946
8947 np[0] = n1;
8948 }
8949 break;
8950
8951 case 2:
8952 {
8953 mpi_size_t i;
8954 mpi_limb_t n1, n0, n2;
8955 mpi_limb_t d1, d0;
8956
8957 np += nsize - 2;
8958 d1 = dp[1];
8959 d0 = dp[0];
8960 n1 = np[1];
8961 n0 = np[0];
8962
8963 if( n1 >= d1 && (n1 > d1 || n0 >= d0) ) {
8964 sub_ddmmss (n1, n0, n1, n0, d1, d0);
8965 most_significant_q_limb = 1;
8966 }
8967
8968 for( i = qextra_limbs + nsize - 2 - 1; i >= 0; i-- ) {
8969 mpi_limb_t q;
8970 mpi_limb_t r;
8971
8972 if( i >= qextra_limbs )
8973 np--;
8974 else
8975 np[0] = 0;
8976
8977 if( n1 == d1 ) {
8978 /* Q should be either 111..111 or 111..110. Need special
8979 * treatment of this rare case as normal division would
8980 * give overflow. */
8981 q = ~(mpi_limb_t)0;
8982
8983 r = n0 + d1;
8984 if( r < d1 ) { /* Carry in the addition? */
8985 add_ssaaaa( n1, n0, r - d0, np[0], 0, d0 );
8986 qp[i] = q;
8987 continue;
8988 }
8989 n1 = d0 - (d0 != 0?1:0);
8990 n0 = -d0;
8991 }
8992 else {
8993 udiv_qrnnd (q, r, n1, n0, d1);
8994 umul_ppmm (n1, n0, d0, q);
8995 }
8996
8997 n2 = np[0];
8998 q_test:
8999 if( n1 > r || (n1 == r && n0 > n2) ) {
9000 /* The estimated Q was too large. */
9001 q--;
9002 sub_ddmmss (n1, n0, n1, n0, 0, d0);
9003 r += d1;
9004 if( r >= d1 ) /* If not carry, test Q again. */
9005 goto q_test;
9006 }
9007
9008 qp[i] = q;
9009 sub_ddmmss (n1, n0, r, n2, n1, n0);
9010 }
9011 np[1] = n1;
9012 np[0] = n0;
9013 }
9014 break;
9015
9016 default:
9017 {
9018 mpi_size_t i;
9019 mpi_limb_t dX, d1, n0;
9020
9021 np += nsize - dsize;
9022 dX = dp[dsize - 1];
9023 d1 = dp[dsize - 2];
9024 n0 = np[dsize - 1];
9025
9026 if( n0 >= dX ) {
9027 if(n0 > dX || mpihelp_cmp(np, dp, dsize - 1) >= 0 ) {
9028 mpihelp_sub_n(np, np, dp, dsize);
9029 n0 = np[dsize - 1];
9030 most_significant_q_limb = 1;
9031 }
9032 }
9033
9034 for( i = qextra_limbs + nsize - dsize - 1; i >= 0; i--) {
9035 mpi_limb_t q;
9036 mpi_limb_t n1, n2;
9037 mpi_limb_t cy_limb;
9038
9039 if( i >= qextra_limbs ) {
9040 np--;
9041 n2 = np[dsize];
9042 }
9043 else {
9044 n2 = np[dsize - 1];
9045 MPN_COPY_DECR (np + 1, np, dsize - 1);
9046 np[0] = 0;
9047 }
9048
9049 if( n0 == dX ) {
9050 /* This might over-estimate q, but it's probably not worth
9051 * the extra code here to find out. */
9052 q = ~(mpi_limb_t)0;
9053 }
9054 else {
9055 mpi_limb_t r;
9056
9057 udiv_qrnnd(q, r, n0, np[dsize - 1], dX);
9058 umul_ppmm(n1, n0, d1, q);
9059
9060 while( n1 > r || (n1 == r && n0 > np[dsize - 2])) {
9061 q--;
9062 r += dX;
9063 if( r < dX ) /* I.e. "carry in previous addition?" */
9064 break;
9065 n1 -= n0 < d1;
9066 n0 -= d1;
9067 }
9068 }
9069
9070 /* Possible optimization: We already have (q * n0) and (1 * n1)
9071 * after the calculation of q. Taking advantage of that, we
9072 * could make this loop make two iterations less. */
9073 cy_limb = mpihelp_submul_1(np, dp, dsize, q);
9074
9075 if( n2 != cy_limb ) {
9076 mpihelp_add_n(np, np, dp, dsize);
9077 q--;
9078 }
9079
9080 qp[i] = q;
9081 n0 = np[dsize - 1];
9082 }
9083 }
9084 }
9085
9086 return most_significant_q_limb;
9087 }
9088
9089
9090 /****************
9091 * Divide (DIVIDEND_PTR,,DIVIDEND_SIZE) by DIVISOR_LIMB.
9092 * Write DIVIDEND_SIZE limbs of quotient at QUOT_PTR.
9093 * Return the single-limb remainder.
9094 * There are no constraints on the value of the divisor.
9095 *
9096 * QUOT_PTR and DIVIDEND_PTR might point to the same limb.
9097 */
9098
9099 mpi_limb_t
9100 mpihelp_divmod_1( mpi_ptr_t quot_ptr,
9101 mpi_ptr_t dividend_ptr, mpi_size_t dividend_size,
9102 mpi_limb_t divisor_limb)
9103 {
9104 mpi_size_t i;
9105 mpi_limb_t n1, n0, r;
9106 int dummy;
9107
9108 if( !dividend_size )
9109 return 0;
9110
9111 /* If multiplication is much faster than division, and the
9112 * dividend is large, pre-invert the divisor, and use
9113 * only multiplications in the inner loop.
9114 *
9115 * This test should be read:
9116 * Does it ever help to use udiv_qrnnd_preinv?
9117 * && Does what we save compensate for the inversion overhead?
9118 */
9119 if( UDIV_TIME > (2 * UMUL_TIME + 6)
9120 && (UDIV_TIME - (2 * UMUL_TIME + 6)) * dividend_size > UDIV_TIME ) {
9121 int normalization_steps;
9122
9123 count_leading_zeros( normalization_steps, divisor_limb );
9124 if( normalization_steps ) {
9125 mpi_limb_t divisor_limb_inverted;
9126
9127 divisor_limb <<= normalization_steps;
9128
9129 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
9130 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
9131 * most significant bit (with weight 2**N) implicit.
9132 */
9133 /* Special case for DIVISOR_LIMB == 100...000. */
9134 if( !(divisor_limb << 1) )
9135 divisor_limb_inverted = ~(mpi_limb_t)0;
9136 else
9137 udiv_qrnnd(divisor_limb_inverted, dummy,
9138 -divisor_limb, 0, divisor_limb);
9139
9140 n1 = dividend_ptr[dividend_size - 1];
9141 r = n1 >> (BITS_PER_MPI_LIMB - normalization_steps);
9142
9143 /* Possible optimization:
9144 * if (r == 0
9145 * && divisor_limb > ((n1 << normalization_steps)
9146 * | (dividend_ptr[dividend_size - 2] >> ...)))
9147 * ...one division less...
9148 */
9149 for( i = dividend_size - 2; i >= 0; i--) {
9150 n0 = dividend_ptr[i];
9151 UDIV_QRNND_PREINV( quot_ptr[i + 1], r, r,
9152 ((n1 << normalization_steps)
9153 | (n0 >> (BITS_PER_MPI_LIMB - normalization_steps))),
9154 divisor_limb, divisor_limb_inverted);
9155 n1 = n0;
9156 }
9157 UDIV_QRNND_PREINV( quot_ptr[0], r, r,
9158 n1 << normalization_steps,
9159 divisor_limb, divisor_limb_inverted);
9160 return r >> normalization_steps;
9161 }
9162 else {
9163 mpi_limb_t divisor_limb_inverted;
9164
9165 /* Compute (2**2N - 2**N * DIVISOR_LIMB) / DIVISOR_LIMB. The
9166 * result is a (N+1)-bit approximation to 1/DIVISOR_LIMB, with the
9167 * most significant bit (with weight 2**N) implicit.
9168 */
9169 /* Special case for DIVISOR_LIMB == 100...000. */
9170 if( !(divisor_limb << 1) )
9171 divisor_limb_inverted = ~(mpi_limb_t) 0;
9172 else
9173 udiv_qrnnd(divisor_limb_inverted, dummy,
9174 -divisor_limb, 0, divisor_limb);
9175
9176 i = dividend_size - 1;
9177 r = dividend_ptr[i];
9178
9179 if( r >= divisor_limb )
9180 r = 0;
9181 else
9182 quot_ptr[i--] = 0;
9183
9184 for( ; i >= 0; i-- ) {
9185 n0 = dividend_ptr[i];
9186 UDIV_QRNND_PREINV( quot_ptr[i], r, r,
9187 n0, divisor_limb, divisor_limb_inverted);
9188 }
9189 return r;
9190 }
9191 }
9192 else {
9193 if(UDIV_NEEDS_NORMALIZATION) {
9194 int normalization_steps;
9195
9196 count_leading_zeros (normalization_steps, divisor_limb);
9197 if( normalization_steps ) {
9198 divisor_limb <<= normalization_steps;
9199
9200 n1 = dividend_ptr[dividend_size - 1];
9201 r = n1 >> (BITS_PER_MPI_LIMB - normalization_steps);
9202
9203 /* Possible optimization:
9204 * if (r == 0
9205 * && divisor_limb > ((n1 << normalization_steps)
9206 * | (dividend_ptr[dividend_size - 2] >> ...)))
9207 * ...one division less...
9208 */
9209 for( i = dividend_size - 2; i >= 0; i--) {
9210 n0 = dividend_ptr[i];
9211 udiv_qrnnd (quot_ptr[i + 1], r, r,
9212 ((n1 << normalization_steps)
9213 | (n0 >> (BITS_PER_MPI_LIMB - normalization_steps))),
9214 divisor_limb);
9215 n1 = n0;
9216 }
9217 udiv_qrnnd (quot_ptr[0], r, r,
9218 n1 << normalization_steps,
9219 divisor_limb);
9220 return r >> normalization_steps;
9221 }
9222 }
9223 /* No normalization needed, either because udiv_qrnnd doesn't require
9224 * it, or because DIVISOR_LIMB is already normalized. */
9225 i = dividend_size - 1;
9226 r = dividend_ptr[i];
9227
9228 if(r >= divisor_limb)
9229 r = 0;
9230 else
9231 quot_ptr[i--] = 0;
9232
9233 for(; i >= 0; i--) {
9234 n0 = dividend_ptr[i];
9235 udiv_qrnnd( quot_ptr[i], r, r, n0, divisor_limb );
9236 }
9237 return r;
9238 }
9239 }
-
+ 3222BFC241FA6104936CC585FDA392F220D88031FA0FDF460BB201A3AA7295E6D1DC75007BF53D2E501734D9FAAA31934EED944CE7452A6AA3AFCD3A333D3C13
mpi/mpih-lshift.c
(0 . 0)(1 . 68)
9244 /* mpihelp-lshift.c - MPI helper functions
9245 * Copyright (C) 1994, 1996, 1998, 2001 Free Software Foundation, Inc.
9246 *
9247 * This file is part of GnuPG.
9248 *
9249 * GnuPG is free software; you can redistribute it and/or modify
9250 * it under the terms of the GNU General Public License as published by
9251 * the Free Software Foundation; either version 3 of the License, or
9252 * (at your option) any later version.
9253 *
9254 * GnuPG is distributed in the hope that it will be useful,
9255 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9256 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9257 * GNU General Public License for more details.
9258 *
9259 * You should have received a copy of the GNU General Public License
9260 * along with this program; if not, see <http://www.gnu.org/licenses/>.
9261 *
9262 * Note: This code is heavily based on the GNU MP Library.
9263 * Actually it's the same code with only minor changes in the
9264 * way the data is stored; this is to support the abstraction
9265 * of an optional secure memory allocation which may be used
9266 * to avoid revealing of sensitive data due to paging etc.
9267 * The GNU MP Library itself is published under the LGPL;
9268 * however I decided to publish this code under the plain GPL.
9269 */
9270
9271 #include <config.h>
9272 #include <stdio.h>
9273 #include <stdlib.h>
9274 #include "mpi-internal.h"
9275
9276 /* Shift U (pointed to by UP and USIZE digits long) CNT bits to the left
9277 * and store the USIZE least significant digits of the result at WP.
9278 * Return the bits shifted out from the most significant digit.
9279 *
9280 * Argument constraints:
9281 * 1. 0 < CNT < BITS_PER_MP_LIMB
9282 * 2. If the result is to be written over the input, WP must be >= UP.
9283 */
9284
9285 mpi_limb_t
9286 mpihelp_lshift( mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize,
9287 unsigned int cnt)
9288 {
9289 mpi_limb_t high_limb, low_limb;
9290 unsigned sh_1, sh_2;
9291 mpi_size_t i;
9292 mpi_limb_t retval;
9293
9294 sh_1 = cnt;
9295 wp += 1;
9296 sh_2 = BITS_PER_MPI_LIMB - sh_1;
9297 i = usize - 1;
9298 low_limb = up[i];
9299 retval = low_limb >> sh_2;
9300 high_limb = low_limb;
9301 while( --i >= 0 ) {
9302 low_limb = up[i];
9303 wp[i] = (high_limb << sh_1) | (low_limb >> sh_2);
9304 high_limb = low_limb;
9305 }
9306 wp[i] = high_limb << sh_1;
9307
9308 return retval;
9309 }
9310
9311
-
+ 2D6F3C1ECB3331CDFB54C9EFA53246CAC6A6DFA16465D2E354C6801974964229CB173E7AFF19C4C92E896B8C65CFBC6DA79EF03C20022772F5C299F1C3CBC063
mpi/mpih-mul.c
(0 . 0)(1 . 527)
9316 /* mpihelp-mul.c - MPI helper functions
9317 * Copyright (C) 1994, 1996, 1998, 1999,
9318 * 2000 Free Software Foundation, Inc.
9319 *
9320 * This file is part of GnuPG.
9321 *
9322 * GnuPG is free software; you can redistribute it and/or modify
9323 * it under the terms of the GNU General Public License as published by
9324 * the Free Software Foundation; either version 3 of the License, or
9325 * (at your option) any later version.
9326 *
9327 * GnuPG is distributed in the hope that it will be useful,
9328 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9329 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9330 * GNU General Public License for more details.
9331 *
9332 * You should have received a copy of the GNU General Public License
9333 * along with this program; if not, see <http://www.gnu.org/licenses/>.
9334 *
9335 * Note: This code is heavily based on the GNU MP Library.
9336 * Actually it's the same code with only minor changes in the
9337 * way the data is stored; this is to support the abstraction
9338 * of an optional secure memory allocation which may be used
9339 * to avoid revealing of sensitive data due to paging etc.
9340 * The GNU MP Library itself is published under the LGPL;
9341 * however I decided to publish this code under the plain GPL.
9342 */
9343
9344 #include <config.h>
9345 #include <stdio.h>
9346 #include <stdlib.h>
9347 #include <string.h>
9348 #include "mpi-internal.h"
9349 #include "longlong.h"
9350
9351
9352
9353 #define MPN_MUL_N_RECURSE(prodp, up, vp, size, tspace) \
9354 do { \
9355 if( (size) < KARATSUBA_THRESHOLD ) \
9356 mul_n_basecase (prodp, up, vp, size); \
9357 else \
9358 mul_n (prodp, up, vp, size, tspace); \
9359 } while (0);
9360
9361 #define MPN_SQR_N_RECURSE(prodp, up, size, tspace) \
9362 do { \
9363 if ((size) < KARATSUBA_THRESHOLD) \
9364 mpih_sqr_n_basecase (prodp, up, size); \
9365 else \
9366 mpih_sqr_n (prodp, up, size, tspace); \
9367 } while (0);
9368
9369
9370
9371
9372 /* Multiply the natural numbers u (pointed to by UP) and v (pointed to by VP),
9373 * both with SIZE limbs, and store the result at PRODP. 2 * SIZE limbs are
9374 * always stored. Return the most significant limb.
9375 *
9376 * Argument constraints:
9377 * 1. PRODP != UP and PRODP != VP, i.e. the destination
9378 * must be distinct from the multiplier and the multiplicand.
9379 *
9380 *
9381 * Handle simple cases with traditional multiplication.
9382 *
9383 * This is the most critical code of multiplication. All multiplies rely
9384 * on this, both small and huge. Small ones arrive here immediately. Huge
9385 * ones arrive here as this is the base case for Karatsuba's recursive
9386 * algorithm below.
9387 */
9388
9389 static mpi_limb_t
9390 mul_n_basecase( mpi_ptr_t prodp, mpi_ptr_t up,
9391 mpi_ptr_t vp, mpi_size_t size)
9392 {
9393 mpi_size_t i;
9394 mpi_limb_t cy;
9395 mpi_limb_t v_limb;
9396
9397 /* Multiply by the first limb in V separately, as the result can be
9398 * stored (not added) to PROD. We also avoid a loop for zeroing. */
9399 v_limb = vp[0];
9400 if( v_limb <= 1 ) {
9401 if( v_limb == 1 )
9402 MPN_COPY( prodp, up, size );
9403 else
9404 MPN_ZERO( prodp, size );
9405 cy = 0;
9406 }
9407 else
9408 cy = mpihelp_mul_1( prodp, up, size, v_limb );
9409
9410 prodp[size] = cy;
9411 prodp++;
9412
9413 /* For each iteration in the outer loop, multiply one limb from
9414 * U with one limb from V, and add it to PROD. */
9415 for( i = 1; i < size; i++ ) {
9416 v_limb = vp[i];
9417 if( v_limb <= 1 ) {
9418 cy = 0;
9419 if( v_limb == 1 )
9420 cy = mpihelp_add_n(prodp, prodp, up, size);
9421 }
9422 else
9423 cy = mpihelp_addmul_1(prodp, up, size, v_limb);
9424
9425 prodp[size] = cy;
9426 prodp++;
9427 }
9428
9429 return cy;
9430 }
9431
9432
9433 static void
9434 mul_n( mpi_ptr_t prodp, mpi_ptr_t up, mpi_ptr_t vp,
9435 mpi_size_t size, mpi_ptr_t tspace )
9436 {
9437 if( size & 1 ) {
9438 /* The size is odd, and the code below doesn't handle that.
9439 * Multiply the least significant (size - 1) limbs with a recursive
9440 * call, and handle the most significant limb of S1 and S2
9441 * separately.
9442 * A slightly faster way to do this would be to make the Karatsuba
9443 * code below behave as if the size were even, and let it check for
9444 * odd size in the end. I.e., in essence move this code to the end.
9445 * Doing so would save us a recursive call, and potentially make the
9446 * stack grow a lot less.
9447 */
9448 mpi_size_t esize = size - 1; /* even size */
9449 mpi_limb_t cy_limb;
9450
9451 MPN_MUL_N_RECURSE( prodp, up, vp, esize, tspace );
9452 cy_limb = mpihelp_addmul_1( prodp + esize, up, esize, vp[esize] );
9453 prodp[esize + esize] = cy_limb;
9454 cy_limb = mpihelp_addmul_1( prodp + esize, vp, size, up[esize] );
9455 prodp[esize + size] = cy_limb;
9456 }
9457 else {
9458 /* Anatolij Alekseevich Karatsuba's divide-and-conquer algorithm.
9459 *
9460 * Split U in two pieces, U1 and U0, such that
9461 * U = U0 + U1*(B**n),
9462 * and V in V1 and V0, such that
9463 * V = V0 + V1*(B**n).
9464 *
9465 * UV is then computed recursively using the identity
9466 *
9467 * 2n n n n
9468 * UV = (B + B )U V + B (U -U )(V -V ) + (B + 1)U V
9469 * 1 1 1 0 0 1 0 0
9470 *
9471 * Where B = 2**BITS_PER_MP_LIMB.
9472 */
9473 mpi_size_t hsize = size >> 1;
9474 mpi_limb_t cy;
9475 int negflg;
9476
9477 /* Product H. ________________ ________________
9478 * |_____U1 x V1____||____U0 x V0_____|
9479 * Put result in upper part of PROD and pass low part of TSPACE
9480 * as new TSPACE.
9481 */
9482 MPN_MUL_N_RECURSE(prodp + size, up + hsize, vp + hsize, hsize, tspace);
9483
9484 /* Product M. ________________
9485 * |_(U1-U0)(V0-V1)_|
9486 */
9487 if( mpihelp_cmp(up + hsize, up, hsize) >= 0 ) {
9488 mpihelp_sub_n(prodp, up + hsize, up, hsize);
9489 negflg = 0;
9490 }
9491 else {
9492 mpihelp_sub_n(prodp, up, up + hsize, hsize);
9493 negflg = 1;
9494 }
9495 if( mpihelp_cmp(vp + hsize, vp, hsize) >= 0 ) {
9496 mpihelp_sub_n(prodp + hsize, vp + hsize, vp, hsize);
9497 negflg ^= 1;
9498 }
9499 else {
9500 mpihelp_sub_n(prodp + hsize, vp, vp + hsize, hsize);
9501 /* No change of NEGFLG. */
9502 }
9503 /* Read temporary operands from low part of PROD.
9504 * Put result in low part of TSPACE using upper part of TSPACE
9505 * as new TSPACE.
9506 */
9507 MPN_MUL_N_RECURSE(tspace, prodp, prodp + hsize, hsize, tspace + size);
9508
9509 /* Add/copy product H. */
9510 MPN_COPY (prodp + hsize, prodp + size, hsize);
9511 cy = mpihelp_add_n( prodp + size, prodp + size,
9512 prodp + size + hsize, hsize);
9513
9514 /* Add product M (if NEGFLG M is a negative number) */
9515 if(negflg)
9516 cy -= mpihelp_sub_n(prodp + hsize, prodp + hsize, tspace, size);
9517 else
9518 cy += mpihelp_add_n(prodp + hsize, prodp + hsize, tspace, size);
9519
9520 /* Product L. ________________ ________________
9521 * |________________||____U0 x V0_____|
9522 * Read temporary operands from low part of PROD.
9523 * Put result in low part of TSPACE using upper part of TSPACE
9524 * as new TSPACE.
9525 */
9526 MPN_MUL_N_RECURSE(tspace, up, vp, hsize, tspace + size);
9527
9528 /* Add/copy Product L (twice) */
9529
9530 cy += mpihelp_add_n(prodp + hsize, prodp + hsize, tspace, size);
9531 if( cy )
9532 mpihelp_add_1(prodp + hsize + size, prodp + hsize + size, hsize, cy);
9533
9534 MPN_COPY(prodp, tspace, hsize);
9535 cy = mpihelp_add_n(prodp + hsize, prodp + hsize, tspace + hsize, hsize);
9536 if( cy )
9537 mpihelp_add_1(prodp + size, prodp + size, size, 1);
9538 }
9539 }
9540
9541
9542 void
9543 mpih_sqr_n_basecase( mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t size )
9544 {
9545 mpi_size_t i;
9546 mpi_limb_t cy_limb;
9547 mpi_limb_t v_limb;
9548
9549 /* Multiply by the first limb in V separately, as the result can be
9550 * stored (not added) to PROD. We also avoid a loop for zeroing. */
9551 v_limb = up[0];
9552 if( v_limb <= 1 ) {
9553 if( v_limb == 1 )
9554 MPN_COPY( prodp, up, size );
9555 else
9556 MPN_ZERO(prodp, size);
9557 cy_limb = 0;
9558 }
9559 else
9560 cy_limb = mpihelp_mul_1( prodp, up, size, v_limb );
9561
9562 prodp[size] = cy_limb;
9563 prodp++;
9564
9565 /* For each iteration in the outer loop, multiply one limb from
9566 * U with one limb from V, and add it to PROD. */
9567 for( i=1; i < size; i++) {
9568 v_limb = up[i];
9569 if( v_limb <= 1 ) {
9570 cy_limb = 0;
9571 if( v_limb == 1 )
9572 cy_limb = mpihelp_add_n(prodp, prodp, up, size);
9573 }
9574 else
9575 cy_limb = mpihelp_addmul_1(prodp, up, size, v_limb);
9576
9577 prodp[size] = cy_limb;
9578 prodp++;
9579 }
9580 }
9581
9582
9583 void
9584 mpih_sqr_n( mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t size, mpi_ptr_t tspace)
9585 {
9586 if( size & 1 ) {
9587 /* The size is odd, and the code below doesn't handle that.
9588 * Multiply the least significant (size - 1) limbs with a recursive
9589 * call, and handle the most significant limb of S1 and S2
9590 * separately.
9591 * A slightly faster way to do this would be to make the Karatsuba
9592 * code below behave as if the size were even, and let it check for
9593 * odd size in the end. I.e., in essence move this code to the end.
9594 * Doing so would save us a recursive call, and potentially make the
9595 * stack grow a lot less.
9596 */
9597 mpi_size_t esize = size - 1; /* even size */
9598 mpi_limb_t cy_limb;
9599
9600 MPN_SQR_N_RECURSE( prodp, up, esize, tspace );
9601 cy_limb = mpihelp_addmul_1( prodp + esize, up, esize, up[esize] );
9602 prodp[esize + esize] = cy_limb;
9603 cy_limb = mpihelp_addmul_1( prodp + esize, up, size, up[esize] );
9604
9605 prodp[esize + size] = cy_limb;
9606 }
9607 else {
9608 mpi_size_t hsize = size >> 1;
9609 mpi_limb_t cy;
9610
9611 /* Product H. ________________ ________________
9612 * |_____U1 x U1____||____U0 x U0_____|
9613 * Put result in upper part of PROD and pass low part of TSPACE
9614 * as new TSPACE.
9615 */
9616 MPN_SQR_N_RECURSE(prodp + size, up + hsize, hsize, tspace);
9617
9618 /* Product M. ________________
9619 * |_(U1-U0)(U0-U1)_|
9620 */
9621 if( mpihelp_cmp( up + hsize, up, hsize) >= 0 )
9622 mpihelp_sub_n( prodp, up + hsize, up, hsize);
9623 else
9624 mpihelp_sub_n (prodp, up, up + hsize, hsize);
9625
9626 /* Read temporary operands from low part of PROD.
9627 * Put result in low part of TSPACE using upper part of TSPACE
9628 * as new TSPACE. */
9629 MPN_SQR_N_RECURSE(tspace, prodp, hsize, tspace + size);
9630
9631 /* Add/copy product H */
9632 MPN_COPY(prodp + hsize, prodp + size, hsize);
9633 cy = mpihelp_add_n(prodp + size, prodp + size,
9634 prodp + size + hsize, hsize);
9635
9636 /* Add product M (if NEGFLG M is a negative number). */
9637 cy -= mpihelp_sub_n (prodp + hsize, prodp + hsize, tspace, size);
9638
9639 /* Product L. ________________ ________________
9640 * |________________||____U0 x U0_____|
9641 * Read temporary operands from low part of PROD.
9642 * Put result in low part of TSPACE using upper part of TSPACE
9643 * as new TSPACE. */
9644 MPN_SQR_N_RECURSE (tspace, up, hsize, tspace + size);
9645
9646 /* Add/copy Product L (twice). */
9647 cy += mpihelp_add_n (prodp + hsize, prodp + hsize, tspace, size);
9648 if( cy )
9649 mpihelp_add_1(prodp + hsize + size, prodp + hsize + size,
9650 hsize, cy);
9651
9652 MPN_COPY(prodp, tspace, hsize);
9653 cy = mpihelp_add_n (prodp + hsize, prodp + hsize, tspace + hsize, hsize);
9654 if( cy )
9655 mpihelp_add_1 (prodp + size, prodp + size, size, 1);
9656 }
9657 }
9658
9659
9660 /* This should be made into an inline function in gmp.h. */
9661 void
9662 mpihelp_mul_n( mpi_ptr_t prodp, mpi_ptr_t up, mpi_ptr_t vp, mpi_size_t size)
9663 {
9664 int secure;
9665
9666 if( up == vp ) {
9667 if( size < KARATSUBA_THRESHOLD )
9668 mpih_sqr_n_basecase( prodp, up, size );
9669 else {
9670 mpi_ptr_t tspace;
9671 secure = m_is_secure( up );
9672 tspace = mpi_alloc_limb_space( 2 * size, secure );
9673 mpih_sqr_n( prodp, up, size, tspace );
9674 mpi_free_limb_space( tspace );
9675 }
9676 }
9677 else {
9678 if( size < KARATSUBA_THRESHOLD )
9679 mul_n_basecase( prodp, up, vp, size );
9680 else {
9681 mpi_ptr_t tspace;
9682 secure = m_is_secure( up ) || m_is_secure( vp );
9683 tspace = mpi_alloc_limb_space( 2 * size, secure );
9684 mul_n (prodp, up, vp, size, tspace);
9685 mpi_free_limb_space( tspace );
9686 }
9687 }
9688 }
9689
9690
9691
9692 void
9693 mpihelp_mul_karatsuba_case( mpi_ptr_t prodp,
9694 mpi_ptr_t up, mpi_size_t usize,
9695 mpi_ptr_t vp, mpi_size_t vsize,
9696 struct karatsuba_ctx *ctx )
9697 {
9698 mpi_limb_t cy;
9699
9700 if( !ctx->tspace || ctx->tspace_size < vsize ) {
9701 if( ctx->tspace )
9702 mpi_free_limb_space( ctx->tspace );
9703 ctx->tspace = mpi_alloc_limb_space( 2 * vsize,
9704 m_is_secure( up ) || m_is_secure( vp ) );
9705 ctx->tspace_size = vsize;
9706 }
9707
9708 MPN_MUL_N_RECURSE( prodp, up, vp, vsize, ctx->tspace );
9709
9710 prodp += vsize;
9711 up += vsize;
9712 usize -= vsize;
9713 if( usize >= vsize ) {
9714 if( !ctx->tp || ctx->tp_size < vsize ) {
9715 if( ctx->tp )
9716 mpi_free_limb_space( ctx->tp );
9717 ctx->tp = mpi_alloc_limb_space( 2 * vsize, m_is_secure( up )
9718 || m_is_secure( vp ) );
9719 ctx->tp_size = vsize;
9720 }
9721
9722 do {
9723 MPN_MUL_N_RECURSE( ctx->tp, up, vp, vsize, ctx->tspace );
9724 cy = mpihelp_add_n( prodp, prodp, ctx->tp, vsize );
9725 mpihelp_add_1( prodp + vsize, ctx->tp + vsize, vsize, cy );
9726 prodp += vsize;
9727 up += vsize;
9728 usize -= vsize;
9729 } while( usize >= vsize );
9730 }
9731
9732 if( usize ) {
9733 if( usize < KARATSUBA_THRESHOLD ) {
9734 mpihelp_mul( ctx->tspace, vp, vsize, up, usize );
9735 }
9736 else {
9737 if( !ctx->next ) {
9738 ctx->next = xmalloc_clear( sizeof *ctx );
9739 }
9740 mpihelp_mul_karatsuba_case( ctx->tspace,
9741 vp, vsize,
9742 up, usize,
9743 ctx->next );
9744 }
9745
9746 cy = mpihelp_add_n( prodp, prodp, ctx->tspace, vsize);
9747 mpihelp_add_1( prodp + vsize, ctx->tspace + vsize, usize, cy );
9748 }
9749 }
9750
9751
9752 void
9753 mpihelp_release_karatsuba_ctx( struct karatsuba_ctx *ctx )
9754 {
9755 struct karatsuba_ctx *ctx2;
9756
9757 if( ctx->tp )
9758 mpi_free_limb_space( ctx->tp );
9759 if( ctx->tspace )
9760 mpi_free_limb_space( ctx->tspace );
9761 for( ctx=ctx->next; ctx; ctx = ctx2 ) {
9762 ctx2 = ctx->next;
9763 if( ctx->tp )
9764 mpi_free_limb_space( ctx->tp );
9765 if( ctx->tspace )
9766 mpi_free_limb_space( ctx->tspace );
9767 xfree( ctx );
9768 }
9769 }
9770
9771 /* Multiply the natural numbers u (pointed to by UP, with USIZE limbs)
9772 * and v (pointed to by VP, with VSIZE limbs), and store the result at
9773 * PRODP. USIZE + VSIZE limbs are always stored, but if the input
9774 * operands are normalized. Return the most significant limb of the
9775 * result.
9776 *
9777 * NOTE: The space pointed to by PRODP is overwritten before finished
9778 * with U and V, so overlap is an error.
9779 *
9780 * Argument constraints:
9781 * 1. USIZE >= VSIZE.
9782 * 2. PRODP != UP and PRODP != VP, i.e. the destination
9783 * must be distinct from the multiplier and the multiplicand.
9784 */
9785
9786 mpi_limb_t
9787 mpihelp_mul( mpi_ptr_t prodp, mpi_ptr_t up, mpi_size_t usize,
9788 mpi_ptr_t vp, mpi_size_t vsize)
9789 {
9790 mpi_ptr_t prod_endp = prodp + usize + vsize - 1;
9791 mpi_limb_t cy;
9792 struct karatsuba_ctx ctx;
9793
9794 if( vsize < KARATSUBA_THRESHOLD ) {
9795 mpi_size_t i;
9796 mpi_limb_t v_limb;
9797
9798 if( !vsize )
9799 return 0;
9800
9801 /* Multiply by the first limb in V separately, as the result can be
9802 * stored (not added) to PROD. We also avoid a loop for zeroing. */
9803 v_limb = vp[0];
9804 if( v_limb <= 1 ) {
9805 if( v_limb == 1 )
9806 MPN_COPY( prodp, up, usize );
9807 else
9808 MPN_ZERO( prodp, usize );
9809 cy = 0;
9810 }
9811 else
9812 cy = mpihelp_mul_1( prodp, up, usize, v_limb );
9813
9814 prodp[usize] = cy;
9815 prodp++;
9816
9817 /* For each iteration in the outer loop, multiply one limb from
9818 * U with one limb from V, and add it to PROD. */
9819 for( i = 1; i < vsize; i++ ) {
9820 v_limb = vp[i];
9821 if( v_limb <= 1 ) {
9822 cy = 0;
9823 if( v_limb == 1 )
9824 cy = mpihelp_add_n(prodp, prodp, up, usize);
9825 }
9826 else
9827 cy = mpihelp_addmul_1(prodp, up, usize, v_limb);
9828
9829 prodp[usize] = cy;
9830 prodp++;
9831 }
9832
9833 return cy;
9834 }
9835
9836 memset( &ctx, 0, sizeof ctx );
9837 mpihelp_mul_karatsuba_case( prodp, up, usize, vp, vsize, &ctx );
9838 mpihelp_release_karatsuba_ctx( &ctx );
9839 return *prod_endp;
9840 }
9841
9842
-
+ 86B925ACDAEDFAAF9C7F7FF783DA4A049C62C8F63929BF288FDC8E4760DC9B451440ED5ED5F8549E8B2CCBD4F00175F068DE9DC337EEDFD8FAD8348D21F3ED13
mpi/mpih-mul1.c
(0 . 0)(1 . 60)
9847 /* mpihelp-mul_1.c - MPI helper functions
9848 * Copyright (C) 1994, 1996, 1997, 1998, 2001 Free Software Foundation, Inc.
9849 *
9850 * This file is part of GnuPG.
9851 *
9852 * GnuPG is free software; you can redistribute it and/or modify
9853 * it under the terms of the GNU General Public License as published by
9854 * the Free Software Foundation; either version 3 of the License, or
9855 * (at your option) any later version.
9856 *
9857 * GnuPG is distributed in the hope that it will be useful,
9858 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9859 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9860 * GNU General Public License for more details.
9861 *
9862 * You should have received a copy of the GNU General Public License
9863 * along with this program; if not, see <http://www.gnu.org/licenses/>.
9864 *
9865 * Note: This code is heavily based on the GNU MP Library.
9866 * Actually it's the same code with only minor changes in the
9867 * way the data is stored; this is to support the abstraction
9868 * of an optional secure memory allocation which may be used
9869 * to avoid revealing of sensitive data due to paging etc.
9870 * The GNU MP Library itself is published under the LGPL;
9871 * however I decided to publish this code under the plain GPL.
9872 */
9873
9874 #include <config.h>
9875 #include <stdio.h>
9876 #include <stdlib.h>
9877 #include "mpi-internal.h"
9878 #include "longlong.h"
9879
9880 mpi_limb_t
9881 mpihelp_mul_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr, mpi_size_t s1_size,
9882 mpi_limb_t s2_limb)
9883 {
9884 mpi_limb_t cy_limb;
9885 mpi_size_t j;
9886 mpi_limb_t prod_high, prod_low;
9887
9888 /* The loop counter and index J goes from -S1_SIZE to -1. This way
9889 * the loop becomes faster. */
9890 j = -s1_size;
9891
9892 /* Offset the base pointers to compensate for the negative indices. */
9893 s1_ptr -= j;
9894 res_ptr -= j;
9895
9896 cy_limb = 0;
9897 do {
9898 umul_ppmm( prod_high, prod_low, s1_ptr[j], s2_limb );
9899 prod_low += cy_limb;
9900 cy_limb = (prod_low < cy_limb?1:0) + prod_high;
9901 res_ptr[j] = prod_low;
9902 } while( ++j );
9903
9904 return cy_limb;
9905 }
9906
-
+ 340744F79D1466A916FCA829C66F86915B808800BF3EBE2CCADABA1D5FD89EF5C5DB486C94B0F01ACE52F13D7A74784B68214499F5AC120AC8449FC9EB5C61C3
mpi/mpih-mul2.c
(0 . 0)(1 . 65)
9911 /* mpihelp-mul_2.c - MPI helper functions
9912 * Copyright (C) 1994, 1996, 1997, 1998, 2001 Free Software Foundation, Inc.
9913 *
9914 * This file is part of GnuPG.
9915 *
9916 * GnuPG is free software; you can redistribute it and/or modify
9917 * it under the terms of the GNU General Public License as published by
9918 * the Free Software Foundation; either version 3 of the License, or
9919 * (at your option) any later version.
9920 *
9921 * GnuPG is distributed in the hope that it will be useful,
9922 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9923 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9924 * GNU General Public License for more details.
9925 *
9926 * You should have received a copy of the GNU General Public License
9927 * along with this program; if not, see <http://www.gnu.org/licenses/>.
9928 *
9929 * Note: This code is heavily based on the GNU MP Library.
9930 * Actually it's the same code with only minor changes in the
9931 * way the data is stored; this is to support the abstraction
9932 * of an optional secure memory allocation which may be used
9933 * to avoid revealing of sensitive data due to paging etc.
9934 * The GNU MP Library itself is published under the LGPL;
9935 * however I decided to publish this code under the plain GPL.
9936 */
9937
9938 #include <config.h>
9939 #include <stdio.h>
9940 #include <stdlib.h>
9941 #include "mpi-internal.h"
9942 #include "longlong.h"
9943
9944
9945 mpi_limb_t
9946 mpihelp_addmul_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
9947 mpi_size_t s1_size, mpi_limb_t s2_limb)
9948 {
9949 mpi_limb_t cy_limb;
9950 mpi_size_t j;
9951 mpi_limb_t prod_high, prod_low;
9952 mpi_limb_t x;
9953
9954 /* The loop counter and index J goes from -SIZE to -1. This way
9955 * the loop becomes faster. */
9956 j = -s1_size;
9957 res_ptr -= j;
9958 s1_ptr -= j;
9959
9960 cy_limb = 0;
9961 do {
9962 umul_ppmm( prod_high, prod_low, s1_ptr[j], s2_limb );
9963
9964 prod_low += cy_limb;
9965 cy_limb = (prod_low < cy_limb?1:0) + prod_high;
9966
9967 x = res_ptr[j];
9968 prod_low = x + prod_low;
9969 cy_limb += prod_low < x?1:0;
9970 res_ptr[j] = prod_low;
9971 } while ( ++j );
9972 return cy_limb;
9973 }
9974
9975
-
+ 683F47357B0F57E3DC50AEFC32BDCD8C20E7A9A4C3DC48D3BA9E5715E12836B6CE53B8DFF653BDB86CDD197DAAB9AF7532DEF5BB06D861BDF48F4DC705AC6AA4
mpi/mpih-mul3.c
(0 . 0)(1 . 66)
9980 /* mpihelp-mul_3.c - MPI helper functions
9981 * Copyright (C) 1994, 1996, 1997, 1998, 2001 Free Software Foundation, Inc.
9982 *
9983 * This file is part of GnuPG.
9984 *
9985 * GnuPG is free software; you can redistribute it and/or modify
9986 * it under the terms of the GNU General Public License as published by
9987 * the Free Software Foundation; either version 3 of the License, or
9988 * (at your option) any later version.
9989 *
9990 * GnuPG is distributed in the hope that it will be useful,
9991 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9992 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9993 * GNU General Public License for more details.
9994 *
9995 * You should have received a copy of the GNU General Public License
9996 * along with this program; if not, see <http://www.gnu.org/licenses/>.
9997 *
9998 * Note: This code is heavily based on the GNU MP Library.
9999 * Actually it's the same code with only minor changes in the
10000 * way the data is stored; this is to support the abstraction
10001 * of an optional secure memory allocation which may be used
10002 * to avoid revealing of sensitive data due to paging etc.
10003 * The GNU MP Library itself is published under the LGPL;
10004 * however I decided to publish this code under the plain GPL.
10005 */
10006
10007 #include <config.h>
10008 #include <stdio.h>
10009 #include <stdlib.h>
10010 #include "mpi-internal.h"
10011 #include "longlong.h"
10012
10013
10014 mpi_limb_t
10015 mpihelp_submul_1( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
10016 mpi_size_t s1_size, mpi_limb_t s2_limb)
10017 {
10018 mpi_limb_t cy_limb;
10019 mpi_size_t j;
10020 mpi_limb_t prod_high, prod_low;
10021 mpi_limb_t x;
10022
10023 /* The loop counter and index J goes from -SIZE to -1. This way
10024 * the loop becomes faster. */
10025 j = -s1_size;
10026 res_ptr -= j;
10027 s1_ptr -= j;
10028
10029 cy_limb = 0;
10030 do {
10031 umul_ppmm( prod_high, prod_low, s1_ptr[j], s2_limb);
10032
10033 prod_low += cy_limb;
10034 cy_limb = (prod_low < cy_limb?1:0) + prod_high;
10035
10036 x = res_ptr[j];
10037 prod_low = x - prod_low;
10038 cy_limb += prod_low > x?1:0;
10039 res_ptr[j] = prod_low;
10040 } while( ++j );
10041
10042 return cy_limb;
10043 }
10044
10045
-
+ B98CF2FB49B284C7FFDA191D6E1A336E87BC9D5C302753C04E704DE455793BD9736D6318E1C314FC8CF97BAEBC830EAE998C35382AFB2810126C1CC9BD18BDCE
mpi/mpih-rshift.c
(0 . 0)(1 . 67)
10050 /* mpih-rshift.c - MPI helper functions
10051 * Copyright (C) 1994, 1996, 1998, 1999,
10052 * 2000, 2001 Free Software Foundation, Inc.
10053 *
10054 * This file is part of GNUPG
10055 *
10056 * GNUPG is free software; you can redistribute it and/or modify
10057 * it under the terms of the GNU General Public License as published by
10058 * the Free Software Foundation; either version 3 of the License, or
10059 * (at your option) any later version.
10060 *
10061 * GNUPG is distributed in the hope that it will be useful,
10062 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10063 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10064 * GNU General Public License for more details.
10065 *
10066 * You should have received a copy of the GNU General Public License
10067 * along with this program; if not, see <http://www.gnu.org/licenses/>.
10068 *
10069 * Note: This code is heavily based on the GNU MP Library.
10070 * Actually it's the same code with only minor changes in the
10071 * way the data is stored; this is to support the abstraction
10072 * of an optional secure memory allocation which may be used
10073 * to avoid revealing of sensitive data due to paging etc.
10074 * The GNU MP Library itself is published under the LGPL;
10075 * however I decided to publish this code under the plain GPL.
10076 */
10077
10078 #include <config.h>
10079 #include <stdio.h>
10080 #include <stdlib.h>
10081 #include "mpi-internal.h"
10082
10083
10084 /* Shift U (pointed to by UP and USIZE limbs long) CNT bits to the right
10085 * and store the USIZE least significant limbs of the result at WP.
10086 * The bits shifted out to the right are returned.
10087 *
10088 * Argument constraints:
10089 * 1. 0 < CNT < BITS_PER_MP_LIMB
10090 * 2. If the result is to be written over the input, WP must be <= UP.
10091 */
10092
10093 mpi_limb_t
10094 mpihelp_rshift( mpi_ptr_t wp, mpi_ptr_t up, mpi_size_t usize, unsigned cnt)
10095 {
10096 mpi_limb_t high_limb, low_limb;
10097 unsigned sh_1, sh_2;
10098 mpi_size_t i;
10099 mpi_limb_t retval;
10100
10101 sh_1 = cnt;
10102 wp -= 1;
10103 sh_2 = BITS_PER_MPI_LIMB - sh_1;
10104 high_limb = up[0];
10105 retval = high_limb << sh_2;
10106 low_limb = high_limb;
10107 for( i=1; i < usize; i++) {
10108 high_limb = up[i];
10109 wp[i] = (low_limb >> sh_1) | (high_limb << sh_2);
10110 low_limb = high_limb;
10111 }
10112 wp[i] = low_limb >> sh_1;
10113
10114 return retval;
10115 }
10116
-
+ 1F021E754F091EAC1AB7B46306B00849F7160CFA7CD0CC8A6481020B6D42CB12058CD12AC9E2B1D7F730688FBE2D876374EC9D5BB7A5F9D66A42CC9259CF2539
mpi/mpih-sub1.c
(0 . 0)(1 . 64)
10121 /* mpihelp-add_2.c - MPI helper functions
10122 * Copyright (C) 1994, 1996, 1997, 1998, 2001 Free Software Foundation, Inc.
10123 *
10124 * This file is part of GnuPG.
10125 *
10126 * GnuPG is free software; you can redistribute it and/or modify
10127 * it under the terms of the GNU General Public License as published by
10128 * the Free Software Foundation; either version 3 of the License, or
10129 * (at your option) any later version.
10130 *
10131 * GnuPG is distributed in the hope that it will be useful,
10132 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10133 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10134 * GNU General Public License for more details.
10135 *
10136 * You should have received a copy of the GNU General Public License
10137 * along with this program; if not, see <http://www.gnu.org/licenses/>.
10138 *
10139 * Note: This code is heavily based on the GNU MP Library.
10140 * Actually it's the same code with only minor changes in the
10141 * way the data is stored; this is to support the abstraction
10142 * of an optional secure memory allocation which may be used
10143 * to avoid revealing of sensitive data due to paging etc.
10144 * The GNU MP Library itself is published under the LGPL;
10145 * however I decided to publish this code under the plain GPL.
10146 */
10147
10148 #include <config.h>
10149 #include <stdio.h>
10150 #include <stdlib.h>
10151 #include "mpi-internal.h"
10152 #include "longlong.h"
10153
10154 mpi_limb_t
10155 mpihelp_sub_n( mpi_ptr_t res_ptr, mpi_ptr_t s1_ptr,
10156 mpi_ptr_t s2_ptr, mpi_size_t size)
10157 {
10158 mpi_limb_t x, y, cy;
10159 mpi_size_t j;
10160
10161 /* The loop counter and index J goes from -SIZE to -1. This way
10162 the loop becomes faster. */
10163 j = -size;
10164
10165 /* Offset the base pointers to compensate for the negative indices. */
10166 s1_ptr -= j;
10167 s2_ptr -= j;
10168 res_ptr -= j;
10169
10170 cy = 0;
10171 do {
10172 y = s2_ptr[j];
10173 x = s1_ptr[j];
10174 y += cy; /* add previous carry to subtrahend */
10175 cy = y < cy; /* get out carry from that addition */
10176 y = x - y; /* main subtract */
10177 cy += y > x; /* get out carry from the subtract, combine */
10178 res_ptr[j] = y;
10179 } while( ++j );
10180
10181 return cy;
10182 }
10183
10184
-
+ 757F8A9FFA7640843ABC7A20EE7F0460FAE4CB11A2928963C85399B7EA7ABA3332F5C1574E86DAB4BBA8384E5BF3F95161C1D1E15DB7B85BB96F369F1E67F6FA
mpi/mpiutil.c
(0 . 0)(1 . 505)
10189 /* mpiutil.ac - Utility functions for MPI
10190 * Copyright (C) 1998, 1999 Free Software Foundation, Inc.
10191 *
10192 * This file is part of GnuPG.
10193 *
10194 * GnuPG is free software; you can redistribute it and/or modify
10195 * it under the terms of the GNU General Public License as published by
10196 * the Free Software Foundation; either version 3 of the License, or
10197 * (at your option) any later version.
10198 *
10199 * GnuPG is distributed in the hope that it will be useful,
10200 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10201 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10202 * GNU General Public License for more details.
10203 *
10204 * You should have received a copy of the GNU General Public License
10205 * along with this program; if not, see <http://www.gnu.org/licenses/>.
10206 */
10207
10208 #include <config.h>
10209 #include <stdio.h>
10210 #include <stdlib.h>
10211 #include <string.h>
10212 #include <assert.h>
10213
10214 #include "mpi.h"
10215 #include "mpi-internal.h"
10216 #include "memory.h"
10217 #include "util.h"
10218
10219
10220 #ifdef M_DEBUG
10221 #undef mpi_alloc
10222 #undef mpi_alloc_secure
10223 #undef mpi_free
10224 #endif
10225
10226 /****************
10227 * Note: It was a bad idea to use the number of limbs to allocate
10228 * because on a alpha the limbs are large but we normally need
10229 * integers of n bits - So we should chnage this to bits (or bytes).
10230 *
10231 * But mpi_alloc is used in a lot of places :-)
10232 */
10233 MPI
10234 #ifdef M_DEBUG
10235 mpi_debug_alloc( unsigned nlimbs, const char *info )
10236 #else
10237 mpi_alloc( unsigned nlimbs )
10238 #endif
10239 {
10240 MPI a;
10241
10242 if( DBG_MEMORY )
10243 log_debug("mpi_alloc(%u)\n", nlimbs*BITS_PER_MPI_LIMB );
10244 #ifdef M_DEBUG
10245 a = m_debug_alloc( sizeof *a, info );
10246 a->d = nlimbs? mpi_debug_alloc_limb_space( nlimbs, 0, info ) : NULL;
10247 #else
10248 a = xmalloc( sizeof *a );
10249 a->d = nlimbs? mpi_alloc_limb_space( nlimbs, 0 ) : NULL;
10250 #endif
10251 a->alloced = nlimbs;
10252 a->nlimbs = 0;
10253 a->sign = 0;
10254 a->flags = 0;
10255 a->nbits = 0;
10256 return a;
10257 }
10258
10259 void
10260 mpi_m_check( MPI a )
10261 {
10262 m_check(a);
10263 m_check(a->d);
10264 }
10265
10266 MPI
10267 #ifdef M_DEBUG
10268 mpi_debug_alloc_secure( unsigned nlimbs, const char *info )
10269 #else
10270 mpi_alloc_secure( unsigned nlimbs )
10271 #endif
10272 {
10273 MPI a;
10274
10275 if( DBG_MEMORY )
10276 log_debug("mpi_alloc_secure(%u)\n", nlimbs*BITS_PER_MPI_LIMB );
10277 #ifdef M_DEBUG
10278 a = m_debug_alloc( sizeof *a, info );
10279 a->d = nlimbs? mpi_debug_alloc_limb_space( nlimbs, 1, info ) : NULL;
10280 #else
10281 a = xmalloc( sizeof *a );
10282 a->d = nlimbs? mpi_alloc_limb_space( nlimbs, 1 ) : NULL;
10283 #endif
10284 a->alloced = nlimbs;
10285 a->flags = 1;
10286 a->nlimbs = 0;
10287 a->sign = 0;
10288 a->nbits = 0;
10289 return a;
10290 }
10291
10292
10293 #if 0
10294 static void *unused_limbs_5;
10295 static void *unused_limbs_32;
10296 static void *unused_limbs_64;
10297 #endif
10298
10299 mpi_ptr_t
10300 #ifdef M_DEBUG
10301 mpi_debug_alloc_limb_space( unsigned nlimbs, int secure, const char *info )
10302 #else
10303 mpi_alloc_limb_space( unsigned nlimbs, int secure )
10304 #endif
10305 {
10306 size_t len = nlimbs * sizeof(mpi_limb_t);
10307 mpi_ptr_t p;
10308
10309 if( DBG_MEMORY )
10310 log_debug("mpi_alloc_limb_space(%u)\n", (unsigned)len*8 );
10311 #if 0
10312 if( !secure ) {
10313 if( nlimbs == 5 && unused_limbs_5 ) { /* DSA 160 bits */
10314 p = unused_limbs_5;
10315 unused_limbs_5 = *p;
10316 return p;
10317 }
10318 else if( nlimbs == 32 && unused_limbs_32 ) { /* DSA 1024 bits */
10319 p = unused_limbs_32;
10320 unused_limbs_32 = *p;
10321 return p;
10322 }
10323 else if( nlimbs == 64 && unused_limbs_64 ) { /* DSA 2*1024 bits */
10324 p = unused_limbs_64;
10325 unused_limbs_64 = *p;
10326 return p;
10327 }
10328 }
10329 #endif
10330
10331 #ifdef M_DEBUG
10332 p = secure? m_debug_alloc_secure(len, info):m_debug_alloc( len, info );
10333 #else
10334 p = secure? xmalloc_secure( len ):xmalloc( len );
10335 #endif
10336
10337 return p;
10338 }
10339
10340 void
10341 #ifdef M_DEBUG
10342 mpi_debug_free_limb_space( mpi_ptr_t a, const char *info )
10343 #else
10344 mpi_free_limb_space( mpi_ptr_t a )
10345 #endif
10346 {
10347 if( !a )
10348 return;
10349 if( DBG_MEMORY )
10350 log_debug("mpi_free_limb_space of size %lu\n", (ulong)m_size(a)*8 );
10351
10352 #if 0
10353 if( !m_is_secure(a) ) {
10354 size_t nlimbs = m_size(a) / 4 ;
10355 void *p = a;
10356
10357 if( nlimbs == 5 ) { /* DSA 160 bits */
10358 *a = unused_limbs_5;
10359 unused_limbs_5 = a;
10360 return;
10361 }
10362 else if( nlimbs == 32 ) { /* DSA 1024 bits */
10363 *a = unused_limbs_32;
10364 unused_limbs_32 = a;
10365 return;
10366 }
10367 else if( nlimbs == 64 ) { /* DSA 2*1024 bits */
10368 *a = unused_limbs_64;
10369 unused_limbs_64 = a;
10370 return;
10371 }
10372 }
10373 #endif
10374
10375 xfree(a);
10376 }
10377
10378
10379 void
10380 mpi_assign_limb_space( MPI a, mpi_ptr_t ap, unsigned nlimbs )
10381 {
10382 mpi_free_limb_space(a->d);
10383 a->d = ap;
10384 a->alloced = nlimbs;
10385 }
10386
10387
10388
10389 /****************
10390 * Resize the array of A to NLIMBS. the additional space is cleared
10391 * (set to 0) [done by xrealloc()]
10392 */
10393 void
10394 #ifdef M_DEBUG
10395 mpi_debug_resize( MPI a, unsigned nlimbs, const char *info )
10396 #else
10397 mpi_resize( MPI a, unsigned nlimbs )
10398 #endif
10399 {
10400 if( nlimbs <= a->alloced )
10401 return; /* no need to do it */
10402 /* Note: a->secure is not used - instead the realloc functions
10403 * take care of it. Maybe we should drop a->secure completely
10404 * and rely on a mpi_is_secure function, which would be
10405 * a wrapper around m_is_secure
10406 */
10407 #ifdef M_DEBUG
10408 if( a->d )
10409 a->d = m_debug_realloc(a->d, nlimbs * sizeof(mpi_limb_t), info );
10410 else
10411 a->d = m_debug_alloc_clear( nlimbs * sizeof(mpi_limb_t), info );
10412 #else
10413 if( a->d )
10414 a->d = xrealloc(a->d, nlimbs * sizeof(mpi_limb_t) );
10415 else
10416 a->d = xmalloc_clear( nlimbs * sizeof(mpi_limb_t) );
10417 #endif
10418 a->alloced = nlimbs;
10419 }
10420
10421 void
10422 mpi_clear( MPI a )
10423 {
10424 a->nlimbs = 0;
10425 a->nbits = 0;
10426 a->flags = 0;
10427 }
10428
10429
10430 void
10431 #ifdef M_DEBUG
10432 mpi_debug_free( MPI a, const char *info )
10433 #else
10434 mpi_free( MPI a )
10435 #endif
10436 {
10437 if( !a )
10438 return;
10439 if( DBG_MEMORY )
10440 log_debug("mpi_free\n" );
10441 if( a->flags & 4 )
10442 xfree( a->d );
10443 else {
10444 #ifdef M_DEBUG
10445 mpi_debug_free_limb_space(a->d, info);
10446 #else
10447 mpi_free_limb_space(a->d);
10448 #endif
10449 }
10450 if( a->flags & ~7 )
10451 log_bug("invalid flag value in mpi\n");
10452 xfree(a);
10453 }
10454
10455
10456 void
10457 mpi_set_secure( MPI a )
10458 {
10459 mpi_ptr_t ap, bp;
10460
10461 if( (a->flags & 1) )
10462 return;
10463 a->flags |= 1;
10464 ap = a->d;
10465 if( !a->nlimbs ) {
10466 assert(!ap);
10467 return;
10468 }
10469 #ifdef M_DEBUG
10470 bp = mpi_debug_alloc_limb_space( a->nlimbs, 1, "set_secure" );
10471 #else
10472 bp = mpi_alloc_limb_space( a->nlimbs, 1 );
10473 #endif
10474 MPN_COPY( bp, ap, a->nlimbs );
10475 a->d = bp;
10476 #ifdef M_DEBUG
10477 mpi_debug_free_limb_space(ap, "set_secure");
10478 #else
10479 mpi_free_limb_space(ap);
10480 #endif
10481 }
10482
10483
10484 MPI
10485 mpi_set_opaque( MPI a, void *p, unsigned int len )
10486 {
10487 if( !a ) {
10488 #ifdef M_DEBUG
10489 a = mpi_debug_alloc(0,"alloc_opaque");
10490 #else
10491 a = mpi_alloc(0);
10492 #endif
10493 }
10494
10495 if( a->flags & 4 )
10496 xfree( a->d );
10497 else {
10498 #ifdef M_DEBUG
10499 mpi_debug_free_limb_space(a->d, "alloc_opaque");
10500 #else
10501 mpi_free_limb_space(a->d);
10502 #endif
10503 }
10504
10505 a->d = p;
10506 a->alloced = 0;
10507 a->nlimbs = 0;
10508 a->nbits = len;
10509 a->flags = 4;
10510 return a;
10511 }
10512
10513
10514 void *
10515 mpi_get_opaque( MPI a, unsigned int *len )
10516 {
10517 if( !(a->flags & 4) )
10518 log_bug("mpi_get_opaque on normal mpi\n");
10519 if( len )
10520 *len = a->nbits;
10521 return a->d;
10522 }
10523
10524
10525 /****************
10526 * Note: This copy function should not interpret the MPI
10527 * but copy it transparently.
10528 */
10529 MPI
10530 #ifdef M_DEBUG
10531 mpi_debug_copy( MPI a, const char *info )
10532 #else
10533 mpi_copy( MPI a )
10534 #endif
10535 {
10536 int i;
10537 MPI b;
10538
10539 if( a && (a->flags & 4) ) {
10540 void *p = m_is_secure(a->d)? xmalloc_secure( a->nbits )
10541 : xmalloc( a->nbits );
10542 memcpy( p, a->d, a->nbits );
10543 b = mpi_set_opaque( NULL, p, a->nbits );
10544 }
10545 else if( a ) {
10546 #ifdef M_DEBUG
10547 b = mpi_is_secure(a)? mpi_debug_alloc_secure( a->nlimbs, info )
10548 : mpi_debug_alloc( a->nlimbs, info );
10549 #else
10550 b = mpi_is_secure(a)? mpi_alloc_secure( a->nlimbs )
10551 : mpi_alloc( a->nlimbs );
10552 #endif
10553 b->nlimbs = a->nlimbs;
10554 b->sign = a->sign;
10555 b->flags = a->flags;
10556 b->nbits = a->nbits;
10557 for(i=0; i < b->nlimbs; i++ )
10558 b->d[i] = a->d[i];
10559 }
10560 else
10561 b = NULL;
10562 return b;
10563 }
10564
10565
10566 /****************
10567 * This function allocates an MPI which is optimized to hold
10568 * a value as large as the one given in the argument and allocates it
10569 * with the same flags as A.
10570 */
10571 MPI
10572 #ifdef M_DEBUG
10573 mpi_debug_alloc_like( MPI a, const char *info )
10574 #else
10575 mpi_alloc_like( MPI a )
10576 #endif
10577 {
10578 MPI b;
10579
10580 if( a && (a->flags & 4) ) {
10581 void *p = m_is_secure(a->d)? xmalloc_secure( a->nbits )
10582 : xmalloc( a->nbits );
10583 memcpy( p, a->d, a->nbits );
10584 b = mpi_set_opaque( NULL, p, a->nbits );
10585 }
10586 else if( a ) {
10587 #ifdef M_DEBUG
10588 b = mpi_is_secure(a)? mpi_debug_alloc_secure( a->nlimbs, info )
10589 : mpi_debug_alloc( a->nlimbs, info );
10590 #else
10591 b = mpi_is_secure(a)? mpi_alloc_secure( a->nlimbs )
10592 : mpi_alloc( a->nlimbs );
10593 #endif
10594 b->nlimbs = 0;
10595 b->sign = 0;
10596 b->flags = a->flags;
10597 b->nbits = 0;
10598 }
10599 else
10600 b = NULL;
10601 return b;
10602 }
10603
10604
10605 void
10606 mpi_set( MPI w, MPI u)
10607 {
10608 mpi_ptr_t wp, up;
10609 mpi_size_t usize = u->nlimbs;
10610 int usign = u->sign;
10611
10612 RESIZE_IF_NEEDED(w, usize);
10613 wp = w->d;
10614 up = u->d;
10615 MPN_COPY( wp, up, usize );
10616 w->nlimbs = usize;
10617 w->nbits = u->nbits;
10618 w->flags = u->flags;
10619 w->sign = usign;
10620 }
10621
10622
10623 void
10624 mpi_set_ui( MPI w, unsigned long u)
10625 {
10626 RESIZE_IF_NEEDED(w, 1);
10627 w->d[0] = u;
10628 w->nlimbs = u? 1:0;
10629 w->sign = 0;
10630 w->nbits = 0;
10631 w->flags = 0;
10632 }
10633
10634
10635 MPI
10636 mpi_alloc_set_ui( unsigned long u)
10637 {
10638 #ifdef M_DEBUG
10639 MPI w = mpi_debug_alloc(1,"alloc_set_ui");
10640 #else
10641 MPI w = mpi_alloc(1);
10642 #endif
10643 w->d[0] = u;
10644 w->nlimbs = u? 1:0;
10645 w->sign = 0;
10646 return w;
10647 }
10648
10649
10650 void
10651 mpi_swap( MPI a, MPI b)
10652 {
10653 struct gcry_mpi tmp;
10654
10655 tmp = *a; *a = *b; *b = tmp;
10656 }
10657
10658
10659 int
10660 mpi_get_nlimbs (MPI a)
10661 {
10662 return a->nlimbs;
10663 }
10664
10665
10666 int
10667 mpi_is_neg (MPI a)
10668 {
10669 return a->sign;
10670 }
10671
10672
10673 /* Return the number of limbs to store an MPI which is specified by
10674 the number of bytes to represent it. */
10675 unsigned int
10676 mpi_nlimb_hint_from_nbytes (unsigned int nbytes)
10677 {
10678 return (nbytes+BYTES_PER_MPI_LIMB-1) / BYTES_PER_MPI_LIMB;
10679 }
10680
10681 /* Return the number of limbs to store an MPI which is specified by
10682 the number of bytes to represent it. */
10683 unsigned int
10684 mpi_nlimb_hint_from_nbits (unsigned int nbits)
10685 {
10686 return (nbits+BITS_PER_MPI_LIMB-1) / BITS_PER_MPI_LIMB;
10687 }
10688
10689 unsigned int
10690 mpi_get_flags (MPI a)
10691 {
10692 return a->flags;
10693 }
-
+ 0FBA934FB804042EF44214806D9256EE9D9E9A51878CA97942941C1EF5A9E81F779C2AB99C0C6F3C9DD01A748DB7D4624E35635FD2A748DF00655F95CBD98F22
mpi/obj/README
(0 . 0)(1 . 1)
10698 obj
-
+ A0B28117315BD9560BE404C97E44252316FD19FF9CBC762BF5D46235034846155D5058E22A73D7010F78CF7442BA6624E2417A719FFCBE2F8A163090706E069C
mpi/secmem.c
(0 . 0)(1 . 519)
10704 /* secmem.c - memory allocation from a secure heap
10705 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
10706 * 2007 Free Software Foundation, Inc.
10707 *
10708 * This file is part of GnuPG.
10709 *
10710 * GnuPG is free software; you can redistribute it and/or modify
10711 * it under the terms of the GNU General Public License as published by
10712 * the Free Software Foundation; either version 3 of the License, or
10713 * (at your option) any later version.
10714 *
10715 * GnuPG is distributed in the hope that it will be useful,
10716 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10717 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10718 * GNU General Public License for more details.
10719 *
10720 * You should have received a copy of the GNU General Public License
10721 * along with this program; if not, see <http://www.gnu.org/licenses/>.
10722 */
10723
10724 #include <config.h>
10725 #include <stdio.h>
10726 #include <stdlib.h>
10727 #include <string.h>
10728 #include <errno.h>
10729 #include <stdarg.h>
10730 #include <unistd.h>
10731 #if defined(HAVE_MLOCK) || defined(HAVE_MMAP)
10732 #include <sys/mman.h>
10733 #include <sys/types.h>
10734 #include <fcntl.h>
10735 #ifdef USE_CAPABILITIES
10736 #include <sys/capability.h>
10737 #endif
10738 #ifdef HAVE_PLOCK
10739 #include <sys/lock.h>
10740 #endif
10741 #endif
10742
10743 #include "types.h"
10744 #include "memory.h"
10745 #include "util.h"
10746
10747 /* MinGW doesn't seem to prototype getpagesize, though it does have
10748 it. */
10749 #if !HAVE_DECL_GETPAGESIZE
10750 int getpagesize(void);
10751 #endif
10752
10753 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
10754 #define MAP_ANONYMOUS MAP_ANON
10755 #endif
10756 /* It seems that Slackware 7.1 does not know about EPERM */
10757 #if !defined(EPERM) && defined(ENOMEM)
10758 #define EPERM ENOMEM
10759 #endif
10760
10761
10762 #define DEFAULT_POOLSIZE 16384
10763
10764 typedef struct memblock_struct MEMBLOCK;
10765 struct memblock_struct {
10766 unsigned size;
10767 union {
10768 MEMBLOCK *next;
10769 PROPERLY_ALIGNED_TYPE aligned;
10770 } u;
10771 };
10772
10773
10774
10775 static void *pool;
10776 static volatile int pool_okay; /* may be checked in an atexit function */
10777 #ifdef HAVE_MMAP
10778 static volatile int pool_is_mmapped;
10779 #endif
10780 static size_t poolsize; /* allocated length */
10781 static size_t poollen; /* used length */
10782 static MEMBLOCK *unused_blocks;
10783 static unsigned max_alloced;
10784 static unsigned cur_alloced;
10785 static unsigned max_blocks;
10786 static unsigned cur_blocks;
10787 static int disable_secmem;
10788 static int show_warning;
10789 static int no_warning;
10790 static int suspend_warning;
10791
10792
10793 static void
10794 print_warn(void)
10795 {
10796 if (!no_warning)
10797 {
10798 log_info(_("WARNING: using insecure memory!\n"));
10799 log_info(_("please see http://www.gnupg.org/faq.html"
10800 " for more information\n"));
10801 }
10802 }
10803
10804
10805 static void
10806 lock_pool( void *p, size_t n )
10807 {
10808 #if defined(USE_CAPABILITIES) && defined(HAVE_MLOCK)
10809 int err;
10810
10811 cap_set_proc( cap_from_text("cap_ipc_lock+ep") );
10812 err = mlock( p, n );
10813 if( err && errno )
10814 err = errno;
10815 cap_set_proc( cap_from_text("cap_ipc_lock+p") );
10816
10817 if( err ) {
10818 if( errno != EPERM
10819 #ifdef EAGAIN /* OpenBSD returns this */
10820 && errno != EAGAIN
10821 #endif
10822 #ifdef ENOSYS /* Some SCOs return this (function not implemented) */
10823 && errno != ENOSYS
10824 #endif
10825 #ifdef ENOMEM /* Linux can return this */
10826 && errno != ENOMEM
10827 #endif
10828 )
10829 log_error("can't lock memory: %s\n", strerror(err));
10830 show_warning = 1;
10831 }
10832
10833 #elif defined(HAVE_MLOCK)
10834 uid_t uid;
10835 int err;
10836
10837 uid = getuid();
10838
10839 #ifdef HAVE_BROKEN_MLOCK
10840 /* ick. but at least we get secured memory. about to lock
10841 entire data segment. */
10842 #ifdef HAVE_PLOCK
10843 # ifdef _AIX
10844 /* The configure for AIX returns broken mlock but the plock has
10845 the strange requirement to somehow set the stack limit first.
10846 The problem might turn out in indeterministic program behaviour
10847 and hanging processes which can somehow be solved when enough
10848 processes are clogging up the memory. To get this problem out
10849 of the way we simply don't try to lock the memory at all.
10850 */
10851 errno = EPERM;
10852 err = errno;
10853 # else /* !_AIX */
10854 err = plock( DATLOCK );
10855 if( err && errno )
10856 err = errno;
10857 # endif /*_AIX*/
10858 #else /*!HAVE_PLOCK*/
10859 if( uid ) {
10860 errno = EPERM;
10861 err = errno;
10862 }
10863 else {
10864 err = mlock( p, n );
10865 if( err && errno )
10866 err = errno;
10867 }
10868 #endif /*!HAVE_PLOCK*/
10869 #else
10870 err = mlock( p, n );
10871 if( err && errno )
10872 err = errno;
10873 #endif
10874
10875 if( uid && !geteuid() ) {
10876 /* check that we really dropped the privs.
10877 * Note: setuid(0) should always fail */
10878 if( setuid( uid ) || getuid() != geteuid() || !setuid(0) )
10879 log_fatal("failed to reset uid: %s\n", strerror(errno));
10880 }
10881
10882 if( err ) {
10883 if( errno != EPERM
10884 #ifdef EAGAIN /* OpenBSD returns this */
10885 && errno != EAGAIN
10886 #endif
10887 #ifdef ENOSYS /* Some SCOs return this (function not implemented) */
10888 && errno != ENOSYS
10889 #endif
10890 #ifdef ENOMEM /* Linux can return this */
10891 && errno != ENOMEM
10892 #endif
10893 )
10894 log_error("can't lock memory: %s\n", strerror(err));
10895 show_warning = 1;
10896 }
10897
10898 #elif defined ( __QNX__ )
10899 /* QNX does not page at all, so the whole secure memory stuff does
10900 * not make much sense. However it is still of use because it
10901 * wipes out the memory on a free().
10902 * Therefore it is sufficient to suppress the warning
10903 */
10904 #elif defined (HAVE_DOSISH_SYSTEM) || defined (__CYGWIN__)
10905 /* It does not make sense to print such a warning, given the fact that
10906 * this whole Windows !@#$% and their user base are inherently insecure
10907 */
10908 #elif defined (__riscos__)
10909 /* no virtual memory on RISC OS, so no pages are swapped to disc,
10910 * besides we don't have mmap, so we don't use it! ;-)
10911 * But don't complain, as explained above.
10912 */
10913 #else
10914 log_info("Please note that you don't have secure memory on this system\n");
10915 #endif
10916 }
10917
10918
10919 static void
10920 init_pool( size_t n)
10921 {
10922 long int pgsize_val;
10923 size_t pgsize;
10924
10925 poolsize = n;
10926
10927 if( disable_secmem )
10928 log_bug("secure memory is disabled");
10929
10930 #if defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
10931 pgsize_val = sysconf (_SC_PAGESIZE);
10932 #elif defined(HAVE_GETPAGESIZE)
10933 pgsize_val = getpagesize ();
10934 #else
10935 pgsize_val = -1;
10936 #endif
10937 pgsize = (pgsize_val != -1 && pgsize_val > 0)? pgsize_val : 4096;
10938
10939
10940 #ifdef HAVE_MMAP
10941 poolsize = (poolsize + pgsize -1 ) & ~(pgsize-1);
10942 #ifdef MAP_ANONYMOUS
10943 pool = mmap( 0, poolsize, PROT_READ|PROT_WRITE,
10944 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
10945 #else /* map /dev/zero instead */
10946 { int fd;
10947
10948 fd = open("/dev/zero", O_RDWR);
10949 if( fd == -1 ) {
10950 log_error("can't open /dev/zero: %s\n", strerror(errno) );
10951 pool = (void*)-1;
10952 }
10953 else {
10954 pool = mmap( 0, poolsize, PROT_READ|PROT_WRITE,
10955 MAP_PRIVATE, fd, 0);
10956 close (fd);
10957 }
10958 }
10959 #endif
10960 if( pool == (void*)-1 )
10961 log_info("can't mmap pool of %u bytes: %s - using malloc\n",
10962 (unsigned)poolsize, strerror(errno));
10963 else {
10964 pool_is_mmapped = 1;
10965 pool_okay = 1;
10966 }
10967
10968 #endif
10969 if( !pool_okay ) {
10970 pool = malloc( poolsize );
10971 if( !pool )
10972 log_fatal("can't allocate memory pool of %u bytes\n",
10973 (unsigned)poolsize);
10974 else
10975 pool_okay = 1;
10976 }
10977 lock_pool( pool, poolsize );
10978 poollen = 0;
10979 }
10980
10981
10982 /* concatenate unused blocks */
10983 static void
10984 compress_pool(void)
10985 {
10986 /* fixme: we really should do this */
10987 }
10988
10989 void
10990 secmem_set_flags( unsigned flags )
10991 {
10992 int was_susp = suspend_warning;
10993
10994 no_warning = flags & 1;
10995 suspend_warning = flags & 2;
10996
10997 /* and now issue the warning if it is not longer suspended */
10998 if( was_susp && !suspend_warning && show_warning ) {
10999 show_warning = 0;
11000 print_warn();
11001 }
11002 }
11003
11004 unsigned
11005 secmem_get_flags(void)
11006 {
11007 unsigned flags;
11008
11009 flags = no_warning ? 1:0;
11010 flags |= suspend_warning ? 2:0;
11011 return flags;
11012 }
11013
11014 /* Returns 1 if memory was locked, 0 if not. */
11015 int
11016 secmem_init( size_t n )
11017 {
11018 if( !n ) {
11019 #ifndef __riscos__
11020 #ifdef USE_CAPABILITIES
11021 /* drop all capabilities */
11022 cap_set_proc( cap_from_text("all-eip") );
11023
11024 #elif !defined(HAVE_DOSISH_SYSTEM)
11025 uid_t uid;
11026
11027 disable_secmem=1;
11028 uid = getuid();
11029 if( uid != geteuid() ) {
11030 if( setuid( uid ) || getuid() != geteuid() || !setuid(0) )
11031 log_fatal("failed to drop setuid\n" );
11032 }
11033 #endif
11034 #endif /* !__riscos__ */
11035 }
11036 else {
11037 if( n < DEFAULT_POOLSIZE )
11038 n = DEFAULT_POOLSIZE;
11039 if( !pool_okay )
11040 init_pool(n);
11041 else
11042 log_error("Oops, secure memory pool already initialized\n");
11043 }
11044
11045 return !show_warning;
11046 }
11047
11048
11049 void *
11050 secmem_malloc( size_t size )
11051 {
11052 MEMBLOCK *mb, *mb2;
11053 int compressed=0;
11054
11055 if( !pool_okay ) {
11056 log_info(
11057 _("operation is not possible without initialized secure memory\n"));
11058 log_info(_("(you may have used the wrong program for this task)\n"));
11059 exit(2);
11060 }
11061 if( show_warning && !suspend_warning ) {
11062 show_warning = 0;
11063 print_warn();
11064 }
11065
11066 /* Blocks are always a multiple of 32. Note that we allocate an
11067 extra of the size of an entire MEMBLOCK. This is required
11068 becuase we do not only need the SIZE info but also extra space
11069 to chain up unused memory blocks. */
11070 size += sizeof(MEMBLOCK);
11071 size = ((size + 31) / 32) * 32;
11072
11073 retry:
11074 /* try to get it from the used blocks */
11075 for(mb = unused_blocks,mb2=NULL; mb; mb2=mb, mb = mb->u.next )
11076 if( mb->size >= size ) {
11077 if( mb2 )
11078 mb2->u.next = mb->u.next;
11079 else
11080 unused_blocks = mb->u.next;
11081 goto leave;
11082 }
11083 /* allocate a new block */
11084 if( (poollen + size <= poolsize) ) {
11085 mb = (void*)((char*)pool + poollen);
11086 poollen += size;
11087 mb->size = size;
11088 }
11089 else if( !compressed ) {
11090 compressed=1;
11091 compress_pool();
11092 goto retry;
11093 }
11094 else
11095 return NULL;
11096
11097 leave:
11098 cur_alloced += mb->size;
11099 cur_blocks++;
11100 if( cur_alloced > max_alloced )
11101 max_alloced = cur_alloced;
11102 if( cur_blocks > max_blocks )
11103 max_blocks = cur_blocks;
11104
11105 return &mb->u.aligned.c;
11106 }
11107
11108
11109 void *
11110 secmexrealloc( void *p, size_t newsize )
11111 {
11112 MEMBLOCK *mb;
11113 size_t size;
11114 void *a;
11115
11116 mb = (MEMBLOCK*)((char*)p - ((size_t) &((MEMBLOCK*)0)->u.aligned.c));
11117 size = mb->size;
11118 if (size < sizeof(MEMBLOCK))
11119 log_bug ("secure memory corrupted at block %p\n", (void *)mb);
11120 size -= ((size_t) &((MEMBLOCK*)0)->u.aligned.c);
11121
11122 if( newsize <= size )
11123 return p; /* It is easier not to shrink the memory. */
11124 a = secmem_malloc( newsize );
11125 if ( a ) {
11126 memcpy(a, p, size);
11127 memset((char*)a+size, 0, newsize-size);
11128 secmem_free(p);
11129 }
11130 return a;
11131 }
11132
11133
11134 void
11135 secmem_free( void *a )
11136 {
11137 MEMBLOCK *mb;
11138 size_t size;
11139
11140 if( !a )
11141 return;
11142
11143 mb = (MEMBLOCK*)((char*)a - ((size_t) &((MEMBLOCK*)0)->u.aligned.c));
11144 size = mb->size;
11145 /* This does not make much sense: probably this memory is held in the
11146 * cache. We do it anyway: */
11147 wipememory2(mb, 0xff, size );
11148 wipememory2(mb, 0xaa, size );
11149 wipememory2(mb, 0x55, size );
11150 wipememory2(mb, 0x00, size );
11151 mb->size = size;
11152 mb->u.next = unused_blocks;
11153 unused_blocks = mb;
11154 cur_blocks--;
11155 cur_alloced -= size;
11156 }
11157
11158
11159 /* Check whether P points into the pool. */
11160 static int
11161 ptr_into_pool_p (const void *p)
11162 {
11163 /* We need to convert pointers to addresses. This is required by
11164 C-99 6.5.8 to avoid undefined behaviour. Using size_t is at
11165 least only implementation defined. See also
11166 http://lists.gnupg.org/pipermail/gcrypt-devel/2007-February/001102.html
11167 */
11168 size_t p_addr = (size_t)p;
11169 size_t pool_addr = (size_t)pool;
11170
11171 return p_addr >= pool_addr && p_addr < pool_addr+poolsize;
11172 }
11173
11174
11175 int
11176 m_is_secure( const void *p )
11177 {
11178 return pool_okay && ptr_into_pool_p (p);
11179 }
11180
11181
11182
11183 /****************
11184 * Warning: This code might be called by an interrupt handler
11185 * and frankly, there should really be such a handler,
11186 * to make sure that the memory is wiped out.
11187 * We hope that the OS wipes out mlocked memory after
11188 * receiving a SIGKILL - it really should do so, otherwise
11189 * there is no chance to get the secure memory cleaned.
11190 */
11191 void
11192 secmem_term()
11193 {
11194 if( !pool_okay )
11195 return;
11196
11197 wipememory2( pool, 0xff, poolsize);
11198 wipememory2( pool, 0xaa, poolsize);
11199 wipememory2( pool, 0x55, poolsize);
11200 wipememory2( pool, 0x00, poolsize);
11201 #ifdef HAVE_MMAP
11202 if( pool_is_mmapped )
11203 munmap( pool, poolsize );
11204 #endif
11205 pool = NULL;
11206 pool_okay = 0;
11207 poolsize=0;
11208 poollen=0;
11209 unused_blocks=NULL;
11210 }
11211
11212
11213 void
11214 secmem_dump_stats()
11215 {
11216 if( disable_secmem )
11217 return;
11218 fprintf(stderr,
11219 "secmem usage: %u/%u bytes in %u/%u blocks of pool %lu/%lu\n",
11220 cur_alloced, max_alloced, cur_blocks, max_blocks,
11221 (ulong)poollen, (ulong)poolsize );
11222 }
-
+ FB984A326A9BCDA1A4CBC05EE279E55CFEFCF157393D2F66405760B256395C3A73F1F41EBFC335722022EA04C79F6E02AB3179ECC9A66E037DD7A106572B4924
mpi/udiv-w-sdiv.c
(0 . 0)(1 . 132)
11227 /* mpihelp_udiv_w_sdiv -- implement udiv_qrnnd on machines with only signed
11228 * division.
11229 * Copyright (C) 1992, 1994, 1996, 1998 Free Software Foundation, Inc.
11230 * Contributed by Peter L. Montgomery.
11231 *
11232 * This file is part of GnuPG.
11233 *
11234 * GnuPG is free software; you can redistribute it and/or modify
11235 * it under the terms of the GNU General Public License as published by
11236 * the Free Software Foundation; either version 3 of the License, or
11237 * (at your option) any later version.
11238 *
11239 * GnuPG is distributed in the hope that it will be useful,
11240 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11241 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11242 * GNU General Public License for more details.
11243 *
11244 * You should have received a copy of the GNU General Public License
11245 * along with this program; if not, see <http://www.gnu.org/licenses/>.
11246 */
11247
11248 #include <config.h>
11249 #include <stdio.h>
11250 #include <stdlib.h>
11251 #include "mpi-internal.h"
11252 #include "longlong.h"
11253
11254
11255 #if 0 /* not yet ported to MPI */
11256
11257 mpi_limb_t
11258 mpihelp_udiv_w_sdiv( mpi_limp_t *rp,
11259 mpi_limp_t *a1,
11260 mpi_limp_t *a0,
11261 mpi_limp_t *d )
11262 {
11263 mp_limb_t q, r;
11264 mp_limb_t c0, c1, b1;
11265
11266 if ((mpi_limb_signed_t) d >= 0)
11267 {
11268 if (a1 < d - a1 - (a0 >> (BITS_PER_MP_LIMB - 1)))
11269 {
11270 /* dividend, divisor, and quotient are nonnegative */
11271 sdiv_qrnnd (q, r, a1, a0, d);
11272 }
11273 else
11274 {
11275 /* Compute c1*2^32 + c0 = a1*2^32 + a0 - 2^31*d */
11276 sub_ddmmss (c1, c0, a1, a0, d >> 1, d << (BITS_PER_MP_LIMB - 1));
11277 /* Divide (c1*2^32 + c0) by d */
11278 sdiv_qrnnd (q, r, c1, c0, d);
11279 /* Add 2^31 to quotient */
11280 q += (mp_limb_t) 1 << (BITS_PER_MP_LIMB - 1);
11281 }
11282 }
11283 else
11284 {
11285 b1 = d >> 1; /* d/2, between 2^30 and 2^31 - 1 */
11286 c1 = a1 >> 1; /* A/2 */
11287 c0 = (a1 << (BITS_PER_MP_LIMB - 1)) + (a0 >> 1);
11288
11289 if (a1 < b1) /* A < 2^32*b1, so A/2 < 2^31*b1 */
11290 {
11291 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
11292
11293 r = 2*r + (a0 & 1); /* Remainder from A/(2*b1) */
11294 if ((d & 1) != 0)
11295 {
11296 if (r >= q)
11297 r = r - q;
11298 else if (q - r <= d)
11299 {
11300 r = r - q + d;
11301 q--;
11302 }
11303 else
11304 {
11305 r = r - q + 2*d;
11306 q -= 2;
11307 }
11308 }
11309 }
11310 else if (c1 < b1) /* So 2^31 <= (A/2)/b1 < 2^32 */
11311 {
11312 c1 = (b1 - 1) - c1;
11313 c0 = ~c0; /* logical NOT */
11314
11315 sdiv_qrnnd (q, r, c1, c0, b1); /* (A/2) / (d/2) */
11316
11317 q = ~q; /* (A/2)/b1 */
11318 r = (b1 - 1) - r;
11319
11320 r = 2*r + (a0 & 1); /* A/(2*b1) */
11321
11322 if ((d & 1) != 0)
11323 {
11324 if (r >= q)
11325 r = r - q;
11326 else if (q - r <= d)
11327 {
11328 r = r - q + d;
11329 q--;
11330 }
11331 else
11332 {
11333 r = r - q + 2*d;
11334 q -= 2;
11335 }
11336 }
11337 }
11338 else /* Implies c1 = b1 */
11339 { /* Hence a1 = d - 1 = 2*b1 - 1 */
11340 if (a0 >= -d)
11341 {
11342 q = -1;
11343 r = a0 + d;
11344 }
11345 else
11346 {
11347 q = -2;
11348 r = a0 + 2*d;
11349 }
11350 }
11351 }
11352
11353 *rp = r;
11354 return q;
11355 }
11356
11357 #endif
11358