2006-05-19 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / gpg.c
blob25b55b705dd60fff547427539cd71c1594503a41
1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <ctype.h>
29 #include <unistd.h>
30 #include <assert.h>
31 #ifdef HAVE_DOSISH_SYSTEM
32 #include <fcntl.h> /* for setmode() */
33 #endif
34 #ifdef HAVE_STAT
35 #include <sys/stat.h> /* for stat() */
36 #endif
37 #include <fcntl.h>
38 #include <assuan.h>
39 #ifdef HAVE_W32_SYSTEM
40 #include <windows.h>
41 #endif
43 #define INCLUDED_BY_MAIN_MODULE 1
44 #include "gpg.h"
45 #include "packet.h"
46 #include "../common/iobuf.h"
47 #include "util.h"
48 #include "main.h"
49 #include "options.h"
50 #include "keydb.h"
51 #include "trustdb.h"
52 #include "cipher.h"
53 #include "filter.h"
54 #include "ttyio.h"
55 #include "i18n.h"
56 #include "status.h"
57 #include "keyserver-internal.h"
58 #include "exec.h"
61 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
62 #define MY_O_BINARY O_BINARY
63 #ifndef S_IRGRP
64 # define S_IRGRP 0
65 # define S_IWGRP 0
66 #endif
67 #else
68 #define MY_O_BINARY 0
69 #endif
72 enum cmd_and_opt_values
74 aNull = 0,
75 oArmor = 'a',
76 aDetachedSign = 'b',
77 aSym = 'c',
78 aDecrypt = 'd',
79 aEncr = 'e',
80 oInteractive = 'i',
81 oKOption = 'k',
82 oDryRun = 'n',
83 oOutput = 'o',
84 oQuiet = 'q',
85 oRecipient = 'r',
86 oHiddenRecipient = 'R',
87 aSign = 's',
88 oTextmodeShort= 't',
89 oLocalUser = 'u',
90 oVerbose = 'v',
91 oCompress = 'z',
92 oSetNotation = 'N',
93 aListSecretKeys = 'K',
94 oBatch = 500,
95 oMaxOutput,
96 oSigNotation,
97 oCertNotation,
98 oShowNotation,
99 oNoShowNotation,
100 aEncrFiles,
101 aEncrSym,
102 aDecryptFiles,
103 aClearsign,
104 aStore,
105 aKeygen,
106 aSignEncr,
107 aSignEncrSym,
108 aSignSym,
109 aSignKey,
110 aLSignKey,
111 aListConfig,
112 aGPGConfList,
113 aListPackets,
114 aEditKey,
115 aDeleteKeys,
116 aDeleteSecretKeys,
117 aDeleteSecretAndPublicKeys,
118 aKMode,
119 aKModeC,
120 aImport,
121 aFastImport,
122 aVerify,
123 aVerifyFiles,
124 aListKeys,
125 aListSigs,
126 aSendKeys,
127 aRecvKeys,
128 aSearchKeys,
129 aRefreshKeys,
130 aFetchKeys,
131 aExport,
132 aExportSecret,
133 aExportSecretSub,
134 aCheckKeys,
135 aGenRevoke,
136 aDesigRevoke,
137 aPrimegen,
138 aPrintMD,
139 aPrintMDs,
140 aCheckTrustDB,
141 aUpdateTrustDB,
142 aFixTrustDB,
143 aListTrustDB,
144 aListTrustPath,
145 aExportOwnerTrust,
146 aListOwnerTrust,
147 aImportOwnerTrust,
148 aDeArmor,
149 aEnArmor,
150 aGenRandom,
151 aRebuildKeydbCaches,
152 aCardStatus,
153 aCardEdit,
154 aChangePIN,
156 oTextmode,
157 oNoTextmode,
158 oExpert,
159 oNoExpert,
160 oDefSigExpire,
161 oAskSigExpire,
162 oNoAskSigExpire,
163 oDefCertExpire,
164 oAskCertExpire,
165 oNoAskCertExpire,
166 oDefCertLevel,
167 oMinCertLevel,
168 oAskCertLevel,
169 oNoAskCertLevel,
170 oFingerprint,
171 oWithFingerprint,
172 oAnswerYes,
173 oAnswerNo,
174 oKeyring,
175 oPrimaryKeyring,
176 oSecretKeyring,
177 oShowKeyring,
178 oDefaultKey,
179 oDefRecipient,
180 oDefRecipientSelf,
181 oNoDefRecipient,
182 oOptions,
183 oDebug,
184 oDebugLevel,
185 oDebugAll,
186 oDebugCCIDDriver,
187 oStatusFD,
188 oStatusFile,
189 oAttributeFD,
190 oAttributeFile,
191 oEmitVersion,
192 oNoEmitVersion,
193 oCompletesNeeded,
194 oMarginalsNeeded,
195 oMaxCertDepth,
196 oLoadExtension,
197 oGnuPG,
198 oRFC1991,
199 oRFC2440,
200 oOpenPGP,
201 oPGP2,
202 oPGP6,
203 oPGP7,
204 oPGP8,
205 oRFC2440Text,
206 oNoRFC2440Text,
207 oCipherAlgo,
208 oDigestAlgo,
209 oCertDigestAlgo,
210 oCompressAlgo,
211 oCompressLevel,
212 oBZ2CompressLevel,
213 oBZ2DecompressLowmem,
214 oPasswd,
215 oPasswdFD,
216 oPasswdFile,
217 oCommandFD,
218 oCommandFile,
219 oQuickRandom,
220 oNoVerbose,
221 oTrustDBName,
222 oNoSecmemWarn,
223 oRequireSecmem,
224 oNoRequireSecmem,
225 oNoPermissionWarn,
226 oNoMDCWarn,
227 oNoArmor,
228 oNoDefKeyring,
229 oNoGreeting,
230 oNoTTY,
231 oNoOptions,
232 oNoBatch,
233 oHomedir,
234 oWithColons,
235 oWithKeyData,
236 oSkipVerify,
237 oCompressKeys,
238 oCompressSigs,
239 oAlwaysTrust,
240 oTrustModel,
241 oForceOwnertrust,
242 oSetFilename,
243 oForYourEyesOnly,
244 oNoForYourEyesOnly,
245 oSetPolicyURL,
246 oSigPolicyURL,
247 oCertPolicyURL,
248 oShowPolicyURL,
249 oNoShowPolicyURL,
250 oSigKeyserverURL,
251 oUseEmbeddedFilename,
252 oNoUseEmbeddedFilename,
253 oComment,
254 oDefaultComment,
255 oNoComments,
256 oThrowKeyids,
257 oNoThrowKeyids,
258 oShowPhotos,
259 oNoShowPhotos,
260 oPhotoViewer,
261 oForceV3Sigs,
262 oNoForceV3Sigs,
263 oForceV4Certs,
264 oNoForceV4Certs,
265 oForceMDC,
266 oNoForceMDC,
267 oDisableMDC,
268 oNoDisableMDC,
269 oS2KMode,
270 oS2KDigest,
271 oS2KCipher,
272 oSimpleSKChecksum,
273 oDisplayCharset,
274 oNotDashEscaped,
275 oEscapeFrom,
276 oNoEscapeFrom,
277 oLockOnce,
278 oLockMultiple,
279 oLockNever,
280 oKeyServer,
281 oKeyServerOptions,
282 oImportOptions,
283 oExportOptions,
284 oListOptions,
285 oVerifyOptions,
286 oTempDir,
287 oExecPath,
288 oEncryptTo,
289 oHiddenEncryptTo,
290 oNoEncryptTo,
291 oLoggerFD,
292 oLoggerFile,
293 oUtf8Strings,
294 oNoUtf8Strings,
295 oDisableCipherAlgo,
296 oDisablePubkeyAlgo,
297 oAllowNonSelfsignedUID,
298 oNoAllowNonSelfsignedUID,
299 oAllowFreeformUID,
300 oNoAllowFreeformUID,
301 oAllowSecretKeyImport,
302 oEnableSpecialFilenames,
303 oNoLiteral,
304 oSetFilesize,
305 oHonorHttpProxy,
306 oFastListMode,
307 oListOnly,
308 oIgnoreTimeConflict,
309 oIgnoreValidFrom,
310 oIgnoreCrcError,
311 oIgnoreMDCError,
312 oShowSessionKey,
313 oOverrideSessionKey,
314 oNoRandomSeedFile,
315 oAutoKeyRetrieve,
316 oNoAutoKeyRetrieve,
317 oUseAgent,
318 oNoUseAgent,
319 oGpgAgentInfo,
320 oMergeOnly,
321 oTryAllSecrets,
322 oTrustedKey,
323 oNoExpensiveTrustChecks,
324 oFixedListMode,
325 oNoSigCache,
326 oNoSigCreateCheck,
327 oAutoCheckTrustDB,
328 oNoAutoCheckTrustDB,
329 oPreservePermissions,
330 oDefaultPreferenceList,
331 oPersonalCipherPreferences,
332 oPersonalDigestPreferences,
333 oPersonalCompressPreferences,
334 oAgentProgram,
335 oDisplay,
336 oTTYname,
337 oTTYtype,
338 oLCctype,
339 oLCmessages,
340 oGroup,
341 oUnGroup,
342 oNoGroups,
343 oStrict,
344 oNoStrict,
345 oMangleDosFilenames,
346 oNoMangleDosFilenames,
347 oEnableProgressFilter,
348 oMultifile,
349 oKeyidFormat,
350 oExitOnStatusWriteError,
351 oLimitCardInsertTries,
352 oRequireCrossCert,
353 oNoRequireCrossCert,
354 oAutoKeyLocate,
355 oNoAutoKeyLocate,
356 oAllowMultisigVerification,
357 oEnableDSA2,
358 oDisableDSA2,
360 oNoop
364 static ARGPARSE_OPTS opts[] = {
366 { 300, NULL, 0, N_("@Commands:\n ") },
368 { aSign, "sign", 256, N_("|[file]|make a signature")},
369 { aClearsign, "clearsign", 256, N_("|[file]|make a clear text signature")},
370 { aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
371 { aEncr, "encrypt", 256, N_("encrypt data")},
372 { aEncrFiles, "encrypt-files", 256, "@"},
373 { aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
374 { aStore, "store", 256, "@"},
375 { aDecrypt, "decrypt", 256, N_("decrypt data (default)")},
376 { aDecryptFiles, "decrypt-files", 256, "@"},
377 { aVerify, "verify" , 256, N_("verify a signature")},
378 { aVerifyFiles, "verify-files" , 256, "@" },
379 { aListKeys, "list-keys", 256, N_("list keys")},
380 { aListKeys, "list-public-keys", 256, "@" },
381 { aListSigs, "list-sigs", 256, N_("list keys and signatures")},
382 { aCheckKeys, "check-sigs",256, N_("list and check key signatures")},
383 { oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
384 { aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
385 { aKeygen, "gen-key", 256, N_("generate a new key pair")},
386 { aDeleteKeys,"delete-keys",256,N_("remove keys from the public keyring")},
387 { aDeleteSecretKeys, "delete-secret-keys",256,
388 N_("remove keys from the secret keyring")},
389 { aSignKey, "sign-key" ,256, N_("sign a key")},
390 { aLSignKey, "lsign-key" ,256, N_("sign a key locally")},
391 { aEditKey, "edit-key" ,256, N_("sign or edit a key")},
392 { aGenRevoke, "gen-revoke",256, N_("generate a revocation certificate")},
393 { aDesigRevoke, "desig-revoke",256, "@" },
394 { aExport, "export" , 256, N_("export keys") },
395 { aSendKeys, "send-keys" , 256, N_("export keys to a key server") },
396 { aRecvKeys, "recv-keys" , 256, N_("import keys from a key server") },
397 { aSearchKeys, "search-keys" , 256,
398 N_("search for keys on a key server") },
399 { aRefreshKeys, "refresh-keys", 256,
400 N_("update all keys from a keyserver")},
401 { aFetchKeys, "fetch-keys" , 256, "@" },
402 { aExportSecret, "export-secret-keys" , 256, "@" },
403 { aExportSecretSub, "export-secret-subkeys" , 256, "@" },
404 { aImport, "import", 256 , N_("import/merge keys")},
405 { aFastImport, "fast-import", 256 , "@"},
406 #ifdef ENABLE_CARD_SUPPORT
407 { aCardStatus, "card-status", 256, N_("print the card status")},
408 { aCardEdit, "card-edit", 256, N_("change data on a card")},
409 { aChangePIN, "change-pin", 256, N_("change a card's PIN")},
410 #endif
411 { aListConfig, "list-config", 256, "@"},
412 { aGPGConfList, "gpgconf-list", 256, "@" },
413 { aListPackets, "list-packets",256, "@"},
414 { aExportOwnerTrust, "export-ownertrust", 256, "@"},
415 { aImportOwnerTrust, "import-ownertrust", 256, "@"},
416 { aUpdateTrustDB,
417 "update-trustdb",0 , N_("update the trust database")},
418 { aCheckTrustDB, "check-trustdb", 0, "@"},
419 { aFixTrustDB, "fix-trustdb", 0, "@"},
420 { aDeArmor, "dearmor", 256, "@"},
421 { aDeArmor, "dearmour", 256, "@"},
422 { aEnArmor, "enarmor", 256, "@"},
423 { aEnArmor, "enarmour", 256, "@"},
424 { aPrintMD, "print-md" , 256, N_("|algo [files]|print message digests")},
425 { aPrimegen, "gen-prime" , 256, "@" },
426 { aGenRandom, "gen-random" , 256, "@" },
428 { 301, NULL, 0, N_("@\nOptions:\n ") },
430 { oArmor, "armor", 0, N_("create ascii armored output")},
431 { oArmor, "armour", 0, "@" },
432 { oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
433 { oHiddenRecipient, "hidden-recipient", 2, "@" },
434 { oRecipient, "remote-user", 2, "@"}, /* old option name */
435 { oDefRecipient, "default-recipient", 2, "@"},
436 { oDefRecipientSelf, "default-recipient-self", 0, "@"},
437 { oNoDefRecipient, "no-default-recipient", 0, "@" },
438 { oTempDir, "temp-directory", 2, "@" },
439 { oExecPath, "exec-path", 2, "@" },
440 { oEncryptTo, "encrypt-to", 2, "@" },
441 { oHiddenEncryptTo, "hidden-encrypt-to", 2, "@" },
442 { oNoEncryptTo, "no-encrypt-to", 0, "@" },
443 { oLocalUser, "local-user",2, N_("use this user-id to sign or decrypt")},
444 { oCompress, NULL, 1, N_("|N|set compress level N (0 disables)") },
445 { oCompressLevel, "compress-level", 1, "@" },
446 { oBZ2CompressLevel, "bzip2-compress-level", 1, "@" },
447 { oBZ2DecompressLowmem, "bzip2-decompress-lowmem", 0, "@" },
448 { oTextmodeShort, NULL, 0, "@"},
449 { oTextmode, "textmode", 0, N_("use canonical text mode")},
450 { oNoTextmode, "no-textmode", 0, "@"},
451 { oExpert, "expert", 0, "@"},
452 { oNoExpert, "no-expert", 0, "@"},
453 { oDefSigExpire, "default-sig-expire", 2, "@"},
454 { oAskSigExpire, "ask-sig-expire", 0, "@"},
455 { oNoAskSigExpire, "no-ask-sig-expire", 0, "@"},
456 { oDefCertExpire, "default-cert-expire", 2, "@"},
457 { oAskCertExpire, "ask-cert-expire", 0, "@"},
458 { oNoAskCertExpire, "no-ask-cert-expire", 0, "@"},
459 { oDefCertLevel, "default-cert-level", 1, "@"},
460 { oMinCertLevel, "min-cert-level", 1, "@"},
461 { oAskCertLevel, "ask-cert-level", 0, "@"},
462 { oNoAskCertLevel, "no-ask-cert-level", 0, "@"},
463 { oOutput, "output", 2, N_("use as output file")},
464 { oMaxOutput, "max-output", 16|4, "@" },
465 { oVerbose, "verbose", 0, N_("verbose") },
466 { oQuiet, "quiet", 0, "@"},
467 { oNoTTY, "no-tty", 0, "@"},
468 { oForceV3Sigs, "force-v3-sigs", 0, "@"},
469 { oNoForceV3Sigs, "no-force-v3-sigs", 0, "@"},
470 { oForceV4Certs, "force-v4-certs", 0, "@"},
471 { oNoForceV4Certs, "no-force-v4-certs", 0, "@"},
472 { oForceMDC, "force-mdc", 0, "@"},
473 { oNoForceMDC, "no-force-mdc", 0, "@" },
474 { oDisableMDC, "disable-mdc", 0, "@"},
475 { oNoDisableMDC, "no-disable-mdc", 0, "@" },
476 { oDryRun, "dry-run", 0, N_("do not make any changes") },
477 { oInteractive, "interactive", 0, N_("prompt before overwriting") },
478 { oUseAgent, "use-agent",0, "@"},
479 { oNoUseAgent, "no-use-agent",0, "@"},
480 { oGpgAgentInfo, "gpg-agent-info",2, "@"},
481 { oBatch, "batch", 0, "@"},
482 { oAnswerYes, "yes", 0, "@"},
483 { oAnswerNo, "no", 0, "@"},
484 { oKeyring, "keyring", 2, "@"},
485 { oPrimaryKeyring, "primary-keyring",2, "@" },
486 { oSecretKeyring, "secret-keyring", 2, "@"},
487 { oShowKeyring, "show-keyring", 0, "@"},
488 { oDefaultKey, "default-key", 2, "@"},
489 { oKeyServer, "keyserver", 2, "@"},
490 { oKeyServerOptions, "keyserver-options",2,"@"},
491 { oImportOptions, "import-options",2,"@"},
492 { oExportOptions, "export-options",2,"@"},
493 { oListOptions, "list-options",2,"@"},
494 { oVerifyOptions, "verify-options",2,"@"},
495 { oDisplayCharset, "display-charset", 2, "@"},
496 { oDisplayCharset, "charset", 2, "@"},
497 { oOptions, "options", 2, "@"},
498 { oDebug, "debug" ,4|16, "@"},
499 { oDebugLevel, "debug-level" ,2, "@"},
500 { oDebugAll, "debug-all" ,0, "@"},
501 { oStatusFD, "status-fd" ,1, "@"},
502 { oStatusFile, "status-file" ,2, "@"},
503 { oAttributeFD, "attribute-fd" ,1, "@" },
504 { oAttributeFile, "attribute-file" ,2, "@" },
505 { oNoop, "sk-comments", 0, "@"},
506 { oNoop, "no-sk-comments", 0, "@"},
507 { oCompletesNeeded, "completes-needed", 1, "@"},
508 { oMarginalsNeeded, "marginals-needed", 1, "@"},
509 { oMaxCertDepth, "max-cert-depth", 1, "@" },
510 { oTrustedKey, "trusted-key", 2, "@"},
511 { oLoadExtension, "load-extension", 2, "@"},
512 { oGnuPG, "gnupg", 0, "@"},
513 { oGnuPG, "no-pgp2", 0, "@"},
514 { oGnuPG, "no-pgp6", 0, "@"},
515 { oGnuPG, "no-pgp7", 0, "@"},
516 { oGnuPG, "no-pgp8", 0, "@"},
517 { oRFC1991, "rfc1991", 0, "@"},
518 { oRFC2440, "rfc2440", 0, "@" },
519 { oOpenPGP, "openpgp", 0, N_("use strict OpenPGP behavior")},
520 { oPGP2, "pgp2", 0, N_("generate PGP 2.x compatible messages")},
521 { oPGP6, "pgp6", 0, "@"},
522 { oPGP7, "pgp7", 0, "@"},
523 { oPGP8, "pgp8", 0, "@"},
524 { oRFC2440Text, "rfc2440-text", 0, "@"},
525 { oNoRFC2440Text, "no-rfc2440-text", 0, "@"},
526 { oS2KMode, "s2k-mode", 1, "@"},
527 { oS2KDigest, "s2k-digest-algo", 2, "@"},
528 { oS2KCipher, "s2k-cipher-algo", 2, "@"},
529 { oSimpleSKChecksum, "simple-sk-checksum", 0, "@"},
530 { oCipherAlgo, "cipher-algo", 2, "@"},
531 { oDigestAlgo, "digest-algo", 2, "@"},
532 { oCertDigestAlgo, "cert-digest-algo", 2 , "@" },
533 { oCompressAlgo,"compress-algo", 2, "@"},
534 { oCompressAlgo, "compression-algo", 2, "@"}, /* Alias */
535 { oThrowKeyids, "throw-keyid", 0, "@"},
536 { oThrowKeyids, "throw-keyids", 0, "@"},
537 { oNoThrowKeyids, "no-throw-keyid", 0, "@" },
538 { oNoThrowKeyids, "no-throw-keyids", 0, "@" },
539 { oShowPhotos, "show-photos", 0, "@" },
540 { oNoShowPhotos, "no-show-photos", 0, "@" },
541 { oPhotoViewer, "photo-viewer", 2, "@" },
542 { oSetNotation, "set-notation", 2, "@" },
543 { oSetNotation, "notation-data", 2, "@" }, /* Alias */
544 { oSigNotation, "sig-notation", 2, "@" },
545 { oCertNotation, "cert-notation", 2, "@" },
547 { 302, NULL, 0, N_(
548 "@\n(See the man page for a complete listing of all commands and options)\n"
551 { 303, NULL, 0, N_("@\nExamples:\n\n"
552 " -se -r Bob [file] sign and encrypt for user Bob\n"
553 " --clearsign [file] make a clear text signature\n"
554 " --detach-sign [file] make a detached signature\n"
555 " --list-keys [names] show keys\n"
556 " --fingerprint [names] show fingerprints\n" ) },
558 /* hidden options */
559 { aListOwnerTrust, "list-ownertrust", 256, "@"}, /* deprecated */
560 { aPrintMDs, "print-mds" , 256, "@"}, /* old */
561 { aListTrustDB, "list-trustdb",0 , "@"},
562 /* Not yet used */
563 /* { aListTrustPath, "list-trust-path",0, "@"}, */
564 { oKOption, NULL, 0, "@"},
565 { oPasswd, "passphrase",2, "@" },
566 { oPasswdFD, "passphrase-fd",1, "@" },
567 { oPasswdFile, "passphrase-file",2, "@" },
568 { oCommandFD, "command-fd",1, "@" },
569 { oCommandFile, "command-file",2, "@" },
570 { oQuickRandom, "quick-random", 0, "@"},
571 { oNoVerbose, "no-verbose", 0, "@"},
572 { oTrustDBName, "trustdb-name", 2, "@" },
573 { oNoSecmemWarn, "no-secmem-warning", 0, "@" },
574 { oRequireSecmem,"require-secmem", 0, "@" },
575 { oNoRequireSecmem,"no-require-secmem", 0, "@" },
576 { oNoPermissionWarn, "no-permission-warning", 0, "@" },
577 { oNoMDCWarn, "no-mdc-warning", 0, "@" },
578 { oNoArmor, "no-armor", 0, "@"},
579 { oNoArmor, "no-armour", 0, "@"},
580 { oNoDefKeyring, "no-default-keyring", 0, "@" },
581 { oNoGreeting, "no-greeting", 0, "@" },
582 { oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
583 { oHomedir, "homedir", 2, "@" }, /* defaults to "~/.gnupg" */
584 { oNoBatch, "no-batch", 0, "@" },
585 { oWithColons, "with-colons", 0, "@"},
586 { oWithKeyData,"with-key-data", 0, "@"},
587 { aListKeys, "list-key", 0, "@" }, /* alias */
588 { aListSigs, "list-sig", 0, "@" }, /* alias */
589 { aCheckKeys, "check-sig",0, "@" }, /* alias */
590 { oSkipVerify, "skip-verify",0, "@" },
591 { oCompressKeys, "compress-keys",0, "@"},
592 { oCompressSigs, "compress-sigs",0, "@"},
593 { oDefCertLevel, "default-cert-check-level", 1, "@"}, /* Old option */
594 { oAlwaysTrust, "always-trust", 0, "@"},
595 { oTrustModel, "trust-model", 2, "@"},
596 { oForceOwnertrust, "force-ownertrust", 2, "@"},
597 { oSetFilename, "set-filename", 2, "@" },
598 { oForYourEyesOnly, "for-your-eyes-only", 0, "@" },
599 { oNoForYourEyesOnly, "no-for-your-eyes-only", 0, "@" },
600 { oSetPolicyURL, "set-policy-url", 2, "@" },
601 { oSigPolicyURL, "sig-policy-url", 2, "@" },
602 { oCertPolicyURL, "cert-policy-url", 2, "@" },
603 { oShowPolicyURL, "show-policy-url", 0, "@" },
604 { oNoShowPolicyURL, "no-show-policy-url", 0, "@" },
605 { oSigKeyserverURL, "sig-keyserver-url", 2, "@" },
606 { oShowNotation, "show-notation", 0, "@" },
607 { oNoShowNotation, "no-show-notation", 0, "@" },
608 { oComment, "comment", 2, "@" },
609 { oDefaultComment, "default-comment", 0, "@" },
610 { oNoComments, "no-comments", 0, "@" },
611 { oEmitVersion, "emit-version", 0, "@"},
612 { oNoEmitVersion, "no-emit-version", 0, "@"},
613 { oNoEmitVersion, "no-version", 0, "@"}, /* alias */
614 { oNotDashEscaped, "not-dash-escaped", 0, "@" },
615 { oEscapeFrom, "escape-from-lines", 0, "@" },
616 { oNoEscapeFrom, "no-escape-from-lines", 0, "@" },
617 { oLockOnce, "lock-once", 0, "@" },
618 { oLockMultiple, "lock-multiple", 0, "@" },
619 { oLockNever, "lock-never", 0, "@" },
620 { oLoggerFD, "logger-fd",1, "@" },
621 { oLoggerFile, "log-file",2, "@" },
622 { oUseEmbeddedFilename, "use-embedded-filename", 0, "@" },
623 { oNoUseEmbeddedFilename, "no-use-embedded-filename", 0, "@" },
624 { oUtf8Strings, "utf8-strings", 0, "@" },
625 { oNoUtf8Strings, "no-utf8-strings", 0, "@" },
626 { oWithFingerprint, "with-fingerprint", 0, "@" },
627 { oDisableCipherAlgo, "disable-cipher-algo", 2, "@" },
628 { oDisablePubkeyAlgo, "disable-pubkey-algo", 2, "@" },
629 { oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", 0, "@" },
630 { oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", 0, "@" },
631 { oAllowFreeformUID, "allow-freeform-uid", 0, "@" },
632 { oNoAllowFreeformUID, "no-allow-freeform-uid", 0, "@" },
633 { oNoLiteral, "no-literal", 0, "@" },
634 { oSetFilesize, "set-filesize", 20, "@" },
635 { oHonorHttpProxy,"honor-http-proxy", 0, "@" },
636 { oFastListMode,"fast-list-mode", 0, "@" },
637 { oFixedListMode,"fixed-list-mode", 0, "@" },
638 { oListOnly, "list-only", 0, "@"},
639 { oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
640 { oIgnoreValidFrom, "ignore-valid-from", 0, "@" },
641 { oIgnoreCrcError, "ignore-crc-error", 0,"@" },
642 { oIgnoreMDCError, "ignore-mdc-error", 0,"@" },
643 { oShowSessionKey, "show-session-key", 0, "@" },
644 { oOverrideSessionKey, "override-session-key", 2, "@" },
645 { oNoRandomSeedFile, "no-random-seed-file", 0, "@" },
646 { oAutoKeyRetrieve, "auto-key-retrieve", 0, "@" },
647 { oNoAutoKeyRetrieve, "no-auto-key-retrieve", 0, "@" },
648 { oNoSigCache, "no-sig-cache", 0, "@" },
649 { oNoSigCreateCheck, "no-sig-create-check", 0, "@" },
650 { oAutoCheckTrustDB, "auto-check-trustdb", 0, "@"},
651 { oNoAutoCheckTrustDB, "no-auto-check-trustdb", 0, "@"},
652 { oMergeOnly, "merge-only", 0, "@" },
653 { oAllowSecretKeyImport, "allow-secret-key-import", 0, "@" },
654 { oTryAllSecrets, "try-all-secrets", 0, "@" },
655 { oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
656 { oNoExpensiveTrustChecks, "no-expensive-trust-checks", 0, "@" },
657 { aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys",256, "@" },
658 { aRebuildKeydbCaches, "rebuild-keydb-caches", 256, "@"},
659 { oPreservePermissions, "preserve-permissions", 0, "@"},
660 { oDefaultPreferenceList, "default-preference-list", 2, "@"},
661 { oPersonalCipherPreferences, "personal-cipher-preferences", 2, "@"},
662 { oPersonalDigestPreferences, "personal-digest-preferences", 2, "@"},
663 { oPersonalCompressPreferences, "personal-compress-preferences", 2, "@"},
664 /* Aliases. I constantly mistype these, and assume other people
665 do as well. */
666 { oPersonalCipherPreferences, "personal-cipher-prefs", 2, "@"},
667 { oPersonalDigestPreferences, "personal-digest-prefs", 2, "@"},
668 { oPersonalCompressPreferences, "personal-compress-prefs", 2, "@"},
669 { oAgentProgram, "agent-program", 2 , "@" },
670 { oDisplay, "display", 2, "@" },
671 { oTTYname, "ttyname", 2, "@" },
672 { oTTYtype, "ttytype", 2, "@" },
673 { oLCctype, "lc-ctype", 2, "@" },
674 { oLCmessages, "lc-messages", 2, "@" },
675 { oGroup, "group", 2, "@" },
676 { oUnGroup, "ungroup", 2, "@" },
677 { oNoGroups, "no-groups", 0, "@" },
678 { oStrict, "strict", 0, "@" },
679 { oNoStrict, "no-strict", 0, "@" },
680 { oMangleDosFilenames, "mangle-dos-filenames", 0, "@" },
681 { oNoMangleDosFilenames, "no-mangle-dos-filenames", 0, "@" },
682 { oEnableProgressFilter, "enable-progress-filter", 0, "@" },
683 { oMultifile, "multifile", 0, "@" },
684 { oKeyidFormat, "keyid-format", 2, "@" },
685 { oExitOnStatusWriteError, "exit-on-status-write-error", 0, "@" },
686 { oLimitCardInsertTries, "limit-card-insert-tries", 1, "@"},
688 { oAllowMultisigVerification, "allow-multisig-verification", 0, "@"},
689 { oEnableDSA2, "enable-dsa2", 0, "@"},
690 { oDisableDSA2, "disable-dsa2", 0, "@"},
692 /* These two are aliases to help users of the PGP command line
693 product use gpg with minimal pain. Many commands are common
694 already as they seem to have borrowed commands from us. Now
695 I'm returning the favor. */
696 { oLocalUser, "sign-with", 2, "@" },
697 { oRecipient, "user", 2, "@" },
698 { oRequireCrossCert, "require-backsigs", 0, "@"},
699 { oRequireCrossCert, "require-cross-certification", 0, "@"},
700 { oNoRequireCrossCert, "no-require-backsigs", 0, "@"},
701 { oNoRequireCrossCert, "no-require-cross-certification", 0, "@"},
702 { oAutoKeyLocate, "auto-key-locate", 2, "@"},
703 { oNoAutoKeyLocate, "no-auto-key-locate", 0, "@"},
704 {0,NULL,0,NULL}
708 #ifdef ENABLE_SELINUX_HACKS
709 #define ALWAYS_ADD_KEYRINGS 1
710 #else
711 #define ALWAYS_ADD_KEYRINGS 0
712 #endif
715 int g10_errors_seen = 0;
717 static int utf8_strings = 0;
718 static int maybe_setuid = 1;
720 static char *build_list( const char *text, char letter,
721 const char *(*mapf)(int), int (*chkf)(int) );
722 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
723 enum cmd_and_opt_values new_cmd );
724 static void print_mds( const char *fname, int algo );
725 static void add_notation_data( const char *string, int which );
726 static void add_policy_url( const char *string, int which );
727 static void add_keyserver_url( const char *string, int which );
728 static void emergency_cleanup (void);
731 static const char *
732 my_strusage( int level )
734 static char *digests, *pubkeys, *ciphers, *zips;
735 const char *p;
736 switch( level ) {
737 case 11: p = "gpg (GnuPG)";
738 break;
739 case 13: p = VERSION; break;
740 case 17: p = PRINTABLE_OS_NAME; break;
741 case 19: p =
742 _("Please report bugs to <gnupg-bugs@gnu.org>.\n");
743 break;
745 #ifdef IS_DEVELOPMENT_VERSION
746 case 20:
747 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
748 break;
749 case 21:
750 p="It is only intended for test purposes and should NOT be";
751 break;
752 case 22:
753 p="used in a production environment or with production keys!";
754 break;
755 #endif
757 case 1:
758 case 40: p =
759 _("Usage: gpg [options] [files] (-h for help)");
760 break;
761 case 41: p =
762 _("Syntax: gpg [options] [files]\n"
763 "sign, check, encrypt or decrypt\n"
764 "default operation depends on the input data\n");
765 break;
767 case 31: p = "\nHome: "; break;
768 #ifndef __riscos__
769 case 32: p = opt.homedir; break;
770 #else /* __riscos__ */
771 case 32: p = make_filename(opt.homedir, NULL); break;
772 #endif /* __riscos__ */
773 case 33: p = _("\nSupported algorithms:\n"); break;
774 case 34:
775 if (!pubkeys)
776 pubkeys = build_list (_("Pubkey: "), 0,
777 gcry_pk_algo_name,
778 openpgp_pk_test_algo );
779 p = pubkeys;
780 break;
781 case 35:
782 if( !ciphers )
783 ciphers = build_list(_("Cipher: "), 'S',
784 gcry_cipher_algo_name,
785 openpgp_cipher_test_algo );
786 p = ciphers;
787 break;
788 case 36:
789 if( !digests )
790 digests = build_list(_("Hash: "), 'H',
791 gcry_md_algo_name,
792 openpgp_md_test_algo );
793 p = digests;
794 break;
795 case 37:
796 if( !zips )
797 zips = build_list(_("Compression: "),'Z',
798 compress_algo_to_string,
799 check_compress_algo);
800 p = zips;
801 break;
803 default: p = NULL;
805 return p;
809 static char *
810 build_list( const char *text, char letter,
811 const char * (*mapf)(int), int (*chkf)(int) )
813 int i;
814 const char *s;
815 size_t n=strlen(text)+2;
816 char *list, *p, *line=NULL;
818 if (maybe_setuid)
819 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
821 for(i=0; i <= 110; i++ )
822 if( !chkf(i) && (s=mapf(i)) )
823 n += strlen(s) + 7 + 2;
824 list = xmalloc( 21 + n ); *list = 0;
825 for(p=NULL, i=0; i <= 110; i++ ) {
826 if( !chkf(i) && (s=mapf(i)) ) {
827 if( !p ) {
828 p = stpcpy( list, text );
829 line=p;
831 else
832 p = stpcpy( p, ", ");
834 if(strlen(line)>60) {
835 int spaces=strlen(text);
837 list=xrealloc(list,n+spaces+1);
838 /* realloc could move the block, so find the end again */
839 p=list;
840 while(*p)
841 p++;
843 p=stpcpy(p, "\n");
844 line=p;
845 for(;spaces;spaces--)
846 p=stpcpy(p, " ");
849 p = stpcpy(p, s );
850 if(opt.verbose && letter)
852 char num[8];
853 sprintf(num," (%c%d)",letter,i);
854 p = stpcpy(p,num);
858 if( p )
859 p = stpcpy(p, "\n" );
860 return list;
864 static void
865 i18n_init(void)
867 #ifdef USE_SIMPLE_GETTEXT
868 set_gettext_file (PACKAGE_GT, "Software\\GNU\\GnuPG");
869 #else
870 #ifdef ENABLE_NLS
871 setlocale (LC_ALL, "");
872 bindtextdomain (PACKAGE_GT, LOCALEDIR);
873 textdomain (PACKAGE_GT);
874 #endif
875 #endif
878 static void
879 wrong_args( const char *text)
881 fputs(_("usage: gpg [options] "),stderr);
882 fputs(text,stderr);
883 putc('\n',stderr);
884 g10_exit(2);
888 static char *
889 make_username( const char *string )
891 char *p;
892 if( utf8_strings )
893 p = xstrdup(string);
894 else
895 p = native_to_utf8( string );
896 return p;
900 /* Setup the debugging. With a LEVEL of NULL only the active debug
901 flags are propagated to the subsystems. With LEVEL set, a specific
902 set of debug flags is set; thus overriding all flags already
903 set. */
904 static void
905 set_debug (const char *level)
907 if (!level)
909 else if (!strcmp (level, "none"))
910 opt.debug = 0;
911 else if (!strcmp (level, "basic"))
912 opt.debug = DBG_MEMSTAT_VALUE;
913 else if (!strcmp (level, "advanced"))
914 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
915 else if (!strcmp (level, "expert"))
916 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
917 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
918 else if (!strcmp (level, "guru"))
919 opt.debug = ~0;
920 else
922 log_error (_("invalid debug-level `%s' given\n"), level);
923 g10_exit (2);
926 if (opt.debug & DBG_MEMORY_VALUE )
927 memory_debug_mode = 1;
928 if (opt.debug & DBG_MEMSTAT_VALUE )
929 memory_stat_debug_mode = 1;
930 if (opt.debug & DBG_MPI_VALUE)
931 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
932 if (opt.debug & DBG_CIPHER_VALUE )
933 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
934 if (opt.debug & DBG_IOBUF_VALUE )
935 iobuf_debug_mode = 1;
936 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
941 /* We need the home directory also in some other directories, so make
942 sure that both variables are always in sync. */
943 static void
944 set_homedir (const char *dir)
946 if (!dir)
947 dir = "";
948 opt.homedir = dir;
952 /* We set the screen dimensions for UI purposes. Do not allow screens
953 smaller than 80x24 for the sake of simplicity. */
954 static void
955 set_screen_dimensions(void)
957 #ifndef HAVE_W32_SYSTEM
958 char *str;
960 str=getenv("COLUMNS");
961 if(str)
962 opt.screen_columns=atoi(str);
964 str=getenv("LINES");
965 if(str)
966 opt.screen_lines=atoi(str);
967 #endif
969 if(opt.screen_columns<80 || opt.screen_columns>255)
970 opt.screen_columns=80;
972 if(opt.screen_lines<24 || opt.screen_lines>255)
973 opt.screen_lines=24;
977 /* Helper to open a file FNAME either for reading or writing to be
978 used with --status-file etc functions. Not generally useful but it
979 avoids the riscos specific functions and well some Windows people
980 might like it too. Prints an error message and returns -1 on
981 error. On success the file descriptor is returned. */
982 static int
983 open_info_file (const char *fname, int for_write)
985 #ifdef __riscos__
986 return riscos_fdopenfile (fname, for_write);
987 #elif defined (ENABLE_SELINUX_HACKS)
988 /* We can't allow these even when testing for a secured filename
989 because files to be secured might not yet been secured. This is
990 similar to the option file but in that case it is unlikely that
991 sensitive information may be retrieved by means of error
992 messages. */
993 return -1;
994 #else
995 int fd;
997 /* if (is_secured_filename (fname)) */
998 /* { */
999 /* fd = -1; */
1000 /* errno = EPERM; */
1001 /* } */
1002 /* else */
1003 /* { */
1006 if (for_write)
1007 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY,
1008 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1009 else
1010 fd = open (fname, O_RDONLY | MY_O_BINARY);
1012 while (fd == -1 && errno == EINTR);
1013 /* } */
1014 if ( fd == -1)
1015 log_error ( for_write? _("can't create `%s': %s\n")
1016 : _("can't open `%s': %s\n"), fname, strerror(errno));
1018 return fd;
1019 #endif
1022 static void
1023 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1025 enum cmd_and_opt_values cmd = *ret_cmd;
1027 if( !cmd || cmd == new_cmd )
1028 cmd = new_cmd;
1029 else if( cmd == aSign && new_cmd == aEncr )
1030 cmd = aSignEncr;
1031 else if( cmd == aEncr && new_cmd == aSign )
1032 cmd = aSignEncr;
1033 else if( cmd == aSign && new_cmd == aSym )
1034 cmd = aSignSym;
1035 else if( cmd == aSym && new_cmd == aSign )
1036 cmd = aSignSym;
1037 else if( cmd == aSym && new_cmd == aEncr )
1038 cmd = aEncrSym;
1039 else if( cmd == aEncr && new_cmd == aSym )
1040 cmd = aEncrSym;
1041 else if( cmd == aKMode && new_cmd == aSym )
1042 cmd = aKModeC;
1043 else if (cmd == aSignEncr && new_cmd == aSym)
1044 cmd = aSignEncrSym;
1045 else if (cmd == aSignSym && new_cmd == aEncr)
1046 cmd = aSignEncrSym;
1047 else if (cmd == aEncrSym && new_cmd == aSign)
1048 cmd = aSignEncrSym;
1049 else if( ( cmd == aSign && new_cmd == aClearsign )
1050 || ( cmd == aClearsign && new_cmd == aSign ) )
1051 cmd = aClearsign;
1052 else {
1053 log_error(_("conflicting commands\n"));
1054 g10_exit(2);
1057 *ret_cmd = cmd;
1061 static void
1062 add_group(char *string)
1064 char *name,*value;
1065 struct groupitem *item;
1067 /* Break off the group name */
1068 name=strsep(&string,"=");
1069 if(string==NULL)
1071 log_error(_("no = sign found in group definition `%s'\n"),name);
1072 return;
1075 trim_trailing_ws(name,strlen(name));
1077 /* Does this group already exist? */
1078 for(item=opt.grouplist;item;item=item->next)
1079 if(strcasecmp(item->name,name)==0)
1080 break;
1082 if(!item)
1084 item=xmalloc(sizeof(struct groupitem));
1085 item->name=name;
1086 item->next=opt.grouplist;
1087 item->values=NULL;
1088 opt.grouplist=item;
1091 /* Break apart the values */
1092 while ((value= strsep(&string," \t")))
1094 if (*value)
1095 add_to_strlist2(&item->values,value,utf8_strings);
1100 static void
1101 rm_group(char *name)
1103 struct groupitem *item,*last=NULL;
1105 trim_trailing_ws(name,strlen(name));
1107 for(item=opt.grouplist;item;last=item,item=item->next)
1109 if(strcasecmp(item->name,name)==0)
1111 if(last)
1112 last->next=item->next;
1113 else
1114 opt.grouplist=item->next;
1116 free_strlist(item->values);
1117 xfree(item);
1118 break;
1124 /* We need to check three things.
1126 0) The homedir. It must be x00, a directory, and owned by the
1127 user.
1129 1) The options/gpg.conf file. Okay unless it or its containing
1130 directory is group or other writable or not owned by us. Disable
1131 exec in this case.
1133 2) Extensions. Same as #1.
1135 Returns true if the item is unsafe. */
1136 static int
1137 check_permissions(const char *path,int item)
1139 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1140 static int homedir_cache=-1;
1141 char *tmppath,*dir;
1142 struct stat statbuf,dirbuf;
1143 int homedir=0,ret=0,checkonly=0;
1144 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1146 if(opt.no_perm_warn)
1147 return 0;
1149 assert(item==0 || item==1 || item==2);
1151 /* extensions may attach a path */
1152 if(item==2 && path[0]!=DIRSEP_C)
1154 if(strchr(path,DIRSEP_C))
1155 tmppath=make_filename(path,NULL);
1156 else
1157 tmppath=make_filename(GNUPG_LIBDIR,path,NULL);
1159 else
1160 tmppath=xstrdup(path);
1162 /* If the item is located in the homedir, but isn't the homedir,
1163 don't continue if we already checked the homedir itself. This is
1164 to avoid user confusion with an extra options file warning which
1165 could be rectified if the homedir itself had proper
1166 permissions. */
1167 if(item!=0 && homedir_cache>-1
1168 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1170 ret=homedir_cache;
1171 goto end;
1174 /* It's okay if the file or directory doesn't exist */
1175 if(stat(tmppath,&statbuf)!=0)
1177 ret=0;
1178 goto end;
1181 /* Now check the enclosing directory. Theoretically, we could walk
1182 this test up to the root directory /, but for the sake of sanity,
1183 I'm stopping at one level down. */
1184 dir=make_dirname(tmppath);
1186 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1188 /* Weird error */
1189 ret=1;
1190 goto end;
1193 xfree(dir);
1195 /* Assume failure */
1196 ret=1;
1198 if(item==0)
1200 /* The homedir must be x00, a directory, and owned by the user. */
1202 if(S_ISDIR(statbuf.st_mode))
1204 if(statbuf.st_uid==getuid())
1206 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1207 ret=0;
1208 else
1209 perm=1;
1211 else
1212 own=1;
1214 homedir_cache=ret;
1217 else if(item==1 || item==2)
1219 /* The options or extension file. Okay unless it or its
1220 containing directory is group or other writable or not owned
1221 by us or root. */
1223 if(S_ISREG(statbuf.st_mode))
1225 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1227 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1229 /* it's not writable, so make sure the enclosing
1230 directory is also not writable */
1231 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1233 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1234 ret=0;
1235 else
1236 enc_dir_perm=1;
1238 else
1239 enc_dir_own=1;
1241 else
1243 /* it's writable, so the enclosing directory had
1244 better not let people get to it. */
1245 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1247 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1248 ret=0;
1249 else
1250 perm=enc_dir_perm=1; /* unclear which one to fix! */
1252 else
1253 enc_dir_own=1;
1256 else
1257 own=1;
1260 else
1261 BUG();
1263 if(!checkonly)
1265 if(own)
1267 if(item==0)
1268 log_info(_("WARNING: unsafe ownership on"
1269 " homedir `%s'\n"),tmppath);
1270 else if(item==1)
1271 log_info(_("WARNING: unsafe ownership on"
1272 " configuration file `%s'\n"),tmppath);
1273 else
1274 log_info(_("WARNING: unsafe ownership on"
1275 " extension `%s'\n"),tmppath);
1277 if(perm)
1279 if(item==0)
1280 log_info(_("WARNING: unsafe permissions on"
1281 " homedir `%s'\n"),tmppath);
1282 else if(item==1)
1283 log_info(_("WARNING: unsafe permissions on"
1284 " configuration file `%s'\n"),tmppath);
1285 else
1286 log_info(_("WARNING: unsafe permissions on"
1287 " extension `%s'\n"),tmppath);
1289 if(enc_dir_own)
1291 if(item==0)
1292 log_info(_("WARNING: unsafe enclosing directory ownership on"
1293 " homedir `%s'\n"),tmppath);
1294 else if(item==1)
1295 log_info(_("WARNING: unsafe enclosing directory ownership on"
1296 " configuration file `%s'\n"),tmppath);
1297 else
1298 log_info(_("WARNING: unsafe enclosing directory ownership on"
1299 " extension `%s'\n"),tmppath);
1301 if(enc_dir_perm)
1303 if(item==0)
1304 log_info(_("WARNING: unsafe enclosing directory permissions on"
1305 " homedir `%s'\n"),tmppath);
1306 else if(item==1)
1307 log_info(_("WARNING: unsafe enclosing directory permissions on"
1308 " configuration file `%s'\n"),tmppath);
1309 else
1310 log_info(_("WARNING: unsafe enclosing directory permissions on"
1311 " extension `%s'\n"),tmppath);
1315 end:
1316 xfree(tmppath);
1318 if(homedir)
1319 homedir_cache=ret;
1321 return ret;
1323 #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
1325 return 0;
1329 static void
1330 print_algo_numbers(int (*checker)(int))
1332 int i,first=1;
1334 for(i=0;i<=110;i++)
1336 if(!checker(i))
1338 if(first)
1339 first=0;
1340 else
1341 printf(";");
1342 printf("%d",i);
1348 /* In the future, we can do all sorts of interesting configuration
1349 output here. For now, just give "group" as the Enigmail folks need
1350 it, and pubkey, cipher, hash, and compress as they may be useful
1351 for frontends. */
1352 static void
1353 list_config(char *items)
1355 int show_all=(items==NULL);
1356 char *name=NULL;
1358 if(!opt.with_colons)
1359 return;
1361 while(show_all || (name=strsep(&items," ")))
1363 int any=0;
1365 if(show_all || ascii_strcasecmp(name,"group")==0)
1367 struct groupitem *iter;
1369 for(iter=opt.grouplist;iter;iter=iter->next)
1371 STRLIST sl;
1373 printf("cfg:group:");
1374 print_string(stdout,iter->name,strlen(iter->name),':');
1375 printf(":");
1377 for(sl=iter->values;sl;sl=sl->next)
1379 print_string2(stdout,sl->d,strlen(sl->d),':',';');
1380 if(sl->next)
1381 printf(";");
1384 printf("\n");
1387 any=1;
1390 if(show_all || ascii_strcasecmp(name,"version")==0)
1392 printf("cfg:version:");
1393 print_string(stdout,VERSION,strlen(VERSION),':');
1394 printf("\n");
1395 any=1;
1398 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1400 printf("cfg:pubkey:");
1401 print_algo_numbers (openpgp_pk_test_algo);
1402 printf("\n");
1403 any=1;
1406 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1408 printf("cfg:cipher:");
1409 print_algo_numbers(openpgp_cipher_test_algo);
1410 printf("\n");
1411 any=1;
1414 if(show_all
1415 || ascii_strcasecmp(name,"digest")==0
1416 || ascii_strcasecmp(name,"hash")==0)
1418 printf("cfg:digest:");
1419 print_algo_numbers(openpgp_md_test_algo);
1420 printf("\n");
1421 any=1;
1424 if(show_all || ascii_strcasecmp(name,"compress")==0)
1426 printf("cfg:compress:");
1427 print_algo_numbers(check_compress_algo);
1428 printf("\n");
1429 any=1;
1432 if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
1434 #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB)
1435 char *p, *p2, *list = ccid_get_reader_list ();
1437 for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
1439 *p2 = 0;
1440 printf("cfg:ccid-reader-id:%s\n", p);
1442 free (list);
1443 #endif
1444 any=1;
1447 if(show_all)
1448 break;
1450 if(!any)
1451 log_error(_("unknown configuration item `%s'\n"),name);
1456 /* List options and default values in the GPG Conf format. This is a
1457 new tool distributed with gnupg 1.9.x but we also want some limited
1458 support in older gpg versions. The output is the name of the
1459 configuration file and a list of options available for editing by
1460 gpgconf. */
1461 static void
1462 gpgconf_list (const char *configfile)
1464 /* The following definitions are taken from gnupg/tools/gpgconf-comp.c. */
1465 #define GC_OPT_FLAG_NONE 0UL
1466 #define GC_OPT_FLAG_DEFAULT (1UL << 4)
1468 printf ("gpgconf-gpg.conf:%lu:\"%s\n",
1469 GC_OPT_FLAG_DEFAULT,configfile?configfile:"/dev/null");
1470 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1471 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1472 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1473 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1477 static int
1478 parse_subpacket_list(char *list)
1480 char *tok;
1481 byte subpackets[128],i;
1482 int count=0;
1484 if(!list)
1486 /* No arguments means all subpackets */
1487 memset(subpackets+1,1,sizeof(subpackets)-1);
1488 count=127;
1490 else
1492 memset(subpackets,0,sizeof(subpackets));
1494 /* Merge with earlier copy */
1495 if(opt.show_subpackets)
1497 byte *in;
1499 for(in=opt.show_subpackets;*in;in++)
1501 if(*in>127 || *in<1)
1502 BUG();
1504 if(!subpackets[*in])
1505 count++;
1506 subpackets[*in]=1;
1510 while((tok=strsep(&list," ,")))
1512 if(!*tok)
1513 continue;
1515 i=atoi(tok);
1516 if(i>127 || i<1)
1517 return 0;
1519 if(!subpackets[i])
1520 count++;
1521 subpackets[i]=1;
1525 xfree(opt.show_subpackets);
1526 opt.show_subpackets=xmalloc(count+1);
1527 opt.show_subpackets[count--]=0;
1529 for(i=1;i<128 && count>=0;i++)
1530 if(subpackets[i])
1531 opt.show_subpackets[count--]=i;
1533 return 1;
1537 static int
1538 parse_list_options(char *str)
1540 char *subpackets=""; /* something that isn't NULL */
1541 struct parse_options lopts[]=
1543 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1544 N_("display photo IDs during key listings")},
1545 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1546 N_("show policy URLs during signature listings")},
1547 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1548 N_("show all notations during signature listings")},
1549 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1550 N_("show IETF standard notations during signature listings")},
1551 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1552 NULL},
1553 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1554 N_("show user-supplied notations during signature listings")},
1555 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1556 N_("show preferred keyserver URLs during signature listings")},
1557 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1558 N_("show user ID validity during key listings")},
1559 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1560 N_("show revoked and expired user IDs in key listings")},
1561 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1562 N_("show revoked and expired subkeys in key listings")},
1563 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1564 N_("show the keyring name in key listings")},
1565 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1566 N_("show expiration dates during signature listings")},
1567 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1568 NULL},
1569 {NULL,0,NULL,NULL}
1572 /* C99 allows for non-constant initializers, but we'd like to
1573 compile everywhere, so fill in the show-sig-subpackets argument
1574 here. Note that if the parse_options array changes, we'll have
1575 to change the subscript here. */
1576 lopts[12].value=&subpackets;
1578 if(parse_options(str,&opt.list_options,lopts,1))
1580 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1582 /* Unset so users can pass multiple lists in. */
1583 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1584 if(!parse_subpacket_list(subpackets))
1585 return 0;
1587 else if(subpackets==NULL && opt.show_subpackets)
1589 /* User did 'no-show-subpackets' */
1590 xfree(opt.show_subpackets);
1591 opt.show_subpackets=NULL;
1594 return 1;
1596 else
1597 return 0;
1601 /* Collapses argc/argv into a single string that must be freed */
1602 static char *
1603 collapse_args(int argc,char *argv[])
1605 char *str=NULL;
1606 int i,first=1,len=0;
1608 for(i=0;i<argc;i++)
1610 len+=strlen(argv[i])+2;
1611 str=xrealloc(str,len);
1612 if(first)
1614 str[0]='\0';
1615 first=0;
1617 else
1618 strcat(str," ");
1620 strcat(str,argv[i]);
1623 return str;
1626 static void
1627 parse_trust_model(const char *model)
1629 if(ascii_strcasecmp(model,"pgp")==0)
1630 opt.trust_model=TM_PGP;
1631 else if(ascii_strcasecmp(model,"classic")==0)
1632 opt.trust_model=TM_CLASSIC;
1633 else if(ascii_strcasecmp(model,"always")==0)
1634 opt.trust_model=TM_ALWAYS;
1635 else if(ascii_strcasecmp(model,"direct")==0)
1636 opt.trust_model=TM_DIRECT;
1637 else if(ascii_strcasecmp(model,"auto")==0)
1638 opt.trust_model=TM_AUTO;
1639 else
1640 log_error("unknown trust model `%s'\n",model);
1644 main (int argc, char **argv )
1646 ARGPARSE_ARGS pargs;
1647 IOBUF a;
1648 int rc=0;
1649 int orig_argc;
1650 char **orig_argv;
1651 const char *fname;
1652 char *username;
1653 int may_coredump;
1654 STRLIST sl, remusr= NULL, locusr=NULL;
1655 STRLIST nrings=NULL, sec_nrings=NULL;
1656 armor_filter_context_t afx;
1657 int detached_sig = 0;
1658 FILE *configfp = NULL;
1659 char *configname = NULL;
1660 char *save_configname = NULL;
1661 unsigned configlineno;
1662 int parse_debug = 0;
1663 int default_config = 1;
1664 int default_keyring = 1;
1665 int greeting = 0;
1666 int nogreeting = 0;
1667 char *logfile = NULL;
1668 int use_random_seed = 1;
1669 enum cmd_and_opt_values cmd = 0;
1670 const char *debug_level = NULL;
1671 const char *trustdb_name = NULL;
1672 char *def_cipher_string = NULL;
1673 char *def_digest_string = NULL;
1674 char *compress_algo_string = NULL;
1675 char *cert_digest_string = NULL;
1676 char *s2k_cipher_string = NULL;
1677 char *s2k_digest_string = NULL;
1678 char *pers_cipher_list = NULL;
1679 char *pers_digest_list = NULL;
1680 char *pers_compress_list = NULL;
1681 int eyes_only=0;
1682 int multifile=0;
1683 int pwfd = -1;
1684 int with_fpr = 0; /* make an option out of --fingerprint */
1685 int any_explicit_recipient = 0;
1686 int require_secmem=0,got_secmem=0;
1688 #ifdef __riscos__
1689 opt.lock_once = 1;
1690 #endif /* __riscos__ */
1693 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1694 when adding any stuff between here and the call to
1695 secmem_init() somewhere after the option parsing. */
1697 trap_unaligned();
1698 set_strusage (my_strusage);
1699 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1700 /* We don't need any locking in libgcrypt unless we use any kind of
1701 threading. */
1702 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
1703 log_set_prefix ("gpg", 1);
1705 /* Check that the libraries are suitable. Do it right here because the
1706 option parsing may need services of the library. */
1707 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1709 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
1710 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1713 /* Put random number into secure memory */
1714 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1716 may_coredump = disable_core_dumps();
1718 gnupg_init_signals (0, emergency_cleanup);
1720 create_dotlock(NULL); /* Register locking cleanup. */
1722 i18n_init();
1724 opt.command_fd = -1; /* no command fd */
1725 opt.compress_level = -1; /* defaults to standard compress level */
1726 opt.bz2_compress_level = -1; /* defaults to standard compress level */
1727 /* note: if you change these lines, look at oOpenPGP */
1728 opt.def_cipher_algo = 0;
1729 opt.def_digest_algo = 0;
1730 opt.cert_digest_algo = 0;
1731 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
1732 opt.s2k_mode = 3; /* iterated+salted */
1733 #ifdef USE_CAST5
1734 opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
1735 #else
1736 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
1737 #endif
1738 opt.completes_needed = 1;
1739 opt.marginals_needed = 3;
1740 opt.max_cert_depth = 5;
1741 opt.pgp2_workarounds = 1;
1742 opt.force_v3_sigs = 1;
1743 opt.escape_from = 1;
1744 opt.import_options=IMPORT_SK2PK;
1745 opt.export_options=EXPORT_ATTRIBUTES;
1746 opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
1747 opt.keyserver_options.export_options=EXPORT_ATTRIBUTES;
1748 opt.keyserver_options.options=
1749 KEYSERVER_HONOR_KEYSERVER_URL|KEYSERVER_HONOR_PKA_RECORD;
1750 opt.verify_options=
1751 VERIFY_SHOW_POLICY_URLS|VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_KEYSERVER_URLS;
1752 opt.trust_model=TM_AUTO;
1753 opt.mangle_dos_filenames=0;
1754 opt.min_cert_level=2;
1755 set_screen_dimensions();
1756 opt.keyid_format=KF_SHORT;
1757 opt.rfc2440_text=1;
1758 opt.def_sig_expire="0";
1759 opt.def_cert_expire="0";
1760 set_homedir ( default_homedir () );
1762 /* Check whether we have a config file on the command line. */
1763 orig_argc = argc;
1764 orig_argv = argv;
1765 pargs.argc = &argc;
1766 pargs.argv = &argv;
1767 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1768 while( arg_parse( &pargs, opts) ) {
1769 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
1770 parse_debug++;
1771 else if( pargs.r_opt == oOptions ) {
1772 /* yes there is one, so we do not try the default one, but
1773 * read the option file when it is encountered at the commandline
1775 default_config = 0;
1777 else if( pargs.r_opt == oNoOptions )
1778 default_config = 0; /* --no-options */
1779 else if( pargs.r_opt == oHomedir )
1780 set_homedir ( pargs.r.ret_str );
1781 else if( pargs.r_opt == oNoPermissionWarn )
1782 opt.no_perm_warn=1;
1783 else if (pargs.r_opt == oStrict )
1785 opt.strict=1;
1786 log_set_strict(1);
1788 else if (pargs.r_opt == oNoStrict )
1790 opt.strict=0;
1791 log_set_strict(0);
1795 #ifdef HAVE_DOSISH_SYSTEM
1796 if ( strchr (opt.homedir,'\\') ) {
1797 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
1798 const char *s = opt.homedir;
1799 for (d=buf,s=opt.homedir; *s; s++)
1801 *d++ = *s == '\\'? '/': *s;
1802 #ifdef HAVE_W32_SYSTEM
1803 if (s[1] && IsDBCSLeadByte (*s))
1804 *d++ = *++s;
1805 #endif
1807 *d = 0;
1808 set_homedir (buf);
1810 #endif
1812 /* Initialize the secure memory. */
1813 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
1814 got_secmem = 1; /* FIXME: gcry_control should return an indicator. */
1815 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
1816 /* There should be no way to get to this spot while still carrying
1817 setuid privs. Just in case, bomb out if we are. */
1818 if(getuid()!=geteuid())
1819 BUG();
1820 #endif
1821 maybe_setuid = 0;
1823 /* Okay, we are now working under our real uid */
1825 /* malloc hooks go here ... */
1826 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
1829 set_native_charset (NULL); /* Try to auto set the character set */
1831 /* Try for a version specific config file first */
1832 if( default_config )
1834 char *name=xstrdup("gpg" EXTSEP_S "conf-" SAFE_VERSION);
1835 char *ver=&name[strlen("gpg" EXTSEP_S "conf-")];
1839 if(configname)
1841 char *tok;
1843 xfree(configname);
1844 configname=NULL;
1846 if((tok=strrchr(ver,SAFE_VERSION_DASH)))
1847 *tok='\0';
1848 else if((tok=strrchr(ver,SAFE_VERSION_DOT)))
1849 *tok='\0';
1850 else
1851 break;
1854 configname = make_filename(opt.homedir,name,NULL);
1856 while(access(configname,R_OK));
1858 xfree(name);
1860 if(!configname)
1861 configname=make_filename(opt.homedir, "gpg" EXTSEP_S "conf", NULL );
1862 if (!access (configname, R_OK))
1863 { /* Print a warning when both config files are present. */
1864 char *p = make_filename(opt.homedir, "options", NULL );
1865 if (!access (p, R_OK))
1866 log_info (_("NOTE: old default options file `%s' ignored\n"), p);
1867 xfree (p);
1869 else
1870 { /* Keep on using the old default one. */
1871 xfree (configname);
1872 configname = make_filename(opt.homedir, "options", NULL );
1875 argc = orig_argc;
1876 argv = orig_argv;
1877 pargs.argc = &argc;
1878 pargs.argv = &argv;
1879 pargs.flags= 1; /* do not remove the args */
1881 /* By this point we have a homedir, and cannot change it. */
1882 check_permissions(opt.homedir,0);
1884 next_pass:
1885 if( configname ) {
1886 if(check_permissions(configname,1))
1888 /* If any options file is unsafe, then disable any external
1889 programs for keyserver calls or photo IDs. Since the
1890 external program to call is set in the options file, a
1891 unsafe options file can lead to an arbitrary program
1892 being run. */
1894 opt.exec_disable=1;
1897 configlineno = 0;
1898 configfp = fopen( configname, "r" );
1899 if (configfp && is_secured_file (fileno (configfp)))
1901 fclose (configfp);
1902 configfp = NULL;
1903 errno = EPERM;
1905 if( !configfp ) {
1906 if( default_config ) {
1907 if( parse_debug )
1908 log_info(_("NOTE: no default option file `%s'\n"),
1909 configname );
1911 else {
1912 log_error(_("option file `%s': %s\n"),
1913 configname, strerror(errno) );
1914 g10_exit(2);
1916 xfree(configname); configname = NULL;
1918 if( parse_debug && configname )
1919 log_info(_("reading options from `%s'\n"), configname );
1920 default_config = 0;
1923 while( optfile_parse( configfp, configname, &configlineno,
1924 &pargs, opts) )
1926 switch( pargs.r_opt )
1928 case aCheckKeys:
1929 case aListConfig:
1930 case aGPGConfList:
1931 case aListPackets:
1932 case aImport:
1933 case aFastImport:
1934 case aSendKeys:
1935 case aRecvKeys:
1936 case aSearchKeys:
1937 case aRefreshKeys:
1938 case aFetchKeys:
1939 case aExport:
1940 set_cmd (&cmd, pargs.r_opt);
1941 break;
1942 case aListKeys: set_cmd( &cmd, aListKeys); break;
1943 case aListSigs: set_cmd( &cmd, aListSigs); break;
1944 case aExportSecret: set_cmd( &cmd, aExportSecret); break;
1945 case aExportSecretSub: set_cmd( &cmd, aExportSecretSub); break;
1946 case aDeleteSecretKeys:
1947 set_cmd( &cmd, aDeleteSecretKeys);
1948 greeting=1;
1949 break;
1950 case aDeleteSecretAndPublicKeys:
1951 set_cmd( &cmd, aDeleteSecretAndPublicKeys);
1952 greeting=1;
1953 break;
1954 case aDeleteKeys: set_cmd( &cmd, aDeleteKeys); greeting=1; break;
1956 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
1957 case aSym: set_cmd( &cmd, aSym); break;
1959 case aDecryptFiles: multifile=1; /* fall through */
1960 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
1962 case aEncrFiles: multifile=1; /* fall through */
1963 case aEncr: set_cmd( &cmd, aEncr); break;
1965 case aVerifyFiles: multifile=1; /* fall through */
1966 case aVerify: set_cmd( &cmd, aVerify); break;
1968 case aSign: set_cmd( &cmd, aSign ); break;
1969 case aKeygen: set_cmd( &cmd, aKeygen); greeting=1; break;
1970 case aSignKey: set_cmd( &cmd, aSignKey); break;
1971 case aLSignKey: set_cmd( &cmd, aLSignKey); break;
1972 case aStore: set_cmd( &cmd, aStore); break;
1973 case aEditKey: set_cmd( &cmd, aEditKey); greeting=1; break;
1974 case aClearsign: set_cmd( &cmd, aClearsign); break;
1975 case aGenRevoke: set_cmd( &cmd, aGenRevoke); break;
1976 case aDesigRevoke: set_cmd( &cmd, aDesigRevoke); break;
1977 case aPrimegen: set_cmd( &cmd, aPrimegen); break;
1978 case aGenRandom: set_cmd( &cmd, aGenRandom); break;
1979 case aPrintMD: set_cmd( &cmd, aPrintMD); break;
1980 case aPrintMDs: set_cmd( &cmd, aPrintMDs); break;
1981 case aListTrustDB: set_cmd( &cmd, aListTrustDB); break;
1982 case aCheckTrustDB: set_cmd( &cmd, aCheckTrustDB); break;
1983 case aUpdateTrustDB: set_cmd( &cmd, aUpdateTrustDB); break;
1984 case aFixTrustDB: set_cmd( &cmd, aFixTrustDB); break;
1985 case aListTrustPath: set_cmd( &cmd, aListTrustPath); break;
1986 case aDeArmor: set_cmd( &cmd, aDeArmor); break;
1987 case aEnArmor: set_cmd( &cmd, aEnArmor); break;
1988 case aListOwnerTrust:
1989 deprecated_warning(configname,configlineno,
1990 "--list-ownertrust","--export-ownertrust","");
1991 case aExportOwnerTrust: set_cmd( &cmd, aExportOwnerTrust); break;
1992 case aImportOwnerTrust: set_cmd( &cmd, aImportOwnerTrust); break;
1993 case aRebuildKeydbCaches: set_cmd( &cmd, aRebuildKeydbCaches); break;
1995 case oArmor: opt.armor = 1; opt.no_armor=0; break;
1996 case oOutput: opt.outfile = pargs.r.ret_str; break;
1997 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
1998 case oQuiet: opt.quiet = 1; break;
1999 case oNoTTY: tty_no_terminal(1); break;
2000 case oDryRun: opt.dry_run = 1; break;
2001 case oInteractive: opt.interactive = 1; break;
2002 case oVerbose:
2003 opt.verbose++;
2004 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2005 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2006 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2007 break;
2008 case oKOption: set_cmd( &cmd, aKMode ); break;
2010 case oBatch: opt.batch = 1; nogreeting = 1; break;
2011 case oUseAgent:
2012 #ifndef __riscos__
2013 opt.use_agent = 1;
2014 #else /* __riscos__ */
2015 opt.use_agent = 0;
2016 riscos_not_implemented("use-agent");
2017 #endif /* __riscos__ */
2018 break;
2019 case oNoUseAgent: opt.use_agent = 0; break;
2020 case oGpgAgentInfo: opt.gpg_agent_info = pargs.r.ret_str; break;
2021 case oAnswerYes: opt.answer_yes = 1; break;
2022 case oAnswerNo: opt.answer_no = 1; break;
2023 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2024 case oPrimaryKeyring:
2025 sl=append_to_strlist( &nrings, pargs.r.ret_str);
2026 sl->flags=2;
2027 break;
2028 case oShowKeyring:
2029 deprecated_warning(configname,configlineno,"--show-keyring",
2030 "--list-options ","show-keyring");
2031 opt.list_options|=LIST_SHOW_KEYRING;
2032 break;
2034 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2035 case oDebugAll: opt.debug = ~0; break;
2036 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2038 case oStatusFD:
2039 set_status_fd( iobuf_translate_file_handle (pargs.r.ret_int, 1) );
2040 break;
2041 case oStatusFile:
2042 set_status_fd ( open_info_file (pargs.r.ret_str, 1) );
2043 break;
2044 case oAttributeFD:
2045 set_attrib_fd(iobuf_translate_file_handle (pargs.r.ret_int, 1));
2046 break;
2047 case oAttributeFile:
2048 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1) );
2049 break;
2050 case oLoggerFD:
2051 log_set_fd (iobuf_translate_file_handle (pargs.r.ret_int, 1));
2052 break;
2053 case oLoggerFile:
2054 logfile = pargs.r.ret_str;
2055 break;
2057 case oWithFingerprint:
2058 opt.with_fingerprint = 1;
2059 with_fpr=1; /*fall thru*/
2060 case oFingerprint: opt.fingerprint++; break;
2061 case oSecretKeyring:
2062 append_to_strlist( &sec_nrings, pargs.r.ret_str);
2063 break;
2064 case oOptions:
2065 /* config files may not be nested (silently ignore them) */
2066 if( !configfp ) {
2067 xfree(configname);
2068 configname = xstrdup(pargs.r.ret_str);
2069 goto next_pass;
2071 break;
2072 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2073 case oNoDefKeyring: default_keyring = 0; break;
2074 case oNoGreeting: nogreeting = 1; break;
2075 case oNoVerbose:
2076 opt.verbose = 0;
2077 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2078 opt.list_sigs=0;
2079 break;
2080 /* Disabled for now:
2081 case oQuickRandom: quick_random_gen(1); break;*/
2082 case oEmitVersion: opt.no_version=0; break;
2083 case oNoEmitVersion: opt.no_version=1; break;
2084 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2085 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2086 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2087 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2088 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2089 case oDefRecipient:
2090 if( *pargs.r.ret_str )
2091 opt.def_recipient = make_username(pargs.r.ret_str);
2092 break;
2093 case oDefRecipientSelf:
2094 xfree(opt.def_recipient); opt.def_recipient = NULL;
2095 opt.def_recipient_self = 1;
2096 break;
2097 case oNoDefRecipient:
2098 xfree(opt.def_recipient); opt.def_recipient = NULL;
2099 opt.def_recipient_self = 0;
2100 break;
2101 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2102 case oHomedir: break;
2103 case oNoBatch: opt.batch = 0; break;
2104 case oWithKeyData: opt.with_key_data=1; /* fall thru */
2105 case oWithColons: opt.with_colons=':'; break;
2107 case oSkipVerify: opt.skip_verify=1; break;
2108 case oCompressKeys: opt.compress_keys = 1; break;
2109 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2110 /* There are many programs (like mutt) that call gpg with
2111 --always-trust so keep this option around for a long
2112 time. */
2113 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2114 case oTrustModel:
2115 parse_trust_model(pargs.r.ret_str);
2116 break;
2117 case oForceOwnertrust:
2118 log_info(_("NOTE: %s is not for normal use!\n"),
2119 "--force-ownertrust");
2120 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2121 if(opt.force_ownertrust==-1)
2123 log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
2124 opt.force_ownertrust=0;
2126 break;
2127 case oLoadExtension:
2128 #ifndef __riscos__
2129 #if defined(USE_DYNAMIC_LINKING) || defined(_WIN32)
2130 if(check_permissions(pargs.r.ret_str,2))
2131 log_info(_("cipher extension `%s' not loaded due to"
2132 " unsafe permissions\n"),pargs.r.ret_str);
2133 else
2134 register_cipher_extension(orig_argc? *orig_argv:NULL,
2135 pargs.r.ret_str);
2136 #endif
2137 #else /* __riscos__ */
2138 riscos_not_implemented("load-extension");
2139 #endif /* __riscos__ */
2140 break;
2141 case oRFC1991:
2142 opt.compliance = CO_RFC1991;
2143 opt.force_v4_certs = 0;
2144 opt.escape_from = 1;
2145 break;
2146 case oOpenPGP:
2147 case oRFC2440:
2148 /* TODO: When 2440bis becomes a RFC, set new values for
2149 oOpenPGP. */
2150 opt.rfc2440_text=1;
2151 opt.compliance = CO_RFC2440;
2152 opt.allow_non_selfsigned_uid = 1;
2153 opt.allow_freeform_uid = 1;
2154 opt.pgp2_workarounds = 0;
2155 opt.escape_from = 0;
2156 opt.force_v3_sigs = 0;
2157 opt.compress_keys = 0; /* not mandated, but we do it */
2158 opt.compress_sigs = 0; /* ditto. */
2159 opt.not_dash_escaped = 0;
2160 opt.def_cipher_algo = 0;
2161 opt.def_digest_algo = 0;
2162 opt.cert_digest_algo = 0;
2163 opt.compress_algo = -1;
2164 opt.s2k_mode = 3; /* iterated+salted */
2165 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2166 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2167 break;
2168 case oPGP2: opt.compliance = CO_PGP2; break;
2169 case oPGP6: opt.compliance = CO_PGP6; break;
2170 case oPGP7: opt.compliance = CO_PGP7; break;
2171 case oPGP8: opt.compliance = CO_PGP8; break;
2172 case oGnuPG: opt.compliance = CO_GNUPG; break;
2173 case oCompressSigs: opt.compress_sigs = 1; break;
2174 case oRFC2440Text: opt.rfc2440_text=1; break;
2175 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2176 case oSetFilename:
2177 if(utf8_strings)
2178 opt.set_filename = pargs.r.ret_str;
2179 else
2180 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2181 break;
2182 case oForYourEyesOnly: eyes_only = 1; break;
2183 case oNoForYourEyesOnly: eyes_only = 0; break;
2184 case oSetPolicyURL:
2185 add_policy_url(pargs.r.ret_str,0);
2186 add_policy_url(pargs.r.ret_str,1);
2187 break;
2188 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2189 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2190 case oShowPolicyURL:
2191 deprecated_warning(configname,configlineno,"--show-policy-url",
2192 "--list-options ","show-policy-urls");
2193 deprecated_warning(configname,configlineno,"--show-policy-url",
2194 "--verify-options ","show-policy-urls");
2195 opt.list_options|=LIST_SHOW_POLICY_URLS;
2196 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2197 break;
2198 case oNoShowPolicyURL:
2199 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2200 "--list-options ","no-show-policy-urls");
2201 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2202 "--verify-options ","no-show-policy-urls");
2203 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2204 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2205 break;
2206 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2207 case oUseEmbeddedFilename:
2208 opt.flags.use_embedded_filename=1;
2209 break;
2210 case oNoUseEmbeddedFilename:
2211 opt.flags.use_embedded_filename=0;
2212 break;
2213 case oComment:
2214 if(pargs.r.ret_str[0])
2215 append_to_strlist(&opt.comments,pargs.r.ret_str);
2216 break;
2217 case oDefaultComment:
2218 deprecated_warning(configname,configlineno,
2219 "--default-comment","--no-comments","");
2220 /* fall through */
2221 case oNoComments:
2222 free_strlist(opt.comments);
2223 opt.comments=NULL;
2224 break;
2225 case oThrowKeyids: opt.throw_keyid = 1; break;
2226 case oNoThrowKeyids: opt.throw_keyid = 0; break;
2227 case oShowPhotos:
2228 deprecated_warning(configname,configlineno,"--show-photos",
2229 "--list-options ","show-photos");
2230 deprecated_warning(configname,configlineno,"--show-photos",
2231 "--verify-options ","show-photos");
2232 opt.list_options|=LIST_SHOW_PHOTOS;
2233 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2234 break;
2235 case oNoShowPhotos:
2236 deprecated_warning(configname,configlineno,"--no-show-photos",
2237 "--list-options ","no-show-photos");
2238 deprecated_warning(configname,configlineno,"--no-show-photos",
2239 "--verify-options ","no-show-photos");
2240 opt.list_options&=~LIST_SHOW_PHOTOS;
2241 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2242 break;
2243 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2244 case oForceV3Sigs: opt.force_v3_sigs = 1; break;
2245 case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
2246 case oForceV4Certs: opt.force_v4_certs = 1; break;
2247 case oNoForceV4Certs: opt.force_v4_certs = 0; break;
2248 case oForceMDC: opt.force_mdc = 1; break;
2249 case oNoForceMDC: opt.force_mdc = 0; break;
2250 case oDisableMDC: opt.disable_mdc = 1; break;
2251 case oNoDisableMDC: opt.disable_mdc = 0; break;
2252 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2253 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2254 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2255 case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
2256 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2257 case oEncryptTo: /* store the recipient in the second list */
2258 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2259 sl->flags = 1;
2260 break;
2261 case oHiddenEncryptTo: /* store the recipient in the second list */
2262 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2263 sl->flags = 1|2;
2264 break;
2265 case oRecipient: /* store the recipient */
2266 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2267 any_explicit_recipient = 1;
2268 break;
2269 case oHiddenRecipient: /* store the recipient with a flag */
2270 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2271 sl->flags = 2;
2272 any_explicit_recipient = 1;
2273 break;
2274 case oTextmodeShort: opt.textmode = 2; break;
2275 case oTextmode: opt.textmode=1; break;
2276 case oNoTextmode: opt.textmode=0; break;
2277 case oExpert: opt.expert = 1; break;
2278 case oNoExpert: opt.expert = 0; break;
2279 case oDefSigExpire:
2280 if(*pargs.r.ret_str!='\0')
2282 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2283 log_error(_("`%s' is not a valid signature expiration\n"),
2284 pargs.r.ret_str);
2285 else
2286 opt.def_sig_expire=pargs.r.ret_str;
2288 break;
2289 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2290 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2291 case oDefCertExpire:
2292 if(*pargs.r.ret_str!='\0')
2294 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2295 log_error(_("`%s' is not a valid signature expiration\n"),
2296 pargs.r.ret_str);
2297 else
2298 opt.def_cert_expire=pargs.r.ret_str;
2300 break;
2301 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2302 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2303 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2304 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2305 case oAskCertLevel: opt.ask_cert_level = 1; break;
2306 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2307 case oLocalUser: /* store the local users */
2308 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2309 break;
2310 case oCompress:
2311 /* this is the -z command line option */
2312 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2313 break;
2314 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2315 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2316 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2317 case oPasswd:
2318 set_passphrase_from_string(pargs.r.ret_str);
2319 break;
2320 case oPasswdFD:
2321 pwfd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
2322 opt.use_agent = 0;
2323 break;
2324 case oPasswdFile:
2325 pwfd = open_info_file (pargs.r.ret_str, 0);
2326 break;
2327 case oCommandFD:
2328 opt.command_fd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
2329 break;
2330 case oCommandFile:
2331 opt.command_fd = open_info_file (pargs.r.ret_str, 0);
2332 break;
2333 case oCipherAlgo:
2334 def_cipher_string = xstrdup(pargs.r.ret_str);
2335 break;
2336 case oDigestAlgo:
2337 def_digest_string = xstrdup(pargs.r.ret_str);
2338 break;
2339 case oCompressAlgo:
2340 /* If it is all digits, stick a Z in front of it for
2341 later. This is for backwards compatibility with
2342 versions that took the compress algorithm number. */
2344 char *pt=pargs.r.ret_str;
2345 while(*pt)
2347 if (!isascii (*pt) || !isdigit (*pt))
2348 break;
2350 pt++;
2353 if(*pt=='\0')
2355 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2356 strcpy(compress_algo_string,"Z");
2357 strcat(compress_algo_string,pargs.r.ret_str);
2359 else
2360 compress_algo_string = xstrdup(pargs.r.ret_str);
2362 break;
2363 case oCertDigestAlgo: cert_digest_string = xstrdup(pargs.r.ret_str); break;
2364 case oNoSecmemWarn: secmem_set_flags( secmem_get_flags() | 1 ); break;
2365 case oRequireSecmem: require_secmem=1; break;
2366 case oNoRequireSecmem: require_secmem=0; break;
2367 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2368 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2369 case oDisplayCharset:
2370 if( set_native_charset( pargs.r.ret_str ) )
2371 log_error(_("`%s' is not a valid character set\n"),
2372 pargs.r.ret_str);
2373 break;
2374 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2375 case oEscapeFrom: opt.escape_from = 1; break;
2376 case oNoEscapeFrom: opt.escape_from = 0; break;
2377 case oLockOnce: opt.lock_once = 1; break;
2378 case oLockNever:
2379 disable_dotlock ();
2380 break;
2381 case oLockMultiple:
2382 #ifndef __riscos__
2383 opt.lock_once = 0;
2384 #else /* __riscos__ */
2385 riscos_not_implemented("lock-multiple");
2386 #endif /* __riscos__ */
2387 break;
2388 case oKeyServer:
2390 struct keyserver_spec *keyserver;
2391 keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
2392 configname,configlineno);
2393 if(!keyserver)
2394 log_error(_("could not parse keyserver URL\n"));
2395 else
2397 keyserver->next=opt.keyserver;
2398 opt.keyserver=keyserver;
2401 break;
2402 case oKeyServerOptions:
2403 if(!parse_keyserver_options(pargs.r.ret_str))
2405 if(configname)
2406 log_error(_("%s:%d: invalid keyserver options\n"),
2407 configname,configlineno);
2408 else
2409 log_error(_("invalid keyserver options\n"));
2411 break;
2412 case oImportOptions:
2413 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2415 if(configname)
2416 log_error(_("%s:%d: invalid import options\n"),
2417 configname,configlineno);
2418 else
2419 log_error(_("invalid import options\n"));
2421 break;
2422 case oExportOptions:
2423 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2425 if(configname)
2426 log_error(_("%s:%d: invalid export options\n"),
2427 configname,configlineno);
2428 else
2429 log_error(_("invalid export options\n"));
2431 break;
2432 case oListOptions:
2433 if(!parse_list_options(pargs.r.ret_str))
2435 if(configname)
2436 log_error(_("%s:%d: invalid list options\n"),
2437 configname,configlineno);
2438 else
2439 log_error(_("invalid list options\n"));
2441 break;
2442 case oVerifyOptions:
2444 struct parse_options vopts[]=
2446 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2447 N_("display photo IDs during signature verification")},
2448 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2449 N_("show policy URLs during signature verification")},
2450 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2451 N_("show all notations during signature verification")},
2452 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2453 N_("show IETF standard notations during signature verification")},
2454 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2455 NULL},
2456 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2457 N_("show user-supplied notations during signature verification")},
2458 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2459 N_("show preferred keyserver URLs during signature verification")},
2460 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2461 N_("show user ID validity during signature verification")},
2462 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2463 N_("show revoked and expired user IDs in signature verification")},
2464 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2465 N_("validate signatures with PKA data")},
2466 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2467 N_("elevate the trust of signatures with valid PKA data")},
2468 {NULL,0,NULL,NULL}
2471 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2473 if(configname)
2474 log_error(_("%s:%d: invalid verify options\n"),
2475 configname,configlineno);
2476 else
2477 log_error(_("invalid verify options\n"));
2480 break;
2481 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2482 case oExecPath:
2483 if(set_exec_path(pargs.r.ret_str))
2484 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2485 else
2486 opt.exec_path_set=1;
2487 break;
2488 case oSetNotation:
2489 add_notation_data( pargs.r.ret_str, 0 );
2490 add_notation_data( pargs.r.ret_str, 1 );
2491 break;
2492 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2493 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2494 case oShowNotation:
2495 deprecated_warning(configname,configlineno,"--show-notation",
2496 "--list-options ","show-notations");
2497 deprecated_warning(configname,configlineno,"--show-notation",
2498 "--verify-options ","show-notations");
2499 opt.list_options|=LIST_SHOW_NOTATIONS;
2500 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2501 break;
2502 case oNoShowNotation:
2503 deprecated_warning(configname,configlineno,"--no-show-notation",
2504 "--list-options ","no-show-notations");
2505 deprecated_warning(configname,configlineno,"--no-show-notation",
2506 "--verify-options ","no-show-notations");
2507 opt.list_options&=~LIST_SHOW_NOTATIONS;
2508 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2509 break;
2510 case oUtf8Strings: utf8_strings = 1; break;
2511 case oNoUtf8Strings: utf8_strings = 0; break;
2512 case oDisableCipherAlgo:
2514 int algo = gcry_cipher_map_name (pargs.r.ret_str);
2515 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2517 break;
2518 case oDisablePubkeyAlgo:
2520 int algo = gcry_pk_map_name (pargs.r.ret_str);
2521 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2523 break;
2524 case oNoSigCache: opt.no_sig_cache = 1; break;
2525 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2526 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2527 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2528 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2529 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2530 case oNoLiteral: opt.no_literal = 1; break;
2531 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2532 case oHonorHttpProxy:
2533 add_to_strlist(&opt.keyserver_options.other,"http-proxy");
2534 deprecated_warning(configname,configlineno,
2535 "--honor-http-proxy",
2536 "--keyserver-options ","http-proxy");
2537 break;
2538 case oFastListMode: opt.fast_list_mode = 1; break;
2539 case oFixedListMode: opt.fixed_list_mode = 1; break;
2540 case oListOnly: opt.list_only=1; break;
2541 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2542 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2543 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2544 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2545 case oNoRandomSeedFile: use_random_seed = 0; break;
2546 case oAutoKeyRetrieve:
2547 case oNoAutoKeyRetrieve:
2548 if(pargs.r_opt==oAutoKeyRetrieve)
2549 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
2550 else
2551 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
2553 deprecated_warning(configname,configlineno,
2554 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
2555 "--no-auto-key-retrieve","--keyserver-options ",
2556 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
2557 "no-auto-key-retrieve");
2558 break;
2559 case oShowSessionKey: opt.show_session_key = 1; break;
2560 case oOverrideSessionKey:
2561 opt.override_session_key = pargs.r.ret_str;
2562 break;
2563 case oMergeOnly:
2564 deprecated_warning(configname,configlineno,"--merge-only",
2565 "--import-options ","merge-only");
2566 opt.import_options|=IMPORT_MERGE_ONLY;
2567 break;
2568 case oAllowSecretKeyImport: /* obsolete */ break;
2569 case oTryAllSecrets: opt.try_all_secrets = 1; break;
2570 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
2571 case oEnableSpecialFilenames:
2572 iobuf_enable_special_filenames (1);
2573 break;
2574 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
2575 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
2576 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
2577 case oPreservePermissions: opt.preserve_permissions=1; break;
2578 case oDefaultPreferenceList:
2579 opt.def_preference_list = pargs.r.ret_str;
2580 break;
2581 case oPersonalCipherPreferences:
2582 pers_cipher_list=pargs.r.ret_str;
2583 break;
2584 case oPersonalDigestPreferences:
2585 pers_digest_list=pargs.r.ret_str;
2586 break;
2587 case oPersonalCompressPreferences:
2588 pers_compress_list=pargs.r.ret_str;
2589 break;
2590 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
2591 case oDisplay: opt.display = pargs.r.ret_str; break;
2592 case oTTYname: opt.ttyname = pargs.r.ret_str; break;
2593 case oTTYtype: opt.ttytype = pargs.r.ret_str; break;
2594 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
2595 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
2596 case oGroup: add_group(pargs.r.ret_str); break;
2597 case oUnGroup: rm_group(pargs.r.ret_str); break;
2598 case oNoGroups:
2599 while(opt.grouplist)
2601 struct groupitem *iter=opt.grouplist;
2602 free_strlist(iter->values);
2603 opt.grouplist=opt.grouplist->next;
2604 xfree(iter);
2606 break;
2607 case oStrict: opt.strict=1; log_set_strict(1); break;
2608 case oNoStrict: opt.strict=0; log_set_strict(0); break;
2609 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
2610 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
2611 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
2612 case oMultifile: multifile=1; break;
2613 case oKeyidFormat:
2614 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
2615 opt.keyid_format=KF_SHORT;
2616 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
2617 opt.keyid_format=KF_LONG;
2618 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
2619 opt.keyid_format=KF_0xSHORT;
2620 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
2621 opt.keyid_format=KF_0xLONG;
2622 else
2623 log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
2624 break;
2626 case oExitOnStatusWriteError:
2627 opt.exit_on_status_write_error = 1;
2628 break;
2630 case oLimitCardInsertTries:
2631 opt.limit_card_insert_tries = pargs.r.ret_int;
2632 break;
2634 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
2635 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
2637 case oAutoKeyLocate:
2638 if(!parse_auto_key_locate(pargs.r.ret_str))
2640 if(configname)
2641 log_error(_("%s:%d: invalid auto-key-locate list\n"),
2642 configname,configlineno);
2643 else
2644 log_error(_("invalid auto-key-locate list\n"));
2646 break;
2647 case oNoAutoKeyLocate:
2648 release_akl();
2649 break;
2651 case oAllowMultisigVerification:
2652 opt.allow_multisig_verification = 1;
2653 break;
2655 case oEnableDSA2: opt.flags.dsa2=1; break;
2656 case oDisableDSA2: opt.flags.dsa2=0; break;
2658 case oNoop: break;
2660 default : pargs.err = configfp? 1:2; break;
2665 if( configfp ) {
2666 fclose( configfp );
2667 configfp = NULL;
2668 /* Remember the first config file name. */
2669 if (!save_configname)
2670 save_configname = configname;
2671 else
2672 xfree(configname);
2673 configname = NULL;
2674 goto next_pass;
2676 xfree( configname ); configname = NULL;
2677 if( log_get_errorcount(0) )
2678 g10_exit(2);
2680 /* The command --gpgconf-list is pretty simple and may be called
2681 directly after the option parsing. */
2682 if (cmd == aGPGConfList)
2684 gpgconf_list (save_configname);
2685 g10_exit (0);
2687 xfree (save_configname);
2689 if( nogreeting )
2690 greeting = 0;
2692 if( greeting ) {
2693 fprintf(stderr, "%s %s; %s\n",
2694 strusage(11), strusage(13), strusage(14) );
2695 fprintf(stderr, "%s\n", strusage(15) );
2697 #ifdef IS_DEVELOPMENT_VERSION
2698 if( !opt.batch )
2700 const char *s;
2702 if((s=strusage(20)))
2703 log_info("%s\n",s);
2704 if((s=strusage(21)))
2705 log_info("%s\n",s);
2706 if((s=strusage(22)))
2707 log_info("%s\n",s);
2709 #endif
2711 /* FIXME: We should use logging to a file only in server mode;
2712 however we have not yet implemetyed that. Thus we try to get
2713 away with --batch as indication for logging to file
2714 required. */
2715 if (logfile && opt.batch)
2717 log_set_file (logfile);
2718 log_set_prefix (NULL, 1|2|4);
2721 if (opt.verbose > 2)
2722 log_info ("using character set `%s'\n", get_native_charset ());
2724 if( may_coredump && !opt.quiet )
2725 log_info(_("WARNING: program may create a core file!\n"));
2727 if (eyes_only) {
2728 if (opt.set_filename)
2729 log_info(_("WARNING: %s overrides %s\n"),
2730 "--for-your-eyes-only","--set-filename");
2732 opt.set_filename="_CONSOLE";
2735 if (opt.no_literal) {
2736 log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
2737 if (opt.textmode)
2738 log_error(_("%s not allowed with %s!\n"),
2739 "--textmode", "--no-literal" );
2740 if (opt.set_filename)
2741 log_error(_("%s makes no sense with %s!\n"),
2742 eyes_only?"--for-your-eyes-only":"--set-filename",
2743 "--no-literal" );
2747 if (opt.set_filesize)
2748 log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
2749 if( opt.batch )
2750 tty_batchmode( 1 );
2752 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
2754 if(require_secmem && !got_secmem)
2756 log_info(_("will not run with insecure memory due to %s\n"),
2757 "--require-secmem");
2758 g10_exit(2);
2761 set_debug (debug_level);
2763 /* Do these after the switch(), so they can override settings. */
2764 if(PGP2)
2766 int unusable=0;
2768 if(cmd==aSign && !detached_sig)
2770 log_info(_("you can only make detached or clear signatures "
2771 "while in --pgp2 mode\n"));
2772 unusable=1;
2774 else if(cmd==aSignEncr || cmd==aSignSym)
2776 log_info(_("you can't sign and encrypt at the "
2777 "same time while in --pgp2 mode\n"));
2778 unusable=1;
2780 else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
2782 log_info(_("you must use files (and not a pipe) when "
2783 "working with --pgp2 enabled.\n"));
2784 unusable=1;
2786 else if(cmd==aEncr || cmd==aSym)
2788 /* Everything else should work without IDEA (except using
2789 a secret key encrypted with IDEA and setting an IDEA
2790 preference, but those have their own error
2791 messages). */
2793 if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
2795 log_info(_("encrypting a message in --pgp2 mode requires "
2796 "the IDEA cipher\n"));
2797 idea_cipher_warn(1);
2798 unusable=1;
2800 else if(cmd==aSym)
2802 /* This only sets IDEA for symmetric encryption
2803 since it is set via select_algo_from_prefs for
2804 pk encryption. */
2805 xfree(def_cipher_string);
2806 def_cipher_string = xstrdup("idea");
2809 /* PGP2 can't handle the output from the textmode
2810 filter, so we disable it for anything that could
2811 create a literal packet (only encryption and
2812 symmetric encryption, since we disable signing
2813 above). */
2814 if(!unusable)
2815 opt.textmode=0;
2818 if(unusable)
2819 compliance_failure();
2820 else
2822 opt.force_v4_certs = 0;
2823 opt.escape_from = 1;
2824 opt.force_v3_sigs = 1;
2825 opt.pgp2_workarounds = 1;
2826 opt.ask_sig_expire = 0;
2827 opt.ask_cert_expire = 0;
2828 xfree(def_digest_string);
2829 def_digest_string = xstrdup("md5");
2830 xfree(s2k_digest_string);
2831 s2k_digest_string = xstrdup("md5");
2832 opt.compress_algo = COMPRESS_ALGO_ZIP;
2835 else if(PGP6)
2837 opt.escape_from=1;
2838 opt.force_v3_sigs=1;
2839 opt.ask_sig_expire=0;
2841 else if(PGP7)
2843 opt.escape_from=1;
2844 opt.force_v3_sigs=1;
2845 opt.ask_sig_expire=0;
2847 else if(PGP8)
2849 opt.escape_from=1;
2853 if( def_cipher_string ) {
2854 opt.def_cipher_algo = gcry_cipher_map_name (def_cipher_string);
2855 if(opt.def_cipher_algo==0 &&
2856 (ascii_strcasecmp(def_cipher_string,"idea")==0
2857 || ascii_strcasecmp(def_cipher_string,"s1")==0))
2858 idea_cipher_warn(1);
2859 xfree(def_cipher_string); def_cipher_string = NULL;
2860 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
2861 log_error(_("selected cipher algorithm is invalid\n"));
2863 if( def_digest_string ) {
2864 opt.def_digest_algo = gcry_md_map_name (def_digest_string);
2865 xfree(def_digest_string); def_digest_string = NULL;
2866 if ( openpgp_md_test_algo (opt.def_digest_algo) )
2867 log_error(_("selected digest algorithm is invalid\n"));
2869 if( compress_algo_string ) {
2870 opt.compress_algo = string_to_compress_algo(compress_algo_string);
2871 xfree(compress_algo_string); compress_algo_string = NULL;
2872 if( check_compress_algo(opt.compress_algo) )
2873 log_error(_("selected compression algorithm is invalid\n"));
2875 if( cert_digest_string ) {
2876 opt.cert_digest_algo = gcry_md_map_name (cert_digest_string);
2877 xfree(cert_digest_string); cert_digest_string = NULL;
2878 if (openpgp_md_test_algo(opt.cert_digest_algo))
2879 log_error(_("selected certification digest algorithm is invalid\n"));
2881 if( s2k_cipher_string ) {
2882 opt.s2k_cipher_algo = gcry_cipher_map_name (s2k_cipher_string);
2883 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
2884 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
2885 log_error(_("selected cipher algorithm is invalid\n"));
2887 if( s2k_digest_string ) {
2888 opt.s2k_digest_algo = gcry_md_map_name (s2k_digest_string);
2889 xfree(s2k_digest_string); s2k_digest_string = NULL;
2890 if (openpgp_md_test_algo(opt.s2k_digest_algo))
2891 log_error(_("selected digest algorithm is invalid\n"));
2893 if( opt.completes_needed < 1 )
2894 log_error(_("completes-needed must be greater than 0\n"));
2895 if( opt.marginals_needed < 2 )
2896 log_error(_("marginals-needed must be greater than 1\n"));
2897 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
2898 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
2899 if(opt.def_cert_level<0 || opt.def_cert_level>3)
2900 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
2901 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
2902 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
2903 switch( opt.s2k_mode ) {
2904 case 0:
2905 log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
2906 break;
2907 case 1: case 3: break;
2908 default:
2909 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
2912 /* This isn't actually needed, but does serve to error out if the
2913 string is invalid. */
2914 if(opt.def_preference_list &&
2915 keygen_set_std_prefs(opt.def_preference_list,0))
2916 log_error(_("invalid default preferences\n"));
2918 /* We provide defaults for the personal digest list. This is
2919 SHA-1. */
2920 if(!pers_digest_list)
2921 pers_digest_list="h2";
2923 if(pers_cipher_list &&
2924 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
2925 log_error(_("invalid personal cipher preferences\n"));
2927 if(pers_digest_list &&
2928 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
2929 log_error(_("invalid personal digest preferences\n"));
2931 if(pers_compress_list &&
2932 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
2933 log_error(_("invalid personal compress preferences\n"));
2935 /* We don't support all possible commands with multifile yet */
2936 if(multifile)
2938 char *cmdname;
2940 switch(cmd)
2942 case aSign:
2943 cmdname="--sign";
2944 break;
2945 case aClearsign:
2946 cmdname="--clearsign";
2947 break;
2948 case aDetachedSign:
2949 cmdname="--detach-sign";
2950 break;
2951 case aSym:
2952 cmdname="--symmetric";
2953 break;
2954 case aEncrSym:
2955 cmdname="--symmetric --encrypt";
2956 break;
2957 case aStore:
2958 cmdname="--store";
2959 break;
2960 default:
2961 cmdname=NULL;
2962 break;
2965 if(cmdname)
2966 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
2969 if( log_get_errorcount(0) )
2970 g10_exit(2);
2972 if(opt.compress_level==0)
2973 opt.compress_algo=COMPRESS_ALGO_NONE;
2975 /* Check our chosen algorithms against the list of legal
2976 algorithms. */
2978 if(!GNUPG)
2980 const char *badalg=NULL;
2981 preftype_t badtype=PREFTYPE_NONE;
2983 if(opt.def_cipher_algo
2984 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
2986 badalg = gcry_cipher_algo_name (opt.def_cipher_algo);
2987 badtype = PREFTYPE_SYM;
2989 else if(opt.def_digest_algo
2990 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
2992 badalg = gcry_md_algo_name (opt.def_digest_algo);
2993 badtype = PREFTYPE_HASH;
2995 else if(opt.cert_digest_algo
2996 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
2998 badalg = gcry_md_algo_name (opt.cert_digest_algo);
2999 badtype = PREFTYPE_HASH;
3001 else if(opt.compress_algo!=-1
3002 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3004 badalg = compress_algo_to_string(opt.compress_algo);
3005 badtype = PREFTYPE_ZIP;
3008 if(badalg)
3010 switch(badtype)
3012 case PREFTYPE_SYM:
3013 log_info(_("you may not use cipher algorithm `%s'"
3014 " while in %s mode\n"),
3015 badalg,compliance_option_string());
3016 break;
3017 case PREFTYPE_HASH:
3018 log_info(_("you may not use digest algorithm `%s'"
3019 " while in %s mode\n"),
3020 badalg,compliance_option_string());
3021 break;
3022 case PREFTYPE_ZIP:
3023 log_info(_("you may not use compression algorithm `%s'"
3024 " while in %s mode\n"),
3025 badalg,compliance_option_string());
3026 break;
3027 default:
3028 BUG();
3031 compliance_failure();
3035 /* Set the random seed file. */
3036 if( use_random_seed ) {
3037 char *p = make_filename(opt.homedir, "random_seed", NULL );
3038 set_random_seed_file(p);
3039 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3040 if (!access (p, F_OK))
3041 register_secured_file (p);
3042 xfree(p);
3045 if( !cmd && opt.fingerprint && !with_fpr ) {
3046 set_cmd( &cmd, aListKeys);
3049 if( cmd == aKMode || cmd == aKModeC ) { /* kludge to be compatible to pgp */
3050 if( cmd == aKModeC ) {
3051 opt.fingerprint = 1;
3052 cmd = aKMode;
3054 opt.list_sigs = 0;
3055 if( opt.verbose > 2 )
3056 opt.check_sigs++;
3057 if( opt.verbose > 1 )
3058 opt.list_sigs++;
3060 opt.verbose = opt.verbose > 1;
3063 /* kludge to let -sat generate a clear text signature */
3064 if( opt.textmode == 2 && !detached_sig && opt.armor && cmd == aSign )
3065 cmd = aClearsign;
3067 if( opt.verbose > 1 )
3068 set_packet_list_mode(1);
3070 /* Add the keyrings, but not for some special commands and not in
3071 case of "-kvv userid keyring". Also avoid adding the secret
3072 keyring for a couple of commands to avoid unneeded access in
3073 case the secrings are stored on a floppy.
3075 We always need to add the keyrings if we are running under
3076 SELinux, this is so that the rings are added to the list of
3077 secured files. */
3078 if( ALWAYS_ADD_KEYRINGS
3079 || (cmd != aDeArmor && cmd != aEnArmor
3080 && !(cmd == aKMode && argc == 2 )) )
3082 if (ALWAYS_ADD_KEYRINGS
3083 || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
3084 && cmd != aVerify && cmd != aSym))
3086 if (!sec_nrings || default_keyring) /* add default secret rings */
3087 keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
3088 for (sl = sec_nrings; sl; sl = sl->next)
3089 keydb_add_resource ( sl->d, 0, 1 );
3091 if( !nrings || default_keyring ) /* add default ring */
3092 keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
3093 for(sl = nrings; sl; sl = sl->next )
3094 keydb_add_resource ( sl->d, sl->flags, 0 );
3096 FREE_STRLIST(nrings);
3097 FREE_STRLIST(sec_nrings);
3100 if( pwfd != -1 ) /* read the passphrase now. */
3101 read_passphrase_from_fd( pwfd );
3103 fname = argc? *argv : NULL;
3105 if(fname && utf8_strings)
3106 opt.flags.utf8_filename=1;
3108 switch( cmd ) {
3109 case aPrimegen:
3110 case aPrintMD:
3111 case aPrintMDs:
3112 case aGenRandom:
3113 case aDeArmor:
3114 case aEnArmor:
3115 case aFixTrustDB:
3116 break;
3117 case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
3118 case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
3119 default: rc = setup_trustdb(1, trustdb_name ); break;
3121 if( rc )
3122 log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
3125 switch (cmd)
3127 case aStore:
3128 case aSym:
3129 case aSign:
3130 case aSignSym:
3131 case aClearsign:
3132 if (!opt.quiet && any_explicit_recipient)
3133 log_info (_("WARNING: recipients (-r) given "
3134 "without using public key encryption\n"));
3135 break;
3136 default:
3137 break;
3140 switch( cmd )
3142 case aStore: /* only store the file */
3143 if( argc > 1 )
3144 wrong_args(_("--store [filename]"));
3145 if( (rc = encode_store(fname)) )
3146 log_error ("storing `%s' failed: %s\n",
3147 print_fname_stdin(fname),g10_errstr(rc) );
3148 break;
3149 case aSym: /* encrypt the given file only with the symmetric cipher */
3150 if( argc > 1 )
3151 wrong_args(_("--symmetric [filename]"));
3152 if( (rc = encode_symmetric(fname)) )
3153 log_error (_("symmetric encryption of `%s' failed: %s\n"),
3154 print_fname_stdin(fname),g10_errstr(rc) );
3155 break;
3157 case aEncr: /* encrypt the given file */
3158 if(multifile)
3159 encode_crypt_files(argc, argv, remusr);
3160 else
3162 if( argc > 1 )
3163 wrong_args(_("--encrypt [filename]"));
3164 if( (rc = encode_crypt(fname,remusr,0)) )
3165 log_error("%s: encryption failed: %s\n",
3166 print_fname_stdin(fname), g10_errstr(rc) );
3168 break;
3170 case aEncrSym:
3171 /* This works with PGP 8 in the sense that it acts just like a
3172 symmetric message. It doesn't work at all with 2 or 6. It
3173 might work with 7, but alas, I don't have a copy to test
3174 with right now. */
3175 if( argc > 1 )
3176 wrong_args(_("--symmetric --encrypt [filename]"));
3177 else if(opt.s2k_mode==0)
3178 log_error(_("you cannot use --symmetric --encrypt"
3179 " with --s2k-mode 0\n"));
3180 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3181 log_error(_("you cannot use --symmetric --encrypt"
3182 " while in %s mode\n"),compliance_option_string());
3183 else
3185 if( (rc = encode_crypt(fname,remusr,1)) )
3186 log_error("%s: encryption failed: %s\n",
3187 print_fname_stdin(fname), g10_errstr(rc) );
3189 break;
3191 case aSign: /* sign the given file */
3192 sl = NULL;
3193 if( detached_sig ) { /* sign all files */
3194 for( ; argc; argc--, argv++ )
3195 add_to_strlist( &sl, *argv );
3197 else {
3198 if( argc > 1 )
3199 wrong_args(_("--sign [filename]"));
3200 if( argc ) {
3201 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3202 strcpy(sl->d, fname);
3205 if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
3206 log_error("signing failed: %s\n", g10_errstr(rc) );
3207 free_strlist(sl);
3208 break;
3210 case aSignEncr: /* sign and encrypt the given file */
3211 if( argc > 1 )
3212 wrong_args(_("--sign --encrypt [filename]"));
3213 if( argc ) {
3214 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3215 strcpy(sl->d, fname);
3217 else
3218 sl = NULL;
3219 if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
3220 log_error("%s: sign+encrypt failed: %s\n",
3221 print_fname_stdin(fname), g10_errstr(rc) );
3222 free_strlist(sl);
3223 break;
3225 case aSignEncrSym: /* sign and encrypt the given file */
3226 if( argc > 1 )
3227 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3228 else if(opt.s2k_mode==0)
3229 log_error(_("you cannot use --symmetric --sign --encrypt"
3230 " with --s2k-mode 0\n"));
3231 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3232 log_error(_("you cannot use --symmetric --sign --encrypt"
3233 " while in %s mode\n"),compliance_option_string());
3234 else
3236 if( argc )
3238 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3239 strcpy(sl->d, fname);
3241 else
3242 sl = NULL;
3243 if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
3244 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3245 print_fname_stdin(fname), g10_errstr(rc) );
3246 free_strlist(sl);
3248 break;
3250 case aSignSym: /* sign and conventionally encrypt the given file */
3251 if (argc > 1)
3252 wrong_args(_("--sign --symmetric [filename]"));
3253 rc = sign_symencrypt_file (fname, locusr);
3254 if (rc)
3255 log_error("%s: sign+symmetric failed: %s\n",
3256 print_fname_stdin(fname), g10_errstr(rc) );
3257 break;
3259 case aClearsign: /* make a clearsig */
3260 if( argc > 1 )
3261 wrong_args(_("--clearsign [filename]"));
3262 if( (rc = clearsign_file(fname, locusr, NULL)) )
3263 log_error("%s: clearsign failed: %s\n",
3264 print_fname_stdin(fname), g10_errstr(rc) );
3265 break;
3267 case aVerify:
3268 if(multifile)
3270 if( (rc = verify_files( argc, argv ) ))
3271 log_error("verify files failed: %s\n", g10_errstr(rc) );
3273 else
3275 if( (rc = verify_signatures( argc, argv ) ))
3276 log_error("verify signatures failed: %s\n", g10_errstr(rc) );
3278 break;
3280 case aDecrypt:
3281 if(multifile)
3282 decrypt_messages(argc, argv);
3283 else
3285 if( argc > 1 )
3286 wrong_args(_("--decrypt [filename]"));
3287 if( (rc = decrypt_message( fname ) ))
3288 log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
3290 break;
3292 case aSignKey:
3293 if( argc != 1 )
3294 wrong_args(_("--sign-key user-id"));
3295 /* fall through */
3296 case aLSignKey:
3297 if( argc != 1 )
3298 wrong_args(_("--lsign-key user-id"));
3299 /* fall through */
3301 sl=NULL;
3303 if(cmd==aSignKey)
3304 append_to_strlist(&sl,"sign");
3305 else if(cmd==aLSignKey)
3306 append_to_strlist(&sl,"lsign");
3307 else
3308 BUG();
3310 append_to_strlist( &sl, "save" );
3311 username = make_username( fname );
3312 keyedit_menu(fname, locusr, sl, 0, 0 );
3313 xfree(username);
3314 free_strlist(sl);
3315 break;
3317 case aEditKey: /* Edit a key signature */
3318 if( !argc )
3319 wrong_args(_("--edit-key user-id [commands]"));
3320 username = make_username( fname );
3321 if( argc > 1 ) {
3322 sl = NULL;
3323 for( argc--, argv++ ; argc; argc--, argv++ )
3324 append_to_strlist( &sl, *argv );
3325 keyedit_menu( username, locusr, sl, 0, 1 );
3326 free_strlist(sl);
3328 else
3329 keyedit_menu(username, locusr, NULL, 0, 1 );
3330 xfree(username);
3331 break;
3333 case aDeleteKeys:
3334 case aDeleteSecretKeys:
3335 case aDeleteSecretAndPublicKeys:
3336 sl = NULL;
3337 /* I'm adding these in reverse order as add_to_strlist2
3338 reverses them again, and it's easier to understand in the
3339 proper order :) */
3340 for( ; argc; argc-- )
3341 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3342 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3343 free_strlist(sl);
3344 break;
3346 case aCheckKeys:
3347 opt.check_sigs = 1;
3348 case aListSigs:
3349 opt.list_sigs = 1;
3350 case aListKeys:
3351 sl = NULL;
3352 for( ; argc; argc--, argv++ )
3353 add_to_strlist2( &sl, *argv, utf8_strings );
3354 public_key_list( sl );
3355 free_strlist(sl);
3356 break;
3357 case aListSecretKeys:
3358 sl = NULL;
3359 for( ; argc; argc--, argv++ )
3360 add_to_strlist2( &sl, *argv, utf8_strings );
3361 secret_key_list( sl );
3362 free_strlist(sl);
3363 break;
3365 case aKMode: /* list keyring -- NOTE: This will be removed soon */
3366 if( argc < 2 ) { /* -kv [userid] */
3367 sl = NULL;
3368 if (argc && **argv)
3369 add_to_strlist2( &sl, *argv, utf8_strings );
3370 public_key_list( sl );
3371 free_strlist(sl);
3373 else if( argc == 2 ) { /* -kv userid keyring */
3374 if( access( argv[1], R_OK ) ) {
3375 log_error(_("can't open `%s': %s\n"),
3376 print_fname_stdin(argv[1]), strerror(errno));
3378 else {
3379 /* add keyring (default keyrings are not registered in this
3380 * special case */
3381 keydb_add_resource( argv[1], 0, 0 );
3382 sl = NULL;
3383 if (**argv)
3384 add_to_strlist2( &sl, *argv, utf8_strings );
3385 public_key_list( sl );
3386 free_strlist(sl);
3389 else
3390 wrong_args(_("-k[v][v][v][c] [user-id] [keyring]") );
3391 break;
3393 case aKeygen: /* generate a key */
3394 if( opt.batch ) {
3395 if( argc > 1 )
3396 wrong_args("--gen-key [parameterfile]");
3397 generate_keypair( argc? *argv : NULL, NULL, NULL );
3399 else {
3400 if( argc )
3401 wrong_args("--gen-key");
3402 generate_keypair(NULL, NULL, NULL);
3404 break;
3406 case aFastImport:
3407 opt.import_options |= IMPORT_FAST;
3408 case aImport:
3409 import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
3410 break;
3412 /* TODO: There are a number of command that use this same
3413 "make strlist, call function, report error, free strlist"
3414 pattern. Join them together here and avoid all that
3415 duplicated code. */
3417 case aExport:
3418 case aSendKeys:
3419 case aRecvKeys:
3420 sl = NULL;
3421 for( ; argc; argc--, argv++ )
3422 append_to_strlist2( &sl, *argv, utf8_strings );
3423 if( cmd == aSendKeys )
3424 rc=keyserver_export( sl );
3425 else if( cmd == aRecvKeys )
3426 rc=keyserver_import( sl );
3427 else
3428 rc=export_pubkeys( sl, opt.export_options );
3429 if(rc)
3431 if(cmd==aSendKeys)
3432 log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
3433 else if(cmd==aRecvKeys)
3434 log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
3435 else
3436 log_error(_("key export failed: %s\n"),g10_errstr(rc));
3438 free_strlist(sl);
3439 break;
3441 case aSearchKeys:
3442 sl = NULL;
3443 for( ; argc; argc--, argv++ )
3444 append_to_strlist2( &sl, *argv, utf8_strings );
3445 rc=keyserver_search( sl );
3446 if(rc)
3447 log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
3448 free_strlist(sl);
3449 break;
3451 case aRefreshKeys:
3452 sl = NULL;
3453 for( ; argc; argc--, argv++ )
3454 append_to_strlist2( &sl, *argv, utf8_strings );
3455 rc=keyserver_refresh(sl);
3456 if(rc)
3457 log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
3458 free_strlist(sl);
3459 break;
3461 case aFetchKeys:
3462 sl = NULL;
3463 for( ; argc; argc--, argv++ )
3464 append_to_strlist2( &sl, *argv, utf8_strings );
3465 rc=keyserver_fetch(sl);
3466 if(rc)
3467 log_error("key fetch failed: %s\n",g10_errstr(rc));
3468 free_strlist(sl);
3469 break;
3471 case aExportSecret:
3472 sl = NULL;
3473 for( ; argc; argc--, argv++ )
3474 add_to_strlist2( &sl, *argv, utf8_strings );
3475 export_seckeys( sl );
3476 free_strlist(sl);
3477 break;
3479 case aExportSecretSub:
3480 sl = NULL;
3481 for( ; argc; argc--, argv++ )
3482 add_to_strlist2( &sl, *argv, utf8_strings );
3483 export_secsubkeys( sl );
3484 free_strlist(sl);
3485 break;
3487 case aGenRevoke:
3488 if( argc != 1 )
3489 wrong_args("--gen-revoke user-id");
3490 username = make_username(*argv);
3491 gen_revoke( username );
3492 xfree( username );
3493 break;
3495 case aDesigRevoke:
3496 if( argc != 1 )
3497 wrong_args("--desig-revoke user-id");
3498 username = make_username(*argv);
3499 gen_desig_revoke( username, locusr );
3500 xfree( username );
3501 break;
3503 case aDeArmor:
3504 if( argc > 1 )
3505 wrong_args("--dearmor [file]");
3506 rc = dearmor_file( argc? *argv: NULL );
3507 if( rc )
3508 log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
3509 break;
3511 case aEnArmor:
3512 if( argc > 1 )
3513 wrong_args("--enarmor [file]");
3514 rc = enarmor_file( argc? *argv: NULL );
3515 if( rc )
3516 log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
3517 break;
3520 case aPrimegen:
3521 #if 0 /*FIXME*/
3522 { int mode = argc < 2 ? 0 : atoi(*argv);
3524 if( mode == 1 && argc == 2 ) {
3525 mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
3527 else if( mode == 2 && argc == 3 ) {
3528 mpi_print( stdout, generate_elg_prime(
3529 0, atoi(argv[1]),
3530 atoi(argv[2]), NULL,NULL ), 1);
3532 else if( mode == 3 && argc == 3 ) {
3533 MPI *factors;
3534 mpi_print( stdout, generate_elg_prime(
3535 1, atoi(argv[1]),
3536 atoi(argv[2]), NULL,&factors ), 1);
3537 putchar('\n');
3538 mpi_print( stdout, factors[0], 1 ); /* print q */
3540 else if( mode == 4 && argc == 3 ) {
3541 MPI g = mpi_alloc(1);
3542 mpi_print( stdout, generate_elg_prime(
3543 0, atoi(argv[1]),
3544 atoi(argv[2]), g, NULL ), 1);
3545 putchar('\n');
3546 mpi_print( stdout, g, 1 );
3547 mpi_free(g);
3549 else
3550 wrong_args("--gen-prime mode bits [qbits] ");
3551 putchar('\n');
3553 #endif
3554 wrong_args("--gen-prime not yet supported ");
3555 break;
3557 case aGenRandom:
3559 int level = argc ? atoi(*argv):0;
3560 int count = argc > 1 ? atoi(argv[1]): 0;
3561 int endless = !count;
3563 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
3564 wrong_args("--gen-random 0|1|2 [count]");
3566 while( endless || count ) {
3567 byte *p;
3568 /* Wee need a multiple of 3, so that in case of
3569 armored output we get a correct string. No
3570 linefolding is done, as it is best to levae this to
3571 other tools */
3572 size_t n = !endless && count < 99? count : 99;
3574 p = gcry_random_bytes (n, level);
3575 #ifdef HAVE_DOSISH_SYSTEM
3576 setmode ( fileno(stdout), O_BINARY );
3577 #endif
3578 if (opt.armor) {
3579 char *tmp = make_radix64_string (p, n);
3580 fputs (tmp, stdout);
3581 xfree (tmp);
3582 if (n%3 == 1)
3583 putchar ('=');
3584 if (n%3)
3585 putchar ('=');
3586 } else {
3587 fwrite( p, n, 1, stdout );
3589 xfree(p);
3590 if( !endless )
3591 count -= n;
3593 if (opt.armor)
3594 putchar ('\n');
3596 break;
3598 case aPrintMD:
3599 if( argc < 1)
3600 wrong_args("--print-md algo [files]");
3602 int all_algos = (**argv=='*' && !(*argv)[1]);
3603 int algo = all_algos? 0 : gcry_md_map_name (*argv);
3605 if( !algo && !all_algos )
3606 log_error(_("invalid hash algorithm `%s'\n"), *argv );
3607 else {
3608 argc--; argv++;
3609 if( !argc )
3610 print_mds(NULL, algo);
3611 else {
3612 for(; argc; argc--, argv++ )
3613 print_mds(*argv, algo);
3617 break;
3619 case aPrintMDs: /* old option */
3620 if( !argc )
3621 print_mds(NULL,0);
3622 else {
3623 for(; argc; argc--, argv++ )
3624 print_mds(*argv,0);
3626 break;
3628 case aListTrustDB:
3629 if( !argc )
3630 list_trustdb(NULL);
3631 else {
3632 for( ; argc; argc--, argv++ )
3633 list_trustdb( *argv );
3635 break;
3637 case aUpdateTrustDB:
3638 if( argc )
3639 wrong_args("--update-trustdb");
3640 update_trustdb();
3641 break;
3643 case aCheckTrustDB:
3644 /* Old versions allowed for arguments - ignore them */
3645 check_trustdb();
3646 break;
3648 case aFixTrustDB:
3649 log_error("this command is not yet implemented.\n");
3650 log_error("A workaround is to use \"--export-ownertrust\", remove\n");
3651 log_error("the trustdb file and do an \"--import-ownertrust\".\n" );
3652 break;
3654 case aListTrustPath:
3655 if( !argc )
3656 wrong_args("--list-trust-path <user-ids>");
3657 for( ; argc; argc--, argv++ ) {
3658 username = make_username( *argv );
3659 list_trust_path( username );
3660 xfree(username);
3662 break;
3664 case aExportOwnerTrust:
3665 if( argc )
3666 wrong_args("--export-ownertrust");
3667 export_ownertrust();
3668 break;
3670 case aImportOwnerTrust:
3671 if( argc > 1 )
3672 wrong_args("--import-ownertrust [file]");
3673 import_ownertrust( argc? *argv:NULL );
3674 break;
3676 case aRebuildKeydbCaches:
3677 if (argc)
3678 wrong_args ("--rebuild-keydb-caches");
3679 keydb_rebuild_caches (1);
3680 break;
3682 #ifdef ENABLE_CARD_SUPPORT
3683 case aCardStatus:
3684 if (argc)
3685 wrong_args ("--card-status");
3686 card_status (stdout, NULL, 0);
3687 break;
3689 case aCardEdit:
3690 if (argc) {
3691 sl = NULL;
3692 for (argc--, argv++ ; argc; argc--, argv++)
3693 append_to_strlist (&sl, *argv);
3694 card_edit (sl);
3695 free_strlist (sl);
3697 else
3698 card_edit (NULL);
3699 break;
3701 case aChangePIN:
3702 if (!argc)
3703 change_pin (0,1);
3704 else if (argc == 1)
3705 change_pin (atoi (*argv),1);
3706 else
3707 wrong_args ("--change-pin [no]");
3708 break;
3709 #endif /* ENABLE_CARD_SUPPORT*/
3711 case aListConfig:
3713 char *str=collapse_args(argc,argv);
3714 list_config(str);
3715 xfree(str);
3717 break;
3719 case aListPackets:
3720 opt.list_packets=2;
3721 default:
3722 if( argc > 1 )
3723 wrong_args(_("[filename]"));
3724 /* Issue some output for the unix newbie */
3725 if( !fname && !opt.outfile && isatty( fileno(stdin) )
3726 && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
3727 log_info(_("Go ahead and type your message ...\n"));
3729 a = iobuf_open(fname);
3730 if (a && is_secured_file (iobuf_get_fd (a)))
3732 iobuf_close (a);
3733 a = NULL;
3734 errno = EPERM;
3736 if( !a )
3737 log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
3738 else {
3740 if( !opt.no_armor ) {
3741 if( use_armor_filter( a ) ) {
3742 memset( &afx, 0, sizeof afx);
3743 iobuf_push_filter( a, armor_filter, &afx );
3746 if( cmd == aListPackets ) {
3747 set_packet_list_mode(1);
3748 opt.list_packets=1;
3750 rc = proc_packets(NULL, a );
3751 if( rc )
3752 log_error("processing message failed: %s\n", g10_errstr(rc) );
3753 iobuf_close(a);
3755 break;
3758 /* cleanup */
3759 FREE_STRLIST(remusr);
3760 FREE_STRLIST(locusr);
3761 g10_exit(0);
3762 return 8; /*NEVER REACHED*/
3766 /* Note: This function is used by signal handlers!. */
3767 static void
3768 emergency_cleanup (void)
3770 gcry_control (GCRYCTL_TERM_SECMEM );
3774 void
3775 g10_exit( int rc )
3777 #ifdef ENABLE_CARD_SUPPORT
3778 card_close ();
3779 #endif
3781 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
3782 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
3784 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
3785 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
3787 if (opt.debug)
3788 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
3790 emergency_cleanup ();
3792 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
3793 exit (rc);
3797 /* Pretty-print hex hashes. This assumes at least an 80-character
3798 display, but there are a few other similar assumptions in the
3799 display code. */
3800 static void
3801 print_hex( gcry_md_hd_t md, int algo, const char *fname )
3803 int i,n,count,indent=0;
3804 const byte *p;
3806 if(fname)
3807 indent=printf("%s: ",fname);
3809 if(indent>40)
3811 printf("\n");
3812 indent=0;
3815 if(algo==DIGEST_ALGO_RMD160)
3816 indent+=printf("RMD160 = ");
3817 else if(algo>0)
3818 indent+=printf("%6s = ", gcry_md_algo_name (algo));
3819 else
3820 algo=abs(algo);
3822 count=indent;
3824 p = gcry_md_read (md, algo);
3825 n = gcry_md_get_algo_dlen (algo);
3827 count += printf ("%02X",*p++);
3829 for(i=1;i<n;i++,p++)
3831 if(n==16)
3833 if(count+2>79)
3835 printf("\n%*s",indent," ");
3836 count=indent;
3838 else
3839 count+=printf(" ");
3841 if(!(i%8))
3842 count+=printf(" ");
3844 else if (n==20)
3846 if(!(i%2))
3848 if(count+4>79)
3850 printf("\n%*s",indent," ");
3851 count=indent;
3853 else
3854 count+=printf(" ");
3857 if(!(i%10))
3858 count+=printf(" ");
3860 else
3862 if(!(i%4))
3864 if(count+8>79)
3866 printf("\n%*s",indent," ");
3867 count=indent;
3869 else
3870 count+=printf(" ");
3874 count+=printf("%02X",*p);
3877 printf("\n");
3880 static void
3881 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
3883 int i, n;
3884 const byte *p;
3886 if ( fname ) {
3887 for (p = fname; *p; p++ ) {
3888 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
3889 printf("%%%02X", *p );
3890 else
3891 putchar( *p );
3894 putchar(':');
3895 printf("%d:", algo );
3896 p = gcry_md_read (md, algo);
3897 n = gcry_md_get_algo_dlen (algo);
3898 for(i=0; i < n ; i++, p++ )
3899 printf("%02X", *p );
3900 putchar(':');
3901 putchar('\n');
3904 static void
3905 print_mds( const char *fname, int algo )
3907 FILE *fp;
3908 char buf[1024];
3909 size_t n;
3910 gcry_md_hd_t md;
3912 if( !fname ) {
3913 fp = stdin;
3914 #ifdef HAVE_DOSISH_SYSTEM
3915 setmode ( fileno(fp) , O_BINARY );
3916 #endif
3918 else {
3919 fp = fopen( fname, "rb" );
3920 if (fp && is_secured_file (fileno (fp)))
3922 fclose (fp);
3923 fp = NULL;
3924 errno = EPERM;
3927 if( !fp ) {
3928 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
3929 return;
3932 gcry_md_open (&md, 0, 0);
3933 if( algo )
3934 gcry_md_enable (md, algo);
3935 else {
3936 gcry_md_enable (md, GCRY_MD_MD5);
3937 gcry_md_enable (md, GCRY_MD_SHA1);
3938 gcry_md_enable (md, GCRY_MD_RMD160);
3939 #ifdef USE_SHA256
3940 gcry_md_enable (md, DIGEST_ALGO_SHA224);
3941 gcry_md_enable (md, GCRY_MD_SHA256);
3942 #endif
3943 #ifdef USE_SHA512
3944 gcry_md_enable (md, GCRY_MD_SHA384);
3945 gcry_md_enable (md, GCRY_MD_SHA512);
3946 #endif
3949 while( (n=fread( buf, 1, DIM(buf), fp )) )
3950 gcry_md_write (md, buf, n);
3951 if( ferror(fp) )
3952 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
3953 else {
3954 gcry_md_final (md);
3955 if ( opt.with_colons ) {
3956 if ( algo )
3957 print_hashline( md, algo, fname );
3958 else {
3959 print_hashline( md, GCRY_MD_MD5, fname );
3960 print_hashline( md, GCRY_MD_SHA1, fname );
3961 print_hashline( md, GCRY_MD_RMD160, fname );
3962 #ifdef USE_SHA256
3963 if (!gcry_md_test_algo (DIGEST_ALGO_SHA224)
3964 print_hashline (md, DIGEST_ALGO_SHA224, fname);
3965 print_hashline( md, GCRY_MD_SHA256, fname );
3966 #endif
3967 #ifdef USE_SHA512
3968 print_hashline( md, GCRY_MD_SHA384, fname );
3969 print_hashline( md, GCRY_MD_SHA512, fname );
3970 #endif
3973 else {
3974 if( algo )
3975 print_hex(md,-algo,fname);
3976 else {
3977 print_hex( md, GCRY_MD_MD5, fname );
3978 print_hex( md, GCRY_MD_SHA1, fname );
3979 print_hex( md, GCRY_MD_RMD160, fname );
3980 #ifdef USE_SHA256
3981 if (!gcry_md_test_algo (DIGEST_ALGO_SHA224)
3982 print_hex (md, DIGEST_ALGO_SHA224, fname);
3983 print_hex( md, GCRY_MD_SHA256, fname );
3984 #endif
3985 #ifdef USE_SHA512
3986 print_hex( md, GCRY_MD_SHA384, fname );
3987 print_hex( md, GCRY_MD_SHA512, fname );
3988 #endif
3992 gcry_md_close(md);
3994 if( fp != stdin )
3995 fclose(fp);
3999 /****************
4000 * Check the supplied name,value string and add it to the notation
4001 * data to be used for signatures. which==0 for sig notations, and 1
4002 * for cert notations.
4004 static void
4005 add_notation_data( const char *string, int which )
4007 struct notation *notation;
4009 notation=string_to_notation(string,utf8_strings);
4010 if(notation)
4012 if(which)
4014 notation->next=opt.cert_notations;
4015 opt.cert_notations=notation;
4017 else
4019 notation->next=opt.sig_notations;
4020 opt.sig_notations=notation;
4025 static void
4026 add_policy_url( const char *string, int which )
4028 unsigned int i,critical=0;
4029 STRLIST sl;
4031 if(*string=='!')
4033 string++;
4034 critical=1;
4037 for(i=0;i<strlen(string);i++)
4038 if( !isascii (string[i]) || iscntrl(string[i]))
4039 break;
4041 if(i==0 || i<strlen(string))
4043 if(which)
4044 log_error(_("the given certification policy URL is invalid\n"));
4045 else
4046 log_error(_("the given signature policy URL is invalid\n"));
4049 if(which)
4050 sl=add_to_strlist( &opt.cert_policy_url, string );
4051 else
4052 sl=add_to_strlist( &opt.sig_policy_url, string );
4054 if(critical)
4055 sl->flags |= 1;
4058 static void
4059 add_keyserver_url( const char *string, int which )
4061 unsigned int i,critical=0;
4062 STRLIST sl;
4064 if(*string=='!')
4066 string++;
4067 critical=1;
4070 for(i=0;i<strlen(string);i++)
4071 if( !isascii (string[i]) || iscntrl(string[i]))
4072 break;
4074 if(i==0 || i<strlen(string))
4076 if(which)
4077 BUG();
4078 else
4079 log_error(_("the given preferred keyserver URL is invalid\n"));
4082 if(which)
4083 BUG();
4084 else
4085 sl=add_to_strlist( &opt.sig_keyserver_url, string );
4087 if(critical)
4088 sl->flags |= 1;