Add gpgconf related dummy options default_pubkey_algo.
[gnupg.git] / g10 / gpg.c
blob720c9f4d8815eb91ccc0ab67bb80e9d1b4071c65
1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2008, 2009 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 3 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, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <assert.h>
29 #ifdef HAVE_STAT
30 #include <sys/stat.h> /* for stat() */
31 #endif
32 #include <fcntl.h>
33 #ifdef HAVE_W32_SYSTEM
34 #include <windows.h>
35 #endif
37 #define INCLUDED_BY_MAIN_MODULE 1
38 #include "gpg.h"
39 #include <assuan.h>
40 #include "packet.h"
41 #include "../common/iobuf.h"
42 #include "util.h"
43 #include "main.h"
44 #include "options.h"
45 #include "keydb.h"
46 #include "trustdb.h"
47 #include "cipher.h"
48 #include "filter.h"
49 #include "ttyio.h"
50 #include "i18n.h"
51 #include "sysutils.h"
52 #include "status.h"
53 #include "keyserver-internal.h"
54 #include "exec.h"
55 #include "gc-opt-flags.h"
57 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
58 #define MY_O_BINARY O_BINARY
59 #ifndef S_IRGRP
60 # define S_IRGRP 0
61 # define S_IWGRP 0
62 #endif
63 #else
64 #define MY_O_BINARY 0
65 #endif
68 enum cmd_and_opt_values
70 aNull = 0,
71 oArmor = 'a',
72 aDetachedSign = 'b',
73 aSym = 'c',
74 aDecrypt = 'd',
75 aEncr = 'e',
76 oInteractive = 'i',
77 aListKeys = 'k',
78 oDryRun = 'n',
79 oOutput = 'o',
80 oQuiet = 'q',
81 oRecipient = 'r',
82 oHiddenRecipient = 'R',
83 aSign = 's',
84 oTextmodeShort= 't',
85 oLocalUser = 'u',
86 oVerbose = 'v',
87 oCompress = 'z',
88 oSetNotation = 'N',
89 aListSecretKeys = 'K',
90 oBatch = 500,
91 oMaxOutput,
92 oSigNotation,
93 oCertNotation,
94 oShowNotation,
95 oNoShowNotation,
96 aEncrFiles,
97 aEncrSym,
98 aDecryptFiles,
99 aClearsign,
100 aStore,
101 aKeygen,
102 aSignEncr,
103 aSignEncrSym,
104 aSignSym,
105 aSignKey,
106 aLSignKey,
107 aListConfig,
108 aGPGConfList,
109 aGPGConfTest,
110 aListPackets,
111 aEditKey,
112 aDeleteKeys,
113 aDeleteSecretKeys,
114 aDeleteSecretAndPublicKeys,
115 aImport,
116 aFastImport,
117 aVerify,
118 aVerifyFiles,
119 aListSigs,
120 aSendKeys,
121 aRecvKeys,
122 aLocateKeys,
123 aSearchKeys,
124 aRefreshKeys,
125 aFetchKeys,
126 aExport,
127 aExportSecret,
128 aExportSecretSub,
129 aCheckKeys,
130 aGenRevoke,
131 aDesigRevoke,
132 aPrimegen,
133 aPrintMD,
134 aPrintMDs,
135 aCheckTrustDB,
136 aUpdateTrustDB,
137 aFixTrustDB,
138 aListTrustDB,
139 aListTrustPath,
140 aExportOwnerTrust,
141 aImportOwnerTrust,
142 aDeArmor,
143 aEnArmor,
144 aGenRandom,
145 aRebuildKeydbCaches,
146 aCardStatus,
147 aCardEdit,
148 aChangePIN,
149 aServer,
151 oTextmode,
152 oNoTextmode,
153 oExpert,
154 oNoExpert,
155 oDefSigExpire,
156 oAskSigExpire,
157 oNoAskSigExpire,
158 oDefCertExpire,
159 oAskCertExpire,
160 oNoAskCertExpire,
161 oDefCertLevel,
162 oMinCertLevel,
163 oAskCertLevel,
164 oNoAskCertLevel,
165 oFingerprint,
166 oWithFingerprint,
167 oAnswerYes,
168 oAnswerNo,
169 oKeyring,
170 oPrimaryKeyring,
171 oSecretKeyring,
172 oShowKeyring,
173 oDefaultKey,
174 oDefRecipient,
175 oDefRecipientSelf,
176 oNoDefRecipient,
177 oOptions,
178 oDebug,
179 oDebugLevel,
180 oDebugAll,
181 oDebugCCIDDriver,
182 oStatusFD,
183 oStatusFile,
184 oAttributeFD,
185 oAttributeFile,
186 oEmitVersion,
187 oNoEmitVersion,
188 oCompletesNeeded,
189 oMarginalsNeeded,
190 oMaxCertDepth,
191 oLoadExtension,
192 oGnuPG,
193 oRFC1991,
194 oRFC2440,
195 oRFC4880,
196 oOpenPGP,
197 oPGP2,
198 oPGP6,
199 oPGP7,
200 oPGP8,
201 oRFC2440Text,
202 oNoRFC2440Text,
203 oCipherAlgo,
204 oDigestAlgo,
205 oCertDigestAlgo,
206 oCompressAlgo,
207 oCompressLevel,
208 oBZ2CompressLevel,
209 oBZ2DecompressLowmem,
210 oPasswd,
211 oPasswdFD,
212 oPasswdFile,
213 oPasswdRepeat,
214 oCommandFD,
215 oCommandFile,
216 oQuickRandom,
217 oNoVerbose,
218 oTrustDBName,
219 oNoSecmemWarn,
220 oRequireSecmem,
221 oNoRequireSecmem,
222 oNoPermissionWarn,
223 oNoMDCWarn,
224 oNoArmor,
225 oNoDefKeyring,
226 oNoGreeting,
227 oNoTTY,
228 oNoOptions,
229 oNoBatch,
230 oHomedir,
231 oWithColons,
232 oWithKeyData,
233 oWithSigList,
234 oWithSigCheck,
235 oSkipVerify,
236 oSkipHiddenRecipients,
237 oNoSkipHiddenRecipients,
238 oCompressKeys,
239 oCompressSigs,
240 oAlwaysTrust,
241 oTrustModel,
242 oForceOwnertrust,
243 oSetFilename,
244 oForYourEyesOnly,
245 oNoForYourEyesOnly,
246 oSetPolicyURL,
247 oSigPolicyURL,
248 oCertPolicyURL,
249 oShowPolicyURL,
250 oNoShowPolicyURL,
251 oSigKeyserverURL,
252 oUseEmbeddedFilename,
253 oNoUseEmbeddedFilename,
254 oComment,
255 oDefaultComment,
256 oNoComments,
257 oThrowKeyids,
258 oNoThrowKeyids,
259 oShowPhotos,
260 oNoShowPhotos,
261 oPhotoViewer,
262 oForceV3Sigs,
263 oNoForceV3Sigs,
264 oForceV4Certs,
265 oNoForceV4Certs,
266 oForceMDC,
267 oNoForceMDC,
268 oDisableMDC,
269 oNoDisableMDC,
270 oS2KMode,
271 oS2KDigest,
272 oS2KCipher,
273 oS2KCount,
274 oSimpleSKChecksum,
275 oDisplayCharset,
276 oNotDashEscaped,
277 oEscapeFrom,
278 oNoEscapeFrom,
279 oLockOnce,
280 oLockMultiple,
281 oLockNever,
282 oKeyServer,
283 oKeyServerOptions,
284 oImportOptions,
285 oExportOptions,
286 oListOptions,
287 oVerifyOptions,
288 oTempDir,
289 oExecPath,
290 oEncryptTo,
291 oHiddenEncryptTo,
292 oNoEncryptTo,
293 oLoggerFD,
294 oLoggerFile,
295 oUtf8Strings,
296 oNoUtf8Strings,
297 oDisableCipherAlgo,
298 oDisablePubkeyAlgo,
299 oAllowNonSelfsignedUID,
300 oNoAllowNonSelfsignedUID,
301 oAllowFreeformUID,
302 oNoAllowFreeformUID,
303 oAllowSecretKeyImport,
304 oEnableSpecialFilenames,
305 oNoLiteral,
306 oSetFilesize,
307 oHonorHttpProxy,
308 oFastListMode,
309 oListOnly,
310 oIgnoreTimeConflict,
311 oIgnoreValidFrom,
312 oIgnoreCrcError,
313 oIgnoreMDCError,
314 oShowSessionKey,
315 oOverrideSessionKey,
316 oNoRandomSeedFile,
317 oAutoKeyRetrieve,
318 oNoAutoKeyRetrieve,
319 oUseAgent,
320 oNoUseAgent,
321 oGpgAgentInfo,
322 oMergeOnly,
323 oTryAllSecrets,
324 oTrustedKey,
325 oNoExpensiveTrustChecks,
326 oFixedListMode,
327 oNoSigCache,
328 oNoSigCreateCheck,
329 oAutoCheckTrustDB,
330 oNoAutoCheckTrustDB,
331 oPreservePermissions,
332 oDefaultPreferenceList,
333 oDefaultKeyserverURL,
334 oPersonalCipherPreferences,
335 oPersonalDigestPreferences,
336 oPersonalCompressPreferences,
337 oAgentProgram,
338 oDisplay,
339 oTTYname,
340 oTTYtype,
341 oLCctype,
342 oLCmessages,
343 oXauthority,
344 oGroup,
345 oUnGroup,
346 oNoGroups,
347 oStrict,
348 oNoStrict,
349 oMangleDosFilenames,
350 oNoMangleDosFilenames,
351 oEnableProgressFilter,
352 oMultifile,
353 oKeyidFormat,
354 oExitOnStatusWriteError,
355 oLimitCardInsertTries,
356 oRequireCrossCert,
357 oNoRequireCrossCert,
358 oAutoKeyLocate,
359 oNoAutoKeyLocate,
360 oAllowMultisigVerification,
361 oEnableDSA2,
362 oDisableDSA2,
363 oAllowMultipleMessages,
364 oNoAllowMultipleMessages,
366 oNoop
370 static ARGPARSE_OPTS opts[] = {
372 ARGPARSE_group (300, N_("@Commands:\n ")),
374 ARGPARSE_c (aSign, "sign", N_("make a signature")),
375 ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature")),
376 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
377 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
378 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
379 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
380 ARGPARSE_c (aStore, "store", "@"),
381 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
382 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
383 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
384 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
385 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
386 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
387 ARGPARSE_c (aListSigs, "list-sigs", N_("list keys and signatures")),
388 ARGPARSE_c (aCheckKeys, "check-sigs",N_("list and check key signatures")),
389 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
390 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
391 ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
392 ARGPARSE_c (aDeleteKeys,"delete-keys",
393 N_("remove keys from the public keyring")),
394 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
395 N_("remove keys from the secret keyring")),
396 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
397 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
398 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
399 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
400 ARGPARSE_c (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")),
401 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
402 ARGPARSE_c (aExport, "export" , N_("export keys") ),
403 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ),
404 ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ),
405 ARGPARSE_c (aSearchKeys, "search-keys" ,
406 N_("search for keys on a key server") ),
407 ARGPARSE_c (aRefreshKeys, "refresh-keys",
408 N_("update all keys from a keyserver")),
409 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
410 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
411 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
412 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
413 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
414 ARGPARSE_c (aFastImport, "fast-import", "@"),
415 #ifdef ENABLE_CARD_SUPPORT
416 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
417 ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")),
418 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
419 #endif
420 ARGPARSE_c (aListConfig, "list-config", "@"),
421 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
422 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
423 ARGPARSE_c (aListPackets, "list-packets","@"),
424 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
425 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
426 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
427 N_("update the trust database")),
428 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
429 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
430 ARGPARSE_c (aDeArmor, "dearmor", "@"),
431 ARGPARSE_c (aDeArmor, "dearmour", "@"),
432 ARGPARSE_c (aEnArmor, "enarmor", "@"),
433 ARGPARSE_c (aEnArmor, "enarmour", "@"),
434 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
435 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
436 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
437 ARGPARSE_c (aServer, "server", N_("run in server mode")),
439 ARGPARSE_group (301, N_("@\nOptions:\n ")),
441 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
442 ARGPARSE_s_n (oArmor, "armour", "@"),
444 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
445 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
446 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
447 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
448 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
449 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
451 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
452 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
453 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
454 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
455 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
456 ARGPARSE_s_s (oLocalUser, "local-user",
457 N_("|USER-ID|use USER-ID to sign or decrypt")),
459 ARGPARSE_s_i (oCompress, NULL,
460 N_("|N|set compress level to N (0 disables)")),
461 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
462 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
463 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
465 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
466 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
467 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
469 ARGPARSE_s_n (oExpert, "expert", "@"),
470 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
472 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
473 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
474 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
475 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
476 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
477 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
478 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
479 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
480 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
481 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
483 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
484 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
486 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
487 ARGPARSE_s_n (oQuiet, "quiet", "@"),
488 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
490 ARGPARSE_s_n (oForceV3Sigs, "force-v3-sigs", "@"),
491 ARGPARSE_s_n (oNoForceV3Sigs, "no-force-v3-sigs", "@"),
492 ARGPARSE_s_n (oForceV4Certs, "force-v4-certs", "@"),
493 ARGPARSE_s_n (oNoForceV4Certs, "no-force-v4-certs", "@"),
494 ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
495 ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
496 ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
497 ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
499 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
500 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
502 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
503 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
504 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
506 ARGPARSE_s_n (oBatch, "batch", "@"),
507 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
508 ARGPARSE_s_n (oAnswerNo, "no", "@"),
509 ARGPARSE_s_s (oKeyring, "keyring", "@"),
510 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
511 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
512 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
513 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
515 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
516 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
517 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
518 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
519 ARGPARSE_s_s (oListOptions, "list-options", "@"),
520 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
522 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
523 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
524 ARGPARSE_s_s (oOptions, "options", "@"),
526 ARGPARSE_p_u (oDebug, "debug", "@"),
527 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
528 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
529 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
530 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
531 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
532 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
534 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
535 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
537 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
538 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
539 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
540 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
542 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
544 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
545 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
546 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
547 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
548 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
549 ARGPARSE_s_n (oRFC1991, "rfc1991", "@"),
550 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
551 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
552 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
553 ARGPARSE_s_n (oPGP2, "pgp2", "@"),
554 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
555 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
556 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
558 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
559 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
560 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
561 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
562 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
563 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
564 ARGPARSE_s_n (oSimpleSKChecksum, "simple-sk-checksum", "@"),
565 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
566 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
567 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
568 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
569 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
570 ARGPARSE_s_n (oThrowKeyids, "throw-keyid", "@"),
571 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
572 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyid", "@"),
573 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
574 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
575 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
576 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
577 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
578 ARGPARSE_s_s (oSetNotation, "notation-data", "@"), /* Alias */
579 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
580 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
582 ARGPARSE_group (302, N_(
583 "@\n(See the man page for a complete listing of all commands and options)\n"
586 ARGPARSE_group (303, N_("@\nExamples:\n\n"
587 " -se -r Bob [file] sign and encrypt for user Bob\n"
588 " --clearsign [file] make a clear text signature\n"
589 " --detach-sign [file] make a detached signature\n"
590 " --list-keys [names] show keys\n"
591 " --fingerprint [names] show fingerprints\n")),
593 /* More hidden commands and options. */
594 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
595 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
596 /* Not yet used:
597 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
598 ARGPARSE_c (aDeleteSecretAndPublicKeys,
599 "delete-secret-and-public-keys", "@"),
600 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
602 ARGPARSE_s_s (oPasswd, "passphrase", "@"),
603 ARGPARSE_s_i (oPasswdFD, "passphrase-fd", "@"),
604 ARGPARSE_s_s (oPasswdFile, "passphrase-file", "@"),
605 ARGPARSE_s_i (oPasswdRepeat, "passphrase-repeat", "@"),
606 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
607 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
608 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
609 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
610 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
611 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
612 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
613 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
614 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
615 ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
616 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
617 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
618 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
619 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
620 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
621 ARGPARSE_s_s (oHomedir, "homedir", "@"),
622 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
623 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
624 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
625 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
626 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
627 ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */
628 ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */
629 ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */
630 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
631 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
632 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
633 ARGPARSE_s_n (oCompressKeys, "compress-keys", "@"),
634 ARGPARSE_s_n (oCompressSigs, "compress-sigs", "@"),
635 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
636 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
637 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
638 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
639 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
640 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
641 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
642 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
643 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
644 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
645 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
646 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
647 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
648 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
649 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
650 ARGPARSE_s_s (oComment, "comment", "@"),
651 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
652 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
653 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
654 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
655 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
656 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
657 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
658 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
659 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
660 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
661 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
662 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
663 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
664 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
665 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
666 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
667 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
668 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
669 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
670 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
671 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
672 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
673 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
674 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
675 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
676 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
677 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
678 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
679 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
680 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
681 ARGPARSE_s_n (oListOnly, "list-only", "@"),
682 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
683 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
684 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
685 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
686 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
687 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
688 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
689 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
690 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
691 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
692 ARGPARSE_s_n (oNoSigCreateCheck, "no-sig-create-check", "@"),
693 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
694 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
695 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
696 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
697 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
698 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
699 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
700 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
701 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
702 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
703 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
704 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
705 ARGPARSE_s_s (oPersonalCompressPreferences,
706 "personal-compress-preferences", "@"),
708 /* Aliases. I constantly mistype these, and assume other people do
709 as well. */
710 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
711 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
712 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
713 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
714 ARGPARSE_s_s (oDisplay, "display", "@"),
715 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
716 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
717 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
718 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
719 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
720 ARGPARSE_s_s (oGroup, "group", "@"),
721 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
722 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
723 ARGPARSE_s_n (oStrict, "strict", "@"),
724 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
725 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
726 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
727 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
728 ARGPARSE_s_n (oMultifile, "multifile", "@"),
729 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
730 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
731 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
733 ARGPARSE_s_n (oAllowMultisigVerification,
734 "allow-multisig-verification", "@"),
735 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
736 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
737 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
738 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
740 /* These two are aliases to help users of the PGP command line
741 product use gpg with minimal pain. Many commands are common
742 already as they seem to have borrowed commands from us. Now I'm
743 returning the favor. */
744 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
745 ARGPARSE_s_s (oRecipient, "user", "@"),
747 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
748 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
749 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
750 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
752 /* New options. Fixme: Should go more to the top. */
753 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
754 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
756 ARGPARSE_end ()
760 #ifdef ENABLE_SELINUX_HACKS
761 #define ALWAYS_ADD_KEYRINGS 1
762 #else
763 #define ALWAYS_ADD_KEYRINGS 0
764 #endif
767 int g10_errors_seen = 0;
769 static int utf8_strings = 0;
770 static int maybe_setuid = 1;
772 static char *build_list( const char *text, char letter,
773 const char *(*mapf)(int), int (*chkf)(int) );
774 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
775 enum cmd_and_opt_values new_cmd );
776 static void print_mds( const char *fname, int algo );
777 static void add_notation_data( const char *string, int which );
778 static void add_policy_url( const char *string, int which );
779 static void add_keyserver_url( const char *string, int which );
780 static void emergency_cleanup (void);
783 static char *
784 make_libversion (const char *libname, const char *(*getfnc)(const char*))
786 const char *s;
787 char *result;
789 if (maybe_setuid)
791 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
792 maybe_setuid = 0;
794 s = getfnc (NULL);
795 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
796 strcpy (stpcpy (stpcpy (result, libname), " "), s);
797 return result;
801 static const char *
802 my_strusage( int level )
804 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
805 const char *p;
807 switch( level ) {
808 case 11: p = "gpg (GnuPG)";
809 break;
810 case 13: p = VERSION; break;
811 case 17: p = PRINTABLE_OS_NAME; break;
812 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
814 case 20:
815 if (!ver_gcry)
816 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
817 p = ver_gcry;
818 break;
820 #ifdef IS_DEVELOPMENT_VERSION
821 case 25:
822 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
823 break;
824 case 26:
825 p="It is only intended for test purposes and should NOT be";
826 break;
827 case 27:
828 p="used in a production environment or with production keys!";
829 break;
830 #endif
832 case 1:
833 case 40: p =
834 _("Usage: gpg [options] [files] (-h for help)");
835 break;
836 case 41: p =
837 _("Syntax: gpg [options] [files]\n"
838 "sign, check, encrypt or decrypt\n"
839 "default operation depends on the input data\n");
840 break;
842 case 31: p = "\nHome: "; break;
843 #ifndef __riscos__
844 case 32: p = opt.homedir; break;
845 #else /* __riscos__ */
846 case 32: p = make_filename(opt.homedir, NULL); break;
847 #endif /* __riscos__ */
848 case 33: p = _("\nSupported algorithms:\n"); break;
849 case 34:
850 if (!pubkeys)
851 pubkeys = build_list (_("Pubkey: "), 0,
852 gcry_pk_algo_name,
853 openpgp_pk_test_algo );
854 p = pubkeys;
855 break;
856 case 35:
857 if( !ciphers )
858 ciphers = build_list(_("Cipher: "), 'S',
859 openpgp_cipher_algo_name,
860 openpgp_cipher_test_algo );
861 p = ciphers;
862 break;
863 case 36:
864 if( !digests )
865 digests = build_list(_("Hash: "), 'H',
866 gcry_md_algo_name,
867 openpgp_md_test_algo );
868 p = digests;
869 break;
870 case 37:
871 if( !zips )
872 zips = build_list(_("Compression: "),'Z',
873 compress_algo_to_string,
874 check_compress_algo);
875 p = zips;
876 break;
878 default: p = NULL;
880 return p;
884 static char *
885 build_list( const char *text, char letter,
886 const char * (*mapf)(int), int (*chkf)(int) )
888 int i;
889 const char *s;
890 size_t n=strlen(text)+2;
891 char *list, *p, *line=NULL;
893 if (maybe_setuid)
894 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
896 for(i=0; i <= 110; i++ )
897 if( !chkf(i) && (s=mapf(i)) )
898 n += strlen(s) + 7 + 2;
899 list = xmalloc( 21 + n ); *list = 0;
900 for(p=NULL, i=0; i <= 110; i++ ) {
901 if( !chkf(i) && (s=mapf(i)) ) {
902 if( !p ) {
903 p = stpcpy( list, text );
904 line=p;
906 else
907 p = stpcpy( p, ", ");
909 if(strlen(line)>60) {
910 int spaces=strlen(text);
912 list=xrealloc(list,n+spaces+1);
913 /* realloc could move the block, so find the end again */
914 p=list;
915 while(*p)
916 p++;
918 p=stpcpy(p, "\n");
919 line=p;
920 for(;spaces;spaces--)
921 p=stpcpy(p, " ");
924 p = stpcpy(p, s );
925 if(opt.verbose && letter)
927 char num[8];
928 sprintf(num," (%c%d)",letter,i);
929 p = stpcpy(p,num);
933 if( p )
934 p = stpcpy(p, "\n" );
935 return list;
939 static void
940 wrong_args( const char *text)
942 fputs(_("usage: gpg [options] "),stderr);
943 fputs(text,stderr);
944 putc('\n',stderr);
945 g10_exit(2);
949 static char *
950 make_username( const char *string )
952 char *p;
953 if( utf8_strings )
954 p = xstrdup(string);
955 else
956 p = native_to_utf8( string );
957 return p;
961 static void
962 set_opt_session_env (const char *name, const char *value)
964 gpg_error_t err;
966 err = session_env_setenv (opt.session_env, name, value);
967 if (err)
968 log_fatal ("error setting session environment: %s\n",
969 gpg_strerror (err));
972 /* Setup the debugging. With a LEVEL of NULL only the active debug
973 flags are propagated to the subsystems. With LEVEL set, a specific
974 set of debug flags is set; thus overriding all flags already
975 set. */
976 static void
977 set_debug (const char *level)
979 if (!level)
981 else if (!strcmp (level, "none"))
982 opt.debug = 0;
983 else if (!strcmp (level, "basic"))
984 opt.debug = DBG_MEMSTAT_VALUE;
985 else if (!strcmp (level, "advanced"))
986 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
987 else if (!strcmp (level, "expert"))
988 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
989 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
990 else if (!strcmp (level, "guru"))
991 opt.debug = ~0;
992 else
994 log_error (_("invalid debug-level `%s' given\n"), level);
995 g10_exit (2);
998 if (opt.debug & DBG_MEMORY_VALUE )
999 memory_debug_mode = 1;
1000 if (opt.debug & DBG_MEMSTAT_VALUE )
1001 memory_stat_debug_mode = 1;
1002 if (opt.debug & DBG_MPI_VALUE)
1003 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1004 if (opt.debug & DBG_CIPHER_VALUE )
1005 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1006 if (opt.debug & DBG_IOBUF_VALUE )
1007 iobuf_debug_mode = 1;
1008 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1013 /* We need the home directory also in some other directories, so make
1014 sure that both variables are always in sync. */
1015 static void
1016 set_homedir (const char *dir)
1018 if (!dir)
1019 dir = "";
1020 opt.homedir = dir;
1024 /* We set the screen dimensions for UI purposes. Do not allow screens
1025 smaller than 80x24 for the sake of simplicity. */
1026 static void
1027 set_screen_dimensions(void)
1029 #ifndef HAVE_W32_SYSTEM
1030 char *str;
1032 str=getenv("COLUMNS");
1033 if(str)
1034 opt.screen_columns=atoi(str);
1036 str=getenv("LINES");
1037 if(str)
1038 opt.screen_lines=atoi(str);
1039 #endif
1041 if(opt.screen_columns<80 || opt.screen_columns>255)
1042 opt.screen_columns=80;
1044 if(opt.screen_lines<24 || opt.screen_lines>255)
1045 opt.screen_lines=24;
1049 /* Helper to open a file FNAME either for reading or writing to be
1050 used with --status-file etc functions. Not generally useful but it
1051 avoids the riscos specific functions and well some Windows people
1052 might like it too. Prints an error message and returns -1 on
1053 error. On success the file descriptor is returned. */
1054 static int
1055 open_info_file (const char *fname, int for_write, int binary)
1057 #ifdef __riscos__
1058 return riscos_fdopenfile (fname, for_write);
1059 #elif defined (ENABLE_SELINUX_HACKS)
1060 /* We can't allow these even when testing for a secured filename
1061 because files to be secured might not yet been secured. This is
1062 similar to the option file but in that case it is unlikely that
1063 sensitive information may be retrieved by means of error
1064 messages. */
1065 (void)fname;
1066 (void)for_write;
1067 (void)binary;
1068 return -1;
1069 #else
1070 int fd;
1072 if (binary)
1073 binary = MY_O_BINARY;
1075 /* if (is_secured_filename (fname)) */
1076 /* { */
1077 /* fd = -1; */
1078 /* errno = EPERM; */
1079 /* } */
1080 /* else */
1081 /* { */
1084 if (for_write)
1085 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1086 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1087 else
1088 fd = open (fname, O_RDONLY | binary);
1090 while (fd == -1 && errno == EINTR);
1091 /* } */
1092 if ( fd == -1)
1093 log_error ( for_write? _("can't create `%s': %s\n")
1094 : _("can't open `%s': %s\n"), fname, strerror(errno));
1096 return fd;
1097 #endif
1100 static void
1101 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1103 enum cmd_and_opt_values cmd = *ret_cmd;
1105 if( !cmd || cmd == new_cmd )
1106 cmd = new_cmd;
1107 else if( cmd == aSign && new_cmd == aEncr )
1108 cmd = aSignEncr;
1109 else if( cmd == aEncr && new_cmd == aSign )
1110 cmd = aSignEncr;
1111 else if( cmd == aSign && new_cmd == aSym )
1112 cmd = aSignSym;
1113 else if( cmd == aSym && new_cmd == aSign )
1114 cmd = aSignSym;
1115 else if( cmd == aSym && new_cmd == aEncr )
1116 cmd = aEncrSym;
1117 else if( cmd == aEncr && new_cmd == aSym )
1118 cmd = aEncrSym;
1119 else if (cmd == aSignEncr && new_cmd == aSym)
1120 cmd = aSignEncrSym;
1121 else if (cmd == aSignSym && new_cmd == aEncr)
1122 cmd = aSignEncrSym;
1123 else if (cmd == aEncrSym && new_cmd == aSign)
1124 cmd = aSignEncrSym;
1125 else if( ( cmd == aSign && new_cmd == aClearsign )
1126 || ( cmd == aClearsign && new_cmd == aSign ) )
1127 cmd = aClearsign;
1128 else {
1129 log_error(_("conflicting commands\n"));
1130 g10_exit(2);
1133 *ret_cmd = cmd;
1137 static void
1138 add_group(char *string)
1140 char *name,*value;
1141 struct groupitem *item;
1143 /* Break off the group name */
1144 name=strsep(&string,"=");
1145 if(string==NULL)
1147 log_error(_("no = sign found in group definition `%s'\n"),name);
1148 return;
1151 trim_trailing_ws(name,strlen(name));
1153 /* Does this group already exist? */
1154 for(item=opt.grouplist;item;item=item->next)
1155 if(strcasecmp(item->name,name)==0)
1156 break;
1158 if(!item)
1160 item=xmalloc(sizeof(struct groupitem));
1161 item->name=name;
1162 item->next=opt.grouplist;
1163 item->values=NULL;
1164 opt.grouplist=item;
1167 /* Break apart the values */
1168 while ((value= strsep(&string," \t")))
1170 if (*value)
1171 add_to_strlist2(&item->values,value,utf8_strings);
1176 static void
1177 rm_group(char *name)
1179 struct groupitem *item,*last=NULL;
1181 trim_trailing_ws(name,strlen(name));
1183 for(item=opt.grouplist;item;last=item,item=item->next)
1185 if(strcasecmp(item->name,name)==0)
1187 if(last)
1188 last->next=item->next;
1189 else
1190 opt.grouplist=item->next;
1192 free_strlist(item->values);
1193 xfree(item);
1194 break;
1200 /* We need to check three things.
1202 0) The homedir. It must be x00, a directory, and owned by the
1203 user.
1205 1) The options/gpg.conf file. Okay unless it or its containing
1206 directory is group or other writable or not owned by us. Disable
1207 exec in this case.
1209 2) Extensions. Same as #1.
1211 Returns true if the item is unsafe. */
1212 static int
1213 check_permissions(const char *path,int item)
1215 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1216 static int homedir_cache=-1;
1217 char *tmppath,*dir;
1218 struct stat statbuf,dirbuf;
1219 int homedir=0,ret=0,checkonly=0;
1220 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1222 if(opt.no_perm_warn)
1223 return 0;
1225 assert(item==0 || item==1 || item==2);
1227 /* extensions may attach a path */
1228 if(item==2 && path[0]!=DIRSEP_C)
1230 if(strchr(path,DIRSEP_C))
1231 tmppath=make_filename(path,NULL);
1232 else
1233 tmppath=make_filename(gnupg_libdir (),path,NULL);
1235 else
1236 tmppath=xstrdup(path);
1238 /* If the item is located in the homedir, but isn't the homedir,
1239 don't continue if we already checked the homedir itself. This is
1240 to avoid user confusion with an extra options file warning which
1241 could be rectified if the homedir itself had proper
1242 permissions. */
1243 if(item!=0 && homedir_cache>-1
1244 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1246 ret=homedir_cache;
1247 goto end;
1250 /* It's okay if the file or directory doesn't exist */
1251 if(stat(tmppath,&statbuf)!=0)
1253 ret=0;
1254 goto end;
1257 /* Now check the enclosing directory. Theoretically, we could walk
1258 this test up to the root directory /, but for the sake of sanity,
1259 I'm stopping at one level down. */
1260 dir=make_dirname(tmppath);
1262 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1264 /* Weird error */
1265 ret=1;
1266 goto end;
1269 xfree(dir);
1271 /* Assume failure */
1272 ret=1;
1274 if(item==0)
1276 /* The homedir must be x00, a directory, and owned by the user. */
1278 if(S_ISDIR(statbuf.st_mode))
1280 if(statbuf.st_uid==getuid())
1282 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1283 ret=0;
1284 else
1285 perm=1;
1287 else
1288 own=1;
1290 homedir_cache=ret;
1293 else if(item==1 || item==2)
1295 /* The options or extension file. Okay unless it or its
1296 containing directory is group or other writable or not owned
1297 by us or root. */
1299 if(S_ISREG(statbuf.st_mode))
1301 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1303 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1305 /* it's not writable, so make sure the enclosing
1306 directory is also not writable */
1307 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1309 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1310 ret=0;
1311 else
1312 enc_dir_perm=1;
1314 else
1315 enc_dir_own=1;
1317 else
1319 /* it's writable, so the enclosing directory had
1320 better not let people get to it. */
1321 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1323 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1324 ret=0;
1325 else
1326 perm=enc_dir_perm=1; /* unclear which one to fix! */
1328 else
1329 enc_dir_own=1;
1332 else
1333 own=1;
1336 else
1337 BUG();
1339 if(!checkonly)
1341 if(own)
1343 if(item==0)
1344 log_info(_("WARNING: unsafe ownership on"
1345 " homedir `%s'\n"),tmppath);
1346 else if(item==1)
1347 log_info(_("WARNING: unsafe ownership on"
1348 " configuration file `%s'\n"),tmppath);
1349 else
1350 log_info(_("WARNING: unsafe ownership on"
1351 " extension `%s'\n"),tmppath);
1353 if(perm)
1355 if(item==0)
1356 log_info(_("WARNING: unsafe permissions on"
1357 " homedir `%s'\n"),tmppath);
1358 else if(item==1)
1359 log_info(_("WARNING: unsafe permissions on"
1360 " configuration file `%s'\n"),tmppath);
1361 else
1362 log_info(_("WARNING: unsafe permissions on"
1363 " extension `%s'\n"),tmppath);
1365 if(enc_dir_own)
1367 if(item==0)
1368 log_info(_("WARNING: unsafe enclosing directory ownership on"
1369 " homedir `%s'\n"),tmppath);
1370 else if(item==1)
1371 log_info(_("WARNING: unsafe enclosing directory ownership on"
1372 " configuration file `%s'\n"),tmppath);
1373 else
1374 log_info(_("WARNING: unsafe enclosing directory ownership on"
1375 " extension `%s'\n"),tmppath);
1377 if(enc_dir_perm)
1379 if(item==0)
1380 log_info(_("WARNING: unsafe enclosing directory permissions on"
1381 " homedir `%s'\n"),tmppath);
1382 else if(item==1)
1383 log_info(_("WARNING: unsafe enclosing directory permissions on"
1384 " configuration file `%s'\n"),tmppath);
1385 else
1386 log_info(_("WARNING: unsafe enclosing directory permissions on"
1387 " extension `%s'\n"),tmppath);
1391 end:
1392 xfree(tmppath);
1394 if(homedir)
1395 homedir_cache=ret;
1397 return ret;
1399 #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
1401 return 0;
1405 static void
1406 print_algo_numbers(int (*checker)(int))
1408 int i,first=1;
1410 for(i=0;i<=110;i++)
1412 if(!checker(i))
1414 if(first)
1415 first=0;
1416 else
1417 printf(";");
1418 printf("%d",i);
1424 static void
1425 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1427 int i,first=1;
1429 for(i=0;i<=110;i++)
1431 if(!checker(i))
1433 if(first)
1434 first=0;
1435 else
1436 printf(";");
1437 printf("%s",mapper(i));
1442 /* In the future, we can do all sorts of interesting configuration
1443 output here. For now, just give "group" as the Enigmail folks need
1444 it, and pubkey, cipher, hash, and compress as they may be useful
1445 for frontends. */
1446 static void
1447 list_config(char *items)
1449 int show_all=(items==NULL);
1450 char *name=NULL;
1452 if(!opt.with_colons)
1453 return;
1455 while(show_all || (name=strsep(&items," ")))
1457 int any=0;
1459 if(show_all || ascii_strcasecmp(name,"group")==0)
1461 struct groupitem *iter;
1463 for(iter=opt.grouplist;iter;iter=iter->next)
1465 strlist_t sl;
1467 printf("cfg:group:");
1468 print_string(stdout,iter->name,strlen(iter->name),':');
1469 printf(":");
1471 for(sl=iter->values;sl;sl=sl->next)
1473 print_sanitized_string2 (stdout, sl->d, ':',';');
1474 if(sl->next)
1475 printf(";");
1478 printf("\n");
1481 any=1;
1484 if(show_all || ascii_strcasecmp(name,"version")==0)
1486 printf("cfg:version:");
1487 print_string(stdout,VERSION,strlen(VERSION),':');
1488 printf("\n");
1489 any=1;
1492 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1494 printf("cfg:pubkey:");
1495 print_algo_numbers (openpgp_pk_test_algo);
1496 printf("\n");
1497 any=1;
1500 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1502 printf("cfg:cipher:");
1503 print_algo_numbers(openpgp_cipher_test_algo);
1504 printf("\n");
1505 any=1;
1508 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1510 printf ("cfg:ciphername:");
1511 print_algo_names (openpgp_cipher_test_algo,openpgp_cipher_algo_name);
1512 printf ("\n");
1513 any = 1;
1516 if(show_all
1517 || ascii_strcasecmp(name,"digest")==0
1518 || ascii_strcasecmp(name,"hash")==0)
1520 printf("cfg:digest:");
1521 print_algo_numbers(openpgp_md_test_algo);
1522 printf("\n");
1523 any=1;
1526 if (show_all
1527 || !ascii_strcasecmp(name,"digestname")
1528 || !ascii_strcasecmp(name,"hashname"))
1530 printf ("cfg:digestname:");
1531 print_algo_names (openpgp_md_test_algo, gcry_md_algo_name);
1532 printf("\n");
1533 any=1;
1536 if(show_all || ascii_strcasecmp(name,"compress")==0)
1538 printf("cfg:compress:");
1539 print_algo_numbers(check_compress_algo);
1540 printf("\n");
1541 any=1;
1544 if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
1546 #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \
1547 && GNUPG_MAJOR_VERSION == 1
1549 char *p, *p2, *list = ccid_get_reader_list ();
1551 for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
1553 *p2 = 0;
1554 printf("cfg:ccid-reader-id:%s\n", p);
1556 free (list);
1557 #endif
1558 any=1;
1561 if(show_all)
1562 break;
1564 if(!any)
1565 log_error(_("unknown configuration item `%s'\n"),name);
1570 /* List options and default values in the GPG Conf format. This is a
1571 new tool distributed with gnupg 1.9.x but we also want some limited
1572 support in older gpg versions. The output is the name of the
1573 configuration file and a list of options available for editing by
1574 gpgconf. */
1575 static void
1576 gpgconf_list (const char *configfile)
1578 char *configfile_esc = percent_escape (configfile, NULL);
1580 printf ("gpgconf-gpg.conf:%lu:\"%s\n",
1581 GC_OPT_FLAG_DEFAULT, configfile_esc ? configfile_esc : "/dev/null");
1582 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1583 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1584 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1585 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1586 printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1587 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1588 printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1589 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1590 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1591 printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1593 /* The next one is an info only item and should match what
1594 keygen:ask_keysize actually implements. */
1595 printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1596 "RSA-2048");
1598 xfree (configfile_esc);
1602 static int
1603 parse_subpacket_list(char *list)
1605 char *tok;
1606 byte subpackets[128],i;
1607 int count=0;
1609 if(!list)
1611 /* No arguments means all subpackets */
1612 memset(subpackets+1,1,sizeof(subpackets)-1);
1613 count=127;
1615 else
1617 memset(subpackets,0,sizeof(subpackets));
1619 /* Merge with earlier copy */
1620 if(opt.show_subpackets)
1622 byte *in;
1624 for(in=opt.show_subpackets;*in;in++)
1626 if(*in>127 || *in<1)
1627 BUG();
1629 if(!subpackets[*in])
1630 count++;
1631 subpackets[*in]=1;
1635 while((tok=strsep(&list," ,")))
1637 if(!*tok)
1638 continue;
1640 i=atoi(tok);
1641 if(i>127 || i<1)
1642 return 0;
1644 if(!subpackets[i])
1645 count++;
1646 subpackets[i]=1;
1650 xfree(opt.show_subpackets);
1651 opt.show_subpackets=xmalloc(count+1);
1652 opt.show_subpackets[count--]=0;
1654 for(i=1;i<128 && count>=0;i++)
1655 if(subpackets[i])
1656 opt.show_subpackets[count--]=i;
1658 return 1;
1662 static int
1663 parse_list_options(char *str)
1665 char *subpackets=""; /* something that isn't NULL */
1666 struct parse_options lopts[]=
1668 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1669 N_("display photo IDs during key listings")},
1670 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1671 N_("show policy URLs during signature listings")},
1672 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1673 N_("show all notations during signature listings")},
1674 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1675 N_("show IETF standard notations during signature listings")},
1676 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1677 NULL},
1678 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1679 N_("show user-supplied notations during signature listings")},
1680 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1681 N_("show preferred keyserver URLs during signature listings")},
1682 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1683 N_("show user ID validity during key listings")},
1684 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1685 N_("show revoked and expired user IDs in key listings")},
1686 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1687 N_("show revoked and expired subkeys in key listings")},
1688 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1689 N_("show the keyring name in key listings")},
1690 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1691 N_("show expiration dates during signature listings")},
1692 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1693 NULL},
1694 {NULL,0,NULL,NULL}
1697 /* C99 allows for non-constant initializers, but we'd like to
1698 compile everywhere, so fill in the show-sig-subpackets argument
1699 here. Note that if the parse_options array changes, we'll have
1700 to change the subscript here. */
1701 lopts[12].value=&subpackets;
1703 if(parse_options(str,&opt.list_options,lopts,1))
1705 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1707 /* Unset so users can pass multiple lists in. */
1708 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1709 if(!parse_subpacket_list(subpackets))
1710 return 0;
1712 else if(subpackets==NULL && opt.show_subpackets)
1714 /* User did 'no-show-subpackets' */
1715 xfree(opt.show_subpackets);
1716 opt.show_subpackets=NULL;
1719 return 1;
1721 else
1722 return 0;
1726 /* Collapses argc/argv into a single string that must be freed */
1727 static char *
1728 collapse_args(int argc,char *argv[])
1730 char *str=NULL;
1731 int i,first=1,len=0;
1733 for(i=0;i<argc;i++)
1735 len+=strlen(argv[i])+2;
1736 str=xrealloc(str,len);
1737 if(first)
1739 str[0]='\0';
1740 first=0;
1742 else
1743 strcat(str," ");
1745 strcat(str,argv[i]);
1748 return str;
1751 static void
1752 parse_trust_model(const char *model)
1754 if(ascii_strcasecmp(model,"pgp")==0)
1755 opt.trust_model=TM_PGP;
1756 else if(ascii_strcasecmp(model,"classic")==0)
1757 opt.trust_model=TM_CLASSIC;
1758 else if(ascii_strcasecmp(model,"always")==0)
1759 opt.trust_model=TM_ALWAYS;
1760 else if(ascii_strcasecmp(model,"direct")==0)
1761 opt.trust_model=TM_DIRECT;
1762 else if(ascii_strcasecmp(model,"auto")==0)
1763 opt.trust_model=TM_AUTO;
1764 else
1765 log_error("unknown trust model `%s'\n",model);
1769 /* Pack an s2k iteration count into the form specified in 2440. If
1770 we're in between valid values, round up. */
1771 static unsigned char
1772 encode_s2k_iterations(int iterations)
1774 unsigned char c=0,result;
1775 unsigned int count;
1777 if(iterations<=1024)
1778 return 0;
1780 if(iterations>=65011712)
1781 return 255;
1783 /* Need count to be in the range 16-31 */
1784 for(count=iterations>>6;count>=32;count>>=1)
1785 c++;
1787 result=(c<<4)|(count-16);
1789 if(S2K_DECODE_COUNT(result)<iterations)
1790 result++;
1792 return result;
1796 /* This fucntion called to initialized a new control object. It is
1797 assumed that this object has been zeroed out before calling this
1798 function. */
1799 static void
1800 gpg_init_default_ctrl (ctrl_t ctrl)
1802 (void)ctrl;
1806 /* This function is called to deinitialize a control object. It is
1807 not deallocated. */
1808 static void
1809 gpg_deinit_default_ctrl (ctrl_t ctrl)
1811 (void)ctrl;
1815 char *
1816 get_default_configname (void)
1818 char *configname = NULL;
1819 char *name = xstrdup ("gpg" EXTSEP_S "conf-" SAFE_VERSION);
1820 char *ver = &name[strlen ("gpg" EXTSEP_S "conf-")];
1824 if (configname)
1826 char *tok;
1828 xfree (configname);
1829 configname = NULL;
1831 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
1832 *tok='\0';
1833 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
1834 *tok='\0';
1835 else
1836 break;
1839 configname = make_filename (opt.homedir, name, NULL);
1841 while (access (configname, R_OK));
1843 xfree(name);
1845 if (! configname)
1846 configname = make_filename (opt.homedir, "gpg" EXTSEP_S "conf", NULL);
1847 if (! access (configname, R_OK))
1849 /* Print a warning when both config files are present. */
1850 char *p = make_filename (opt.homedir, "options", NULL);
1851 if (! access (p, R_OK))
1852 log_info (_("NOTE: old default options file `%s' ignored\n"), p);
1853 xfree (p);
1855 else
1857 /* Use the old default only if it exists. */
1858 char *p = make_filename (opt.homedir, "options", NULL);
1859 if (!access (p, R_OK))
1861 xfree (configname);
1862 configname = p;
1864 else
1865 xfree (p);
1868 return configname;
1873 main (int argc, char **argv)
1875 ARGPARSE_ARGS pargs;
1876 IOBUF a;
1877 int rc=0;
1878 int orig_argc;
1879 char **orig_argv;
1880 const char *fname;
1881 char *username;
1882 int may_coredump;
1883 strlist_t sl, remusr= NULL, locusr=NULL;
1884 strlist_t nrings=NULL, sec_nrings=NULL;
1885 armor_filter_context_t *afx = NULL;
1886 int detached_sig = 0;
1887 FILE *configfp = NULL;
1888 char *configname = NULL;
1889 char *save_configname = NULL;
1890 char *default_configname = NULL;
1891 unsigned configlineno;
1892 int parse_debug = 0;
1893 int default_config = 1;
1894 int default_keyring = 1;
1895 int greeting = 0;
1896 int nogreeting = 0;
1897 char *logfile = NULL;
1898 int use_random_seed = 1;
1899 enum cmd_and_opt_values cmd = 0;
1900 const char *debug_level = NULL;
1901 const char *trustdb_name = NULL;
1902 char *def_cipher_string = NULL;
1903 char *def_digest_string = NULL;
1904 char *compress_algo_string = NULL;
1905 char *cert_digest_string = NULL;
1906 char *s2k_cipher_string = NULL;
1907 char *s2k_digest_string = NULL;
1908 char *pers_cipher_list = NULL;
1909 char *pers_digest_list = NULL;
1910 char *pers_compress_list = NULL;
1911 int eyes_only=0;
1912 int multifile=0;
1913 int pwfd = -1;
1914 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
1915 int any_explicit_recipient = 0;
1916 int require_secmem=0,got_secmem=0;
1917 struct assuan_malloc_hooks malloc_hooks;
1919 #ifdef __riscos__
1920 opt.lock_once = 1;
1921 #endif /* __riscos__ */
1924 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1925 when adding any stuff between here and the call to
1926 secmem_init() somewhere after the option parsing. */
1927 gnupg_reopen_std ("gpg");
1928 trap_unaligned ();
1929 gnupg_rl_initialize ();
1930 set_strusage (my_strusage);
1931 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1932 log_set_prefix ("gpg", 1);
1934 /* Make sure that our subsystems are ready. */
1935 i18n_init();
1936 init_common_subsystems ();
1938 /* Check that the libraries are suitable. Do it right here because the
1939 option parsing may need services of the library. */
1940 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1942 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
1943 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1946 /* Put random number into secure memory */
1947 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1949 may_coredump = disable_core_dumps();
1951 gnupg_init_signals (0, emergency_cleanup);
1953 create_dotlock(NULL); /* Register locking cleanup. */
1955 opt.session_env = session_env_new ();
1956 if (!opt.session_env)
1957 log_fatal ("error allocating session environment block: %s\n",
1958 strerror (errno));
1960 opt.command_fd = -1; /* no command fd */
1961 opt.compress_level = -1; /* defaults to standard compress level */
1962 opt.bz2_compress_level = -1; /* defaults to standard compress level */
1963 /* note: if you change these lines, look at oOpenPGP */
1964 opt.def_cipher_algo = 0;
1965 opt.def_digest_algo = 0;
1966 opt.cert_digest_algo = 0;
1967 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
1968 opt.s2k_mode = 3; /* iterated+salted */
1969 opt.s2k_count = 96; /* 65536 iterations */
1970 #ifdef USE_CAST5
1971 opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
1972 #else
1973 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
1974 #endif
1975 opt.completes_needed = 1;
1976 opt.marginals_needed = 3;
1977 opt.max_cert_depth = 5;
1978 opt.pgp2_workarounds = 1;
1979 opt.escape_from = 1;
1980 opt.flags.require_cross_cert = 1;
1981 opt.import_options=IMPORT_SK2PK;
1982 opt.export_options=EXPORT_ATTRIBUTES;
1983 opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
1984 opt.keyserver_options.export_options=EXPORT_ATTRIBUTES;
1985 opt.keyserver_options.options=
1986 KEYSERVER_HONOR_KEYSERVER_URL|KEYSERVER_HONOR_PKA_RECORD;
1987 opt.verify_options=
1988 VERIFY_SHOW_POLICY_URLS|VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_KEYSERVER_URLS;
1989 opt.trust_model=TM_AUTO;
1990 opt.mangle_dos_filenames=0;
1991 opt.min_cert_level=2;
1992 set_screen_dimensions();
1993 opt.keyid_format=KF_SHORT;
1994 opt.def_sig_expire="0";
1995 opt.def_cert_expire="0";
1996 set_homedir ( default_homedir () );
1997 opt.passwd_repeat=1;
1999 /* Check whether we have a config file on the command line. */
2000 orig_argc = argc;
2001 orig_argv = argv;
2002 pargs.argc = &argc;
2003 pargs.argv = &argv;
2004 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
2005 while( arg_parse( &pargs, opts) ) {
2006 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
2007 parse_debug++;
2008 else if( pargs.r_opt == oOptions ) {
2009 /* yes there is one, so we do not try the default one, but
2010 * read the option file when it is encountered at the commandline
2012 default_config = 0;
2014 else if( pargs.r_opt == oNoOptions )
2016 default_config = 0; /* --no-options */
2017 opt.no_homedir_creation = 1;
2019 else if( pargs.r_opt == oHomedir )
2020 set_homedir ( pargs.r.ret_str );
2021 else if( pargs.r_opt == oNoPermissionWarn )
2022 opt.no_perm_warn=1;
2023 else if (pargs.r_opt == oStrict )
2025 /* Not used */
2027 else if (pargs.r_opt == oNoStrict )
2029 /* Not used */
2033 #ifdef HAVE_DOSISH_SYSTEM
2034 if ( strchr (opt.homedir,'\\') ) {
2035 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
2036 const char *s = opt.homedir;
2037 for (d=buf,s=opt.homedir; *s; s++)
2039 *d++ = *s == '\\'? '/': *s;
2040 #ifdef HAVE_W32_SYSTEM
2041 if (s[1] && IsDBCSLeadByte (*s))
2042 *d++ = *++s;
2043 #endif
2045 *d = 0;
2046 set_homedir (buf);
2048 #endif
2050 /* Initialize the secure memory. */
2051 if (!gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0))
2052 got_secmem = 1;
2053 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2054 /* There should be no way to get to this spot while still carrying
2055 setuid privs. Just in case, bomb out if we are. */
2056 if ( getuid () != geteuid () )
2057 BUG ();
2058 #endif
2059 maybe_setuid = 0;
2061 /* Okay, we are now working under our real uid */
2063 /* malloc hooks go here ... */
2064 malloc_hooks.malloc = gcry_malloc;
2065 malloc_hooks.realloc = gcry_realloc;
2066 malloc_hooks.free = gcry_free;
2067 assuan_set_malloc_hooks (&malloc_hooks);
2068 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
2069 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2071 /* Try for a version specific config file first */
2072 default_configname = get_default_configname ();
2073 if (default_config)
2074 configname = xstrdup (default_configname);
2076 argc = orig_argc;
2077 argv = orig_argv;
2078 pargs.argc = &argc;
2079 pargs.argv = &argv;
2080 pargs.flags= 1; /* do not remove the args */
2082 /* By this point we have a homedir, and cannot change it. */
2083 check_permissions(opt.homedir,0);
2085 next_pass:
2086 if( configname ) {
2087 if(check_permissions(configname,1))
2089 /* If any options file is unsafe, then disable any external
2090 programs for keyserver calls or photo IDs. Since the
2091 external program to call is set in the options file, a
2092 unsafe options file can lead to an arbitrary program
2093 being run. */
2095 opt.exec_disable=1;
2098 configlineno = 0;
2099 configfp = fopen( configname, "r" );
2100 if (configfp && is_secured_file (fileno (configfp)))
2102 fclose (configfp);
2103 configfp = NULL;
2104 errno = EPERM;
2106 if( !configfp ) {
2107 if( default_config ) {
2108 if( parse_debug )
2109 log_info(_("NOTE: no default option file `%s'\n"),
2110 configname );
2112 else {
2113 log_error(_("option file `%s': %s\n"),
2114 configname, strerror(errno) );
2115 g10_exit(2);
2117 xfree(configname); configname = NULL;
2119 if( parse_debug && configname )
2120 log_info(_("reading options from `%s'\n"), configname );
2121 default_config = 0;
2124 while( optfile_parse( configfp, configname, &configlineno,
2125 &pargs, opts) )
2127 switch( pargs.r_opt )
2129 case aCheckKeys:
2130 case aListConfig:
2131 case aGPGConfList:
2132 case aGPGConfTest:
2133 case aListPackets:
2134 case aImport:
2135 case aFastImport:
2136 case aSendKeys:
2137 case aRecvKeys:
2138 case aSearchKeys:
2139 case aRefreshKeys:
2140 case aFetchKeys:
2141 case aExport:
2142 #ifdef ENABLE_CARD_SUPPORT
2143 case aCardStatus:
2144 case aCardEdit:
2145 case aChangePIN:
2146 #endif /* ENABLE_CARD_SUPPORT*/
2147 case aListKeys:
2148 case aLocateKeys:
2149 case aListSigs:
2150 case aExportSecret:
2151 case aExportSecretSub:
2152 case aSym:
2153 case aClearsign:
2154 case aGenRevoke:
2155 case aDesigRevoke:
2156 case aPrimegen:
2157 case aGenRandom:
2158 case aPrintMD:
2159 case aPrintMDs:
2160 case aListTrustDB:
2161 case aCheckTrustDB:
2162 case aUpdateTrustDB:
2163 case aFixTrustDB:
2164 case aListTrustPath:
2165 case aDeArmor:
2166 case aEnArmor:
2167 case aSign:
2168 case aSignKey:
2169 case aLSignKey:
2170 case aStore:
2171 case aExportOwnerTrust:
2172 case aImportOwnerTrust:
2173 case aRebuildKeydbCaches:
2174 set_cmd (&cmd, pargs.r_opt);
2175 break;
2177 case aKeygen:
2178 case aEditKey:
2179 case aDeleteSecretKeys:
2180 case aDeleteSecretAndPublicKeys:
2181 case aDeleteKeys:
2182 set_cmd (&cmd, pargs.r_opt);
2183 greeting=1;
2184 break;
2186 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2188 case aDecryptFiles: multifile=1; /* fall through */
2189 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2191 case aEncrFiles: multifile=1; /* fall through */
2192 case aEncr: set_cmd( &cmd, aEncr); break;
2194 case aVerifyFiles: multifile=1; /* fall through */
2195 case aVerify: set_cmd( &cmd, aVerify); break;
2197 case aServer:
2198 set_cmd (&cmd, pargs.r_opt);
2199 opt.batch = 1;
2200 break;
2202 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2203 case oOutput: opt.outfile = pargs.r.ret_str; break;
2204 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2205 case oQuiet: opt.quiet = 1; break;
2206 case oNoTTY: tty_no_terminal(1); break;
2207 case oDryRun: opt.dry_run = 1; break;
2208 case oInteractive: opt.interactive = 1; break;
2209 case oVerbose:
2210 opt.verbose++;
2211 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2212 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2213 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2214 break;
2216 case oBatch:
2217 opt.batch = 1;
2218 nogreeting = 1;
2219 break;
2221 case oUseAgent: /* Dummy. */
2222 break;
2223 case oNoUseAgent:
2224 obsolete_option (configname, configlineno, "--no-use-agent");
2225 break;
2226 case oGpgAgentInfo:
2227 obsolete_option (configname, configlineno, "--gpg-agent-info");
2228 break;
2230 case oAnswerYes: opt.answer_yes = 1; break;
2231 case oAnswerNo: opt.answer_no = 1; break;
2232 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2233 case oPrimaryKeyring:
2234 sl=append_to_strlist( &nrings, pargs.r.ret_str);
2235 sl->flags=2;
2236 break;
2237 case oShowKeyring:
2238 deprecated_warning(configname,configlineno,"--show-keyring",
2239 "--list-options ","show-keyring");
2240 opt.list_options|=LIST_SHOW_KEYRING;
2241 break;
2243 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2244 case oDebugAll: opt.debug = ~0; break;
2245 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2247 case oStatusFD:
2248 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2249 break;
2250 case oStatusFile:
2251 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2252 break;
2253 case oAttributeFD:
2254 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2255 break;
2256 case oAttributeFile:
2257 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2258 break;
2259 case oLoggerFD:
2260 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2261 break;
2262 case oLoggerFile:
2263 logfile = pargs.r.ret_str;
2264 break;
2266 case oWithFingerprint:
2267 opt.with_fingerprint = 1;
2268 opt.fingerprint++;
2269 break;
2270 case oFingerprint:
2271 opt.fingerprint++;
2272 fpr_maybe_cmd = 1;
2273 break;
2275 case oSecretKeyring:
2276 append_to_strlist( &sec_nrings, pargs.r.ret_str);
2277 break;
2278 case oOptions:
2279 /* config files may not be nested (silently ignore them) */
2280 if( !configfp ) {
2281 xfree(configname);
2282 configname = xstrdup(pargs.r.ret_str);
2283 goto next_pass;
2285 break;
2286 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2287 case oNoDefKeyring: default_keyring = 0; break;
2288 case oNoGreeting: nogreeting = 1; break;
2289 case oNoVerbose:
2290 opt.verbose = 0;
2291 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2292 opt.list_sigs=0;
2293 break;
2294 case oQuickRandom:
2295 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2296 break;
2297 case oEmitVersion: opt.no_version=0; break;
2298 case oNoEmitVersion: opt.no_version=1; break;
2299 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2300 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2301 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2302 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2303 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2304 case oDefRecipient:
2305 if( *pargs.r.ret_str )
2306 opt.def_recipient = make_username(pargs.r.ret_str);
2307 break;
2308 case oDefRecipientSelf:
2309 xfree(opt.def_recipient); opt.def_recipient = NULL;
2310 opt.def_recipient_self = 1;
2311 break;
2312 case oNoDefRecipient:
2313 xfree(opt.def_recipient); opt.def_recipient = NULL;
2314 opt.def_recipient_self = 0;
2315 break;
2316 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2317 case oHomedir: break;
2318 case oNoBatch: opt.batch = 0; break;
2320 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2321 case oWithColons: opt.with_colons=':'; break;
2323 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2324 case oWithSigList: opt.list_sigs = 1; break;
2326 case oSkipVerify: opt.skip_verify=1; break;
2328 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2329 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2331 case oCompressKeys: opt.compress_keys = 1; break;
2332 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2333 /* There are many programs (like mutt) that call gpg with
2334 --always-trust so keep this option around for a long
2335 time. */
2336 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2337 case oTrustModel:
2338 parse_trust_model(pargs.r.ret_str);
2339 break;
2340 case oForceOwnertrust:
2341 log_info(_("NOTE: %s is not for normal use!\n"),
2342 "--force-ownertrust");
2343 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2344 if(opt.force_ownertrust==-1)
2346 log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
2347 opt.force_ownertrust=0;
2349 break;
2350 case oLoadExtension:
2351 /* Dummy so that gpg 1.4 conf files can work. Should
2352 eventually be removed. */
2353 break;
2354 case oRFC1991:
2355 opt.compliance = CO_RFC1991;
2356 opt.force_v4_certs = 0;
2357 opt.escape_from = 1;
2358 break;
2359 case oOpenPGP:
2360 case oRFC4880:
2361 /* This is effectively the same as RFC2440, but with
2362 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2363 --require-cross-certification". */
2364 opt.compliance = CO_RFC4880;
2365 opt.flags.dsa2 = 1;
2366 opt.flags.require_cross_cert = 1;
2367 opt.rfc2440_text = 0;
2368 opt.allow_non_selfsigned_uid = 1;
2369 opt.allow_freeform_uid = 1;
2370 opt.pgp2_workarounds = 0;
2371 opt.escape_from = 1;
2372 opt.force_v3_sigs = 0;
2373 opt.compress_keys = 0; /* not mandated, but we do it */
2374 opt.compress_sigs = 0; /* ditto. */
2375 opt.not_dash_escaped = 0;
2376 opt.def_cipher_algo = 0;
2377 opt.def_digest_algo = 0;
2378 opt.cert_digest_algo = 0;
2379 opt.compress_algo = -1;
2380 opt.s2k_mode = 3; /* iterated+salted */
2381 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2382 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2383 break;
2384 case oRFC2440:
2385 opt.compliance = CO_RFC2440;
2386 opt.flags.dsa2 = 0;
2387 opt.rfc2440_text = 1;
2388 opt.allow_non_selfsigned_uid = 1;
2389 opt.allow_freeform_uid = 1;
2390 opt.pgp2_workarounds = 0;
2391 opt.escape_from = 0;
2392 opt.force_v3_sigs = 0;
2393 opt.compress_keys = 0; /* not mandated, but we do it */
2394 opt.compress_sigs = 0; /* ditto. */
2395 opt.not_dash_escaped = 0;
2396 opt.def_cipher_algo = 0;
2397 opt.def_digest_algo = 0;
2398 opt.cert_digest_algo = 0;
2399 opt.compress_algo = -1;
2400 opt.s2k_mode = 3; /* iterated+salted */
2401 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2402 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2403 break;
2404 case oPGP2: opt.compliance = CO_PGP2; break;
2405 case oPGP6: opt.compliance = CO_PGP6; break;
2406 case oPGP7: opt.compliance = CO_PGP7; break;
2407 case oPGP8: opt.compliance = CO_PGP8; break;
2408 case oGnuPG: opt.compliance = CO_GNUPG; break;
2409 case oCompressSigs: opt.compress_sigs = 1; break;
2410 case oRFC2440Text: opt.rfc2440_text=1; break;
2411 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2412 case oSetFilename:
2413 if(utf8_strings)
2414 opt.set_filename = pargs.r.ret_str;
2415 else
2416 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2417 break;
2418 case oForYourEyesOnly: eyes_only = 1; break;
2419 case oNoForYourEyesOnly: eyes_only = 0; break;
2420 case oSetPolicyURL:
2421 add_policy_url(pargs.r.ret_str,0);
2422 add_policy_url(pargs.r.ret_str,1);
2423 break;
2424 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2425 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2426 case oShowPolicyURL:
2427 deprecated_warning(configname,configlineno,"--show-policy-url",
2428 "--list-options ","show-policy-urls");
2429 deprecated_warning(configname,configlineno,"--show-policy-url",
2430 "--verify-options ","show-policy-urls");
2431 opt.list_options|=LIST_SHOW_POLICY_URLS;
2432 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2433 break;
2434 case oNoShowPolicyURL:
2435 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2436 "--list-options ","no-show-policy-urls");
2437 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2438 "--verify-options ","no-show-policy-urls");
2439 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2440 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2441 break;
2442 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2443 case oUseEmbeddedFilename:
2444 opt.flags.use_embedded_filename=1;
2445 break;
2446 case oNoUseEmbeddedFilename:
2447 opt.flags.use_embedded_filename=0;
2448 break;
2449 case oComment:
2450 if(pargs.r.ret_str[0])
2451 append_to_strlist(&opt.comments,pargs.r.ret_str);
2452 break;
2453 case oDefaultComment:
2454 deprecated_warning(configname,configlineno,
2455 "--default-comment","--no-comments","");
2456 /* fall through */
2457 case oNoComments:
2458 free_strlist(opt.comments);
2459 opt.comments=NULL;
2460 break;
2461 case oThrowKeyids: opt.throw_keyid = 1; break;
2462 case oNoThrowKeyids: opt.throw_keyid = 0; break;
2463 case oShowPhotos:
2464 deprecated_warning(configname,configlineno,"--show-photos",
2465 "--list-options ","show-photos");
2466 deprecated_warning(configname,configlineno,"--show-photos",
2467 "--verify-options ","show-photos");
2468 opt.list_options|=LIST_SHOW_PHOTOS;
2469 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2470 break;
2471 case oNoShowPhotos:
2472 deprecated_warning(configname,configlineno,"--no-show-photos",
2473 "--list-options ","no-show-photos");
2474 deprecated_warning(configname,configlineno,"--no-show-photos",
2475 "--verify-options ","no-show-photos");
2476 opt.list_options&=~LIST_SHOW_PHOTOS;
2477 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2478 break;
2479 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2480 case oForceV3Sigs: opt.force_v3_sigs = 1; break;
2481 case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
2482 case oForceV4Certs: opt.force_v4_certs = 1; break;
2483 case oNoForceV4Certs: opt.force_v4_certs = 0; break;
2484 case oForceMDC: opt.force_mdc = 1; break;
2485 case oNoForceMDC: opt.force_mdc = 0; break;
2486 case oDisableMDC: opt.disable_mdc = 1; break;
2487 case oNoDisableMDC: opt.disable_mdc = 0; break;
2488 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2489 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2490 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2491 case oS2KCount:
2492 opt.s2k_count=encode_s2k_iterations(pargs.r.ret_int);
2493 break;
2494 case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
2495 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2496 case oEncryptTo: /* store the recipient in the second list */
2497 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2498 sl->flags = 1;
2499 break;
2500 case oHiddenEncryptTo: /* store the recipient in the second list */
2501 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2502 sl->flags = 1|2;
2503 break;
2504 case oRecipient: /* store the recipient */
2505 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2506 any_explicit_recipient = 1;
2507 break;
2508 case oHiddenRecipient: /* store the recipient with a flag */
2509 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2510 sl->flags = 2;
2511 any_explicit_recipient = 1;
2512 break;
2513 case oTextmodeShort: opt.textmode = 2; break;
2514 case oTextmode: opt.textmode=1; break;
2515 case oNoTextmode: opt.textmode=0; break;
2516 case oExpert: opt.expert = 1; break;
2517 case oNoExpert: opt.expert = 0; break;
2518 case oDefSigExpire:
2519 if(*pargs.r.ret_str!='\0')
2521 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2522 log_error(_("`%s' is not a valid signature expiration\n"),
2523 pargs.r.ret_str);
2524 else
2525 opt.def_sig_expire=pargs.r.ret_str;
2527 break;
2528 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2529 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2530 case oDefCertExpire:
2531 if(*pargs.r.ret_str!='\0')
2533 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2534 log_error(_("`%s' is not a valid signature expiration\n"),
2535 pargs.r.ret_str);
2536 else
2537 opt.def_cert_expire=pargs.r.ret_str;
2539 break;
2540 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2541 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2542 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2543 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2544 case oAskCertLevel: opt.ask_cert_level = 1; break;
2545 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2546 case oLocalUser: /* store the local users */
2547 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2548 break;
2549 case oCompress:
2550 /* this is the -z command line option */
2551 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2552 break;
2553 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2554 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2555 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2556 case oPasswd:
2557 set_passphrase_from_string(pargs.r.ret_str);
2558 break;
2559 case oPasswdFD:
2560 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2561 break;
2562 case oPasswdFile:
2563 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
2564 break;
2565 case oPasswdRepeat: opt.passwd_repeat=pargs.r.ret_int; break;
2566 case oCommandFD:
2567 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2568 break;
2569 case oCommandFile:
2570 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
2571 break;
2572 case oCipherAlgo:
2573 def_cipher_string = xstrdup(pargs.r.ret_str);
2574 break;
2575 case oDigestAlgo:
2576 def_digest_string = xstrdup(pargs.r.ret_str);
2577 break;
2578 case oCompressAlgo:
2579 /* If it is all digits, stick a Z in front of it for
2580 later. This is for backwards compatibility with
2581 versions that took the compress algorithm number. */
2583 char *pt=pargs.r.ret_str;
2584 while(*pt)
2586 if (!isascii (*pt) || !isdigit (*pt))
2587 break;
2589 pt++;
2592 if(*pt=='\0')
2594 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2595 strcpy(compress_algo_string,"Z");
2596 strcat(compress_algo_string,pargs.r.ret_str);
2598 else
2599 compress_algo_string = xstrdup(pargs.r.ret_str);
2601 break;
2602 case oCertDigestAlgo:
2603 cert_digest_string = xstrdup(pargs.r.ret_str);
2604 break;
2606 case oNoSecmemWarn:
2607 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
2608 break;
2610 case oRequireSecmem: require_secmem=1; break;
2611 case oNoRequireSecmem: require_secmem=0; break;
2612 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2613 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2614 case oDisplayCharset:
2615 if( set_native_charset( pargs.r.ret_str ) )
2616 log_error(_("`%s' is not a valid character set\n"),
2617 pargs.r.ret_str);
2618 break;
2619 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2620 case oEscapeFrom: opt.escape_from = 1; break;
2621 case oNoEscapeFrom: opt.escape_from = 0; break;
2622 case oLockOnce: opt.lock_once = 1; break;
2623 case oLockNever:
2624 disable_dotlock ();
2625 break;
2626 case oLockMultiple:
2627 #ifndef __riscos__
2628 opt.lock_once = 0;
2629 #else /* __riscos__ */
2630 riscos_not_implemented("lock-multiple");
2631 #endif /* __riscos__ */
2632 break;
2633 case oKeyServer:
2635 struct keyserver_spec *keyserver;
2636 keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
2637 configname,configlineno);
2638 if(!keyserver)
2639 log_error(_("could not parse keyserver URL\n"));
2640 else
2642 keyserver->next=opt.keyserver;
2643 opt.keyserver=keyserver;
2646 break;
2647 case oKeyServerOptions:
2648 if(!parse_keyserver_options(pargs.r.ret_str))
2650 if(configname)
2651 log_error(_("%s:%d: invalid keyserver options\n"),
2652 configname,configlineno);
2653 else
2654 log_error(_("invalid keyserver options\n"));
2656 break;
2657 case oImportOptions:
2658 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2660 if(configname)
2661 log_error(_("%s:%d: invalid import options\n"),
2662 configname,configlineno);
2663 else
2664 log_error(_("invalid import options\n"));
2666 break;
2667 case oExportOptions:
2668 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2670 if(configname)
2671 log_error(_("%s:%d: invalid export options\n"),
2672 configname,configlineno);
2673 else
2674 log_error(_("invalid export options\n"));
2676 break;
2677 case oListOptions:
2678 if(!parse_list_options(pargs.r.ret_str))
2680 if(configname)
2681 log_error(_("%s:%d: invalid list options\n"),
2682 configname,configlineno);
2683 else
2684 log_error(_("invalid list options\n"));
2686 break;
2687 case oVerifyOptions:
2689 struct parse_options vopts[]=
2691 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2692 N_("display photo IDs during signature verification")},
2693 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2694 N_("show policy URLs during signature verification")},
2695 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2696 N_("show all notations during signature verification")},
2697 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2698 N_("show IETF standard notations during signature verification")},
2699 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2700 NULL},
2701 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2702 N_("show user-supplied notations during signature verification")},
2703 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2704 N_("show preferred keyserver URLs during signature verification")},
2705 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2706 N_("show user ID validity during signature verification")},
2707 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2708 N_("show revoked and expired user IDs in signature verification")},
2709 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
2710 N_("show only the primary user ID in signature verification")},
2711 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2712 N_("validate signatures with PKA data")},
2713 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2714 N_("elevate the trust of signatures with valid PKA data")},
2715 {NULL,0,NULL,NULL}
2718 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2720 if(configname)
2721 log_error(_("%s:%d: invalid verify options\n"),
2722 configname,configlineno);
2723 else
2724 log_error(_("invalid verify options\n"));
2727 break;
2728 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2729 case oExecPath:
2730 if(set_exec_path(pargs.r.ret_str))
2731 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2732 else
2733 opt.exec_path_set=1;
2734 break;
2735 case oSetNotation:
2736 add_notation_data( pargs.r.ret_str, 0 );
2737 add_notation_data( pargs.r.ret_str, 1 );
2738 break;
2739 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2740 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2741 case oShowNotation:
2742 deprecated_warning(configname,configlineno,"--show-notation",
2743 "--list-options ","show-notations");
2744 deprecated_warning(configname,configlineno,"--show-notation",
2745 "--verify-options ","show-notations");
2746 opt.list_options|=LIST_SHOW_NOTATIONS;
2747 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2748 break;
2749 case oNoShowNotation:
2750 deprecated_warning(configname,configlineno,"--no-show-notation",
2751 "--list-options ","no-show-notations");
2752 deprecated_warning(configname,configlineno,"--no-show-notation",
2753 "--verify-options ","no-show-notations");
2754 opt.list_options&=~LIST_SHOW_NOTATIONS;
2755 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2756 break;
2757 case oUtf8Strings: utf8_strings = 1; break;
2758 case oNoUtf8Strings: utf8_strings = 0; break;
2759 case oDisableCipherAlgo:
2761 int algo = string_to_cipher_algo (pargs.r.ret_str);
2762 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2764 break;
2765 case oDisablePubkeyAlgo:
2767 int algo = gcry_pk_map_name (pargs.r.ret_str);
2768 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2770 break;
2771 case oNoSigCache: opt.no_sig_cache = 1; break;
2772 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2773 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2774 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2775 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2776 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2777 case oNoLiteral: opt.no_literal = 1; break;
2778 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2779 case oHonorHttpProxy:
2780 add_to_strlist(&opt.keyserver_options.other,"http-proxy");
2781 deprecated_warning(configname,configlineno,
2782 "--honor-http-proxy",
2783 "--keyserver-options ","http-proxy");
2784 break;
2785 case oFastListMode: opt.fast_list_mode = 1; break;
2786 case oFixedListMode: /* Dummy */ break;
2787 case oListOnly: opt.list_only=1; break;
2788 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2789 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2790 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2791 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2792 case oNoRandomSeedFile: use_random_seed = 0; break;
2793 case oAutoKeyRetrieve:
2794 case oNoAutoKeyRetrieve:
2795 if(pargs.r_opt==oAutoKeyRetrieve)
2796 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
2797 else
2798 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
2800 deprecated_warning(configname,configlineno,
2801 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
2802 "--no-auto-key-retrieve","--keyserver-options ",
2803 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
2804 "no-auto-key-retrieve");
2805 break;
2806 case oShowSessionKey: opt.show_session_key = 1; break;
2807 case oOverrideSessionKey:
2808 opt.override_session_key = pargs.r.ret_str;
2809 break;
2810 case oMergeOnly:
2811 deprecated_warning(configname,configlineno,"--merge-only",
2812 "--import-options ","merge-only");
2813 opt.import_options|=IMPORT_MERGE_ONLY;
2814 break;
2815 case oAllowSecretKeyImport: /* obsolete */ break;
2816 case oTryAllSecrets: opt.try_all_secrets = 1; break;
2817 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
2818 case oEnableSpecialFilenames:
2819 iobuf_enable_special_filenames (1);
2820 break;
2821 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
2822 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
2823 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
2824 case oPreservePermissions: opt.preserve_permissions=1; break;
2825 case oDefaultPreferenceList:
2826 opt.def_preference_list = pargs.r.ret_str;
2827 break;
2828 case oDefaultKeyserverURL:
2830 struct keyserver_spec *keyserver;
2831 keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
2832 configname,configlineno);
2833 if(!keyserver)
2834 log_error(_("could not parse keyserver URL\n"));
2835 else
2836 free_keyserver_spec(keyserver);
2838 opt.def_keyserver_url = pargs.r.ret_str;
2840 break;
2841 case oPersonalCipherPreferences:
2842 pers_cipher_list=pargs.r.ret_str;
2843 break;
2844 case oPersonalDigestPreferences:
2845 pers_digest_list=pargs.r.ret_str;
2846 break;
2847 case oPersonalCompressPreferences:
2848 pers_compress_list=pargs.r.ret_str;
2849 break;
2850 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
2852 case oDisplay:
2853 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
2854 break;
2855 case oTTYname:
2856 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
2857 break;
2858 case oTTYtype:
2859 set_opt_session_env ("TERM", pargs.r.ret_str);
2860 break;
2861 case oXauthority:
2862 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
2863 break;
2865 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
2866 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
2868 case oGroup: add_group(pargs.r.ret_str); break;
2869 case oUnGroup: rm_group(pargs.r.ret_str); break;
2870 case oNoGroups:
2871 while(opt.grouplist)
2873 struct groupitem *iter=opt.grouplist;
2874 free_strlist(iter->values);
2875 opt.grouplist=opt.grouplist->next;
2876 xfree(iter);
2878 break;
2880 case oStrict:
2881 case oNoStrict:
2882 /* Not used */
2883 break;
2885 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
2886 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
2887 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
2888 case oMultifile: multifile=1; break;
2889 case oKeyidFormat:
2890 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
2891 opt.keyid_format=KF_SHORT;
2892 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
2893 opt.keyid_format=KF_LONG;
2894 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
2895 opt.keyid_format=KF_0xSHORT;
2896 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
2897 opt.keyid_format=KF_0xLONG;
2898 else
2899 log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
2900 break;
2902 case oExitOnStatusWriteError:
2903 opt.exit_on_status_write_error = 1;
2904 break;
2906 case oLimitCardInsertTries:
2907 opt.limit_card_insert_tries = pargs.r.ret_int;
2908 break;
2910 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
2911 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
2913 case oAutoKeyLocate:
2914 if(!parse_auto_key_locate(pargs.r.ret_str))
2916 if(configname)
2917 log_error(_("%s:%d: invalid auto-key-locate list\n"),
2918 configname,configlineno);
2919 else
2920 log_error(_("invalid auto-key-locate list\n"));
2922 break;
2923 case oNoAutoKeyLocate:
2924 release_akl();
2925 break;
2927 case oEnableDSA2: opt.flags.dsa2=1; break;
2928 case oDisableDSA2: opt.flags.dsa2=0; break;
2930 case oAllowMultisigVerification:
2931 case oAllowMultipleMessages:
2932 opt.flags.allow_multiple_messages=1;
2933 break;
2935 case oNoAllowMultipleMessages:
2936 opt.flags.allow_multiple_messages=0;
2937 break;
2939 case oNoop: break;
2941 default:
2942 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
2943 break;
2948 if( configfp ) {
2949 fclose( configfp );
2950 configfp = NULL;
2951 /* Remember the first config file name. */
2952 if (!save_configname)
2953 save_configname = configname;
2954 else
2955 xfree(configname);
2956 configname = NULL;
2957 goto next_pass;
2959 xfree( configname ); configname = NULL;
2960 if( log_get_errorcount(0) )
2961 g10_exit(2);
2963 /* The command --gpgconf-list is pretty simple and may be called
2964 directly after the option parsing. */
2965 if (cmd == aGPGConfList)
2967 gpgconf_list (save_configname ? save_configname : default_configname);
2968 g10_exit (0);
2970 xfree (save_configname);
2971 xfree (default_configname);
2973 if( nogreeting )
2974 greeting = 0;
2976 if( greeting ) {
2977 fprintf(stderr, "%s %s; %s\n",
2978 strusage(11), strusage(13), strusage(14) );
2979 fprintf(stderr, "%s\n", strusage(15) );
2981 #ifdef IS_DEVELOPMENT_VERSION
2982 if (!opt.batch)
2984 const char *s;
2986 if((s=strusage(25)))
2987 log_info("%s\n",s);
2988 if((s=strusage(26)))
2989 log_info("%s\n",s);
2990 if((s=strusage(27)))
2991 log_info("%s\n",s);
2993 #endif
2995 /* FIXME: We should use logging to a file only in server mode;
2996 however we have not yet implemetyed that. Thus we try to get
2997 away with --batch as indication for logging to file
2998 required. */
2999 if (logfile && opt.batch)
3001 log_set_file (logfile);
3002 log_set_prefix (NULL, 1|2|4);
3005 /* Older Libgcrypts fail with an assertion during DSA key
3006 generation. Better disable DSA2 entirely. */
3007 if (opt.flags.dsa2 && !gcry_check_version ("1.4.0") )
3009 log_info ("WARNING: "
3010 "DSA2 is only available with Libgcrypt 1.4 and later\n");
3011 opt.flags.dsa2 = 0;
3014 if (opt.verbose > 2)
3015 log_info ("using character set `%s'\n", get_native_charset ());
3017 if( may_coredump && !opt.quiet )
3018 log_info(_("WARNING: program may create a core file!\n"));
3020 if (eyes_only) {
3021 if (opt.set_filename)
3022 log_info(_("WARNING: %s overrides %s\n"),
3023 "--for-your-eyes-only","--set-filename");
3025 opt.set_filename="_CONSOLE";
3028 if (opt.no_literal) {
3029 log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
3030 if (opt.textmode)
3031 log_error(_("%s not allowed with %s!\n"),
3032 "--textmode", "--no-literal" );
3033 if (opt.set_filename)
3034 log_error(_("%s makes no sense with %s!\n"),
3035 eyes_only?"--for-your-eyes-only":"--set-filename",
3036 "--no-literal" );
3040 if (opt.set_filesize)
3041 log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
3042 if( opt.batch )
3043 tty_batchmode( 1 );
3045 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3047 if(require_secmem && !got_secmem)
3049 log_info(_("will not run with insecure memory due to %s\n"),
3050 "--require-secmem");
3051 g10_exit(2);
3054 set_debug (debug_level);
3056 /* Do these after the switch(), so they can override settings. */
3057 if(PGP2)
3059 int unusable=0;
3061 if(cmd==aSign && !detached_sig)
3063 log_info(_("you can only make detached or clear signatures "
3064 "while in --pgp2 mode\n"));
3065 unusable=1;
3067 else if(cmd==aSignEncr || cmd==aSignSym)
3069 log_info(_("you can't sign and encrypt at the "
3070 "same time while in --pgp2 mode\n"));
3071 unusable=1;
3073 else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
3075 log_info(_("you must use files (and not a pipe) when "
3076 "working with --pgp2 enabled.\n"));
3077 unusable=1;
3079 else if(cmd==aEncr || cmd==aSym)
3081 /* Everything else should work without IDEA (except using
3082 a secret key encrypted with IDEA and setting an IDEA
3083 preference, but those have their own error
3084 messages). */
3086 if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
3088 log_info(_("encrypting a message in --pgp2 mode requires "
3089 "the IDEA cipher\n"));
3090 idea_cipher_warn(1);
3091 unusable=1;
3093 else if(cmd==aSym)
3095 /* This only sets IDEA for symmetric encryption
3096 since it is set via select_algo_from_prefs for
3097 pk encryption. */
3098 xfree(def_cipher_string);
3099 def_cipher_string = xstrdup("idea");
3102 /* PGP2 can't handle the output from the textmode
3103 filter, so we disable it for anything that could
3104 create a literal packet (only encryption and
3105 symmetric encryption, since we disable signing
3106 above). */
3107 if(!unusable)
3108 opt.textmode=0;
3111 if(unusable)
3112 compliance_failure();
3113 else
3115 opt.force_v4_certs = 0;
3116 opt.escape_from = 1;
3117 opt.force_v3_sigs = 1;
3118 opt.pgp2_workarounds = 1;
3119 opt.ask_sig_expire = 0;
3120 opt.ask_cert_expire = 0;
3121 xfree(def_digest_string);
3122 def_digest_string = xstrdup("md5");
3123 xfree(s2k_digest_string);
3124 s2k_digest_string = xstrdup("md5");
3125 opt.compress_algo = COMPRESS_ALGO_ZIP;
3128 else if(PGP6)
3130 opt.disable_mdc=1;
3131 opt.escape_from=1;
3132 opt.force_v3_sigs=1;
3133 opt.ask_sig_expire=0;
3135 else if(PGP7)
3137 opt.escape_from=1;
3138 opt.force_v3_sigs=1;
3139 opt.ask_sig_expire=0;
3141 else if(PGP8)
3143 opt.escape_from=1;
3147 if( def_cipher_string ) {
3148 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3149 if(opt.def_cipher_algo==0 &&
3150 (ascii_strcasecmp(def_cipher_string,"idea")==0
3151 || ascii_strcasecmp(def_cipher_string,"s1")==0))
3152 idea_cipher_warn(1);
3153 xfree(def_cipher_string); def_cipher_string = NULL;
3154 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3155 log_error(_("selected cipher algorithm is invalid\n"));
3157 if( def_digest_string ) {
3158 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3159 xfree(def_digest_string); def_digest_string = NULL;
3160 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3161 log_error(_("selected digest algorithm is invalid\n"));
3163 if( compress_algo_string ) {
3164 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3165 xfree(compress_algo_string); compress_algo_string = NULL;
3166 if( check_compress_algo(opt.compress_algo) )
3167 log_error(_("selected compression algorithm is invalid\n"));
3169 if( cert_digest_string ) {
3170 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3171 xfree(cert_digest_string); cert_digest_string = NULL;
3172 if (openpgp_md_test_algo(opt.cert_digest_algo))
3173 log_error(_("selected certification digest algorithm is invalid\n"));
3175 if( s2k_cipher_string ) {
3176 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3177 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3178 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3179 log_error(_("selected cipher algorithm is invalid\n"));
3181 if( s2k_digest_string ) {
3182 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3183 xfree(s2k_digest_string); s2k_digest_string = NULL;
3184 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3185 log_error(_("selected digest algorithm is invalid\n"));
3187 if( opt.completes_needed < 1 )
3188 log_error(_("completes-needed must be greater than 0\n"));
3189 if( opt.marginals_needed < 2 )
3190 log_error(_("marginals-needed must be greater than 1\n"));
3191 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3192 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3193 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3194 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3195 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3196 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3197 switch( opt.s2k_mode ) {
3198 case 0:
3199 log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
3200 break;
3201 case 1: case 3: break;
3202 default:
3203 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3206 /* This isn't actually needed, but does serve to error out if the
3207 string is invalid. */
3208 if(opt.def_preference_list &&
3209 keygen_set_std_prefs(opt.def_preference_list,0))
3210 log_error(_("invalid default preferences\n"));
3212 if(pers_cipher_list &&
3213 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3214 log_error(_("invalid personal cipher preferences\n"));
3216 if(pers_digest_list &&
3217 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3218 log_error(_("invalid personal digest preferences\n"));
3220 if(pers_compress_list &&
3221 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3222 log_error(_("invalid personal compress preferences\n"));
3224 /* We don't support all possible commands with multifile yet */
3225 if(multifile)
3227 char *cmdname;
3229 switch(cmd)
3231 case aSign:
3232 cmdname="--sign";
3233 break;
3234 case aClearsign:
3235 cmdname="--clearsign";
3236 break;
3237 case aDetachedSign:
3238 cmdname="--detach-sign";
3239 break;
3240 case aSym:
3241 cmdname="--symmetric";
3242 break;
3243 case aEncrSym:
3244 cmdname="--symmetric --encrypt";
3245 break;
3246 case aStore:
3247 cmdname="--store";
3248 break;
3249 default:
3250 cmdname=NULL;
3251 break;
3254 if(cmdname)
3255 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3258 if( log_get_errorcount(0) )
3259 g10_exit(2);
3261 if(opt.compress_level==0)
3262 opt.compress_algo=COMPRESS_ALGO_NONE;
3264 /* Check our chosen algorithms against the list of legal
3265 algorithms. */
3267 if(!GNUPG)
3269 const char *badalg=NULL;
3270 preftype_t badtype=PREFTYPE_NONE;
3272 if(opt.def_cipher_algo
3273 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3275 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3276 badtype = PREFTYPE_SYM;
3278 else if(opt.def_digest_algo
3279 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3281 badalg = gcry_md_algo_name (opt.def_digest_algo);
3282 badtype = PREFTYPE_HASH;
3284 else if(opt.cert_digest_algo
3285 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3287 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3288 badtype = PREFTYPE_HASH;
3290 else if(opt.compress_algo!=-1
3291 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3293 badalg = compress_algo_to_string(opt.compress_algo);
3294 badtype = PREFTYPE_ZIP;
3297 if(badalg)
3299 switch(badtype)
3301 case PREFTYPE_SYM:
3302 log_info(_("you may not use cipher algorithm `%s'"
3303 " while in %s mode\n"),
3304 badalg,compliance_option_string());
3305 break;
3306 case PREFTYPE_HASH:
3307 log_info(_("you may not use digest algorithm `%s'"
3308 " while in %s mode\n"),
3309 badalg,compliance_option_string());
3310 break;
3311 case PREFTYPE_ZIP:
3312 log_info(_("you may not use compression algorithm `%s'"
3313 " while in %s mode\n"),
3314 badalg,compliance_option_string());
3315 break;
3316 default:
3317 BUG();
3320 compliance_failure();
3324 /* Set the random seed file. */
3325 if( use_random_seed ) {
3326 char *p = make_filename(opt.homedir, "random_seed", NULL );
3327 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3328 if (!access (p, F_OK))
3329 register_secured_file (p);
3330 xfree(p);
3333 /* If there is no command but the --fingerprint is given, default
3334 to the --list-keys command. */
3335 if (!cmd && fpr_maybe_cmd)
3337 set_cmd (&cmd, aListKeys);
3341 if( opt.verbose > 1 )
3342 set_packet_list_mode(1);
3344 /* Add the keyrings, but not for some special commands. Also
3345 avoid adding the secret keyring for a couple of commands to
3346 avoid unneeded access in case the secrings are stored on a
3347 floppy.
3349 We always need to add the keyrings if we are running under
3350 SELinux, this is so that the rings are added to the list of
3351 secured files. */
3352 if( ALWAYS_ADD_KEYRINGS
3353 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) )
3355 if (ALWAYS_ADD_KEYRINGS
3356 || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
3357 && cmd != aVerify && cmd != aSym && cmd != aLocateKeys))
3359 if (!sec_nrings || default_keyring) /* add default secret rings */
3360 keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
3361 for (sl = sec_nrings; sl; sl = sl->next)
3362 keydb_add_resource ( sl->d, 0, 1 );
3364 if( !nrings || default_keyring ) /* add default ring */
3365 keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
3366 for(sl = nrings; sl; sl = sl->next )
3367 keydb_add_resource ( sl->d, sl->flags, 0 );
3369 FREE_STRLIST(nrings);
3370 FREE_STRLIST(sec_nrings);
3372 if (cmd == aGPGConfTest)
3373 g10_exit(0);
3376 if( pwfd != -1 ) /* Read the passphrase now. */
3377 read_passphrase_from_fd( pwfd );
3379 fname = argc? *argv : NULL;
3381 if(fname && utf8_strings)
3382 opt.flags.utf8_filename=1;
3384 switch( cmd ) {
3385 case aPrimegen:
3386 case aPrintMD:
3387 case aPrintMDs:
3388 case aGenRandom:
3389 case aDeArmor:
3390 case aEnArmor:
3391 break;
3392 case aFixTrustDB:
3393 case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
3394 case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
3395 default: rc = setup_trustdb(1, trustdb_name ); break;
3397 if( rc )
3398 log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
3401 switch (cmd)
3403 case aStore:
3404 case aSym:
3405 case aSign:
3406 case aSignSym:
3407 case aClearsign:
3408 if (!opt.quiet && any_explicit_recipient)
3409 log_info (_("WARNING: recipients (-r) given "
3410 "without using public key encryption\n"));
3411 break;
3412 default:
3413 break;
3416 switch( cmd )
3418 case aServer:
3420 ctrl_t ctrl = xtrycalloc (1, sizeof *ctrl);
3421 gpg_init_default_ctrl (ctrl);
3422 gpg_server (ctrl);
3423 gpg_deinit_default_ctrl (ctrl);
3424 xfree (ctrl);
3426 break;
3428 case aStore: /* only store the file */
3429 if( argc > 1 )
3430 wrong_args(_("--store [filename]"));
3431 if( (rc = encrypt_store(fname)) )
3432 log_error ("storing `%s' failed: %s\n",
3433 print_fname_stdin(fname),g10_errstr(rc) );
3434 break;
3435 case aSym: /* encrypt the given file only with the symmetric cipher */
3436 if( argc > 1 )
3437 wrong_args(_("--symmetric [filename]"));
3438 if( (rc = encrypt_symmetric(fname)) )
3439 log_error (_("symmetric encryption of `%s' failed: %s\n"),
3440 print_fname_stdin(fname),g10_errstr(rc) );
3441 break;
3443 case aEncr: /* encrypt the given file */
3444 if(multifile)
3445 encrypt_crypt_files(argc, argv, remusr);
3446 else
3448 if( argc > 1 )
3449 wrong_args(_("--encrypt [filename]"));
3450 if( (rc = encrypt_crypt (-1, fname, remusr, 0, NULL, -1)) )
3451 log_error("%s: encryption failed: %s\n",
3452 print_fname_stdin(fname), g10_errstr(rc) );
3454 break;
3456 case aEncrSym:
3457 /* This works with PGP 8 in the sense that it acts just like a
3458 symmetric message. It doesn't work at all with 2 or 6. It
3459 might work with 7, but alas, I don't have a copy to test
3460 with right now. */
3461 if( argc > 1 )
3462 wrong_args(_("--symmetric --encrypt [filename]"));
3463 else if(opt.s2k_mode==0)
3464 log_error(_("you cannot use --symmetric --encrypt"
3465 " with --s2k-mode 0\n"));
3466 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3467 log_error(_("you cannot use --symmetric --encrypt"
3468 " while in %s mode\n"),compliance_option_string());
3469 else
3471 if( (rc = encrypt_crypt (-1, fname, remusr, 1, NULL, -1)) )
3472 log_error("%s: encryption failed: %s\n",
3473 print_fname_stdin(fname), g10_errstr(rc) );
3475 break;
3477 case aSign: /* sign the given file */
3478 sl = NULL;
3479 if( detached_sig ) { /* sign all files */
3480 for( ; argc; argc--, argv++ )
3481 add_to_strlist( &sl, *argv );
3483 else {
3484 if( argc > 1 )
3485 wrong_args(_("--sign [filename]"));
3486 if( argc ) {
3487 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3488 strcpy(sl->d, fname);
3491 if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
3492 log_error("signing failed: %s\n", g10_errstr(rc) );
3493 free_strlist(sl);
3494 break;
3496 case aSignEncr: /* sign and encrypt the given file */
3497 if( argc > 1 )
3498 wrong_args(_("--sign --encrypt [filename]"));
3499 if( argc ) {
3500 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3501 strcpy(sl->d, fname);
3503 else
3504 sl = NULL;
3505 if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
3506 log_error("%s: sign+encrypt failed: %s\n",
3507 print_fname_stdin(fname), g10_errstr(rc) );
3508 free_strlist(sl);
3509 break;
3511 case aSignEncrSym: /* sign and encrypt the given file */
3512 if( argc > 1 )
3513 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3514 else if(opt.s2k_mode==0)
3515 log_error(_("you cannot use --symmetric --sign --encrypt"
3516 " with --s2k-mode 0\n"));
3517 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3518 log_error(_("you cannot use --symmetric --sign --encrypt"
3519 " while in %s mode\n"),compliance_option_string());
3520 else
3522 if( argc )
3524 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3525 strcpy(sl->d, fname);
3527 else
3528 sl = NULL;
3529 if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
3530 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3531 print_fname_stdin(fname), g10_errstr(rc) );
3532 free_strlist(sl);
3534 break;
3536 case aSignSym: /* sign and conventionally encrypt the given file */
3537 if (argc > 1)
3538 wrong_args(_("--sign --symmetric [filename]"));
3539 rc = sign_symencrypt_file (fname, locusr);
3540 if (rc)
3541 log_error("%s: sign+symmetric failed: %s\n",
3542 print_fname_stdin(fname), g10_errstr(rc) );
3543 break;
3545 case aClearsign: /* make a clearsig */
3546 if( argc > 1 )
3547 wrong_args(_("--clearsign [filename]"));
3548 if( (rc = clearsign_file(fname, locusr, NULL)) )
3549 log_error("%s: clearsign failed: %s\n",
3550 print_fname_stdin(fname), g10_errstr(rc) );
3551 break;
3553 case aVerify:
3554 if(multifile)
3556 if( (rc = verify_files( argc, argv ) ))
3557 log_error("verify files failed: %s\n", g10_errstr(rc) );
3559 else
3561 if( (rc = verify_signatures( argc, argv ) ))
3562 log_error("verify signatures failed: %s\n", g10_errstr(rc) );
3564 break;
3566 case aDecrypt:
3567 if(multifile)
3568 decrypt_messages(argc, argv);
3569 else
3571 if( argc > 1 )
3572 wrong_args(_("--decrypt [filename]"));
3573 if( (rc = decrypt_message( fname ) ))
3574 log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
3576 break;
3578 case aSignKey:
3579 if( argc != 1 )
3580 wrong_args(_("--sign-key user-id"));
3581 /* fall through */
3582 case aLSignKey:
3583 if( argc != 1 )
3584 wrong_args(_("--lsign-key user-id"));
3585 /* fall through */
3587 sl=NULL;
3589 if(cmd==aSignKey)
3590 append_to_strlist(&sl,"sign");
3591 else if(cmd==aLSignKey)
3592 append_to_strlist(&sl,"lsign");
3593 else
3594 BUG();
3596 append_to_strlist( &sl, "save" );
3597 username = make_username( fname );
3598 keyedit_menu (username, locusr, sl, 0, 0 );
3599 xfree(username);
3600 free_strlist(sl);
3601 break;
3603 case aEditKey: /* Edit a key signature */
3604 if( !argc )
3605 wrong_args(_("--edit-key user-id [commands]"));
3606 username = make_username( fname );
3607 if( argc > 1 ) {
3608 sl = NULL;
3609 for( argc--, argv++ ; argc; argc--, argv++ )
3610 append_to_strlist( &sl, *argv );
3611 keyedit_menu( username, locusr, sl, 0, 1 );
3612 free_strlist(sl);
3614 else
3615 keyedit_menu(username, locusr, NULL, 0, 1 );
3616 xfree(username);
3617 break;
3619 case aDeleteKeys:
3620 case aDeleteSecretKeys:
3621 case aDeleteSecretAndPublicKeys:
3622 sl = NULL;
3623 /* I'm adding these in reverse order as add_to_strlist2
3624 reverses them again, and it's easier to understand in the
3625 proper order :) */
3626 for( ; argc; argc-- )
3627 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3628 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3629 free_strlist(sl);
3630 break;
3632 case aCheckKeys:
3633 opt.check_sigs = 1;
3634 case aListSigs:
3635 opt.list_sigs = 1;
3636 case aListKeys:
3637 sl = NULL;
3638 for( ; argc; argc--, argv++ )
3639 add_to_strlist2( &sl, *argv, utf8_strings );
3640 public_key_list( sl, 0 );
3641 free_strlist(sl);
3642 break;
3643 case aListSecretKeys:
3644 sl = NULL;
3645 for( ; argc; argc--, argv++ )
3646 add_to_strlist2( &sl, *argv, utf8_strings );
3647 secret_key_list( sl );
3648 free_strlist(sl);
3649 break;
3650 case aLocateKeys:
3651 sl = NULL;
3652 for (; argc; argc--, argv++)
3653 add_to_strlist2( &sl, *argv, utf8_strings );
3654 public_key_list (sl, 1);
3655 free_strlist (sl);
3656 break;
3658 case aKeygen: /* generate a key */
3659 if( opt.batch ) {
3660 if( argc > 1 )
3661 wrong_args("--gen-key [parameterfile]");
3662 generate_keypair( argc? *argv : NULL, NULL, NULL );
3664 else {
3665 if( argc )
3666 wrong_args("--gen-key");
3667 generate_keypair(NULL, NULL, NULL);
3669 break;
3671 case aFastImport:
3672 opt.import_options |= IMPORT_FAST;
3673 case aImport:
3674 import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
3675 break;
3677 /* TODO: There are a number of command that use this same
3678 "make strlist, call function, report error, free strlist"
3679 pattern. Join them together here and avoid all that
3680 duplicated code. */
3682 case aExport:
3683 case aSendKeys:
3684 case aRecvKeys:
3685 sl = NULL;
3686 for( ; argc; argc--, argv++ )
3687 append_to_strlist2( &sl, *argv, utf8_strings );
3688 if( cmd == aSendKeys )
3689 rc=keyserver_export( sl );
3690 else if( cmd == aRecvKeys )
3691 rc=keyserver_import( sl );
3692 else
3693 rc=export_pubkeys( sl, opt.export_options );
3694 if(rc)
3696 if(cmd==aSendKeys)
3697 log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
3698 else if(cmd==aRecvKeys)
3699 log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
3700 else
3701 log_error(_("key export failed: %s\n"),g10_errstr(rc));
3703 free_strlist(sl);
3704 break;
3706 case aSearchKeys:
3707 sl = NULL;
3708 for( ; argc; argc--, argv++ )
3709 append_to_strlist2( &sl, *argv, utf8_strings );
3710 rc=keyserver_search( sl );
3711 if(rc)
3712 log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
3713 free_strlist(sl);
3714 break;
3716 case aRefreshKeys:
3717 sl = NULL;
3718 for( ; argc; argc--, argv++ )
3719 append_to_strlist2( &sl, *argv, utf8_strings );
3720 rc=keyserver_refresh(sl);
3721 if(rc)
3722 log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
3723 free_strlist(sl);
3724 break;
3726 case aFetchKeys:
3727 sl = NULL;
3728 for( ; argc; argc--, argv++ )
3729 append_to_strlist2( &sl, *argv, utf8_strings );
3730 rc=keyserver_fetch(sl);
3731 if(rc)
3732 log_error("key fetch failed: %s\n",g10_errstr(rc));
3733 free_strlist(sl);
3734 break;
3736 case aExportSecret:
3737 sl = NULL;
3738 for( ; argc; argc--, argv++ )
3739 add_to_strlist2( &sl, *argv, utf8_strings );
3740 export_seckeys( sl );
3741 free_strlist(sl);
3742 break;
3744 case aExportSecretSub:
3745 sl = NULL;
3746 for( ; argc; argc--, argv++ )
3747 add_to_strlist2( &sl, *argv, utf8_strings );
3748 export_secsubkeys( sl );
3749 free_strlist(sl);
3750 break;
3752 case aGenRevoke:
3753 if( argc != 1 )
3754 wrong_args("--gen-revoke user-id");
3755 username = make_username(*argv);
3756 gen_revoke( username );
3757 xfree( username );
3758 break;
3760 case aDesigRevoke:
3761 if( argc != 1 )
3762 wrong_args("--desig-revoke user-id");
3763 username = make_username(*argv);
3764 gen_desig_revoke( username, locusr );
3765 xfree( username );
3766 break;
3768 case aDeArmor:
3769 if( argc > 1 )
3770 wrong_args("--dearmor [file]");
3771 rc = dearmor_file( argc? *argv: NULL );
3772 if( rc )
3773 log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
3774 break;
3776 case aEnArmor:
3777 if( argc > 1 )
3778 wrong_args("--enarmor [file]");
3779 rc = enarmor_file( argc? *argv: NULL );
3780 if( rc )
3781 log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
3782 break;
3785 case aPrimegen:
3786 #if 0 /*FIXME*/
3787 { int mode = argc < 2 ? 0 : atoi(*argv);
3789 if( mode == 1 && argc == 2 ) {
3790 mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
3792 else if( mode == 2 && argc == 3 ) {
3793 mpi_print( stdout, generate_elg_prime(
3794 0, atoi(argv[1]),
3795 atoi(argv[2]), NULL,NULL ), 1);
3797 else if( mode == 3 && argc == 3 ) {
3798 MPI *factors;
3799 mpi_print( stdout, generate_elg_prime(
3800 1, atoi(argv[1]),
3801 atoi(argv[2]), NULL,&factors ), 1);
3802 putchar('\n');
3803 mpi_print( stdout, factors[0], 1 ); /* print q */
3805 else if( mode == 4 && argc == 3 ) {
3806 MPI g = mpi_alloc(1);
3807 mpi_print( stdout, generate_elg_prime(
3808 0, atoi(argv[1]),
3809 atoi(argv[2]), g, NULL ), 1);
3810 putchar('\n');
3811 mpi_print( stdout, g, 1 );
3812 mpi_free(g);
3814 else
3815 wrong_args("--gen-prime mode bits [qbits] ");
3816 putchar('\n');
3818 #endif
3819 wrong_args("--gen-prime not yet supported ");
3820 break;
3822 case aGenRandom:
3824 int level = argc ? atoi(*argv):0;
3825 int count = argc > 1 ? atoi(argv[1]): 0;
3826 int endless = !count;
3828 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
3829 wrong_args("--gen-random 0|1|2 [count]");
3831 while( endless || count ) {
3832 byte *p;
3833 /* Wee need a multiple of 3, so that in case of
3834 armored output we get a correct string. No
3835 linefolding is done, as it is best to levae this to
3836 other tools */
3837 size_t n = !endless && count < 99? count : 99;
3839 p = gcry_random_bytes (n, level);
3840 #ifdef HAVE_DOSISH_SYSTEM
3841 setmode ( fileno(stdout), O_BINARY );
3842 #endif
3843 if (opt.armor) {
3844 char *tmp = make_radix64_string (p, n);
3845 fputs (tmp, stdout);
3846 xfree (tmp);
3847 if (n%3 == 1)
3848 putchar ('=');
3849 if (n%3)
3850 putchar ('=');
3851 } else {
3852 fwrite( p, n, 1, stdout );
3854 xfree(p);
3855 if( !endless )
3856 count -= n;
3858 if (opt.armor)
3859 putchar ('\n');
3861 break;
3863 case aPrintMD:
3864 if( argc < 1)
3865 wrong_args("--print-md algo [files]");
3867 int all_algos = (**argv=='*' && !(*argv)[1]);
3868 int algo = all_algos? 0 : gcry_md_map_name (*argv);
3870 if( !algo && !all_algos )
3871 log_error(_("invalid hash algorithm `%s'\n"), *argv );
3872 else {
3873 argc--; argv++;
3874 if( !argc )
3875 print_mds(NULL, algo);
3876 else {
3877 for(; argc; argc--, argv++ )
3878 print_mds(*argv, algo);
3882 break;
3884 case aPrintMDs: /* old option */
3885 if( !argc )
3886 print_mds(NULL,0);
3887 else {
3888 for(; argc; argc--, argv++ )
3889 print_mds(*argv,0);
3891 break;
3893 case aListTrustDB:
3894 if( !argc )
3895 list_trustdb(NULL);
3896 else {
3897 for( ; argc; argc--, argv++ )
3898 list_trustdb( *argv );
3900 break;
3902 case aUpdateTrustDB:
3903 if( argc )
3904 wrong_args("--update-trustdb");
3905 update_trustdb();
3906 break;
3908 case aCheckTrustDB:
3909 /* Old versions allowed for arguments - ignore them */
3910 check_trustdb();
3911 break;
3913 case aFixTrustDB:
3914 how_to_fix_the_trustdb ();
3915 break;
3917 case aListTrustPath:
3918 if( !argc )
3919 wrong_args("--list-trust-path <user-ids>");
3920 for( ; argc; argc--, argv++ ) {
3921 username = make_username( *argv );
3922 list_trust_path( username );
3923 xfree(username);
3925 break;
3927 case aExportOwnerTrust:
3928 if( argc )
3929 wrong_args("--export-ownertrust");
3930 export_ownertrust();
3931 break;
3933 case aImportOwnerTrust:
3934 if( argc > 1 )
3935 wrong_args("--import-ownertrust [file]");
3936 import_ownertrust( argc? *argv:NULL );
3937 break;
3939 case aRebuildKeydbCaches:
3940 if (argc)
3941 wrong_args ("--rebuild-keydb-caches");
3942 keydb_rebuild_caches (1);
3943 break;
3945 #ifdef ENABLE_CARD_SUPPORT
3946 case aCardStatus:
3947 if (argc)
3948 wrong_args ("--card-status");
3949 card_status (stdout, NULL, 0);
3950 break;
3952 case aCardEdit:
3953 if (argc) {
3954 sl = NULL;
3955 for (argc--, argv++ ; argc; argc--, argv++)
3956 append_to_strlist (&sl, *argv);
3957 card_edit (sl);
3958 free_strlist (sl);
3960 else
3961 card_edit (NULL);
3962 break;
3964 case aChangePIN:
3965 if (!argc)
3966 change_pin (0,1);
3967 else if (argc == 1)
3968 change_pin (atoi (*argv),1);
3969 else
3970 wrong_args ("--change-pin [no]");
3971 break;
3972 #endif /* ENABLE_CARD_SUPPORT*/
3974 case aListConfig:
3976 char *str=collapse_args(argc,argv);
3977 list_config(str);
3978 xfree(str);
3980 break;
3982 case aListPackets:
3983 opt.list_packets=2;
3984 default:
3985 if( argc > 1 )
3986 wrong_args(_("[filename]"));
3987 /* Issue some output for the unix newbie */
3988 if( !fname && !opt.outfile && isatty( fileno(stdin) )
3989 && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
3990 log_info(_("Go ahead and type your message ...\n"));
3992 a = iobuf_open(fname);
3993 if (a && is_secured_file (iobuf_get_fd (a)))
3995 iobuf_close (a);
3996 a = NULL;
3997 errno = EPERM;
3999 if( !a )
4000 log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
4001 else {
4003 if( !opt.no_armor ) {
4004 if( use_armor_filter( a ) ) {
4005 afx = new_armor_context ();
4006 push_armor_filter (afx, a);
4009 if( cmd == aListPackets ) {
4010 set_packet_list_mode(1);
4011 opt.list_packets=1;
4013 rc = proc_packets(NULL, a );
4014 if( rc )
4015 log_error("processing message failed: %s\n", g10_errstr(rc) );
4016 iobuf_close(a);
4018 break;
4021 /* cleanup */
4022 release_armor_context (afx);
4023 FREE_STRLIST(remusr);
4024 FREE_STRLIST(locusr);
4025 g10_exit(0);
4026 return 8; /*NEVER REACHED*/
4030 /* Note: This function is used by signal handlers!. */
4031 static void
4032 emergency_cleanup (void)
4034 gcry_control (GCRYCTL_TERM_SECMEM );
4038 void
4039 g10_exit( int rc )
4041 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
4042 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
4044 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
4045 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
4047 if (opt.debug)
4048 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
4050 emergency_cleanup ();
4052 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
4053 exit (rc);
4057 /* Pretty-print hex hashes. This assumes at least an 80-character
4058 display, but there are a few other similar assumptions in the
4059 display code. */
4060 static void
4061 print_hex( gcry_md_hd_t md, int algo, const char *fname )
4063 int i,n,count,indent=0;
4064 const byte *p;
4066 if(fname)
4067 indent=printf("%s: ",fname);
4069 if(indent>40)
4071 printf("\n");
4072 indent=0;
4075 if(algo==DIGEST_ALGO_RMD160)
4076 indent+=printf("RMD160 = ");
4077 else if(algo>0)
4078 indent+=printf("%6s = ", gcry_md_algo_name (algo));
4079 else
4080 algo=abs(algo);
4082 count=indent;
4084 p = gcry_md_read (md, algo);
4085 n = gcry_md_get_algo_dlen (algo);
4087 count += printf ("%02X",*p++);
4089 for(i=1;i<n;i++,p++)
4091 if(n==16)
4093 if(count+2>79)
4095 printf("\n%*s",indent," ");
4096 count=indent;
4098 else
4099 count+=printf(" ");
4101 if(!(i%8))
4102 count+=printf(" ");
4104 else if (n==20)
4106 if(!(i%2))
4108 if(count+4>79)
4110 printf("\n%*s",indent," ");
4111 count=indent;
4113 else
4114 count+=printf(" ");
4117 if(!(i%10))
4118 count+=printf(" ");
4120 else
4122 if(!(i%4))
4124 if(count+8>79)
4126 printf("\n%*s",indent," ");
4127 count=indent;
4129 else
4130 count+=printf(" ");
4134 count+=printf("%02X",*p);
4137 printf("\n");
4140 static void
4141 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
4143 int i, n;
4144 const byte *p;
4146 if ( fname ) {
4147 for (p = fname; *p; p++ ) {
4148 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
4149 printf("%%%02X", *p );
4150 else
4151 putchar( *p );
4154 putchar(':');
4155 printf("%d:", algo );
4156 p = gcry_md_read (md, algo);
4157 n = gcry_md_get_algo_dlen (algo);
4158 for(i=0; i < n ; i++, p++ )
4159 printf("%02X", *p );
4160 putchar(':');
4161 putchar('\n');
4164 static void
4165 print_mds( const char *fname, int algo )
4167 FILE *fp;
4168 char buf[1024];
4169 size_t n;
4170 gcry_md_hd_t md;
4172 if( !fname ) {
4173 fp = stdin;
4174 #ifdef HAVE_DOSISH_SYSTEM
4175 setmode ( fileno(fp) , O_BINARY );
4176 #endif
4178 else {
4179 fp = fopen( fname, "rb" );
4180 if (fp && is_secured_file (fileno (fp)))
4182 fclose (fp);
4183 fp = NULL;
4184 errno = EPERM;
4187 if( !fp ) {
4188 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4189 return;
4192 gcry_md_open (&md, 0, 0);
4193 if( algo )
4194 gcry_md_enable (md, algo);
4195 else {
4196 gcry_md_enable (md, GCRY_MD_MD5);
4197 gcry_md_enable (md, GCRY_MD_SHA1);
4198 gcry_md_enable (md, GCRY_MD_RMD160);
4199 if (!openpgp_md_test_algo (GCRY_MD_SHA224))
4200 gcry_md_enable (md, GCRY_MD_SHA224);
4201 if (!openpgp_md_test_algo (GCRY_MD_SHA256))
4202 gcry_md_enable (md, GCRY_MD_SHA256);
4203 if (!openpgp_md_test_algo (GCRY_MD_SHA384))
4204 gcry_md_enable (md, GCRY_MD_SHA384);
4205 if (!openpgp_md_test_algo (GCRY_MD_SHA512))
4206 gcry_md_enable (md, GCRY_MD_SHA512);
4209 while( (n=fread( buf, 1, DIM(buf), fp )) )
4210 gcry_md_write (md, buf, n);
4211 if( ferror(fp) )
4212 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4213 else {
4214 gcry_md_final (md);
4215 if ( opt.with_colons ) {
4216 if ( algo )
4217 print_hashline( md, algo, fname );
4218 else {
4219 print_hashline( md, GCRY_MD_MD5, fname );
4220 print_hashline( md, GCRY_MD_SHA1, fname );
4221 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4222 print_hashline( md, GCRY_MD_RMD160, fname );
4223 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4224 print_hashline (md, GCRY_MD_SHA224, fname);
4225 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4226 print_hashline( md, GCRY_MD_SHA256, fname );
4227 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4228 print_hashline ( md, GCRY_MD_SHA384, fname );
4229 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4230 print_hashline ( md, GCRY_MD_SHA512, fname );
4233 else {
4234 if( algo )
4235 print_hex(md,-algo,fname);
4236 else {
4237 print_hex( md, GCRY_MD_MD5, fname );
4238 print_hex( md, GCRY_MD_SHA1, fname );
4239 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4240 print_hex( md, GCRY_MD_RMD160, fname );
4241 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4242 print_hex (md, GCRY_MD_SHA224, fname);
4243 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4244 print_hex( md, GCRY_MD_SHA256, fname );
4245 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4246 print_hex( md, GCRY_MD_SHA384, fname );
4247 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4248 print_hex( md, GCRY_MD_SHA512, fname );
4252 gcry_md_close(md);
4254 if( fp != stdin )
4255 fclose(fp);
4259 /****************
4260 * Check the supplied name,value string and add it to the notation
4261 * data to be used for signatures. which==0 for sig notations, and 1
4262 * for cert notations.
4264 static void
4265 add_notation_data( const char *string, int which )
4267 struct notation *notation;
4269 notation=string_to_notation(string,utf8_strings);
4270 if(notation)
4272 if(which)
4274 notation->next=opt.cert_notations;
4275 opt.cert_notations=notation;
4277 else
4279 notation->next=opt.sig_notations;
4280 opt.sig_notations=notation;
4285 static void
4286 add_policy_url( const char *string, int which )
4288 unsigned int i,critical=0;
4289 strlist_t sl;
4291 if(*string=='!')
4293 string++;
4294 critical=1;
4297 for(i=0;i<strlen(string);i++)
4298 if( !isascii (string[i]) || iscntrl(string[i]))
4299 break;
4301 if(i==0 || i<strlen(string))
4303 if(which)
4304 log_error(_("the given certification policy URL is invalid\n"));
4305 else
4306 log_error(_("the given signature policy URL is invalid\n"));
4309 if(which)
4310 sl=add_to_strlist( &opt.cert_policy_url, string );
4311 else
4312 sl=add_to_strlist( &opt.sig_policy_url, string );
4314 if(critical)
4315 sl->flags |= 1;
4318 static void
4319 add_keyserver_url( const char *string, int which )
4321 unsigned int i,critical=0;
4322 strlist_t sl;
4324 if(*string=='!')
4326 string++;
4327 critical=1;
4330 for(i=0;i<strlen(string);i++)
4331 if( !isascii (string[i]) || iscntrl(string[i]))
4332 break;
4334 if(i==0 || i<strlen(string))
4336 if(which)
4337 BUG();
4338 else
4339 log_error(_("the given preferred keyserver URL is invalid\n"));
4342 if(which)
4343 BUG();
4344 else
4345 sl=add_to_strlist( &opt.sig_keyserver_url, string );
4347 if(critical)
4348 sl->flags |= 1;