Implement the server comamnd DECRYPT.
[gnupg.git] / g10 / gpg.c
blob5b70e4fc314dc5b70932acf7cb44c68d443149f3
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 oCompressKeys,
237 oCompressSigs,
238 oAlwaysTrust,
239 oTrustModel,
240 oForceOwnertrust,
241 oSetFilename,
242 oForYourEyesOnly,
243 oNoForYourEyesOnly,
244 oSetPolicyURL,
245 oSigPolicyURL,
246 oCertPolicyURL,
247 oShowPolicyURL,
248 oNoShowPolicyURL,
249 oSigKeyserverURL,
250 oUseEmbeddedFilename,
251 oNoUseEmbeddedFilename,
252 oComment,
253 oDefaultComment,
254 oNoComments,
255 oThrowKeyids,
256 oNoThrowKeyids,
257 oShowPhotos,
258 oNoShowPhotos,
259 oPhotoViewer,
260 oForceV3Sigs,
261 oNoForceV3Sigs,
262 oForceV4Certs,
263 oNoForceV4Certs,
264 oForceMDC,
265 oNoForceMDC,
266 oDisableMDC,
267 oNoDisableMDC,
268 oS2KMode,
269 oS2KDigest,
270 oS2KCipher,
271 oS2KCount,
272 oSimpleSKChecksum,
273 oDisplayCharset,
274 oNotDashEscaped,
275 oEscapeFrom,
276 oNoEscapeFrom,
277 oLockOnce,
278 oLockMultiple,
279 oLockNever,
280 oKeyServer,
281 oKeyServerOptions,
282 oImportOptions,
283 oExportOptions,
284 oListOptions,
285 oVerifyOptions,
286 oTempDir,
287 oExecPath,
288 oEncryptTo,
289 oHiddenEncryptTo,
290 oNoEncryptTo,
291 oLoggerFD,
292 oLoggerFile,
293 oUtf8Strings,
294 oNoUtf8Strings,
295 oDisableCipherAlgo,
296 oDisablePubkeyAlgo,
297 oAllowNonSelfsignedUID,
298 oNoAllowNonSelfsignedUID,
299 oAllowFreeformUID,
300 oNoAllowFreeformUID,
301 oAllowSecretKeyImport,
302 oEnableSpecialFilenames,
303 oNoLiteral,
304 oSetFilesize,
305 oHonorHttpProxy,
306 oFastListMode,
307 oListOnly,
308 oIgnoreTimeConflict,
309 oIgnoreValidFrom,
310 oIgnoreCrcError,
311 oIgnoreMDCError,
312 oShowSessionKey,
313 oOverrideSessionKey,
314 oNoRandomSeedFile,
315 oAutoKeyRetrieve,
316 oNoAutoKeyRetrieve,
317 oUseAgent,
318 oNoUseAgent,
319 oGpgAgentInfo,
320 oMergeOnly,
321 oTryAllSecrets,
322 oTrustedKey,
323 oNoExpensiveTrustChecks,
324 oFixedListMode,
325 oNoSigCache,
326 oNoSigCreateCheck,
327 oAutoCheckTrustDB,
328 oNoAutoCheckTrustDB,
329 oPreservePermissions,
330 oDefaultPreferenceList,
331 oDefaultKeyserverURL,
332 oPersonalCipherPreferences,
333 oPersonalDigestPreferences,
334 oPersonalCompressPreferences,
335 oAgentProgram,
336 oDisplay,
337 oTTYname,
338 oTTYtype,
339 oLCctype,
340 oLCmessages,
341 oXauthority,
342 oGroup,
343 oUnGroup,
344 oNoGroups,
345 oStrict,
346 oNoStrict,
347 oMangleDosFilenames,
348 oNoMangleDosFilenames,
349 oEnableProgressFilter,
350 oMultifile,
351 oKeyidFormat,
352 oExitOnStatusWriteError,
353 oLimitCardInsertTries,
354 oRequireCrossCert,
355 oNoRequireCrossCert,
356 oAutoKeyLocate,
357 oNoAutoKeyLocate,
358 oAllowMultisigVerification,
359 oEnableDSA2,
360 oDisableDSA2,
361 oAllowMultipleMessages,
362 oNoAllowMultipleMessages,
364 oNoop
368 static ARGPARSE_OPTS opts[] = {
370 ARGPARSE_group (300, N_("@Commands:\n ")),
372 ARGPARSE_c (aSign, "sign", N_("make a signature")),
373 ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature")),
374 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
375 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
376 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
377 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
378 ARGPARSE_c (aStore, "store", "@"),
379 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
380 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
381 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
382 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
383 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
384 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
385 ARGPARSE_c (aListSigs, "list-sigs", N_("list keys and signatures")),
386 ARGPARSE_c (aCheckKeys, "check-sigs",N_("list and check key signatures")),
387 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
388 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
389 ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
390 ARGPARSE_c (aDeleteKeys,"delete-keys",
391 N_("remove keys from the public keyring")),
392 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
393 N_("remove keys from the secret keyring")),
394 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
395 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
396 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
397 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
398 ARGPARSE_c (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")),
399 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
400 ARGPARSE_c (aExport, "export" , N_("export keys") ),
401 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ),
402 ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ),
403 ARGPARSE_c (aSearchKeys, "search-keys" ,
404 N_("search for keys on a key server") ),
405 ARGPARSE_c (aRefreshKeys, "refresh-keys",
406 N_("update all keys from a keyserver")),
407 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
408 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
409 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
410 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
411 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
412 ARGPARSE_c (aFastImport, "fast-import", "@"),
413 #ifdef ENABLE_CARD_SUPPORT
414 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
415 ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")),
416 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
417 #endif
418 ARGPARSE_c (aListConfig, "list-config", "@"),
419 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
420 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
421 ARGPARSE_c (aListPackets, "list-packets","@"),
422 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
423 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
424 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
425 N_("update the trust database")),
426 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
427 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
428 ARGPARSE_c (aDeArmor, "dearmor", "@"),
429 ARGPARSE_c (aDeArmor, "dearmour", "@"),
430 ARGPARSE_c (aEnArmor, "enarmor", "@"),
431 ARGPARSE_c (aEnArmor, "enarmour", "@"),
432 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
433 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
434 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
435 ARGPARSE_c (aServer, "server", N_("run in server mode")),
437 ARGPARSE_group (301, N_("@\nOptions:\n ")),
439 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
440 ARGPARSE_s_n (oArmor, "armour", "@"),
442 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
443 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
444 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
445 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
446 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
447 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
449 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
450 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
451 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
452 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
453 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
454 ARGPARSE_s_s (oLocalUser, "local-user",
455 N_("|USER-ID|use USER-ID to sign or decrypt")),
457 ARGPARSE_s_i (oCompress, NULL,
458 N_("|N|set compress level to N (0 disables)")),
459 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
460 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
461 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
463 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
464 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
465 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
467 ARGPARSE_s_n (oExpert, "expert", "@"),
468 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
470 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
471 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
472 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
473 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
474 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
475 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
476 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
477 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
478 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
479 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
481 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
482 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
484 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
485 ARGPARSE_s_n (oQuiet, "quiet", "@"),
486 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
488 ARGPARSE_s_n (oForceV3Sigs, "force-v3-sigs", "@"),
489 ARGPARSE_s_n (oNoForceV3Sigs, "no-force-v3-sigs", "@"),
490 ARGPARSE_s_n (oForceV4Certs, "force-v4-certs", "@"),
491 ARGPARSE_s_n (oNoForceV4Certs, "no-force-v4-certs", "@"),
492 ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
493 ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
494 ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
495 ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
497 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
498 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
500 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
501 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
502 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
504 ARGPARSE_s_n (oBatch, "batch", "@"),
505 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
506 ARGPARSE_s_n (oAnswerNo, "no", "@"),
507 ARGPARSE_s_s (oKeyring, "keyring", "@"),
508 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
509 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
510 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
511 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
513 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
514 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
515 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
516 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
517 ARGPARSE_s_s (oListOptions, "list-options", "@"),
518 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
520 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
521 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
522 ARGPARSE_s_s (oOptions, "options", "@"),
524 ARGPARSE_p_u (oDebug, "debug", "@"),
525 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
526 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
527 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
528 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
529 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
530 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
532 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
533 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
535 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
536 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
537 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
538 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
540 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
542 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
543 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
544 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
545 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
546 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
547 ARGPARSE_s_n (oRFC1991, "rfc1991", "@"),
548 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
549 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
550 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
551 ARGPARSE_s_n (oPGP2, "pgp2", "@"),
552 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
553 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
554 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
556 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
557 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
558 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
559 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
560 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
561 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
562 ARGPARSE_s_n (oSimpleSKChecksum, "simple-sk-checksum", "@"),
563 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
564 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
565 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
566 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
567 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
568 ARGPARSE_s_n (oThrowKeyids, "throw-keyid", "@"),
569 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
570 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyid", "@"),
571 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
572 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
573 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
574 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
575 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
576 ARGPARSE_s_s (oSetNotation, "notation-data", "@"), /* Alias */
577 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
578 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
580 ARGPARSE_group (302, N_(
581 "@\n(See the man page for a complete listing of all commands and options)\n"
584 ARGPARSE_group (303, N_("@\nExamples:\n\n"
585 " -se -r Bob [file] sign and encrypt for user Bob\n"
586 " --clearsign [file] make a clear text signature\n"
587 " --detach-sign [file] make a detached signature\n"
588 " --list-keys [names] show keys\n"
589 " --fingerprint [names] show fingerprints\n")),
591 /* More hidden commands and options. */
592 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
593 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
594 /* Not yet used:
595 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
596 ARGPARSE_c (aDeleteSecretAndPublicKeys,
597 "delete-secret-and-public-keys", "@"),
598 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
600 ARGPARSE_s_s (oPasswd, "passphrase", "@"),
601 ARGPARSE_s_i (oPasswdFD, "passphrase-fd", "@"),
602 ARGPARSE_s_s (oPasswdFile, "passphrase-file", "@"),
603 ARGPARSE_s_i (oPasswdRepeat, "passphrase-repeat", "@"),
604 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
605 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
606 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
607 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
608 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
609 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
610 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
611 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
612 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
613 ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
614 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
615 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
616 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
617 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
618 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
619 ARGPARSE_s_s (oHomedir, "homedir", "@"),
620 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
621 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
622 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
623 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
624 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
625 ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */
626 ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */
627 ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */
628 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
629 ARGPARSE_s_n (oCompressKeys, "compress-keys", "@"),
630 ARGPARSE_s_n (oCompressSigs, "compress-sigs", "@"),
631 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
632 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
633 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
634 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
635 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
636 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
637 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
638 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
639 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
640 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
641 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
642 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
643 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
644 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
645 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
646 ARGPARSE_s_s (oComment, "comment", "@"),
647 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
648 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
649 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
650 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
651 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
652 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
653 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
654 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
655 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
656 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
657 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
658 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
659 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
660 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
661 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
662 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
663 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
664 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
665 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
666 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
667 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
668 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
669 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
670 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
671 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
672 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
673 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
674 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
675 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
676 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
677 ARGPARSE_s_n (oListOnly, "list-only", "@"),
678 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
679 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
680 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
681 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
682 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
683 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
684 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
685 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
686 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
687 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
688 ARGPARSE_s_n (oNoSigCreateCheck, "no-sig-create-check", "@"),
689 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
690 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
691 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
692 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
693 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
694 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
695 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
696 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
697 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
698 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
699 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
700 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
701 ARGPARSE_s_s (oPersonalCompressPreferences,
702 "personal-compress-preferences", "@"),
704 /* Aliases. I constantly mistype these, and assume other people do
705 as well. */
706 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
707 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
708 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
709 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
710 ARGPARSE_s_s (oDisplay, "display", "@"),
711 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
712 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
713 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
714 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
715 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
716 ARGPARSE_s_s (oGroup, "group", "@"),
717 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
718 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
719 ARGPARSE_s_n (oStrict, "strict", "@"),
720 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
721 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
722 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
723 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
724 ARGPARSE_s_n (oMultifile, "multifile", "@"),
725 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
726 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
727 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
729 ARGPARSE_s_n (oAllowMultisigVerification,
730 "allow-multisig-verification", "@"),
731 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
732 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
733 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
734 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
736 /* These two are aliases to help users of the PGP command line
737 product use gpg with minimal pain. Many commands are common
738 already as they seem to have borrowed commands from us. Now I'm
739 returning the favor. */
740 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
741 ARGPARSE_s_s (oRecipient, "user", "@"),
743 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
744 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
745 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
746 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
748 /* New options. Fixme: Should go more to the top. */
749 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
750 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
752 ARGPARSE_end ()
756 #ifdef ENABLE_SELINUX_HACKS
757 #define ALWAYS_ADD_KEYRINGS 1
758 #else
759 #define ALWAYS_ADD_KEYRINGS 0
760 #endif
763 int g10_errors_seen = 0;
765 static int utf8_strings = 0;
766 static int maybe_setuid = 1;
768 static char *build_list( const char *text, char letter,
769 const char *(*mapf)(int), int (*chkf)(int) );
770 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
771 enum cmd_and_opt_values new_cmd );
772 static void print_mds( const char *fname, int algo );
773 static void add_notation_data( const char *string, int which );
774 static void add_policy_url( const char *string, int which );
775 static void add_keyserver_url( const char *string, int which );
776 static void emergency_cleanup (void);
779 static char *
780 make_libversion (const char *libname, const char *(*getfnc)(const char*))
782 const char *s;
783 char *result;
785 if (maybe_setuid)
787 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
788 maybe_setuid = 0;
790 s = getfnc (NULL);
791 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
792 strcpy (stpcpy (stpcpy (result, libname), " "), s);
793 return result;
797 static const char *
798 my_strusage( int level )
800 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
801 const char *p;
803 switch( level ) {
804 case 11: p = "gpg (GnuPG)";
805 break;
806 case 13: p = VERSION; break;
807 case 17: p = PRINTABLE_OS_NAME; break;
808 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
810 case 20:
811 if (!ver_gcry)
812 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
813 p = ver_gcry;
814 break;
816 #ifdef IS_DEVELOPMENT_VERSION
817 case 25:
818 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
819 break;
820 case 26:
821 p="It is only intended for test purposes and should NOT be";
822 break;
823 case 27:
824 p="used in a production environment or with production keys!";
825 break;
826 #endif
828 case 1:
829 case 40: p =
830 _("Usage: gpg [options] [files] (-h for help)");
831 break;
832 case 41: p =
833 _("Syntax: gpg [options] [files]\n"
834 "sign, check, encrypt or decrypt\n"
835 "default operation depends on the input data\n");
836 break;
838 case 31: p = "\nHome: "; break;
839 #ifndef __riscos__
840 case 32: p = opt.homedir; break;
841 #else /* __riscos__ */
842 case 32: p = make_filename(opt.homedir, NULL); break;
843 #endif /* __riscos__ */
844 case 33: p = _("\nSupported algorithms:\n"); break;
845 case 34:
846 if (!pubkeys)
847 pubkeys = build_list (_("Pubkey: "), 0,
848 gcry_pk_algo_name,
849 openpgp_pk_test_algo );
850 p = pubkeys;
851 break;
852 case 35:
853 if( !ciphers )
854 ciphers = build_list(_("Cipher: "), 'S',
855 openpgp_cipher_algo_name,
856 openpgp_cipher_test_algo );
857 p = ciphers;
858 break;
859 case 36:
860 if( !digests )
861 digests = build_list(_("Hash: "), 'H',
862 gcry_md_algo_name,
863 openpgp_md_test_algo );
864 p = digests;
865 break;
866 case 37:
867 if( !zips )
868 zips = build_list(_("Compression: "),'Z',
869 compress_algo_to_string,
870 check_compress_algo);
871 p = zips;
872 break;
874 default: p = NULL;
876 return p;
880 static char *
881 build_list( const char *text, char letter,
882 const char * (*mapf)(int), int (*chkf)(int) )
884 int i;
885 const char *s;
886 size_t n=strlen(text)+2;
887 char *list, *p, *line=NULL;
889 if (maybe_setuid)
890 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
892 for(i=0; i <= 110; i++ )
893 if( !chkf(i) && (s=mapf(i)) )
894 n += strlen(s) + 7 + 2;
895 list = xmalloc( 21 + n ); *list = 0;
896 for(p=NULL, i=0; i <= 110; i++ ) {
897 if( !chkf(i) && (s=mapf(i)) ) {
898 if( !p ) {
899 p = stpcpy( list, text );
900 line=p;
902 else
903 p = stpcpy( p, ", ");
905 if(strlen(line)>60) {
906 int spaces=strlen(text);
908 list=xrealloc(list,n+spaces+1);
909 /* realloc could move the block, so find the end again */
910 p=list;
911 while(*p)
912 p++;
914 p=stpcpy(p, "\n");
915 line=p;
916 for(;spaces;spaces--)
917 p=stpcpy(p, " ");
920 p = stpcpy(p, s );
921 if(opt.verbose && letter)
923 char num[8];
924 sprintf(num," (%c%d)",letter,i);
925 p = stpcpy(p,num);
929 if( p )
930 p = stpcpy(p, "\n" );
931 return list;
935 static void
936 wrong_args( const char *text)
938 fputs(_("usage: gpg [options] "),stderr);
939 fputs(text,stderr);
940 putc('\n',stderr);
941 g10_exit(2);
945 static char *
946 make_username( const char *string )
948 char *p;
949 if( utf8_strings )
950 p = xstrdup(string);
951 else
952 p = native_to_utf8( string );
953 return p;
957 static void
958 set_opt_session_env (const char *name, const char *value)
960 gpg_error_t err;
962 err = session_env_setenv (opt.session_env, name, value);
963 if (err)
964 log_fatal ("error setting session environment: %s\n",
965 gpg_strerror (err));
968 /* Setup the debugging. With a LEVEL of NULL only the active debug
969 flags are propagated to the subsystems. With LEVEL set, a specific
970 set of debug flags is set; thus overriding all flags already
971 set. */
972 static void
973 set_debug (const char *level)
975 if (!level)
977 else if (!strcmp (level, "none"))
978 opt.debug = 0;
979 else if (!strcmp (level, "basic"))
980 opt.debug = DBG_MEMSTAT_VALUE;
981 else if (!strcmp (level, "advanced"))
982 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
983 else if (!strcmp (level, "expert"))
984 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
985 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
986 else if (!strcmp (level, "guru"))
987 opt.debug = ~0;
988 else
990 log_error (_("invalid debug-level `%s' given\n"), level);
991 g10_exit (2);
994 if (opt.debug & DBG_MEMORY_VALUE )
995 memory_debug_mode = 1;
996 if (opt.debug & DBG_MEMSTAT_VALUE )
997 memory_stat_debug_mode = 1;
998 if (opt.debug & DBG_MPI_VALUE)
999 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1000 if (opt.debug & DBG_CIPHER_VALUE )
1001 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1002 if (opt.debug & DBG_IOBUF_VALUE )
1003 iobuf_debug_mode = 1;
1004 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1009 /* We need the home directory also in some other directories, so make
1010 sure that both variables are always in sync. */
1011 static void
1012 set_homedir (const char *dir)
1014 if (!dir)
1015 dir = "";
1016 opt.homedir = dir;
1020 /* We set the screen dimensions for UI purposes. Do not allow screens
1021 smaller than 80x24 for the sake of simplicity. */
1022 static void
1023 set_screen_dimensions(void)
1025 #ifndef HAVE_W32_SYSTEM
1026 char *str;
1028 str=getenv("COLUMNS");
1029 if(str)
1030 opt.screen_columns=atoi(str);
1032 str=getenv("LINES");
1033 if(str)
1034 opt.screen_lines=atoi(str);
1035 #endif
1037 if(opt.screen_columns<80 || opt.screen_columns>255)
1038 opt.screen_columns=80;
1040 if(opt.screen_lines<24 || opt.screen_lines>255)
1041 opt.screen_lines=24;
1045 /* Helper to open a file FNAME either for reading or writing to be
1046 used with --status-file etc functions. Not generally useful but it
1047 avoids the riscos specific functions and well some Windows people
1048 might like it too. Prints an error message and returns -1 on
1049 error. On success the file descriptor is returned. */
1050 static int
1051 open_info_file (const char *fname, int for_write, int binary)
1053 #ifdef __riscos__
1054 return riscos_fdopenfile (fname, for_write);
1055 #elif defined (ENABLE_SELINUX_HACKS)
1056 /* We can't allow these even when testing for a secured filename
1057 because files to be secured might not yet been secured. This is
1058 similar to the option file but in that case it is unlikely that
1059 sensitive information may be retrieved by means of error
1060 messages. */
1061 (void)fname;
1062 (void)for_write;
1063 (void)binary;
1064 return -1;
1065 #else
1066 int fd;
1068 if (binary)
1069 binary = MY_O_BINARY;
1071 /* if (is_secured_filename (fname)) */
1072 /* { */
1073 /* fd = -1; */
1074 /* errno = EPERM; */
1075 /* } */
1076 /* else */
1077 /* { */
1080 if (for_write)
1081 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1082 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1083 else
1084 fd = open (fname, O_RDONLY | binary);
1086 while (fd == -1 && errno == EINTR);
1087 /* } */
1088 if ( fd == -1)
1089 log_error ( for_write? _("can't create `%s': %s\n")
1090 : _("can't open `%s': %s\n"), fname, strerror(errno));
1092 return fd;
1093 #endif
1096 static void
1097 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1099 enum cmd_and_opt_values cmd = *ret_cmd;
1101 if( !cmd || cmd == new_cmd )
1102 cmd = new_cmd;
1103 else if( cmd == aSign && new_cmd == aEncr )
1104 cmd = aSignEncr;
1105 else if( cmd == aEncr && new_cmd == aSign )
1106 cmd = aSignEncr;
1107 else if( cmd == aSign && new_cmd == aSym )
1108 cmd = aSignSym;
1109 else if( cmd == aSym && new_cmd == aSign )
1110 cmd = aSignSym;
1111 else if( cmd == aSym && new_cmd == aEncr )
1112 cmd = aEncrSym;
1113 else if( cmd == aEncr && new_cmd == aSym )
1114 cmd = aEncrSym;
1115 else if (cmd == aSignEncr && new_cmd == aSym)
1116 cmd = aSignEncrSym;
1117 else if (cmd == aSignSym && new_cmd == aEncr)
1118 cmd = aSignEncrSym;
1119 else if (cmd == aEncrSym && new_cmd == aSign)
1120 cmd = aSignEncrSym;
1121 else if( ( cmd == aSign && new_cmd == aClearsign )
1122 || ( cmd == aClearsign && new_cmd == aSign ) )
1123 cmd = aClearsign;
1124 else {
1125 log_error(_("conflicting commands\n"));
1126 g10_exit(2);
1129 *ret_cmd = cmd;
1133 static void
1134 add_group(char *string)
1136 char *name,*value;
1137 struct groupitem *item;
1139 /* Break off the group name */
1140 name=strsep(&string,"=");
1141 if(string==NULL)
1143 log_error(_("no = sign found in group definition `%s'\n"),name);
1144 return;
1147 trim_trailing_ws(name,strlen(name));
1149 /* Does this group already exist? */
1150 for(item=opt.grouplist;item;item=item->next)
1151 if(strcasecmp(item->name,name)==0)
1152 break;
1154 if(!item)
1156 item=xmalloc(sizeof(struct groupitem));
1157 item->name=name;
1158 item->next=opt.grouplist;
1159 item->values=NULL;
1160 opt.grouplist=item;
1163 /* Break apart the values */
1164 while ((value= strsep(&string," \t")))
1166 if (*value)
1167 add_to_strlist2(&item->values,value,utf8_strings);
1172 static void
1173 rm_group(char *name)
1175 struct groupitem *item,*last=NULL;
1177 trim_trailing_ws(name,strlen(name));
1179 for(item=opt.grouplist;item;last=item,item=item->next)
1181 if(strcasecmp(item->name,name)==0)
1183 if(last)
1184 last->next=item->next;
1185 else
1186 opt.grouplist=item->next;
1188 free_strlist(item->values);
1189 xfree(item);
1190 break;
1196 /* We need to check three things.
1198 0) The homedir. It must be x00, a directory, and owned by the
1199 user.
1201 1) The options/gpg.conf file. Okay unless it or its containing
1202 directory is group or other writable or not owned by us. Disable
1203 exec in this case.
1205 2) Extensions. Same as #1.
1207 Returns true if the item is unsafe. */
1208 static int
1209 check_permissions(const char *path,int item)
1211 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1212 static int homedir_cache=-1;
1213 char *tmppath,*dir;
1214 struct stat statbuf,dirbuf;
1215 int homedir=0,ret=0,checkonly=0;
1216 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1218 if(opt.no_perm_warn)
1219 return 0;
1221 assert(item==0 || item==1 || item==2);
1223 /* extensions may attach a path */
1224 if(item==2 && path[0]!=DIRSEP_C)
1226 if(strchr(path,DIRSEP_C))
1227 tmppath=make_filename(path,NULL);
1228 else
1229 tmppath=make_filename(gnupg_libdir (),path,NULL);
1231 else
1232 tmppath=xstrdup(path);
1234 /* If the item is located in the homedir, but isn't the homedir,
1235 don't continue if we already checked the homedir itself. This is
1236 to avoid user confusion with an extra options file warning which
1237 could be rectified if the homedir itself had proper
1238 permissions. */
1239 if(item!=0 && homedir_cache>-1
1240 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1242 ret=homedir_cache;
1243 goto end;
1246 /* It's okay if the file or directory doesn't exist */
1247 if(stat(tmppath,&statbuf)!=0)
1249 ret=0;
1250 goto end;
1253 /* Now check the enclosing directory. Theoretically, we could walk
1254 this test up to the root directory /, but for the sake of sanity,
1255 I'm stopping at one level down. */
1256 dir=make_dirname(tmppath);
1258 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1260 /* Weird error */
1261 ret=1;
1262 goto end;
1265 xfree(dir);
1267 /* Assume failure */
1268 ret=1;
1270 if(item==0)
1272 /* The homedir must be x00, a directory, and owned by the user. */
1274 if(S_ISDIR(statbuf.st_mode))
1276 if(statbuf.st_uid==getuid())
1278 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1279 ret=0;
1280 else
1281 perm=1;
1283 else
1284 own=1;
1286 homedir_cache=ret;
1289 else if(item==1 || item==2)
1291 /* The options or extension file. Okay unless it or its
1292 containing directory is group or other writable or not owned
1293 by us or root. */
1295 if(S_ISREG(statbuf.st_mode))
1297 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1299 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1301 /* it's not writable, so make sure the enclosing
1302 directory is also not writable */
1303 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1305 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1306 ret=0;
1307 else
1308 enc_dir_perm=1;
1310 else
1311 enc_dir_own=1;
1313 else
1315 /* it's writable, so the enclosing directory had
1316 better not let people get to it. */
1317 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1319 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1320 ret=0;
1321 else
1322 perm=enc_dir_perm=1; /* unclear which one to fix! */
1324 else
1325 enc_dir_own=1;
1328 else
1329 own=1;
1332 else
1333 BUG();
1335 if(!checkonly)
1337 if(own)
1339 if(item==0)
1340 log_info(_("WARNING: unsafe ownership on"
1341 " homedir `%s'\n"),tmppath);
1342 else if(item==1)
1343 log_info(_("WARNING: unsafe ownership on"
1344 " configuration file `%s'\n"),tmppath);
1345 else
1346 log_info(_("WARNING: unsafe ownership on"
1347 " extension `%s'\n"),tmppath);
1349 if(perm)
1351 if(item==0)
1352 log_info(_("WARNING: unsafe permissions on"
1353 " homedir `%s'\n"),tmppath);
1354 else if(item==1)
1355 log_info(_("WARNING: unsafe permissions on"
1356 " configuration file `%s'\n"),tmppath);
1357 else
1358 log_info(_("WARNING: unsafe permissions on"
1359 " extension `%s'\n"),tmppath);
1361 if(enc_dir_own)
1363 if(item==0)
1364 log_info(_("WARNING: unsafe enclosing directory ownership on"
1365 " homedir `%s'\n"),tmppath);
1366 else if(item==1)
1367 log_info(_("WARNING: unsafe enclosing directory ownership on"
1368 " configuration file `%s'\n"),tmppath);
1369 else
1370 log_info(_("WARNING: unsafe enclosing directory ownership on"
1371 " extension `%s'\n"),tmppath);
1373 if(enc_dir_perm)
1375 if(item==0)
1376 log_info(_("WARNING: unsafe enclosing directory permissions on"
1377 " homedir `%s'\n"),tmppath);
1378 else if(item==1)
1379 log_info(_("WARNING: unsafe enclosing directory permissions on"
1380 " configuration file `%s'\n"),tmppath);
1381 else
1382 log_info(_("WARNING: unsafe enclosing directory permissions on"
1383 " extension `%s'\n"),tmppath);
1387 end:
1388 xfree(tmppath);
1390 if(homedir)
1391 homedir_cache=ret;
1393 return ret;
1395 #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
1397 return 0;
1401 static void
1402 print_algo_numbers(int (*checker)(int))
1404 int i,first=1;
1406 for(i=0;i<=110;i++)
1408 if(!checker(i))
1410 if(first)
1411 first=0;
1412 else
1413 printf(";");
1414 printf("%d",i);
1420 static void
1421 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1423 int i,first=1;
1425 for(i=0;i<=110;i++)
1427 if(!checker(i))
1429 if(first)
1430 first=0;
1431 else
1432 printf(";");
1433 printf("%s",mapper(i));
1438 /* In the future, we can do all sorts of interesting configuration
1439 output here. For now, just give "group" as the Enigmail folks need
1440 it, and pubkey, cipher, hash, and compress as they may be useful
1441 for frontends. */
1442 static void
1443 list_config(char *items)
1445 int show_all=(items==NULL);
1446 char *name=NULL;
1448 if(!opt.with_colons)
1449 return;
1451 while(show_all || (name=strsep(&items," ")))
1453 int any=0;
1455 if(show_all || ascii_strcasecmp(name,"group")==0)
1457 struct groupitem *iter;
1459 for(iter=opt.grouplist;iter;iter=iter->next)
1461 strlist_t sl;
1463 printf("cfg:group:");
1464 print_string(stdout,iter->name,strlen(iter->name),':');
1465 printf(":");
1467 for(sl=iter->values;sl;sl=sl->next)
1469 print_sanitized_string2 (stdout, sl->d, ':',';');
1470 if(sl->next)
1471 printf(";");
1474 printf("\n");
1477 any=1;
1480 if(show_all || ascii_strcasecmp(name,"version")==0)
1482 printf("cfg:version:");
1483 print_string(stdout,VERSION,strlen(VERSION),':');
1484 printf("\n");
1485 any=1;
1488 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1490 printf("cfg:pubkey:");
1491 print_algo_numbers (openpgp_pk_test_algo);
1492 printf("\n");
1493 any=1;
1496 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1498 printf("cfg:cipher:");
1499 print_algo_numbers(openpgp_cipher_test_algo);
1500 printf("\n");
1501 any=1;
1504 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1506 printf ("cfg:ciphername:");
1507 print_algo_names (openpgp_cipher_test_algo,openpgp_cipher_algo_name);
1508 printf ("\n");
1509 any = 1;
1512 if(show_all
1513 || ascii_strcasecmp(name,"digest")==0
1514 || ascii_strcasecmp(name,"hash")==0)
1516 printf("cfg:digest:");
1517 print_algo_numbers(openpgp_md_test_algo);
1518 printf("\n");
1519 any=1;
1522 if (show_all
1523 || !ascii_strcasecmp(name,"digestname")
1524 || !ascii_strcasecmp(name,"hashname"))
1526 printf ("cfg:digestname:");
1527 print_algo_names (openpgp_md_test_algo, gcry_md_algo_name);
1528 printf("\n");
1529 any=1;
1532 if(show_all || ascii_strcasecmp(name,"compress")==0)
1534 printf("cfg:compress:");
1535 print_algo_numbers(check_compress_algo);
1536 printf("\n");
1537 any=1;
1540 if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
1542 #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \
1543 && GNUPG_MAJOR_VERSION == 1
1545 char *p, *p2, *list = ccid_get_reader_list ();
1547 for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
1549 *p2 = 0;
1550 printf("cfg:ccid-reader-id:%s\n", p);
1552 free (list);
1553 #endif
1554 any=1;
1557 if(show_all)
1558 break;
1560 if(!any)
1561 log_error(_("unknown configuration item `%s'\n"),name);
1566 /* List options and default values in the GPG Conf format. This is a
1567 new tool distributed with gnupg 1.9.x but we also want some limited
1568 support in older gpg versions. The output is the name of the
1569 configuration file and a list of options available for editing by
1570 gpgconf. */
1571 static void
1572 gpgconf_list (const char *configfile)
1574 char *configfile_esc = percent_escape (configfile, NULL);
1576 printf ("gpgconf-gpg.conf:%lu:\"%s\n",
1577 GC_OPT_FLAG_DEFAULT, configfile_esc ? configfile_esc : "/dev/null");
1578 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1579 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1580 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1581 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1582 printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1583 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1584 printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1585 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1586 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1587 printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1589 xfree (configfile_esc);
1593 static int
1594 parse_subpacket_list(char *list)
1596 char *tok;
1597 byte subpackets[128],i;
1598 int count=0;
1600 if(!list)
1602 /* No arguments means all subpackets */
1603 memset(subpackets+1,1,sizeof(subpackets)-1);
1604 count=127;
1606 else
1608 memset(subpackets,0,sizeof(subpackets));
1610 /* Merge with earlier copy */
1611 if(opt.show_subpackets)
1613 byte *in;
1615 for(in=opt.show_subpackets;*in;in++)
1617 if(*in>127 || *in<1)
1618 BUG();
1620 if(!subpackets[*in])
1621 count++;
1622 subpackets[*in]=1;
1626 while((tok=strsep(&list," ,")))
1628 if(!*tok)
1629 continue;
1631 i=atoi(tok);
1632 if(i>127 || i<1)
1633 return 0;
1635 if(!subpackets[i])
1636 count++;
1637 subpackets[i]=1;
1641 xfree(opt.show_subpackets);
1642 opt.show_subpackets=xmalloc(count+1);
1643 opt.show_subpackets[count--]=0;
1645 for(i=1;i<128 && count>=0;i++)
1646 if(subpackets[i])
1647 opt.show_subpackets[count--]=i;
1649 return 1;
1653 static int
1654 parse_list_options(char *str)
1656 char *subpackets=""; /* something that isn't NULL */
1657 struct parse_options lopts[]=
1659 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1660 N_("display photo IDs during key listings")},
1661 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1662 N_("show policy URLs during signature listings")},
1663 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1664 N_("show all notations during signature listings")},
1665 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1666 N_("show IETF standard notations during signature listings")},
1667 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1668 NULL},
1669 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1670 N_("show user-supplied notations during signature listings")},
1671 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1672 N_("show preferred keyserver URLs during signature listings")},
1673 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1674 N_("show user ID validity during key listings")},
1675 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1676 N_("show revoked and expired user IDs in key listings")},
1677 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1678 N_("show revoked and expired subkeys in key listings")},
1679 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1680 N_("show the keyring name in key listings")},
1681 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1682 N_("show expiration dates during signature listings")},
1683 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1684 NULL},
1685 {NULL,0,NULL,NULL}
1688 /* C99 allows for non-constant initializers, but we'd like to
1689 compile everywhere, so fill in the show-sig-subpackets argument
1690 here. Note that if the parse_options array changes, we'll have
1691 to change the subscript here. */
1692 lopts[12].value=&subpackets;
1694 if(parse_options(str,&opt.list_options,lopts,1))
1696 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1698 /* Unset so users can pass multiple lists in. */
1699 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1700 if(!parse_subpacket_list(subpackets))
1701 return 0;
1703 else if(subpackets==NULL && opt.show_subpackets)
1705 /* User did 'no-show-subpackets' */
1706 xfree(opt.show_subpackets);
1707 opt.show_subpackets=NULL;
1710 return 1;
1712 else
1713 return 0;
1717 /* Collapses argc/argv into a single string that must be freed */
1718 static char *
1719 collapse_args(int argc,char *argv[])
1721 char *str=NULL;
1722 int i,first=1,len=0;
1724 for(i=0;i<argc;i++)
1726 len+=strlen(argv[i])+2;
1727 str=xrealloc(str,len);
1728 if(first)
1730 str[0]='\0';
1731 first=0;
1733 else
1734 strcat(str," ");
1736 strcat(str,argv[i]);
1739 return str;
1742 static void
1743 parse_trust_model(const char *model)
1745 if(ascii_strcasecmp(model,"pgp")==0)
1746 opt.trust_model=TM_PGP;
1747 else if(ascii_strcasecmp(model,"classic")==0)
1748 opt.trust_model=TM_CLASSIC;
1749 else if(ascii_strcasecmp(model,"always")==0)
1750 opt.trust_model=TM_ALWAYS;
1751 else if(ascii_strcasecmp(model,"direct")==0)
1752 opt.trust_model=TM_DIRECT;
1753 else if(ascii_strcasecmp(model,"auto")==0)
1754 opt.trust_model=TM_AUTO;
1755 else
1756 log_error("unknown trust model `%s'\n",model);
1760 /* Pack an s2k iteration count into the form specified in 2440. If
1761 we're in between valid values, round up. */
1762 static unsigned char
1763 encode_s2k_iterations(int iterations)
1765 unsigned char c=0,result;
1766 unsigned int count;
1768 if(iterations<=1024)
1769 return 0;
1771 if(iterations>=65011712)
1772 return 255;
1774 /* Need count to be in the range 16-31 */
1775 for(count=iterations>>6;count>=32;count>>=1)
1776 c++;
1778 result=(c<<4)|(count-16);
1780 if(S2K_DECODE_COUNT(result)<iterations)
1781 result++;
1783 return result;
1787 /* This fucntion called to initialized a new control object. It is
1788 assumed that this object has been zeroed out before calling this
1789 function. */
1790 static void
1791 gpg_init_default_ctrl (ctrl_t ctrl)
1793 (void)ctrl;
1797 /* This function is called to deinitialize a control object. It is
1798 not deallocated. */
1799 static void
1800 gpg_deinit_default_ctrl (ctrl_t ctrl)
1802 (void)ctrl;
1806 char *
1807 get_default_configname (void)
1809 char *configname = NULL;
1810 char *name = xstrdup ("gpg" EXTSEP_S "conf-" SAFE_VERSION);
1811 char *ver = &name[strlen ("gpg" EXTSEP_S "conf-")];
1815 if (configname)
1817 char *tok;
1819 xfree (configname);
1820 configname = NULL;
1822 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
1823 *tok='\0';
1824 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
1825 *tok='\0';
1826 else
1827 break;
1830 configname = make_filename (opt.homedir, name, NULL);
1832 while (access (configname, R_OK));
1834 xfree(name);
1836 if (! configname)
1837 configname = make_filename (opt.homedir, "gpg" EXTSEP_S "conf", NULL);
1838 if (! access (configname, R_OK))
1840 /* Print a warning when both config files are present. */
1841 char *p = make_filename (opt.homedir, "options", NULL);
1842 if (! access (p, R_OK))
1843 log_info (_("NOTE: old default options file `%s' ignored\n"), p);
1844 xfree (p);
1846 else
1848 /* Use the old default only if it exists. */
1849 char *p = make_filename (opt.homedir, "options", NULL);
1850 if (!access (p, R_OK))
1852 xfree (configname);
1853 configname = p;
1855 else
1856 xfree (p);
1859 return configname;
1864 main (int argc, char **argv)
1866 ARGPARSE_ARGS pargs;
1867 IOBUF a;
1868 int rc=0;
1869 int orig_argc;
1870 char **orig_argv;
1871 const char *fname;
1872 char *username;
1873 int may_coredump;
1874 strlist_t sl, remusr= NULL, locusr=NULL;
1875 strlist_t nrings=NULL, sec_nrings=NULL;
1876 armor_filter_context_t *afx = NULL;
1877 int detached_sig = 0;
1878 FILE *configfp = NULL;
1879 char *configname = NULL;
1880 char *save_configname = NULL;
1881 char *default_configname = NULL;
1882 unsigned configlineno;
1883 int parse_debug = 0;
1884 int default_config = 1;
1885 int default_keyring = 1;
1886 int greeting = 0;
1887 int nogreeting = 0;
1888 char *logfile = NULL;
1889 int use_random_seed = 1;
1890 enum cmd_and_opt_values cmd = 0;
1891 const char *debug_level = NULL;
1892 const char *trustdb_name = NULL;
1893 char *def_cipher_string = NULL;
1894 char *def_digest_string = NULL;
1895 char *compress_algo_string = NULL;
1896 char *cert_digest_string = NULL;
1897 char *s2k_cipher_string = NULL;
1898 char *s2k_digest_string = NULL;
1899 char *pers_cipher_list = NULL;
1900 char *pers_digest_list = NULL;
1901 char *pers_compress_list = NULL;
1902 int eyes_only=0;
1903 int multifile=0;
1904 int pwfd = -1;
1905 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
1906 int any_explicit_recipient = 0;
1907 int require_secmem=0,got_secmem=0;
1908 struct assuan_malloc_hooks malloc_hooks;
1910 #ifdef __riscos__
1911 opt.lock_once = 1;
1912 #endif /* __riscos__ */
1915 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1916 when adding any stuff between here and the call to
1917 secmem_init() somewhere after the option parsing. */
1918 gnupg_reopen_std ("gpg");
1919 trap_unaligned ();
1920 gnupg_rl_initialize ();
1921 set_strusage (my_strusage);
1922 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1923 log_set_prefix ("gpg", 1);
1925 /* Make sure that our subsystems are ready. */
1926 i18n_init();
1927 init_common_subsystems ();
1929 /* Check that the libraries are suitable. Do it right here because the
1930 option parsing may need services of the library. */
1931 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1933 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
1934 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1937 /* Put random number into secure memory */
1938 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1940 may_coredump = disable_core_dumps();
1942 gnupg_init_signals (0, emergency_cleanup);
1944 create_dotlock(NULL); /* Register locking cleanup. */
1946 opt.session_env = session_env_new ();
1947 if (!opt.session_env)
1948 log_fatal ("error allocating session environment block: %s\n",
1949 strerror (errno));
1951 opt.command_fd = -1; /* no command fd */
1952 opt.compress_level = -1; /* defaults to standard compress level */
1953 opt.bz2_compress_level = -1; /* defaults to standard compress level */
1954 /* note: if you change these lines, look at oOpenPGP */
1955 opt.def_cipher_algo = 0;
1956 opt.def_digest_algo = 0;
1957 opt.cert_digest_algo = 0;
1958 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
1959 opt.s2k_mode = 3; /* iterated+salted */
1960 opt.s2k_count = 96; /* 65536 iterations */
1961 #ifdef USE_CAST5
1962 opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
1963 #else
1964 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
1965 #endif
1966 opt.completes_needed = 1;
1967 opt.marginals_needed = 3;
1968 opt.max_cert_depth = 5;
1969 opt.pgp2_workarounds = 1;
1970 opt.escape_from = 1;
1971 opt.flags.require_cross_cert = 1;
1972 opt.import_options=IMPORT_SK2PK;
1973 opt.export_options=EXPORT_ATTRIBUTES;
1974 opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
1975 opt.keyserver_options.export_options=EXPORT_ATTRIBUTES;
1976 opt.keyserver_options.options=
1977 KEYSERVER_HONOR_KEYSERVER_URL|KEYSERVER_HONOR_PKA_RECORD;
1978 opt.verify_options=
1979 VERIFY_SHOW_POLICY_URLS|VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_KEYSERVER_URLS;
1980 opt.trust_model=TM_AUTO;
1981 opt.mangle_dos_filenames=0;
1982 opt.min_cert_level=2;
1983 set_screen_dimensions();
1984 opt.keyid_format=KF_SHORT;
1985 opt.def_sig_expire="0";
1986 opt.def_cert_expire="0";
1987 set_homedir ( default_homedir () );
1988 opt.passwd_repeat=1;
1990 /* Check whether we have a config file on the command line. */
1991 orig_argc = argc;
1992 orig_argv = argv;
1993 pargs.argc = &argc;
1994 pargs.argv = &argv;
1995 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1996 while( arg_parse( &pargs, opts) ) {
1997 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
1998 parse_debug++;
1999 else if( pargs.r_opt == oOptions ) {
2000 /* yes there is one, so we do not try the default one, but
2001 * read the option file when it is encountered at the commandline
2003 default_config = 0;
2005 else if( pargs.r_opt == oNoOptions )
2007 default_config = 0; /* --no-options */
2008 opt.no_homedir_creation = 1;
2010 else if( pargs.r_opt == oHomedir )
2011 set_homedir ( pargs.r.ret_str );
2012 else if( pargs.r_opt == oNoPermissionWarn )
2013 opt.no_perm_warn=1;
2014 else if (pargs.r_opt == oStrict )
2016 /* Not used */
2018 else if (pargs.r_opt == oNoStrict )
2020 /* Not used */
2024 #ifdef HAVE_DOSISH_SYSTEM
2025 if ( strchr (opt.homedir,'\\') ) {
2026 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
2027 const char *s = opt.homedir;
2028 for (d=buf,s=opt.homedir; *s; s++)
2030 *d++ = *s == '\\'? '/': *s;
2031 #ifdef HAVE_W32_SYSTEM
2032 if (s[1] && IsDBCSLeadByte (*s))
2033 *d++ = *++s;
2034 #endif
2036 *d = 0;
2037 set_homedir (buf);
2039 #endif
2041 /* Initialize the secure memory. */
2042 if (!gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0))
2043 got_secmem = 1;
2044 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2045 /* There should be no way to get to this spot while still carrying
2046 setuid privs. Just in case, bomb out if we are. */
2047 if ( getuid () != geteuid () )
2048 BUG ();
2049 #endif
2050 maybe_setuid = 0;
2052 /* Okay, we are now working under our real uid */
2054 /* malloc hooks go here ... */
2055 malloc_hooks.malloc = gcry_malloc;
2056 malloc_hooks.realloc = gcry_realloc;
2057 malloc_hooks.free = gcry_free;
2058 assuan_set_malloc_hooks (&malloc_hooks);
2059 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
2060 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2062 /* Try for a version specific config file first */
2063 default_configname = get_default_configname ();
2064 if (default_config)
2065 configname = xstrdup (default_configname);
2067 argc = orig_argc;
2068 argv = orig_argv;
2069 pargs.argc = &argc;
2070 pargs.argv = &argv;
2071 pargs.flags= 1; /* do not remove the args */
2073 /* By this point we have a homedir, and cannot change it. */
2074 check_permissions(opt.homedir,0);
2076 next_pass:
2077 if( configname ) {
2078 if(check_permissions(configname,1))
2080 /* If any options file is unsafe, then disable any external
2081 programs for keyserver calls or photo IDs. Since the
2082 external program to call is set in the options file, a
2083 unsafe options file can lead to an arbitrary program
2084 being run. */
2086 opt.exec_disable=1;
2089 configlineno = 0;
2090 configfp = fopen( configname, "r" );
2091 if (configfp && is_secured_file (fileno (configfp)))
2093 fclose (configfp);
2094 configfp = NULL;
2095 errno = EPERM;
2097 if( !configfp ) {
2098 if( default_config ) {
2099 if( parse_debug )
2100 log_info(_("NOTE: no default option file `%s'\n"),
2101 configname );
2103 else {
2104 log_error(_("option file `%s': %s\n"),
2105 configname, strerror(errno) );
2106 g10_exit(2);
2108 xfree(configname); configname = NULL;
2110 if( parse_debug && configname )
2111 log_info(_("reading options from `%s'\n"), configname );
2112 default_config = 0;
2115 while( optfile_parse( configfp, configname, &configlineno,
2116 &pargs, opts) )
2118 switch( pargs.r_opt )
2120 case aCheckKeys:
2121 case aListConfig:
2122 case aGPGConfList:
2123 case aGPGConfTest:
2124 case aListPackets:
2125 case aImport:
2126 case aFastImport:
2127 case aSendKeys:
2128 case aRecvKeys:
2129 case aSearchKeys:
2130 case aRefreshKeys:
2131 case aFetchKeys:
2132 case aExport:
2133 #ifdef ENABLE_CARD_SUPPORT
2134 case aCardStatus:
2135 case aCardEdit:
2136 case aChangePIN:
2137 #endif /* ENABLE_CARD_SUPPORT*/
2138 case aListKeys:
2139 case aLocateKeys:
2140 case aListSigs:
2141 case aExportSecret:
2142 case aExportSecretSub:
2143 case aSym:
2144 case aClearsign:
2145 case aGenRevoke:
2146 case aDesigRevoke:
2147 case aPrimegen:
2148 case aGenRandom:
2149 case aPrintMD:
2150 case aPrintMDs:
2151 case aListTrustDB:
2152 case aCheckTrustDB:
2153 case aUpdateTrustDB:
2154 case aFixTrustDB:
2155 case aListTrustPath:
2156 case aDeArmor:
2157 case aEnArmor:
2158 case aSign:
2159 case aSignKey:
2160 case aLSignKey:
2161 case aStore:
2162 case aExportOwnerTrust:
2163 case aImportOwnerTrust:
2164 case aRebuildKeydbCaches:
2165 set_cmd (&cmd, pargs.r_opt);
2166 break;
2168 case aKeygen:
2169 case aEditKey:
2170 case aDeleteSecretKeys:
2171 case aDeleteSecretAndPublicKeys:
2172 case aDeleteKeys:
2173 set_cmd (&cmd, pargs.r_opt);
2174 greeting=1;
2175 break;
2177 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2179 case aDecryptFiles: multifile=1; /* fall through */
2180 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2182 case aEncrFiles: multifile=1; /* fall through */
2183 case aEncr: set_cmd( &cmd, aEncr); break;
2185 case aVerifyFiles: multifile=1; /* fall through */
2186 case aVerify: set_cmd( &cmd, aVerify); break;
2188 case aServer:
2189 set_cmd (&cmd, pargs.r_opt);
2190 opt.batch = 1;
2191 break;
2193 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2194 case oOutput: opt.outfile = pargs.r.ret_str; break;
2195 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2196 case oQuiet: opt.quiet = 1; break;
2197 case oNoTTY: tty_no_terminal(1); break;
2198 case oDryRun: opt.dry_run = 1; break;
2199 case oInteractive: opt.interactive = 1; break;
2200 case oVerbose:
2201 opt.verbose++;
2202 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2203 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2204 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2205 break;
2207 case oBatch:
2208 opt.batch = 1;
2209 nogreeting = 1;
2210 break;
2212 case oUseAgent: /* Dummy. */
2213 break;
2214 case oNoUseAgent:
2215 obsolete_option (configname, configlineno, "--no-use-agent");
2216 break;
2217 case oGpgAgentInfo:
2218 obsolete_option (configname, configlineno, "--gpg-agent-info");
2219 break;
2221 case oAnswerYes: opt.answer_yes = 1; break;
2222 case oAnswerNo: opt.answer_no = 1; break;
2223 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2224 case oPrimaryKeyring:
2225 sl=append_to_strlist( &nrings, pargs.r.ret_str);
2226 sl->flags=2;
2227 break;
2228 case oShowKeyring:
2229 deprecated_warning(configname,configlineno,"--show-keyring",
2230 "--list-options ","show-keyring");
2231 opt.list_options|=LIST_SHOW_KEYRING;
2232 break;
2234 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2235 case oDebugAll: opt.debug = ~0; break;
2236 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2238 case oStatusFD:
2239 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2240 break;
2241 case oStatusFile:
2242 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2243 break;
2244 case oAttributeFD:
2245 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2246 break;
2247 case oAttributeFile:
2248 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2249 break;
2250 case oLoggerFD:
2251 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2252 break;
2253 case oLoggerFile:
2254 logfile = pargs.r.ret_str;
2255 break;
2257 case oWithFingerprint:
2258 opt.with_fingerprint = 1;
2259 opt.fingerprint++;
2260 break;
2261 case oFingerprint:
2262 opt.fingerprint++;
2263 fpr_maybe_cmd = 1;
2264 break;
2266 case oSecretKeyring:
2267 append_to_strlist( &sec_nrings, pargs.r.ret_str);
2268 break;
2269 case oOptions:
2270 /* config files may not be nested (silently ignore them) */
2271 if( !configfp ) {
2272 xfree(configname);
2273 configname = xstrdup(pargs.r.ret_str);
2274 goto next_pass;
2276 break;
2277 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2278 case oNoDefKeyring: default_keyring = 0; break;
2279 case oNoGreeting: nogreeting = 1; break;
2280 case oNoVerbose:
2281 opt.verbose = 0;
2282 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2283 opt.list_sigs=0;
2284 break;
2285 case oQuickRandom:
2286 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2287 break;
2288 case oEmitVersion: opt.no_version=0; break;
2289 case oNoEmitVersion: opt.no_version=1; break;
2290 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2291 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2292 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2293 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2294 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2295 case oDefRecipient:
2296 if( *pargs.r.ret_str )
2297 opt.def_recipient = make_username(pargs.r.ret_str);
2298 break;
2299 case oDefRecipientSelf:
2300 xfree(opt.def_recipient); opt.def_recipient = NULL;
2301 opt.def_recipient_self = 1;
2302 break;
2303 case oNoDefRecipient:
2304 xfree(opt.def_recipient); opt.def_recipient = NULL;
2305 opt.def_recipient_self = 0;
2306 break;
2307 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2308 case oHomedir: break;
2309 case oNoBatch: opt.batch = 0; break;
2311 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2312 case oWithColons: opt.with_colons=':'; break;
2314 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2315 case oWithSigList: opt.list_sigs = 1; break;
2317 case oSkipVerify: opt.skip_verify=1; break;
2318 case oCompressKeys: opt.compress_keys = 1; break;
2319 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2320 /* There are many programs (like mutt) that call gpg with
2321 --always-trust so keep this option around for a long
2322 time. */
2323 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2324 case oTrustModel:
2325 parse_trust_model(pargs.r.ret_str);
2326 break;
2327 case oForceOwnertrust:
2328 log_info(_("NOTE: %s is not for normal use!\n"),
2329 "--force-ownertrust");
2330 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2331 if(opt.force_ownertrust==-1)
2333 log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
2334 opt.force_ownertrust=0;
2336 break;
2337 case oLoadExtension:
2338 /* Dummy so that gpg 1.4 conf files can work. Should
2339 eventually be removed. */
2340 break;
2341 case oRFC1991:
2342 opt.compliance = CO_RFC1991;
2343 opt.force_v4_certs = 0;
2344 opt.escape_from = 1;
2345 break;
2346 case oOpenPGP:
2347 case oRFC4880:
2348 /* This is effectively the same as RFC2440, but with
2349 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2350 --require-cross-certification". */
2351 opt.compliance = CO_RFC4880;
2352 opt.flags.dsa2 = 1;
2353 opt.flags.require_cross_cert = 1;
2354 opt.rfc2440_text = 0;
2355 opt.allow_non_selfsigned_uid = 1;
2356 opt.allow_freeform_uid = 1;
2357 opt.pgp2_workarounds = 0;
2358 opt.escape_from = 1;
2359 opt.force_v3_sigs = 0;
2360 opt.compress_keys = 0; /* not mandated, but we do it */
2361 opt.compress_sigs = 0; /* ditto. */
2362 opt.not_dash_escaped = 0;
2363 opt.def_cipher_algo = 0;
2364 opt.def_digest_algo = 0;
2365 opt.cert_digest_algo = 0;
2366 opt.compress_algo = -1;
2367 opt.s2k_mode = 3; /* iterated+salted */
2368 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2369 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2370 break;
2371 case oRFC2440:
2372 opt.compliance = CO_RFC2440;
2373 opt.flags.dsa2 = 0;
2374 opt.rfc2440_text = 1;
2375 opt.allow_non_selfsigned_uid = 1;
2376 opt.allow_freeform_uid = 1;
2377 opt.pgp2_workarounds = 0;
2378 opt.escape_from = 0;
2379 opt.force_v3_sigs = 0;
2380 opt.compress_keys = 0; /* not mandated, but we do it */
2381 opt.compress_sigs = 0; /* ditto. */
2382 opt.not_dash_escaped = 0;
2383 opt.def_cipher_algo = 0;
2384 opt.def_digest_algo = 0;
2385 opt.cert_digest_algo = 0;
2386 opt.compress_algo = -1;
2387 opt.s2k_mode = 3; /* iterated+salted */
2388 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2389 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2390 break;
2391 case oPGP2: opt.compliance = CO_PGP2; break;
2392 case oPGP6: opt.compliance = CO_PGP6; break;
2393 case oPGP7: opt.compliance = CO_PGP7; break;
2394 case oPGP8: opt.compliance = CO_PGP8; break;
2395 case oGnuPG: opt.compliance = CO_GNUPG; break;
2396 case oCompressSigs: opt.compress_sigs = 1; break;
2397 case oRFC2440Text: opt.rfc2440_text=1; break;
2398 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2399 case oSetFilename:
2400 if(utf8_strings)
2401 opt.set_filename = pargs.r.ret_str;
2402 else
2403 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2404 break;
2405 case oForYourEyesOnly: eyes_only = 1; break;
2406 case oNoForYourEyesOnly: eyes_only = 0; break;
2407 case oSetPolicyURL:
2408 add_policy_url(pargs.r.ret_str,0);
2409 add_policy_url(pargs.r.ret_str,1);
2410 break;
2411 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2412 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2413 case oShowPolicyURL:
2414 deprecated_warning(configname,configlineno,"--show-policy-url",
2415 "--list-options ","show-policy-urls");
2416 deprecated_warning(configname,configlineno,"--show-policy-url",
2417 "--verify-options ","show-policy-urls");
2418 opt.list_options|=LIST_SHOW_POLICY_URLS;
2419 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2420 break;
2421 case oNoShowPolicyURL:
2422 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2423 "--list-options ","no-show-policy-urls");
2424 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2425 "--verify-options ","no-show-policy-urls");
2426 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2427 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2428 break;
2429 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2430 case oUseEmbeddedFilename:
2431 opt.flags.use_embedded_filename=1;
2432 break;
2433 case oNoUseEmbeddedFilename:
2434 opt.flags.use_embedded_filename=0;
2435 break;
2436 case oComment:
2437 if(pargs.r.ret_str[0])
2438 append_to_strlist(&opt.comments,pargs.r.ret_str);
2439 break;
2440 case oDefaultComment:
2441 deprecated_warning(configname,configlineno,
2442 "--default-comment","--no-comments","");
2443 /* fall through */
2444 case oNoComments:
2445 free_strlist(opt.comments);
2446 opt.comments=NULL;
2447 break;
2448 case oThrowKeyids: opt.throw_keyid = 1; break;
2449 case oNoThrowKeyids: opt.throw_keyid = 0; break;
2450 case oShowPhotos:
2451 deprecated_warning(configname,configlineno,"--show-photos",
2452 "--list-options ","show-photos");
2453 deprecated_warning(configname,configlineno,"--show-photos",
2454 "--verify-options ","show-photos");
2455 opt.list_options|=LIST_SHOW_PHOTOS;
2456 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2457 break;
2458 case oNoShowPhotos:
2459 deprecated_warning(configname,configlineno,"--no-show-photos",
2460 "--list-options ","no-show-photos");
2461 deprecated_warning(configname,configlineno,"--no-show-photos",
2462 "--verify-options ","no-show-photos");
2463 opt.list_options&=~LIST_SHOW_PHOTOS;
2464 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2465 break;
2466 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2467 case oForceV3Sigs: opt.force_v3_sigs = 1; break;
2468 case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
2469 case oForceV4Certs: opt.force_v4_certs = 1; break;
2470 case oNoForceV4Certs: opt.force_v4_certs = 0; break;
2471 case oForceMDC: opt.force_mdc = 1; break;
2472 case oNoForceMDC: opt.force_mdc = 0; break;
2473 case oDisableMDC: opt.disable_mdc = 1; break;
2474 case oNoDisableMDC: opt.disable_mdc = 0; break;
2475 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2476 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2477 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2478 case oS2KCount:
2479 opt.s2k_count=encode_s2k_iterations(pargs.r.ret_int);
2480 break;
2481 case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
2482 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2483 case oEncryptTo: /* store the recipient in the second list */
2484 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2485 sl->flags = 1;
2486 break;
2487 case oHiddenEncryptTo: /* store the recipient in the second list */
2488 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2489 sl->flags = 1|2;
2490 break;
2491 case oRecipient: /* store the recipient */
2492 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2493 any_explicit_recipient = 1;
2494 break;
2495 case oHiddenRecipient: /* store the recipient with a flag */
2496 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2497 sl->flags = 2;
2498 any_explicit_recipient = 1;
2499 break;
2500 case oTextmodeShort: opt.textmode = 2; break;
2501 case oTextmode: opt.textmode=1; break;
2502 case oNoTextmode: opt.textmode=0; break;
2503 case oExpert: opt.expert = 1; break;
2504 case oNoExpert: opt.expert = 0; break;
2505 case oDefSigExpire:
2506 if(*pargs.r.ret_str!='\0')
2508 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2509 log_error(_("`%s' is not a valid signature expiration\n"),
2510 pargs.r.ret_str);
2511 else
2512 opt.def_sig_expire=pargs.r.ret_str;
2514 break;
2515 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2516 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2517 case oDefCertExpire:
2518 if(*pargs.r.ret_str!='\0')
2520 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2521 log_error(_("`%s' is not a valid signature expiration\n"),
2522 pargs.r.ret_str);
2523 else
2524 opt.def_cert_expire=pargs.r.ret_str;
2526 break;
2527 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2528 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2529 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2530 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2531 case oAskCertLevel: opt.ask_cert_level = 1; break;
2532 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2533 case oLocalUser: /* store the local users */
2534 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2535 break;
2536 case oCompress:
2537 /* this is the -z command line option */
2538 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2539 break;
2540 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2541 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2542 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2543 case oPasswd:
2544 set_passphrase_from_string(pargs.r.ret_str);
2545 break;
2546 case oPasswdFD:
2547 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2548 break;
2549 case oPasswdFile:
2550 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
2551 break;
2552 case oPasswdRepeat: opt.passwd_repeat=pargs.r.ret_int; break;
2553 case oCommandFD:
2554 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2555 break;
2556 case oCommandFile:
2557 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
2558 break;
2559 case oCipherAlgo:
2560 def_cipher_string = xstrdup(pargs.r.ret_str);
2561 break;
2562 case oDigestAlgo:
2563 def_digest_string = xstrdup(pargs.r.ret_str);
2564 break;
2565 case oCompressAlgo:
2566 /* If it is all digits, stick a Z in front of it for
2567 later. This is for backwards compatibility with
2568 versions that took the compress algorithm number. */
2570 char *pt=pargs.r.ret_str;
2571 while(*pt)
2573 if (!isascii (*pt) || !isdigit (*pt))
2574 break;
2576 pt++;
2579 if(*pt=='\0')
2581 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2582 strcpy(compress_algo_string,"Z");
2583 strcat(compress_algo_string,pargs.r.ret_str);
2585 else
2586 compress_algo_string = xstrdup(pargs.r.ret_str);
2588 break;
2589 case oCertDigestAlgo:
2590 cert_digest_string = xstrdup(pargs.r.ret_str);
2591 break;
2593 case oNoSecmemWarn:
2594 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
2595 break;
2597 case oRequireSecmem: require_secmem=1; break;
2598 case oNoRequireSecmem: require_secmem=0; break;
2599 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2600 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2601 case oDisplayCharset:
2602 if( set_native_charset( pargs.r.ret_str ) )
2603 log_error(_("`%s' is not a valid character set\n"),
2604 pargs.r.ret_str);
2605 break;
2606 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2607 case oEscapeFrom: opt.escape_from = 1; break;
2608 case oNoEscapeFrom: opt.escape_from = 0; break;
2609 case oLockOnce: opt.lock_once = 1; break;
2610 case oLockNever:
2611 disable_dotlock ();
2612 break;
2613 case oLockMultiple:
2614 #ifndef __riscos__
2615 opt.lock_once = 0;
2616 #else /* __riscos__ */
2617 riscos_not_implemented("lock-multiple");
2618 #endif /* __riscos__ */
2619 break;
2620 case oKeyServer:
2622 struct keyserver_spec *keyserver;
2623 keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
2624 configname,configlineno);
2625 if(!keyserver)
2626 log_error(_("could not parse keyserver URL\n"));
2627 else
2629 keyserver->next=opt.keyserver;
2630 opt.keyserver=keyserver;
2633 break;
2634 case oKeyServerOptions:
2635 if(!parse_keyserver_options(pargs.r.ret_str))
2637 if(configname)
2638 log_error(_("%s:%d: invalid keyserver options\n"),
2639 configname,configlineno);
2640 else
2641 log_error(_("invalid keyserver options\n"));
2643 break;
2644 case oImportOptions:
2645 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2647 if(configname)
2648 log_error(_("%s:%d: invalid import options\n"),
2649 configname,configlineno);
2650 else
2651 log_error(_("invalid import options\n"));
2653 break;
2654 case oExportOptions:
2655 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2657 if(configname)
2658 log_error(_("%s:%d: invalid export options\n"),
2659 configname,configlineno);
2660 else
2661 log_error(_("invalid export options\n"));
2663 break;
2664 case oListOptions:
2665 if(!parse_list_options(pargs.r.ret_str))
2667 if(configname)
2668 log_error(_("%s:%d: invalid list options\n"),
2669 configname,configlineno);
2670 else
2671 log_error(_("invalid list options\n"));
2673 break;
2674 case oVerifyOptions:
2676 struct parse_options vopts[]=
2678 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2679 N_("display photo IDs during signature verification")},
2680 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2681 N_("show policy URLs during signature verification")},
2682 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2683 N_("show all notations during signature verification")},
2684 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2685 N_("show IETF standard notations during signature verification")},
2686 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2687 NULL},
2688 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2689 N_("show user-supplied notations during signature verification")},
2690 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2691 N_("show preferred keyserver URLs during signature verification")},
2692 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2693 N_("show user ID validity during signature verification")},
2694 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2695 N_("show revoked and expired user IDs in signature verification")},
2696 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
2697 N_("show only the primary user ID in signature verification")},
2698 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2699 N_("validate signatures with PKA data")},
2700 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2701 N_("elevate the trust of signatures with valid PKA data")},
2702 {NULL,0,NULL,NULL}
2705 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2707 if(configname)
2708 log_error(_("%s:%d: invalid verify options\n"),
2709 configname,configlineno);
2710 else
2711 log_error(_("invalid verify options\n"));
2714 break;
2715 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2716 case oExecPath:
2717 if(set_exec_path(pargs.r.ret_str))
2718 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2719 else
2720 opt.exec_path_set=1;
2721 break;
2722 case oSetNotation:
2723 add_notation_data( pargs.r.ret_str, 0 );
2724 add_notation_data( pargs.r.ret_str, 1 );
2725 break;
2726 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2727 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2728 case oShowNotation:
2729 deprecated_warning(configname,configlineno,"--show-notation",
2730 "--list-options ","show-notations");
2731 deprecated_warning(configname,configlineno,"--show-notation",
2732 "--verify-options ","show-notations");
2733 opt.list_options|=LIST_SHOW_NOTATIONS;
2734 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2735 break;
2736 case oNoShowNotation:
2737 deprecated_warning(configname,configlineno,"--no-show-notation",
2738 "--list-options ","no-show-notations");
2739 deprecated_warning(configname,configlineno,"--no-show-notation",
2740 "--verify-options ","no-show-notations");
2741 opt.list_options&=~LIST_SHOW_NOTATIONS;
2742 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2743 break;
2744 case oUtf8Strings: utf8_strings = 1; break;
2745 case oNoUtf8Strings: utf8_strings = 0; break;
2746 case oDisableCipherAlgo:
2748 int algo = string_to_cipher_algo (pargs.r.ret_str);
2749 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2751 break;
2752 case oDisablePubkeyAlgo:
2754 int algo = gcry_pk_map_name (pargs.r.ret_str);
2755 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2757 break;
2758 case oNoSigCache: opt.no_sig_cache = 1; break;
2759 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2760 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2761 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2762 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2763 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2764 case oNoLiteral: opt.no_literal = 1; break;
2765 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2766 case oHonorHttpProxy:
2767 add_to_strlist(&opt.keyserver_options.other,"http-proxy");
2768 deprecated_warning(configname,configlineno,
2769 "--honor-http-proxy",
2770 "--keyserver-options ","http-proxy");
2771 break;
2772 case oFastListMode: opt.fast_list_mode = 1; break;
2773 case oFixedListMode: /* Dummy */ break;
2774 case oListOnly: opt.list_only=1; break;
2775 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2776 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2777 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2778 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2779 case oNoRandomSeedFile: use_random_seed = 0; break;
2780 case oAutoKeyRetrieve:
2781 case oNoAutoKeyRetrieve:
2782 if(pargs.r_opt==oAutoKeyRetrieve)
2783 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
2784 else
2785 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
2787 deprecated_warning(configname,configlineno,
2788 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
2789 "--no-auto-key-retrieve","--keyserver-options ",
2790 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
2791 "no-auto-key-retrieve");
2792 break;
2793 case oShowSessionKey: opt.show_session_key = 1; break;
2794 case oOverrideSessionKey:
2795 opt.override_session_key = pargs.r.ret_str;
2796 break;
2797 case oMergeOnly:
2798 deprecated_warning(configname,configlineno,"--merge-only",
2799 "--import-options ","merge-only");
2800 opt.import_options|=IMPORT_MERGE_ONLY;
2801 break;
2802 case oAllowSecretKeyImport: /* obsolete */ break;
2803 case oTryAllSecrets: opt.try_all_secrets = 1; break;
2804 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
2805 case oEnableSpecialFilenames:
2806 iobuf_enable_special_filenames (1);
2807 break;
2808 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
2809 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
2810 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
2811 case oPreservePermissions: opt.preserve_permissions=1; break;
2812 case oDefaultPreferenceList:
2813 opt.def_preference_list = pargs.r.ret_str;
2814 break;
2815 case oDefaultKeyserverURL:
2817 struct keyserver_spec *keyserver;
2818 keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
2819 configname,configlineno);
2820 if(!keyserver)
2821 log_error(_("could not parse keyserver URL\n"));
2822 else
2823 free_keyserver_spec(keyserver);
2825 opt.def_keyserver_url = pargs.r.ret_str;
2827 break;
2828 case oPersonalCipherPreferences:
2829 pers_cipher_list=pargs.r.ret_str;
2830 break;
2831 case oPersonalDigestPreferences:
2832 pers_digest_list=pargs.r.ret_str;
2833 break;
2834 case oPersonalCompressPreferences:
2835 pers_compress_list=pargs.r.ret_str;
2836 break;
2837 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
2839 case oDisplay:
2840 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
2841 break;
2842 case oTTYname:
2843 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
2844 break;
2845 case oTTYtype:
2846 set_opt_session_env ("TERM", pargs.r.ret_str);
2847 break;
2848 case oXauthority:
2849 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
2850 break;
2852 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
2853 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
2855 case oGroup: add_group(pargs.r.ret_str); break;
2856 case oUnGroup: rm_group(pargs.r.ret_str); break;
2857 case oNoGroups:
2858 while(opt.grouplist)
2860 struct groupitem *iter=opt.grouplist;
2861 free_strlist(iter->values);
2862 opt.grouplist=opt.grouplist->next;
2863 xfree(iter);
2865 break;
2867 case oStrict:
2868 case oNoStrict:
2869 /* Not used */
2870 break;
2872 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
2873 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
2874 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
2875 case oMultifile: multifile=1; break;
2876 case oKeyidFormat:
2877 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
2878 opt.keyid_format=KF_SHORT;
2879 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
2880 opt.keyid_format=KF_LONG;
2881 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
2882 opt.keyid_format=KF_0xSHORT;
2883 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
2884 opt.keyid_format=KF_0xLONG;
2885 else
2886 log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
2887 break;
2889 case oExitOnStatusWriteError:
2890 opt.exit_on_status_write_error = 1;
2891 break;
2893 case oLimitCardInsertTries:
2894 opt.limit_card_insert_tries = pargs.r.ret_int;
2895 break;
2897 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
2898 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
2900 case oAutoKeyLocate:
2901 if(!parse_auto_key_locate(pargs.r.ret_str))
2903 if(configname)
2904 log_error(_("%s:%d: invalid auto-key-locate list\n"),
2905 configname,configlineno);
2906 else
2907 log_error(_("invalid auto-key-locate list\n"));
2909 break;
2910 case oNoAutoKeyLocate:
2911 release_akl();
2912 break;
2914 case oEnableDSA2: opt.flags.dsa2=1; break;
2915 case oDisableDSA2: opt.flags.dsa2=0; break;
2917 case oAllowMultisigVerification:
2918 case oAllowMultipleMessages:
2919 opt.flags.allow_multiple_messages=1;
2920 break;
2922 case oNoAllowMultipleMessages:
2923 opt.flags.allow_multiple_messages=0;
2924 break;
2926 case oNoop: break;
2928 default:
2929 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
2930 break;
2935 if( configfp ) {
2936 fclose( configfp );
2937 configfp = NULL;
2938 /* Remember the first config file name. */
2939 if (!save_configname)
2940 save_configname = configname;
2941 else
2942 xfree(configname);
2943 configname = NULL;
2944 goto next_pass;
2946 xfree( configname ); configname = NULL;
2947 if( log_get_errorcount(0) )
2948 g10_exit(2);
2950 /* The command --gpgconf-list is pretty simple and may be called
2951 directly after the option parsing. */
2952 if (cmd == aGPGConfList)
2954 gpgconf_list (save_configname ? save_configname : default_configname);
2955 g10_exit (0);
2957 xfree (save_configname);
2958 xfree (default_configname);
2960 if( nogreeting )
2961 greeting = 0;
2963 if( greeting ) {
2964 fprintf(stderr, "%s %s; %s\n",
2965 strusage(11), strusage(13), strusage(14) );
2966 fprintf(stderr, "%s\n", strusage(15) );
2968 #ifdef IS_DEVELOPMENT_VERSION
2969 if (!opt.batch)
2971 const char *s;
2973 if((s=strusage(25)))
2974 log_info("%s\n",s);
2975 if((s=strusage(26)))
2976 log_info("%s\n",s);
2977 if((s=strusage(27)))
2978 log_info("%s\n",s);
2980 #endif
2982 /* FIXME: We should use logging to a file only in server mode;
2983 however we have not yet implemetyed that. Thus we try to get
2984 away with --batch as indication for logging to file
2985 required. */
2986 if (logfile && opt.batch)
2988 log_set_file (logfile);
2989 log_set_prefix (NULL, 1|2|4);
2992 /* Older Libgcrypts fail with an assertion during DSA key
2993 generation. Better disable DSA2 entirely. */
2994 if (opt.flags.dsa2 && !gcry_check_version ("1.4.0") )
2996 log_info ("WARNING: "
2997 "DSA2 is only available with Libgcrypt 1.4 and later\n");
2998 opt.flags.dsa2 = 0;
3001 if (opt.verbose > 2)
3002 log_info ("using character set `%s'\n", get_native_charset ());
3004 if( may_coredump && !opt.quiet )
3005 log_info(_("WARNING: program may create a core file!\n"));
3007 if (eyes_only) {
3008 if (opt.set_filename)
3009 log_info(_("WARNING: %s overrides %s\n"),
3010 "--for-your-eyes-only","--set-filename");
3012 opt.set_filename="_CONSOLE";
3015 if (opt.no_literal) {
3016 log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
3017 if (opt.textmode)
3018 log_error(_("%s not allowed with %s!\n"),
3019 "--textmode", "--no-literal" );
3020 if (opt.set_filename)
3021 log_error(_("%s makes no sense with %s!\n"),
3022 eyes_only?"--for-your-eyes-only":"--set-filename",
3023 "--no-literal" );
3027 if (opt.set_filesize)
3028 log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
3029 if( opt.batch )
3030 tty_batchmode( 1 );
3032 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3034 if(require_secmem && !got_secmem)
3036 log_info(_("will not run with insecure memory due to %s\n"),
3037 "--require-secmem");
3038 g10_exit(2);
3041 set_debug (debug_level);
3043 /* Do these after the switch(), so they can override settings. */
3044 if(PGP2)
3046 int unusable=0;
3048 if(cmd==aSign && !detached_sig)
3050 log_info(_("you can only make detached or clear signatures "
3051 "while in --pgp2 mode\n"));
3052 unusable=1;
3054 else if(cmd==aSignEncr || cmd==aSignSym)
3056 log_info(_("you can't sign and encrypt at the "
3057 "same time while in --pgp2 mode\n"));
3058 unusable=1;
3060 else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
3062 log_info(_("you must use files (and not a pipe) when "
3063 "working with --pgp2 enabled.\n"));
3064 unusable=1;
3066 else if(cmd==aEncr || cmd==aSym)
3068 /* Everything else should work without IDEA (except using
3069 a secret key encrypted with IDEA and setting an IDEA
3070 preference, but those have their own error
3071 messages). */
3073 if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
3075 log_info(_("encrypting a message in --pgp2 mode requires "
3076 "the IDEA cipher\n"));
3077 idea_cipher_warn(1);
3078 unusable=1;
3080 else if(cmd==aSym)
3082 /* This only sets IDEA for symmetric encryption
3083 since it is set via select_algo_from_prefs for
3084 pk encryption. */
3085 xfree(def_cipher_string);
3086 def_cipher_string = xstrdup("idea");
3089 /* PGP2 can't handle the output from the textmode
3090 filter, so we disable it for anything that could
3091 create a literal packet (only encryption and
3092 symmetric encryption, since we disable signing
3093 above). */
3094 if(!unusable)
3095 opt.textmode=0;
3098 if(unusable)
3099 compliance_failure();
3100 else
3102 opt.force_v4_certs = 0;
3103 opt.escape_from = 1;
3104 opt.force_v3_sigs = 1;
3105 opt.pgp2_workarounds = 1;
3106 opt.ask_sig_expire = 0;
3107 opt.ask_cert_expire = 0;
3108 xfree(def_digest_string);
3109 def_digest_string = xstrdup("md5");
3110 xfree(s2k_digest_string);
3111 s2k_digest_string = xstrdup("md5");
3112 opt.compress_algo = COMPRESS_ALGO_ZIP;
3115 else if(PGP6)
3117 opt.disable_mdc=1;
3118 opt.escape_from=1;
3119 opt.force_v3_sigs=1;
3120 opt.ask_sig_expire=0;
3122 else if(PGP7)
3124 opt.escape_from=1;
3125 opt.force_v3_sigs=1;
3126 opt.ask_sig_expire=0;
3128 else if(PGP8)
3130 opt.escape_from=1;
3134 if( def_cipher_string ) {
3135 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3136 if(opt.def_cipher_algo==0 &&
3137 (ascii_strcasecmp(def_cipher_string,"idea")==0
3138 || ascii_strcasecmp(def_cipher_string,"s1")==0))
3139 idea_cipher_warn(1);
3140 xfree(def_cipher_string); def_cipher_string = NULL;
3141 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3142 log_error(_("selected cipher algorithm is invalid\n"));
3144 if( def_digest_string ) {
3145 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3146 xfree(def_digest_string); def_digest_string = NULL;
3147 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3148 log_error(_("selected digest algorithm is invalid\n"));
3150 if( compress_algo_string ) {
3151 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3152 xfree(compress_algo_string); compress_algo_string = NULL;
3153 if( check_compress_algo(opt.compress_algo) )
3154 log_error(_("selected compression algorithm is invalid\n"));
3156 if( cert_digest_string ) {
3157 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3158 xfree(cert_digest_string); cert_digest_string = NULL;
3159 if (openpgp_md_test_algo(opt.cert_digest_algo))
3160 log_error(_("selected certification digest algorithm is invalid\n"));
3162 if( s2k_cipher_string ) {
3163 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3164 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3165 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3166 log_error(_("selected cipher algorithm is invalid\n"));
3168 if( s2k_digest_string ) {
3169 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3170 xfree(s2k_digest_string); s2k_digest_string = NULL;
3171 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3172 log_error(_("selected digest algorithm is invalid\n"));
3174 if( opt.completes_needed < 1 )
3175 log_error(_("completes-needed must be greater than 0\n"));
3176 if( opt.marginals_needed < 2 )
3177 log_error(_("marginals-needed must be greater than 1\n"));
3178 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3179 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3180 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3181 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3182 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3183 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3184 switch( opt.s2k_mode ) {
3185 case 0:
3186 log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
3187 break;
3188 case 1: case 3: break;
3189 default:
3190 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3193 /* This isn't actually needed, but does serve to error out if the
3194 string is invalid. */
3195 if(opt.def_preference_list &&
3196 keygen_set_std_prefs(opt.def_preference_list,0))
3197 log_error(_("invalid default preferences\n"));
3199 if(pers_cipher_list &&
3200 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3201 log_error(_("invalid personal cipher preferences\n"));
3203 if(pers_digest_list &&
3204 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3205 log_error(_("invalid personal digest preferences\n"));
3207 if(pers_compress_list &&
3208 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3209 log_error(_("invalid personal compress preferences\n"));
3211 /* We don't support all possible commands with multifile yet */
3212 if(multifile)
3214 char *cmdname;
3216 switch(cmd)
3218 case aSign:
3219 cmdname="--sign";
3220 break;
3221 case aClearsign:
3222 cmdname="--clearsign";
3223 break;
3224 case aDetachedSign:
3225 cmdname="--detach-sign";
3226 break;
3227 case aSym:
3228 cmdname="--symmetric";
3229 break;
3230 case aEncrSym:
3231 cmdname="--symmetric --encrypt";
3232 break;
3233 case aStore:
3234 cmdname="--store";
3235 break;
3236 default:
3237 cmdname=NULL;
3238 break;
3241 if(cmdname)
3242 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3245 if( log_get_errorcount(0) )
3246 g10_exit(2);
3248 if(opt.compress_level==0)
3249 opt.compress_algo=COMPRESS_ALGO_NONE;
3251 /* Check our chosen algorithms against the list of legal
3252 algorithms. */
3254 if(!GNUPG)
3256 const char *badalg=NULL;
3257 preftype_t badtype=PREFTYPE_NONE;
3259 if(opt.def_cipher_algo
3260 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3262 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3263 badtype = PREFTYPE_SYM;
3265 else if(opt.def_digest_algo
3266 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3268 badalg = gcry_md_algo_name (opt.def_digest_algo);
3269 badtype = PREFTYPE_HASH;
3271 else if(opt.cert_digest_algo
3272 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3274 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3275 badtype = PREFTYPE_HASH;
3277 else if(opt.compress_algo!=-1
3278 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3280 badalg = compress_algo_to_string(opt.compress_algo);
3281 badtype = PREFTYPE_ZIP;
3284 if(badalg)
3286 switch(badtype)
3288 case PREFTYPE_SYM:
3289 log_info(_("you may not use cipher algorithm `%s'"
3290 " while in %s mode\n"),
3291 badalg,compliance_option_string());
3292 break;
3293 case PREFTYPE_HASH:
3294 log_info(_("you may not use digest algorithm `%s'"
3295 " while in %s mode\n"),
3296 badalg,compliance_option_string());
3297 break;
3298 case PREFTYPE_ZIP:
3299 log_info(_("you may not use compression algorithm `%s'"
3300 " while in %s mode\n"),
3301 badalg,compliance_option_string());
3302 break;
3303 default:
3304 BUG();
3307 compliance_failure();
3311 /* Set the random seed file. */
3312 if( use_random_seed ) {
3313 char *p = make_filename(opt.homedir, "random_seed", NULL );
3314 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3315 if (!access (p, F_OK))
3316 register_secured_file (p);
3317 xfree(p);
3320 /* If there is no command but the --fingerprint is given, default
3321 to the --list-keys command. */
3322 if (!cmd && fpr_maybe_cmd)
3324 set_cmd (&cmd, aListKeys);
3328 if( opt.verbose > 1 )
3329 set_packet_list_mode(1);
3331 /* Add the keyrings, but not for some special commands. Also
3332 avoid adding the secret keyring for a couple of commands to
3333 avoid unneeded access in case the secrings are stored on a
3334 floppy.
3336 We always need to add the keyrings if we are running under
3337 SELinux, this is so that the rings are added to the list of
3338 secured files. */
3339 if( ALWAYS_ADD_KEYRINGS
3340 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) )
3342 if (ALWAYS_ADD_KEYRINGS
3343 || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
3344 && cmd != aVerify && cmd != aSym && cmd != aLocateKeys))
3346 if (!sec_nrings || default_keyring) /* add default secret rings */
3347 keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
3348 for (sl = sec_nrings; sl; sl = sl->next)
3349 keydb_add_resource ( sl->d, 0, 1 );
3351 if( !nrings || default_keyring ) /* add default ring */
3352 keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
3353 for(sl = nrings; sl; sl = sl->next )
3354 keydb_add_resource ( sl->d, sl->flags, 0 );
3356 FREE_STRLIST(nrings);
3357 FREE_STRLIST(sec_nrings);
3359 if (cmd == aGPGConfTest)
3360 g10_exit(0);
3363 if( pwfd != -1 ) /* Read the passphrase now. */
3364 read_passphrase_from_fd( pwfd );
3366 fname = argc? *argv : NULL;
3368 if(fname && utf8_strings)
3369 opt.flags.utf8_filename=1;
3371 switch( cmd ) {
3372 case aPrimegen:
3373 case aPrintMD:
3374 case aPrintMDs:
3375 case aGenRandom:
3376 case aDeArmor:
3377 case aEnArmor:
3378 break;
3379 case aFixTrustDB:
3380 case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
3381 case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
3382 default: rc = setup_trustdb(1, trustdb_name ); break;
3384 if( rc )
3385 log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
3388 switch (cmd)
3390 case aStore:
3391 case aSym:
3392 case aSign:
3393 case aSignSym:
3394 case aClearsign:
3395 if (!opt.quiet && any_explicit_recipient)
3396 log_info (_("WARNING: recipients (-r) given "
3397 "without using public key encryption\n"));
3398 break;
3399 default:
3400 break;
3403 switch( cmd )
3405 case aServer:
3407 ctrl_t ctrl = xtrycalloc (1, sizeof *ctrl);
3408 gpg_init_default_ctrl (ctrl);
3409 gpg_server (ctrl);
3410 gpg_deinit_default_ctrl (ctrl);
3411 xfree (ctrl);
3413 break;
3415 case aStore: /* only store the file */
3416 if( argc > 1 )
3417 wrong_args(_("--store [filename]"));
3418 if( (rc = encrypt_store(fname)) )
3419 log_error ("storing `%s' failed: %s\n",
3420 print_fname_stdin(fname),g10_errstr(rc) );
3421 break;
3422 case aSym: /* encrypt the given file only with the symmetric cipher */
3423 if( argc > 1 )
3424 wrong_args(_("--symmetric [filename]"));
3425 if( (rc = encrypt_symmetric(fname)) )
3426 log_error (_("symmetric encryption of `%s' failed: %s\n"),
3427 print_fname_stdin(fname),g10_errstr(rc) );
3428 break;
3430 case aEncr: /* encrypt the given file */
3431 if(multifile)
3432 encrypt_crypt_files(argc, argv, remusr);
3433 else
3435 if( argc > 1 )
3436 wrong_args(_("--encrypt [filename]"));
3437 if( (rc = encrypt_crypt (-1, fname, remusr, 0, NULL, -1)) )
3438 log_error("%s: encryption failed: %s\n",
3439 print_fname_stdin(fname), g10_errstr(rc) );
3441 break;
3443 case aEncrSym:
3444 /* This works with PGP 8 in the sense that it acts just like a
3445 symmetric message. It doesn't work at all with 2 or 6. It
3446 might work with 7, but alas, I don't have a copy to test
3447 with right now. */
3448 if( argc > 1 )
3449 wrong_args(_("--symmetric --encrypt [filename]"));
3450 else if(opt.s2k_mode==0)
3451 log_error(_("you cannot use --symmetric --encrypt"
3452 " with --s2k-mode 0\n"));
3453 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3454 log_error(_("you cannot use --symmetric --encrypt"
3455 " while in %s mode\n"),compliance_option_string());
3456 else
3458 if( (rc = encrypt_crypt (-1, fname, remusr, 1, NULL, -1)) )
3459 log_error("%s: encryption failed: %s\n",
3460 print_fname_stdin(fname), g10_errstr(rc) );
3462 break;
3464 case aSign: /* sign the given file */
3465 sl = NULL;
3466 if( detached_sig ) { /* sign all files */
3467 for( ; argc; argc--, argv++ )
3468 add_to_strlist( &sl, *argv );
3470 else {
3471 if( argc > 1 )
3472 wrong_args(_("--sign [filename]"));
3473 if( argc ) {
3474 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3475 strcpy(sl->d, fname);
3478 if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
3479 log_error("signing failed: %s\n", g10_errstr(rc) );
3480 free_strlist(sl);
3481 break;
3483 case aSignEncr: /* sign and encrypt the given file */
3484 if( argc > 1 )
3485 wrong_args(_("--sign --encrypt [filename]"));
3486 if( argc ) {
3487 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3488 strcpy(sl->d, fname);
3490 else
3491 sl = NULL;
3492 if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
3493 log_error("%s: sign+encrypt failed: %s\n",
3494 print_fname_stdin(fname), g10_errstr(rc) );
3495 free_strlist(sl);
3496 break;
3498 case aSignEncrSym: /* sign and encrypt the given file */
3499 if( argc > 1 )
3500 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3501 else if(opt.s2k_mode==0)
3502 log_error(_("you cannot use --symmetric --sign --encrypt"
3503 " with --s2k-mode 0\n"));
3504 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3505 log_error(_("you cannot use --symmetric --sign --encrypt"
3506 " while in %s mode\n"),compliance_option_string());
3507 else
3509 if( argc )
3511 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3512 strcpy(sl->d, fname);
3514 else
3515 sl = NULL;
3516 if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
3517 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3518 print_fname_stdin(fname), g10_errstr(rc) );
3519 free_strlist(sl);
3521 break;
3523 case aSignSym: /* sign and conventionally encrypt the given file */
3524 if (argc > 1)
3525 wrong_args(_("--sign --symmetric [filename]"));
3526 rc = sign_symencrypt_file (fname, locusr);
3527 if (rc)
3528 log_error("%s: sign+symmetric failed: %s\n",
3529 print_fname_stdin(fname), g10_errstr(rc) );
3530 break;
3532 case aClearsign: /* make a clearsig */
3533 if( argc > 1 )
3534 wrong_args(_("--clearsign [filename]"));
3535 if( (rc = clearsign_file(fname, locusr, NULL)) )
3536 log_error("%s: clearsign failed: %s\n",
3537 print_fname_stdin(fname), g10_errstr(rc) );
3538 break;
3540 case aVerify:
3541 if(multifile)
3543 if( (rc = verify_files( argc, argv ) ))
3544 log_error("verify files failed: %s\n", g10_errstr(rc) );
3546 else
3548 if( (rc = verify_signatures( argc, argv ) ))
3549 log_error("verify signatures failed: %s\n", g10_errstr(rc) );
3551 break;
3553 case aDecrypt:
3554 if(multifile)
3555 decrypt_messages(argc, argv);
3556 else
3558 if( argc > 1 )
3559 wrong_args(_("--decrypt [filename]"));
3560 if( (rc = decrypt_message( fname ) ))
3561 log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
3563 break;
3565 case aSignKey:
3566 if( argc != 1 )
3567 wrong_args(_("--sign-key user-id"));
3568 /* fall through */
3569 case aLSignKey:
3570 if( argc != 1 )
3571 wrong_args(_("--lsign-key user-id"));
3572 /* fall through */
3574 sl=NULL;
3576 if(cmd==aSignKey)
3577 append_to_strlist(&sl,"sign");
3578 else if(cmd==aLSignKey)
3579 append_to_strlist(&sl,"lsign");
3580 else
3581 BUG();
3583 append_to_strlist( &sl, "save" );
3584 username = make_username( fname );
3585 keyedit_menu (username, locusr, sl, 0, 0 );
3586 xfree(username);
3587 free_strlist(sl);
3588 break;
3590 case aEditKey: /* Edit a key signature */
3591 if( !argc )
3592 wrong_args(_("--edit-key user-id [commands]"));
3593 username = make_username( fname );
3594 if( argc > 1 ) {
3595 sl = NULL;
3596 for( argc--, argv++ ; argc; argc--, argv++ )
3597 append_to_strlist( &sl, *argv );
3598 keyedit_menu( username, locusr, sl, 0, 1 );
3599 free_strlist(sl);
3601 else
3602 keyedit_menu(username, locusr, NULL, 0, 1 );
3603 xfree(username);
3604 break;
3606 case aDeleteKeys:
3607 case aDeleteSecretKeys:
3608 case aDeleteSecretAndPublicKeys:
3609 sl = NULL;
3610 /* I'm adding these in reverse order as add_to_strlist2
3611 reverses them again, and it's easier to understand in the
3612 proper order :) */
3613 for( ; argc; argc-- )
3614 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3615 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3616 free_strlist(sl);
3617 break;
3619 case aCheckKeys:
3620 opt.check_sigs = 1;
3621 case aListSigs:
3622 opt.list_sigs = 1;
3623 case aListKeys:
3624 sl = NULL;
3625 for( ; argc; argc--, argv++ )
3626 add_to_strlist2( &sl, *argv, utf8_strings );
3627 public_key_list( sl, 0 );
3628 free_strlist(sl);
3629 break;
3630 case aListSecretKeys:
3631 sl = NULL;
3632 for( ; argc; argc--, argv++ )
3633 add_to_strlist2( &sl, *argv, utf8_strings );
3634 secret_key_list( sl );
3635 free_strlist(sl);
3636 break;
3637 case aLocateKeys:
3638 sl = NULL;
3639 for (; argc; argc--, argv++)
3640 add_to_strlist2( &sl, *argv, utf8_strings );
3641 public_key_list (sl, 1);
3642 free_strlist (sl);
3643 break;
3645 case aKeygen: /* generate a key */
3646 if( opt.batch ) {
3647 if( argc > 1 )
3648 wrong_args("--gen-key [parameterfile]");
3649 generate_keypair( argc? *argv : NULL, NULL, NULL );
3651 else {
3652 if( argc )
3653 wrong_args("--gen-key");
3654 generate_keypair(NULL, NULL, NULL);
3656 break;
3658 case aFastImport:
3659 opt.import_options |= IMPORT_FAST;
3660 case aImport:
3661 import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
3662 break;
3664 /* TODO: There are a number of command that use this same
3665 "make strlist, call function, report error, free strlist"
3666 pattern. Join them together here and avoid all that
3667 duplicated code. */
3669 case aExport:
3670 case aSendKeys:
3671 case aRecvKeys:
3672 sl = NULL;
3673 for( ; argc; argc--, argv++ )
3674 append_to_strlist2( &sl, *argv, utf8_strings );
3675 if( cmd == aSendKeys )
3676 rc=keyserver_export( sl );
3677 else if( cmd == aRecvKeys )
3678 rc=keyserver_import( sl );
3679 else
3680 rc=export_pubkeys( sl, opt.export_options );
3681 if(rc)
3683 if(cmd==aSendKeys)
3684 log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
3685 else if(cmd==aRecvKeys)
3686 log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
3687 else
3688 log_error(_("key export failed: %s\n"),g10_errstr(rc));
3690 free_strlist(sl);
3691 break;
3693 case aSearchKeys:
3694 sl = NULL;
3695 for( ; argc; argc--, argv++ )
3696 append_to_strlist2( &sl, *argv, utf8_strings );
3697 rc=keyserver_search( sl );
3698 if(rc)
3699 log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
3700 free_strlist(sl);
3701 break;
3703 case aRefreshKeys:
3704 sl = NULL;
3705 for( ; argc; argc--, argv++ )
3706 append_to_strlist2( &sl, *argv, utf8_strings );
3707 rc=keyserver_refresh(sl);
3708 if(rc)
3709 log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
3710 free_strlist(sl);
3711 break;
3713 case aFetchKeys:
3714 sl = NULL;
3715 for( ; argc; argc--, argv++ )
3716 append_to_strlist2( &sl, *argv, utf8_strings );
3717 rc=keyserver_fetch(sl);
3718 if(rc)
3719 log_error("key fetch failed: %s\n",g10_errstr(rc));
3720 free_strlist(sl);
3721 break;
3723 case aExportSecret:
3724 sl = NULL;
3725 for( ; argc; argc--, argv++ )
3726 add_to_strlist2( &sl, *argv, utf8_strings );
3727 export_seckeys( sl );
3728 free_strlist(sl);
3729 break;
3731 case aExportSecretSub:
3732 sl = NULL;
3733 for( ; argc; argc--, argv++ )
3734 add_to_strlist2( &sl, *argv, utf8_strings );
3735 export_secsubkeys( sl );
3736 free_strlist(sl);
3737 break;
3739 case aGenRevoke:
3740 if( argc != 1 )
3741 wrong_args("--gen-revoke user-id");
3742 username = make_username(*argv);
3743 gen_revoke( username );
3744 xfree( username );
3745 break;
3747 case aDesigRevoke:
3748 if( argc != 1 )
3749 wrong_args("--desig-revoke user-id");
3750 username = make_username(*argv);
3751 gen_desig_revoke( username, locusr );
3752 xfree( username );
3753 break;
3755 case aDeArmor:
3756 if( argc > 1 )
3757 wrong_args("--dearmor [file]");
3758 rc = dearmor_file( argc? *argv: NULL );
3759 if( rc )
3760 log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
3761 break;
3763 case aEnArmor:
3764 if( argc > 1 )
3765 wrong_args("--enarmor [file]");
3766 rc = enarmor_file( argc? *argv: NULL );
3767 if( rc )
3768 log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
3769 break;
3772 case aPrimegen:
3773 #if 0 /*FIXME*/
3774 { int mode = argc < 2 ? 0 : atoi(*argv);
3776 if( mode == 1 && argc == 2 ) {
3777 mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
3779 else if( mode == 2 && argc == 3 ) {
3780 mpi_print( stdout, generate_elg_prime(
3781 0, atoi(argv[1]),
3782 atoi(argv[2]), NULL,NULL ), 1);
3784 else if( mode == 3 && argc == 3 ) {
3785 MPI *factors;
3786 mpi_print( stdout, generate_elg_prime(
3787 1, atoi(argv[1]),
3788 atoi(argv[2]), NULL,&factors ), 1);
3789 putchar('\n');
3790 mpi_print( stdout, factors[0], 1 ); /* print q */
3792 else if( mode == 4 && argc == 3 ) {
3793 MPI g = mpi_alloc(1);
3794 mpi_print( stdout, generate_elg_prime(
3795 0, atoi(argv[1]),
3796 atoi(argv[2]), g, NULL ), 1);
3797 putchar('\n');
3798 mpi_print( stdout, g, 1 );
3799 mpi_free(g);
3801 else
3802 wrong_args("--gen-prime mode bits [qbits] ");
3803 putchar('\n');
3805 #endif
3806 wrong_args("--gen-prime not yet supported ");
3807 break;
3809 case aGenRandom:
3811 int level = argc ? atoi(*argv):0;
3812 int count = argc > 1 ? atoi(argv[1]): 0;
3813 int endless = !count;
3815 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
3816 wrong_args("--gen-random 0|1|2 [count]");
3818 while( endless || count ) {
3819 byte *p;
3820 /* Wee need a multiple of 3, so that in case of
3821 armored output we get a correct string. No
3822 linefolding is done, as it is best to levae this to
3823 other tools */
3824 size_t n = !endless && count < 99? count : 99;
3826 p = gcry_random_bytes (n, level);
3827 #ifdef HAVE_DOSISH_SYSTEM
3828 setmode ( fileno(stdout), O_BINARY );
3829 #endif
3830 if (opt.armor) {
3831 char *tmp = make_radix64_string (p, n);
3832 fputs (tmp, stdout);
3833 xfree (tmp);
3834 if (n%3 == 1)
3835 putchar ('=');
3836 if (n%3)
3837 putchar ('=');
3838 } else {
3839 fwrite( p, n, 1, stdout );
3841 xfree(p);
3842 if( !endless )
3843 count -= n;
3845 if (opt.armor)
3846 putchar ('\n');
3848 break;
3850 case aPrintMD:
3851 if( argc < 1)
3852 wrong_args("--print-md algo [files]");
3854 int all_algos = (**argv=='*' && !(*argv)[1]);
3855 int algo = all_algos? 0 : gcry_md_map_name (*argv);
3857 if( !algo && !all_algos )
3858 log_error(_("invalid hash algorithm `%s'\n"), *argv );
3859 else {
3860 argc--; argv++;
3861 if( !argc )
3862 print_mds(NULL, algo);
3863 else {
3864 for(; argc; argc--, argv++ )
3865 print_mds(*argv, algo);
3869 break;
3871 case aPrintMDs: /* old option */
3872 if( !argc )
3873 print_mds(NULL,0);
3874 else {
3875 for(; argc; argc--, argv++ )
3876 print_mds(*argv,0);
3878 break;
3880 case aListTrustDB:
3881 if( !argc )
3882 list_trustdb(NULL);
3883 else {
3884 for( ; argc; argc--, argv++ )
3885 list_trustdb( *argv );
3887 break;
3889 case aUpdateTrustDB:
3890 if( argc )
3891 wrong_args("--update-trustdb");
3892 update_trustdb();
3893 break;
3895 case aCheckTrustDB:
3896 /* Old versions allowed for arguments - ignore them */
3897 check_trustdb();
3898 break;
3900 case aFixTrustDB:
3901 how_to_fix_the_trustdb ();
3902 break;
3904 case aListTrustPath:
3905 if( !argc )
3906 wrong_args("--list-trust-path <user-ids>");
3907 for( ; argc; argc--, argv++ ) {
3908 username = make_username( *argv );
3909 list_trust_path( username );
3910 xfree(username);
3912 break;
3914 case aExportOwnerTrust:
3915 if( argc )
3916 wrong_args("--export-ownertrust");
3917 export_ownertrust();
3918 break;
3920 case aImportOwnerTrust:
3921 if( argc > 1 )
3922 wrong_args("--import-ownertrust [file]");
3923 import_ownertrust( argc? *argv:NULL );
3924 break;
3926 case aRebuildKeydbCaches:
3927 if (argc)
3928 wrong_args ("--rebuild-keydb-caches");
3929 keydb_rebuild_caches (1);
3930 break;
3932 #ifdef ENABLE_CARD_SUPPORT
3933 case aCardStatus:
3934 if (argc)
3935 wrong_args ("--card-status");
3936 card_status (stdout, NULL, 0);
3937 break;
3939 case aCardEdit:
3940 if (argc) {
3941 sl = NULL;
3942 for (argc--, argv++ ; argc; argc--, argv++)
3943 append_to_strlist (&sl, *argv);
3944 card_edit (sl);
3945 free_strlist (sl);
3947 else
3948 card_edit (NULL);
3949 break;
3951 case aChangePIN:
3952 if (!argc)
3953 change_pin (0,1);
3954 else if (argc == 1)
3955 change_pin (atoi (*argv),1);
3956 else
3957 wrong_args ("--change-pin [no]");
3958 break;
3959 #endif /* ENABLE_CARD_SUPPORT*/
3961 case aListConfig:
3963 char *str=collapse_args(argc,argv);
3964 list_config(str);
3965 xfree(str);
3967 break;
3969 case aListPackets:
3970 opt.list_packets=2;
3971 default:
3972 if( argc > 1 )
3973 wrong_args(_("[filename]"));
3974 /* Issue some output for the unix newbie */
3975 if( !fname && !opt.outfile && isatty( fileno(stdin) )
3976 && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
3977 log_info(_("Go ahead and type your message ...\n"));
3979 a = iobuf_open(fname);
3980 if (a && is_secured_file (iobuf_get_fd (a)))
3982 iobuf_close (a);
3983 a = NULL;
3984 errno = EPERM;
3986 if( !a )
3987 log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
3988 else {
3990 if( !opt.no_armor ) {
3991 if( use_armor_filter( a ) ) {
3992 afx = new_armor_context ();
3993 push_armor_filter (afx, a);
3996 if( cmd == aListPackets ) {
3997 set_packet_list_mode(1);
3998 opt.list_packets=1;
4000 rc = proc_packets(NULL, a );
4001 if( rc )
4002 log_error("processing message failed: %s\n", g10_errstr(rc) );
4003 iobuf_close(a);
4005 break;
4008 /* cleanup */
4009 release_armor_context (afx);
4010 FREE_STRLIST(remusr);
4011 FREE_STRLIST(locusr);
4012 g10_exit(0);
4013 return 8; /*NEVER REACHED*/
4017 /* Note: This function is used by signal handlers!. */
4018 static void
4019 emergency_cleanup (void)
4021 gcry_control (GCRYCTL_TERM_SECMEM );
4025 void
4026 g10_exit( int rc )
4028 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
4029 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
4031 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
4032 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
4034 if (opt.debug)
4035 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
4037 emergency_cleanup ();
4039 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
4040 exit (rc);
4044 /* Pretty-print hex hashes. This assumes at least an 80-character
4045 display, but there are a few other similar assumptions in the
4046 display code. */
4047 static void
4048 print_hex( gcry_md_hd_t md, int algo, const char *fname )
4050 int i,n,count,indent=0;
4051 const byte *p;
4053 if(fname)
4054 indent=printf("%s: ",fname);
4056 if(indent>40)
4058 printf("\n");
4059 indent=0;
4062 if(algo==DIGEST_ALGO_RMD160)
4063 indent+=printf("RMD160 = ");
4064 else if(algo>0)
4065 indent+=printf("%6s = ", gcry_md_algo_name (algo));
4066 else
4067 algo=abs(algo);
4069 count=indent;
4071 p = gcry_md_read (md, algo);
4072 n = gcry_md_get_algo_dlen (algo);
4074 count += printf ("%02X",*p++);
4076 for(i=1;i<n;i++,p++)
4078 if(n==16)
4080 if(count+2>79)
4082 printf("\n%*s",indent," ");
4083 count=indent;
4085 else
4086 count+=printf(" ");
4088 if(!(i%8))
4089 count+=printf(" ");
4091 else if (n==20)
4093 if(!(i%2))
4095 if(count+4>79)
4097 printf("\n%*s",indent," ");
4098 count=indent;
4100 else
4101 count+=printf(" ");
4104 if(!(i%10))
4105 count+=printf(" ");
4107 else
4109 if(!(i%4))
4111 if(count+8>79)
4113 printf("\n%*s",indent," ");
4114 count=indent;
4116 else
4117 count+=printf(" ");
4121 count+=printf("%02X",*p);
4124 printf("\n");
4127 static void
4128 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
4130 int i, n;
4131 const byte *p;
4133 if ( fname ) {
4134 for (p = fname; *p; p++ ) {
4135 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
4136 printf("%%%02X", *p );
4137 else
4138 putchar( *p );
4141 putchar(':');
4142 printf("%d:", algo );
4143 p = gcry_md_read (md, algo);
4144 n = gcry_md_get_algo_dlen (algo);
4145 for(i=0; i < n ; i++, p++ )
4146 printf("%02X", *p );
4147 putchar(':');
4148 putchar('\n');
4151 static void
4152 print_mds( const char *fname, int algo )
4154 FILE *fp;
4155 char buf[1024];
4156 size_t n;
4157 gcry_md_hd_t md;
4159 if( !fname ) {
4160 fp = stdin;
4161 #ifdef HAVE_DOSISH_SYSTEM
4162 setmode ( fileno(fp) , O_BINARY );
4163 #endif
4165 else {
4166 fp = fopen( fname, "rb" );
4167 if (fp && is_secured_file (fileno (fp)))
4169 fclose (fp);
4170 fp = NULL;
4171 errno = EPERM;
4174 if( !fp ) {
4175 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4176 return;
4179 gcry_md_open (&md, 0, 0);
4180 if( algo )
4181 gcry_md_enable (md, algo);
4182 else {
4183 gcry_md_enable (md, GCRY_MD_MD5);
4184 gcry_md_enable (md, GCRY_MD_SHA1);
4185 gcry_md_enable (md, GCRY_MD_RMD160);
4186 if (!openpgp_md_test_algo (GCRY_MD_SHA224))
4187 gcry_md_enable (md, GCRY_MD_SHA224);
4188 if (!openpgp_md_test_algo (GCRY_MD_SHA256))
4189 gcry_md_enable (md, GCRY_MD_SHA256);
4190 if (!openpgp_md_test_algo (GCRY_MD_SHA384))
4191 gcry_md_enable (md, GCRY_MD_SHA384);
4192 if (!openpgp_md_test_algo (GCRY_MD_SHA512))
4193 gcry_md_enable (md, GCRY_MD_SHA512);
4196 while( (n=fread( buf, 1, DIM(buf), fp )) )
4197 gcry_md_write (md, buf, n);
4198 if( ferror(fp) )
4199 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4200 else {
4201 gcry_md_final (md);
4202 if ( opt.with_colons ) {
4203 if ( algo )
4204 print_hashline( md, algo, fname );
4205 else {
4206 print_hashline( md, GCRY_MD_MD5, fname );
4207 print_hashline( md, GCRY_MD_SHA1, fname );
4208 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4209 print_hashline( md, GCRY_MD_RMD160, fname );
4210 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4211 print_hashline (md, GCRY_MD_SHA224, fname);
4212 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4213 print_hashline( md, GCRY_MD_SHA256, fname );
4214 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4215 print_hashline ( md, GCRY_MD_SHA384, fname );
4216 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4217 print_hashline ( md, GCRY_MD_SHA512, fname );
4220 else {
4221 if( algo )
4222 print_hex(md,-algo,fname);
4223 else {
4224 print_hex( md, GCRY_MD_MD5, fname );
4225 print_hex( md, GCRY_MD_SHA1, fname );
4226 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4227 print_hex( md, GCRY_MD_RMD160, fname );
4228 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4229 print_hex (md, GCRY_MD_SHA224, fname);
4230 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4231 print_hex( md, GCRY_MD_SHA256, fname );
4232 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4233 print_hex( md, GCRY_MD_SHA384, fname );
4234 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4235 print_hex( md, GCRY_MD_SHA512, fname );
4239 gcry_md_close(md);
4241 if( fp != stdin )
4242 fclose(fp);
4246 /****************
4247 * Check the supplied name,value string and add it to the notation
4248 * data to be used for signatures. which==0 for sig notations, and 1
4249 * for cert notations.
4251 static void
4252 add_notation_data( const char *string, int which )
4254 struct notation *notation;
4256 notation=string_to_notation(string,utf8_strings);
4257 if(notation)
4259 if(which)
4261 notation->next=opt.cert_notations;
4262 opt.cert_notations=notation;
4264 else
4266 notation->next=opt.sig_notations;
4267 opt.sig_notations=notation;
4272 static void
4273 add_policy_url( const char *string, int which )
4275 unsigned int i,critical=0;
4276 strlist_t sl;
4278 if(*string=='!')
4280 string++;
4281 critical=1;
4284 for(i=0;i<strlen(string);i++)
4285 if( !isascii (string[i]) || iscntrl(string[i]))
4286 break;
4288 if(i==0 || i<strlen(string))
4290 if(which)
4291 log_error(_("the given certification policy URL is invalid\n"));
4292 else
4293 log_error(_("the given signature policy URL is invalid\n"));
4296 if(which)
4297 sl=add_to_strlist( &opt.cert_policy_url, string );
4298 else
4299 sl=add_to_strlist( &opt.sig_policy_url, string );
4301 if(critical)
4302 sl->flags |= 1;
4305 static void
4306 add_keyserver_url( const char *string, int which )
4308 unsigned int i,critical=0;
4309 strlist_t sl;
4311 if(*string=='!')
4313 string++;
4314 critical=1;
4317 for(i=0;i<strlen(string);i++)
4318 if( !isascii (string[i]) || iscntrl(string[i]))
4319 break;
4321 if(i==0 || i<strlen(string))
4323 if(which)
4324 BUG();
4325 else
4326 log_error(_("the given preferred keyserver URL is invalid\n"));
4329 if(which)
4330 BUG();
4331 else
4332 sl=add_to_strlist( &opt.sig_keyserver_url, string );
4334 if(critical)
4335 sl->flags |= 1;