* srv.c (getsrv): Raise maximum packet size to 2048, as PACKETSZ is
[gnupg.git] / g10 / gpg.c
blob1fe7a77d332cc5e3a3ccc305588968c49f75a6b2
1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2008 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 #include <assuan.h>
34 #ifdef HAVE_W32_SYSTEM
35 #include <windows.h>
36 #endif
38 #define INCLUDED_BY_MAIN_MODULE 1
39 #include "gpg.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 (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")),
398 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
399 ARGPARSE_c (aExport, "export" , N_("export keys") ),
400 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ),
401 ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ),
402 ARGPARSE_c (aSearchKeys, "search-keys" ,
403 N_("search for keys on a key server") ),
404 ARGPARSE_c (aRefreshKeys, "refresh-keys",
405 N_("update all keys from a keyserver")),
406 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
407 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
408 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
409 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
410 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
411 ARGPARSE_c (aFastImport, "fast-import", "@"),
412 #ifdef ENABLE_CARD_SUPPORT
413 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
414 ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")),
415 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
416 #endif
417 ARGPARSE_c (aListConfig, "list-config", "@"),
418 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
419 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
420 ARGPARSE_c (aListPackets, "list-packets","@"),
421 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
422 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
423 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
424 N_("update the trust database")),
425 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
426 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
427 ARGPARSE_c (aDeArmor, "dearmor", "@"),
428 ARGPARSE_c (aDeArmor, "dearmour", "@"),
429 ARGPARSE_c (aEnArmor, "enarmor", "@"),
430 ARGPARSE_c (aEnArmor, "enarmour", "@"),
431 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
432 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
433 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
434 ARGPARSE_c (aServer, "server", N_("run in server mode")),
436 ARGPARSE_group (301, N_("@\nOptions:\n ")),
438 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
439 ARGPARSE_s_n (oArmor, "armour", "@"),
441 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
442 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
443 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
444 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
445 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
446 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
448 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
449 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
450 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
451 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
452 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
453 ARGPARSE_s_s (oLocalUser, "local-user",
454 N_("|USER-ID|use USER-ID to sign or decrypt")),
456 ARGPARSE_s_i (oCompress, NULL,
457 N_("|N|set compress level to N (0 disables)")),
458 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
459 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
460 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
462 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
463 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
464 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
466 ARGPARSE_s_n (oExpert, "expert", "@"),
467 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
469 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
470 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
471 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
472 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
473 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
474 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
475 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
476 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
477 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
478 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
480 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
481 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
483 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
484 ARGPARSE_s_n (oQuiet, "quiet", "@"),
485 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
487 ARGPARSE_s_n (oForceV3Sigs, "force-v3-sigs", "@"),
488 ARGPARSE_s_n (oNoForceV3Sigs, "no-force-v3-sigs", "@"),
489 ARGPARSE_s_n (oForceV4Certs, "force-v4-certs", "@"),
490 ARGPARSE_s_n (oNoForceV4Certs, "no-force-v4-certs", "@"),
491 ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
492 ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
493 ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
494 ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
496 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
497 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
499 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
500 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
501 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
503 ARGPARSE_s_n (oBatch, "batch", "@"),
504 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
505 ARGPARSE_s_n (oAnswerNo, "no", "@"),
506 ARGPARSE_s_s (oKeyring, "keyring", "@"),
507 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
508 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
509 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
510 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
512 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
513 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
514 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
515 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
516 ARGPARSE_s_s (oListOptions, "list-options", "@"),
517 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
519 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
520 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
521 ARGPARSE_s_s (oOptions, "options", "@"),
523 ARGPARSE_p_u (oDebug, "debug", "@"),
524 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
525 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
526 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
527 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
528 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
529 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
531 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
532 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
534 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
535 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
536 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
537 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
539 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
541 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
542 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
543 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
544 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
545 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
546 ARGPARSE_s_n (oRFC1991, "rfc1991", "@"),
547 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
548 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
549 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
550 ARGPARSE_s_n (oPGP2, "pgp2", "@"),
551 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
552 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
553 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
555 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
556 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
557 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
558 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
559 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
560 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
561 ARGPARSE_s_n (oSimpleSKChecksum, "simple-sk-checksum", "@"),
562 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
563 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
564 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
565 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
566 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
567 ARGPARSE_s_n (oThrowKeyids, "throw-keyid", "@"),
568 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
569 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyid", "@"),
570 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
571 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
572 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
573 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
574 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
575 ARGPARSE_s_s (oSetNotation, "notation-data", "@"), /* Alias */
576 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
577 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
579 ARGPARSE_group (302, N_(
580 "@\n(See the man page for a complete listing of all commands and options)\n"
583 ARGPARSE_group (303, N_("@\nExamples:\n\n"
584 " -se -r Bob [file] sign and encrypt for user Bob\n"
585 " --clearsign [file] make a clear text signature\n"
586 " --detach-sign [file] make a detached signature\n"
587 " --list-keys [names] show keys\n"
588 " --fingerprint [names] show fingerprints\n")),
590 /* More hidden commands and options. */
591 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
592 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
593 /* Not yet used:
594 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
595 ARGPARSE_c (aDeleteSecretAndPublicKeys,
596 "delete-secret-and-public-keys", "@"),
597 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
599 ARGPARSE_s_s (oPasswd, "passphrase", "@"),
600 ARGPARSE_s_i (oPasswdFD, "passphrase-fd", "@"),
601 ARGPARSE_s_s (oPasswdFile, "passphrase-file", "@"),
602 ARGPARSE_s_i (oPasswdRepeat, "passphrase-repeat", "@"),
603 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
604 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
605 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
606 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
607 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
608 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
609 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
610 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
611 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
612 ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
613 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
614 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
615 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
616 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
617 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
618 ARGPARSE_s_s (oHomedir, "homedir", "@"),
619 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
620 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
621 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
622 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
623 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
624 ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */
625 ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */
626 ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */
627 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
628 ARGPARSE_s_n (oCompressKeys, "compress-keys", "@"),
629 ARGPARSE_s_n (oCompressSigs, "compress-sigs", "@"),
630 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
631 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
632 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
633 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
634 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
635 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
636 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
637 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
638 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
639 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
640 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
641 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
642 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
643 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
644 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
645 ARGPARSE_s_s (oComment, "comment", "@"),
646 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
647 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
648 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
649 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
650 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
651 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
652 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
653 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
654 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
655 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
656 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
657 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
658 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
659 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
660 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
661 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
662 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
663 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
664 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
665 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
666 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
667 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
668 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
669 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
670 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
671 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
672 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
673 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
674 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
675 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
676 ARGPARSE_s_n (oListOnly, "list-only", "@"),
677 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
678 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
679 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
680 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
681 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
682 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
683 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
684 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
685 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
686 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
687 ARGPARSE_s_n (oNoSigCreateCheck, "no-sig-create-check", "@"),
688 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
689 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
690 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
691 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
692 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
693 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
694 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
695 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
696 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
697 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
698 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
699 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
700 ARGPARSE_s_s (oPersonalCompressPreferences,
701 "personal-compress-preferences", "@"),
703 /* Aliases. I constantly mistype these, and assume other people do
704 as well. */
705 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
706 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
707 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
708 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
709 ARGPARSE_s_s (oDisplay, "display", "@"),
710 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
711 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
712 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
713 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
714 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
715 ARGPARSE_s_s (oGroup, "group", "@"),
716 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
717 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
718 ARGPARSE_s_n (oStrict, "strict", "@"),
719 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
720 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
721 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
722 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
723 ARGPARSE_s_n (oMultifile, "multifile", "@"),
724 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
725 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
726 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
728 ARGPARSE_s_n (oAllowMultisigVerification,
729 "allow-multisig-verification", "@"),
730 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
731 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
732 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
733 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
735 /* These two are aliases to help users of the PGP command line
736 product use gpg with minimal pain. Many commands are common
737 already as they seem to have borrowed commands from us. Now I'm
738 returning the favor. */
739 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
740 ARGPARSE_s_s (oRecipient, "user", "@"),
742 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
743 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
744 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
745 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
747 /* New options. Fixme: Should go more to the top. */
748 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
749 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
751 ARGPARSE_end ()
755 #ifdef ENABLE_SELINUX_HACKS
756 #define ALWAYS_ADD_KEYRINGS 1
757 #else
758 #define ALWAYS_ADD_KEYRINGS 0
759 #endif
762 int g10_errors_seen = 0;
764 static int utf8_strings = 0;
765 static int maybe_setuid = 1;
767 static char *build_list( const char *text, char letter,
768 const char *(*mapf)(int), int (*chkf)(int) );
769 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
770 enum cmd_and_opt_values new_cmd );
771 static void print_mds( const char *fname, int algo );
772 static void add_notation_data( const char *string, int which );
773 static void add_policy_url( const char *string, int which );
774 static void add_keyserver_url( const char *string, int which );
775 static void emergency_cleanup (void);
778 static char *
779 make_libversion (const char *libname, const char *(*getfnc)(const char*))
781 const char *s;
782 char *result;
784 if (maybe_setuid)
786 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
787 maybe_setuid = 0;
789 s = getfnc (NULL);
790 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
791 strcpy (stpcpy (stpcpy (result, libname), " "), s);
792 return result;
796 static const char *
797 my_strusage( int level )
799 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
800 const char *p;
802 switch( level ) {
803 case 11: p = "gpg (GnuPG)";
804 break;
805 case 13: p = VERSION; break;
806 case 17: p = PRINTABLE_OS_NAME; break;
807 case 19: p =
808 _("Please report bugs to <gnupg-bugs@gnu.org>.\n");
809 break;
811 case 20:
812 if (!ver_gcry)
813 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
814 p = ver_gcry;
815 break;
817 #ifdef IS_DEVELOPMENT_VERSION
818 case 25:
819 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
820 break;
821 case 26:
822 p="It is only intended for test purposes and should NOT be";
823 break;
824 case 27:
825 p="used in a production environment or with production keys!";
826 break;
827 #endif
829 case 1:
830 case 40: p =
831 _("Usage: gpg [options] [files] (-h for help)");
832 break;
833 case 41: p =
834 _("Syntax: gpg [options] [files]\n"
835 "sign, check, encrypt or decrypt\n"
836 "default operation depends on the input data\n");
837 break;
839 case 31: p = "\nHome: "; break;
840 #ifndef __riscos__
841 case 32: p = opt.homedir; break;
842 #else /* __riscos__ */
843 case 32: p = make_filename(opt.homedir, NULL); break;
844 #endif /* __riscos__ */
845 case 33: p = _("\nSupported algorithms:\n"); break;
846 case 34:
847 if (!pubkeys)
848 pubkeys = build_list (_("Pubkey: "), 0,
849 gcry_pk_algo_name,
850 openpgp_pk_test_algo );
851 p = pubkeys;
852 break;
853 case 35:
854 if( !ciphers )
855 ciphers = build_list(_("Cipher: "), 'S',
856 openpgp_cipher_algo_name,
857 openpgp_cipher_test_algo );
858 p = ciphers;
859 break;
860 case 36:
861 if( !digests )
862 digests = build_list(_("Hash: "), 'H',
863 gcry_md_algo_name,
864 openpgp_md_test_algo );
865 p = digests;
866 break;
867 case 37:
868 if( !zips )
869 zips = build_list(_("Compression: "),'Z',
870 compress_algo_to_string,
871 check_compress_algo);
872 p = zips;
873 break;
875 default: p = NULL;
877 return p;
881 static char *
882 build_list( const char *text, char letter,
883 const char * (*mapf)(int), int (*chkf)(int) )
885 int i;
886 const char *s;
887 size_t n=strlen(text)+2;
888 char *list, *p, *line=NULL;
890 if (maybe_setuid)
891 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
893 for(i=0; i <= 110; i++ )
894 if( !chkf(i) && (s=mapf(i)) )
895 n += strlen(s) + 7 + 2;
896 list = xmalloc( 21 + n ); *list = 0;
897 for(p=NULL, i=0; i <= 110; i++ ) {
898 if( !chkf(i) && (s=mapf(i)) ) {
899 if( !p ) {
900 p = stpcpy( list, text );
901 line=p;
903 else
904 p = stpcpy( p, ", ");
906 if(strlen(line)>60) {
907 int spaces=strlen(text);
909 list=xrealloc(list,n+spaces+1);
910 /* realloc could move the block, so find the end again */
911 p=list;
912 while(*p)
913 p++;
915 p=stpcpy(p, "\n");
916 line=p;
917 for(;spaces;spaces--)
918 p=stpcpy(p, " ");
921 p = stpcpy(p, s );
922 if(opt.verbose && letter)
924 char num[8];
925 sprintf(num," (%c%d)",letter,i);
926 p = stpcpy(p,num);
930 if( p )
931 p = stpcpy(p, "\n" );
932 return list;
936 static void
937 wrong_args( const char *text)
939 fputs(_("usage: gpg [options] "),stderr);
940 fputs(text,stderr);
941 putc('\n',stderr);
942 g10_exit(2);
946 static char *
947 make_username( const char *string )
949 char *p;
950 if( utf8_strings )
951 p = xstrdup(string);
952 else
953 p = native_to_utf8( string );
954 return p;
958 /* Setup the debugging. With a LEVEL of NULL only the active debug
959 flags are propagated to the subsystems. With LEVEL set, a specific
960 set of debug flags is set; thus overriding all flags already
961 set. */
962 static void
963 set_debug (const char *level)
965 if (!level)
967 else if (!strcmp (level, "none"))
968 opt.debug = 0;
969 else if (!strcmp (level, "basic"))
970 opt.debug = DBG_MEMSTAT_VALUE;
971 else if (!strcmp (level, "advanced"))
972 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
973 else if (!strcmp (level, "expert"))
974 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
975 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
976 else if (!strcmp (level, "guru"))
977 opt.debug = ~0;
978 else
980 log_error (_("invalid debug-level `%s' given\n"), level);
981 g10_exit (2);
984 if (opt.debug & DBG_MEMORY_VALUE )
985 memory_debug_mode = 1;
986 if (opt.debug & DBG_MEMSTAT_VALUE )
987 memory_stat_debug_mode = 1;
988 if (opt.debug & DBG_MPI_VALUE)
989 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
990 if (opt.debug & DBG_CIPHER_VALUE )
991 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
992 if (opt.debug & DBG_IOBUF_VALUE )
993 iobuf_debug_mode = 1;
994 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
999 /* We need the home directory also in some other directories, so make
1000 sure that both variables are always in sync. */
1001 static void
1002 set_homedir (const char *dir)
1004 if (!dir)
1005 dir = "";
1006 opt.homedir = dir;
1010 /* We set the screen dimensions for UI purposes. Do not allow screens
1011 smaller than 80x24 for the sake of simplicity. */
1012 static void
1013 set_screen_dimensions(void)
1015 #ifndef HAVE_W32_SYSTEM
1016 char *str;
1018 str=getenv("COLUMNS");
1019 if(str)
1020 opt.screen_columns=atoi(str);
1022 str=getenv("LINES");
1023 if(str)
1024 opt.screen_lines=atoi(str);
1025 #endif
1027 if(opt.screen_columns<80 || opt.screen_columns>255)
1028 opt.screen_columns=80;
1030 if(opt.screen_lines<24 || opt.screen_lines>255)
1031 opt.screen_lines=24;
1035 /* Helper to open a file FNAME either for reading or writing to be
1036 used with --status-file etc functions. Not generally useful but it
1037 avoids the riscos specific functions and well some Windows people
1038 might like it too. Prints an error message and returns -1 on
1039 error. On success the file descriptor is returned. */
1040 static int
1041 open_info_file (const char *fname, int for_write, int binary)
1043 #ifdef __riscos__
1044 return riscos_fdopenfile (fname, for_write);
1045 #elif defined (ENABLE_SELINUX_HACKS)
1046 /* We can't allow these even when testing for a secured filename
1047 because files to be secured might not yet been secured. This is
1048 similar to the option file but in that case it is unlikely that
1049 sensitive information may be retrieved by means of error
1050 messages. */
1051 (void)fname;
1052 (void)for_write;
1053 (void)binary;
1054 return -1;
1055 #else
1056 int fd;
1058 if (binary)
1059 binary = MY_O_BINARY;
1061 /* if (is_secured_filename (fname)) */
1062 /* { */
1063 /* fd = -1; */
1064 /* errno = EPERM; */
1065 /* } */
1066 /* else */
1067 /* { */
1070 if (for_write)
1071 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1072 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1073 else
1074 fd = open (fname, O_RDONLY | binary);
1076 while (fd == -1 && errno == EINTR);
1077 /* } */
1078 if ( fd == -1)
1079 log_error ( for_write? _("can't create `%s': %s\n")
1080 : _("can't open `%s': %s\n"), fname, strerror(errno));
1082 return fd;
1083 #endif
1086 static void
1087 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1089 enum cmd_and_opt_values cmd = *ret_cmd;
1091 if( !cmd || cmd == new_cmd )
1092 cmd = new_cmd;
1093 else if( cmd == aSign && new_cmd == aEncr )
1094 cmd = aSignEncr;
1095 else if( cmd == aEncr && new_cmd == aSign )
1096 cmd = aSignEncr;
1097 else if( cmd == aSign && new_cmd == aSym )
1098 cmd = aSignSym;
1099 else if( cmd == aSym && new_cmd == aSign )
1100 cmd = aSignSym;
1101 else if( cmd == aSym && new_cmd == aEncr )
1102 cmd = aEncrSym;
1103 else if( cmd == aEncr && new_cmd == aSym )
1104 cmd = aEncrSym;
1105 else if (cmd == aSignEncr && new_cmd == aSym)
1106 cmd = aSignEncrSym;
1107 else if (cmd == aSignSym && new_cmd == aEncr)
1108 cmd = aSignEncrSym;
1109 else if (cmd == aEncrSym && new_cmd == aSign)
1110 cmd = aSignEncrSym;
1111 else if( ( cmd == aSign && new_cmd == aClearsign )
1112 || ( cmd == aClearsign && new_cmd == aSign ) )
1113 cmd = aClearsign;
1114 else {
1115 log_error(_("conflicting commands\n"));
1116 g10_exit(2);
1119 *ret_cmd = cmd;
1123 static void
1124 add_group(char *string)
1126 char *name,*value;
1127 struct groupitem *item;
1129 /* Break off the group name */
1130 name=strsep(&string,"=");
1131 if(string==NULL)
1133 log_error(_("no = sign found in group definition `%s'\n"),name);
1134 return;
1137 trim_trailing_ws(name,strlen(name));
1139 /* Does this group already exist? */
1140 for(item=opt.grouplist;item;item=item->next)
1141 if(strcasecmp(item->name,name)==0)
1142 break;
1144 if(!item)
1146 item=xmalloc(sizeof(struct groupitem));
1147 item->name=name;
1148 item->next=opt.grouplist;
1149 item->values=NULL;
1150 opt.grouplist=item;
1153 /* Break apart the values */
1154 while ((value= strsep(&string," \t")))
1156 if (*value)
1157 add_to_strlist2(&item->values,value,utf8_strings);
1162 static void
1163 rm_group(char *name)
1165 struct groupitem *item,*last=NULL;
1167 trim_trailing_ws(name,strlen(name));
1169 for(item=opt.grouplist;item;last=item,item=item->next)
1171 if(strcasecmp(item->name,name)==0)
1173 if(last)
1174 last->next=item->next;
1175 else
1176 opt.grouplist=item->next;
1178 free_strlist(item->values);
1179 xfree(item);
1180 break;
1186 /* We need to check three things.
1188 0) The homedir. It must be x00, a directory, and owned by the
1189 user.
1191 1) The options/gpg.conf file. Okay unless it or its containing
1192 directory is group or other writable or not owned by us. Disable
1193 exec in this case.
1195 2) Extensions. Same as #1.
1197 Returns true if the item is unsafe. */
1198 static int
1199 check_permissions(const char *path,int item)
1201 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1202 static int homedir_cache=-1;
1203 char *tmppath,*dir;
1204 struct stat statbuf,dirbuf;
1205 int homedir=0,ret=0,checkonly=0;
1206 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1208 if(opt.no_perm_warn)
1209 return 0;
1211 assert(item==0 || item==1 || item==2);
1213 /* extensions may attach a path */
1214 if(item==2 && path[0]!=DIRSEP_C)
1216 if(strchr(path,DIRSEP_C))
1217 tmppath=make_filename(path,NULL);
1218 else
1219 tmppath=make_filename(gnupg_libdir (),path,NULL);
1221 else
1222 tmppath=xstrdup(path);
1224 /* If the item is located in the homedir, but isn't the homedir,
1225 don't continue if we already checked the homedir itself. This is
1226 to avoid user confusion with an extra options file warning which
1227 could be rectified if the homedir itself had proper
1228 permissions. */
1229 if(item!=0 && homedir_cache>-1
1230 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1232 ret=homedir_cache;
1233 goto end;
1236 /* It's okay if the file or directory doesn't exist */
1237 if(stat(tmppath,&statbuf)!=0)
1239 ret=0;
1240 goto end;
1243 /* Now check the enclosing directory. Theoretically, we could walk
1244 this test up to the root directory /, but for the sake of sanity,
1245 I'm stopping at one level down. */
1246 dir=make_dirname(tmppath);
1248 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1250 /* Weird error */
1251 ret=1;
1252 goto end;
1255 xfree(dir);
1257 /* Assume failure */
1258 ret=1;
1260 if(item==0)
1262 /* The homedir must be x00, a directory, and owned by the user. */
1264 if(S_ISDIR(statbuf.st_mode))
1266 if(statbuf.st_uid==getuid())
1268 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1269 ret=0;
1270 else
1271 perm=1;
1273 else
1274 own=1;
1276 homedir_cache=ret;
1279 else if(item==1 || item==2)
1281 /* The options or extension file. Okay unless it or its
1282 containing directory is group or other writable or not owned
1283 by us or root. */
1285 if(S_ISREG(statbuf.st_mode))
1287 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1289 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1291 /* it's not writable, so make sure the enclosing
1292 directory is also not writable */
1293 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1295 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1296 ret=0;
1297 else
1298 enc_dir_perm=1;
1300 else
1301 enc_dir_own=1;
1303 else
1305 /* it's writable, so the enclosing directory had
1306 better not let people get to it. */
1307 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1309 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1310 ret=0;
1311 else
1312 perm=enc_dir_perm=1; /* unclear which one to fix! */
1314 else
1315 enc_dir_own=1;
1318 else
1319 own=1;
1322 else
1323 BUG();
1325 if(!checkonly)
1327 if(own)
1329 if(item==0)
1330 log_info(_("WARNING: unsafe ownership on"
1331 " homedir `%s'\n"),tmppath);
1332 else if(item==1)
1333 log_info(_("WARNING: unsafe ownership on"
1334 " configuration file `%s'\n"),tmppath);
1335 else
1336 log_info(_("WARNING: unsafe ownership on"
1337 " extension `%s'\n"),tmppath);
1339 if(perm)
1341 if(item==0)
1342 log_info(_("WARNING: unsafe permissions on"
1343 " homedir `%s'\n"),tmppath);
1344 else if(item==1)
1345 log_info(_("WARNING: unsafe permissions on"
1346 " configuration file `%s'\n"),tmppath);
1347 else
1348 log_info(_("WARNING: unsafe permissions on"
1349 " extension `%s'\n"),tmppath);
1351 if(enc_dir_own)
1353 if(item==0)
1354 log_info(_("WARNING: unsafe enclosing directory ownership on"
1355 " homedir `%s'\n"),tmppath);
1356 else if(item==1)
1357 log_info(_("WARNING: unsafe enclosing directory ownership on"
1358 " configuration file `%s'\n"),tmppath);
1359 else
1360 log_info(_("WARNING: unsafe enclosing directory ownership on"
1361 " extension `%s'\n"),tmppath);
1363 if(enc_dir_perm)
1365 if(item==0)
1366 log_info(_("WARNING: unsafe enclosing directory permissions on"
1367 " homedir `%s'\n"),tmppath);
1368 else if(item==1)
1369 log_info(_("WARNING: unsafe enclosing directory permissions on"
1370 " configuration file `%s'\n"),tmppath);
1371 else
1372 log_info(_("WARNING: unsafe enclosing directory permissions on"
1373 " extension `%s'\n"),tmppath);
1377 end:
1378 xfree(tmppath);
1380 if(homedir)
1381 homedir_cache=ret;
1383 return ret;
1385 #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
1387 return 0;
1391 static void
1392 print_algo_numbers(int (*checker)(int))
1394 int i,first=1;
1396 for(i=0;i<=110;i++)
1398 if(!checker(i))
1400 if(first)
1401 first=0;
1402 else
1403 printf(";");
1404 printf("%d",i);
1410 static void
1411 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1413 int i,first=1;
1415 for(i=0;i<=110;i++)
1417 if(!checker(i))
1419 if(first)
1420 first=0;
1421 else
1422 printf(";");
1423 printf("%s",mapper(i));
1428 /* In the future, we can do all sorts of interesting configuration
1429 output here. For now, just give "group" as the Enigmail folks need
1430 it, and pubkey, cipher, hash, and compress as they may be useful
1431 for frontends. */
1432 static void
1433 list_config(char *items)
1435 int show_all=(items==NULL);
1436 char *name=NULL;
1438 if(!opt.with_colons)
1439 return;
1441 while(show_all || (name=strsep(&items," ")))
1443 int any=0;
1445 if(show_all || ascii_strcasecmp(name,"group")==0)
1447 struct groupitem *iter;
1449 for(iter=opt.grouplist;iter;iter=iter->next)
1451 strlist_t sl;
1453 printf("cfg:group:");
1454 print_string(stdout,iter->name,strlen(iter->name),':');
1455 printf(":");
1457 for(sl=iter->values;sl;sl=sl->next)
1459 print_sanitized_string2 (stdout, sl->d, ':',';');
1460 if(sl->next)
1461 printf(";");
1464 printf("\n");
1467 any=1;
1470 if(show_all || ascii_strcasecmp(name,"version")==0)
1472 printf("cfg:version:");
1473 print_string(stdout,VERSION,strlen(VERSION),':');
1474 printf("\n");
1475 any=1;
1478 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1480 printf("cfg:pubkey:");
1481 print_algo_numbers (openpgp_pk_test_algo);
1482 printf("\n");
1483 any=1;
1486 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1488 printf("cfg:cipher:");
1489 print_algo_numbers(openpgp_cipher_test_algo);
1490 printf("\n");
1491 any=1;
1494 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1496 printf ("cfg:ciphername:");
1497 print_algo_names (openpgp_cipher_test_algo,openpgp_cipher_algo_name);
1498 printf ("\n");
1499 any = 1;
1502 if(show_all
1503 || ascii_strcasecmp(name,"digest")==0
1504 || ascii_strcasecmp(name,"hash")==0)
1506 printf("cfg:digest:");
1507 print_algo_numbers(openpgp_md_test_algo);
1508 printf("\n");
1509 any=1;
1512 if (show_all
1513 || !ascii_strcasecmp(name,"digestname")
1514 || !ascii_strcasecmp(name,"hashname"))
1516 printf ("cfg:digestname:");
1517 print_algo_names (openpgp_md_test_algo, gcry_md_algo_name);
1518 printf("\n");
1519 any=1;
1522 if(show_all || ascii_strcasecmp(name,"compress")==0)
1524 printf("cfg:compress:");
1525 print_algo_numbers(check_compress_algo);
1526 printf("\n");
1527 any=1;
1530 if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
1532 #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \
1533 && GNUPG_MAJOR_VERSION == 1
1535 char *p, *p2, *list = ccid_get_reader_list ();
1537 for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
1539 *p2 = 0;
1540 printf("cfg:ccid-reader-id:%s\n", p);
1542 free (list);
1543 #endif
1544 any=1;
1547 if(show_all)
1548 break;
1550 if(!any)
1551 log_error(_("unknown configuration item `%s'\n"),name);
1556 /* List options and default values in the GPG Conf format. This is a
1557 new tool distributed with gnupg 1.9.x but we also want some limited
1558 support in older gpg versions. The output is the name of the
1559 configuration file and a list of options available for editing by
1560 gpgconf. */
1561 static void
1562 gpgconf_list (const char *configfile)
1564 char *configfile_esc = percent_escape (configfile, NULL);
1566 printf ("gpgconf-gpg.conf:%lu:\"%s\n",
1567 GC_OPT_FLAG_DEFAULT, configfile_esc ? configfile_esc : "/dev/null");
1568 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1569 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1570 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1571 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1572 printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1573 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1574 printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1575 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1576 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1577 printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1579 xfree (configfile_esc);
1583 static int
1584 parse_subpacket_list(char *list)
1586 char *tok;
1587 byte subpackets[128],i;
1588 int count=0;
1590 if(!list)
1592 /* No arguments means all subpackets */
1593 memset(subpackets+1,1,sizeof(subpackets)-1);
1594 count=127;
1596 else
1598 memset(subpackets,0,sizeof(subpackets));
1600 /* Merge with earlier copy */
1601 if(opt.show_subpackets)
1603 byte *in;
1605 for(in=opt.show_subpackets;*in;in++)
1607 if(*in>127 || *in<1)
1608 BUG();
1610 if(!subpackets[*in])
1611 count++;
1612 subpackets[*in]=1;
1616 while((tok=strsep(&list," ,")))
1618 if(!*tok)
1619 continue;
1621 i=atoi(tok);
1622 if(i>127 || i<1)
1623 return 0;
1625 if(!subpackets[i])
1626 count++;
1627 subpackets[i]=1;
1631 xfree(opt.show_subpackets);
1632 opt.show_subpackets=xmalloc(count+1);
1633 opt.show_subpackets[count--]=0;
1635 for(i=1;i<128 && count>=0;i++)
1636 if(subpackets[i])
1637 opt.show_subpackets[count--]=i;
1639 return 1;
1643 static int
1644 parse_list_options(char *str)
1646 char *subpackets=""; /* something that isn't NULL */
1647 struct parse_options lopts[]=
1649 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1650 N_("display photo IDs during key listings")},
1651 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1652 N_("show policy URLs during signature listings")},
1653 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1654 N_("show all notations during signature listings")},
1655 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1656 N_("show IETF standard notations during signature listings")},
1657 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1658 NULL},
1659 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1660 N_("show user-supplied notations during signature listings")},
1661 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1662 N_("show preferred keyserver URLs during signature listings")},
1663 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1664 N_("show user ID validity during key listings")},
1665 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1666 N_("show revoked and expired user IDs in key listings")},
1667 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1668 N_("show revoked and expired subkeys in key listings")},
1669 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1670 N_("show the keyring name in key listings")},
1671 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1672 N_("show expiration dates during signature listings")},
1673 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1674 NULL},
1675 {NULL,0,NULL,NULL}
1678 /* C99 allows for non-constant initializers, but we'd like to
1679 compile everywhere, so fill in the show-sig-subpackets argument
1680 here. Note that if the parse_options array changes, we'll have
1681 to change the subscript here. */
1682 lopts[12].value=&subpackets;
1684 if(parse_options(str,&opt.list_options,lopts,1))
1686 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1688 /* Unset so users can pass multiple lists in. */
1689 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1690 if(!parse_subpacket_list(subpackets))
1691 return 0;
1693 else if(subpackets==NULL && opt.show_subpackets)
1695 /* User did 'no-show-subpackets' */
1696 xfree(opt.show_subpackets);
1697 opt.show_subpackets=NULL;
1700 return 1;
1702 else
1703 return 0;
1707 /* Collapses argc/argv into a single string that must be freed */
1708 static char *
1709 collapse_args(int argc,char *argv[])
1711 char *str=NULL;
1712 int i,first=1,len=0;
1714 for(i=0;i<argc;i++)
1716 len+=strlen(argv[i])+2;
1717 str=xrealloc(str,len);
1718 if(first)
1720 str[0]='\0';
1721 first=0;
1723 else
1724 strcat(str," ");
1726 strcat(str,argv[i]);
1729 return str;
1732 static void
1733 parse_trust_model(const char *model)
1735 if(ascii_strcasecmp(model,"pgp")==0)
1736 opt.trust_model=TM_PGP;
1737 else if(ascii_strcasecmp(model,"classic")==0)
1738 opt.trust_model=TM_CLASSIC;
1739 else if(ascii_strcasecmp(model,"always")==0)
1740 opt.trust_model=TM_ALWAYS;
1741 else if(ascii_strcasecmp(model,"direct")==0)
1742 opt.trust_model=TM_DIRECT;
1743 else if(ascii_strcasecmp(model,"auto")==0)
1744 opt.trust_model=TM_AUTO;
1745 else
1746 log_error("unknown trust model `%s'\n",model);
1750 /* Pack an s2k iteration count into the form specified in 2440. If
1751 we're in between valid values, round up. */
1752 static unsigned char
1753 encode_s2k_iterations(int iterations)
1755 unsigned char c=0,result;
1756 unsigned int count;
1758 if(iterations<=1024)
1759 return 0;
1761 if(iterations>=65011712)
1762 return 255;
1764 /* Need count to be in the range 16-31 */
1765 for(count=iterations>>6;count>=32;count>>=1)
1766 c++;
1768 result=(c<<4)|(count-16);
1770 if(S2K_DECODE_COUNT(result)<iterations)
1771 result++;
1773 return result;
1777 /* This fucntion called to initialized a new control object. It is
1778 assumed that this object has been zeroed out before calling this
1779 function. */
1780 static void
1781 gpg_init_default_ctrl (ctrl_t ctrl)
1783 (void)ctrl;
1787 /* This function is called to deinitialize a control object. It is
1788 not deallocated. */
1789 static void
1790 gpg_deinit_default_ctrl (ctrl_t ctrl)
1792 (void)ctrl;
1796 char *
1797 get_default_configname (void)
1799 char *configname = NULL;
1800 char *name = xstrdup ("gpg" EXTSEP_S "conf-" SAFE_VERSION);
1801 char *ver = &name[strlen ("gpg" EXTSEP_S "conf-")];
1805 if (configname)
1807 char *tok;
1809 xfree (configname);
1810 configname = NULL;
1812 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
1813 *tok='\0';
1814 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
1815 *tok='\0';
1816 else
1817 break;
1820 configname = make_filename (opt.homedir, name, NULL);
1822 while (access (configname, R_OK));
1824 xfree(name);
1826 if (! configname)
1827 configname = make_filename (opt.homedir, "gpg" EXTSEP_S "conf", NULL);
1828 if (! access (configname, R_OK))
1830 /* Print a warning when both config files are present. */
1831 char *p = make_filename (opt.homedir, "options", NULL);
1832 if (! access (p, R_OK))
1833 log_info (_("NOTE: old default options file `%s' ignored\n"), p);
1834 xfree (p);
1836 else
1838 /* Use the old default only if it exists. */
1839 char *p = make_filename (opt.homedir, "options", NULL);
1840 if (!access (p, R_OK))
1842 xfree (configname);
1843 configname = p;
1845 else
1846 xfree (p);
1849 return configname;
1854 main (int argc, char **argv)
1856 ARGPARSE_ARGS pargs;
1857 IOBUF a;
1858 int rc=0;
1859 int orig_argc;
1860 char **orig_argv;
1861 const char *fname;
1862 char *username;
1863 int may_coredump;
1864 strlist_t sl, remusr= NULL, locusr=NULL;
1865 strlist_t nrings=NULL, sec_nrings=NULL;
1866 armor_filter_context_t *afx = NULL;
1867 int detached_sig = 0;
1868 FILE *configfp = NULL;
1869 char *configname = NULL;
1870 char *save_configname = NULL;
1871 char *default_configname = NULL;
1872 unsigned configlineno;
1873 int parse_debug = 0;
1874 int default_config = 1;
1875 int default_keyring = 1;
1876 int greeting = 0;
1877 int nogreeting = 0;
1878 char *logfile = NULL;
1879 int use_random_seed = 1;
1880 enum cmd_and_opt_values cmd = 0;
1881 const char *debug_level = NULL;
1882 const char *trustdb_name = NULL;
1883 char *def_cipher_string = NULL;
1884 char *def_digest_string = NULL;
1885 char *compress_algo_string = NULL;
1886 char *cert_digest_string = NULL;
1887 char *s2k_cipher_string = NULL;
1888 char *s2k_digest_string = NULL;
1889 char *pers_cipher_list = NULL;
1890 char *pers_digest_list = NULL;
1891 char *pers_compress_list = NULL;
1892 int eyes_only=0;
1893 int multifile=0;
1894 int pwfd = -1;
1895 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
1896 int any_explicit_recipient = 0;
1897 int require_secmem=0,got_secmem=0;
1899 #ifdef __riscos__
1900 opt.lock_once = 1;
1901 #endif /* __riscos__ */
1904 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1905 when adding any stuff between here and the call to
1906 secmem_init() somewhere after the option parsing. */
1907 gnupg_reopen_std ("gpg");
1908 trap_unaligned ();
1909 gnupg_rl_initialize ();
1910 set_strusage (my_strusage);
1911 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1912 /* We don't need any locking in libgcrypt unless we use any kind of
1913 threading. */
1914 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
1915 log_set_prefix ("gpg", 1);
1917 /* Make sure that our subsystems are ready. */
1918 i18n_init();
1919 init_common_subsystems ();
1921 /* Check that the libraries are suitable. Do it right here because the
1922 option parsing may need services of the library. */
1923 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1925 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
1926 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1929 /* Put random number into secure memory */
1930 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1932 may_coredump = disable_core_dumps();
1934 gnupg_init_signals (0, emergency_cleanup);
1936 create_dotlock(NULL); /* Register locking cleanup. */
1939 opt.command_fd = -1; /* no command fd */
1940 opt.compress_level = -1; /* defaults to standard compress level */
1941 opt.bz2_compress_level = -1; /* defaults to standard compress level */
1942 /* note: if you change these lines, look at oOpenPGP */
1943 opt.def_cipher_algo = 0;
1944 opt.def_digest_algo = 0;
1945 opt.cert_digest_algo = 0;
1946 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
1947 opt.s2k_mode = 3; /* iterated+salted */
1948 opt.s2k_count = 96; /* 65536 iterations */
1949 #ifdef USE_CAST5
1950 opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
1951 #else
1952 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
1953 #endif
1954 opt.completes_needed = 1;
1955 opt.marginals_needed = 3;
1956 opt.max_cert_depth = 5;
1957 opt.pgp2_workarounds = 1;
1958 opt.escape_from = 1;
1959 opt.flags.require_cross_cert = 1;
1960 opt.import_options=IMPORT_SK2PK;
1961 opt.export_options=EXPORT_ATTRIBUTES;
1962 opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
1963 opt.keyserver_options.export_options=EXPORT_ATTRIBUTES;
1964 opt.keyserver_options.options=
1965 KEYSERVER_HONOR_KEYSERVER_URL|KEYSERVER_HONOR_PKA_RECORD;
1966 opt.verify_options=
1967 VERIFY_SHOW_POLICY_URLS|VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_KEYSERVER_URLS;
1968 opt.trust_model=TM_AUTO;
1969 opt.mangle_dos_filenames=0;
1970 opt.min_cert_level=2;
1971 set_screen_dimensions();
1972 opt.keyid_format=KF_SHORT;
1973 opt.def_sig_expire="0";
1974 opt.def_cert_expire="0";
1975 set_homedir ( default_homedir () );
1976 opt.passwd_repeat=1;
1978 /* Check whether we have a config file on the command line. */
1979 orig_argc = argc;
1980 orig_argv = argv;
1981 pargs.argc = &argc;
1982 pargs.argv = &argv;
1983 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1984 while( arg_parse( &pargs, opts) ) {
1985 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
1986 parse_debug++;
1987 else if( pargs.r_opt == oOptions ) {
1988 /* yes there is one, so we do not try the default one, but
1989 * read the option file when it is encountered at the commandline
1991 default_config = 0;
1993 else if( pargs.r_opt == oNoOptions )
1995 default_config = 0; /* --no-options */
1996 opt.no_homedir_creation = 1;
1998 else if( pargs.r_opt == oHomedir )
1999 set_homedir ( pargs.r.ret_str );
2000 else if( pargs.r_opt == oNoPermissionWarn )
2001 opt.no_perm_warn=1;
2002 else if (pargs.r_opt == oStrict )
2004 /* Not used */
2006 else if (pargs.r_opt == oNoStrict )
2008 /* Not used */
2012 #ifdef HAVE_DOSISH_SYSTEM
2013 if ( strchr (opt.homedir,'\\') ) {
2014 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
2015 const char *s = opt.homedir;
2016 for (d=buf,s=opt.homedir; *s; s++)
2018 *d++ = *s == '\\'? '/': *s;
2019 #ifdef HAVE_W32_SYSTEM
2020 if (s[1] && IsDBCSLeadByte (*s))
2021 *d++ = *++s;
2022 #endif
2024 *d = 0;
2025 set_homedir (buf);
2027 #endif
2029 /* Initialize the secure memory. */
2030 if (!gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0))
2031 got_secmem = 1;
2032 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2033 /* There should be no way to get to this spot while still carrying
2034 setuid privs. Just in case, bomb out if we are. */
2035 if ( getuid () != geteuid () )
2036 BUG ();
2037 #endif
2038 maybe_setuid = 0;
2040 /* Okay, we are now working under our real uid */
2042 /* malloc hooks go here ... */
2043 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
2044 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
2047 /* Try for a version specific config file first */
2048 default_configname = get_default_configname ();
2049 if (default_config)
2050 configname = xstrdup (default_configname);
2052 argc = orig_argc;
2053 argv = orig_argv;
2054 pargs.argc = &argc;
2055 pargs.argv = &argv;
2056 pargs.flags= 1; /* do not remove the args */
2058 /* By this point we have a homedir, and cannot change it. */
2059 check_permissions(opt.homedir,0);
2061 next_pass:
2062 if( configname ) {
2063 if(check_permissions(configname,1))
2065 /* If any options file is unsafe, then disable any external
2066 programs for keyserver calls or photo IDs. Since the
2067 external program to call is set in the options file, a
2068 unsafe options file can lead to an arbitrary program
2069 being run. */
2071 opt.exec_disable=1;
2074 configlineno = 0;
2075 configfp = fopen( configname, "r" );
2076 if (configfp && is_secured_file (fileno (configfp)))
2078 fclose (configfp);
2079 configfp = NULL;
2080 errno = EPERM;
2082 if( !configfp ) {
2083 if( default_config ) {
2084 if( parse_debug )
2085 log_info(_("NOTE: no default option file `%s'\n"),
2086 configname );
2088 else {
2089 log_error(_("option file `%s': %s\n"),
2090 configname, strerror(errno) );
2091 g10_exit(2);
2093 xfree(configname); configname = NULL;
2095 if( parse_debug && configname )
2096 log_info(_("reading options from `%s'\n"), configname );
2097 default_config = 0;
2100 while( optfile_parse( configfp, configname, &configlineno,
2101 &pargs, opts) )
2103 switch( pargs.r_opt )
2105 case aCheckKeys:
2106 case aListConfig:
2107 case aGPGConfList:
2108 case aGPGConfTest:
2109 case aListPackets:
2110 case aImport:
2111 case aFastImport:
2112 case aSendKeys:
2113 case aRecvKeys:
2114 case aSearchKeys:
2115 case aRefreshKeys:
2116 case aFetchKeys:
2117 case aExport:
2118 #ifdef ENABLE_CARD_SUPPORT
2119 case aCardStatus:
2120 case aCardEdit:
2121 case aChangePIN:
2122 #endif /* ENABLE_CARD_SUPPORT*/
2123 case aListKeys:
2124 case aLocateKeys:
2125 case aListSigs:
2126 case aExportSecret:
2127 case aExportSecretSub:
2128 case aSym:
2129 case aClearsign:
2130 case aGenRevoke:
2131 case aDesigRevoke:
2132 case aPrimegen:
2133 case aGenRandom:
2134 case aPrintMD:
2135 case aPrintMDs:
2136 case aListTrustDB:
2137 case aCheckTrustDB:
2138 case aUpdateTrustDB:
2139 case aFixTrustDB:
2140 case aListTrustPath:
2141 case aDeArmor:
2142 case aEnArmor:
2143 case aSign:
2144 case aSignKey:
2145 case aLSignKey:
2146 case aStore:
2147 case aExportOwnerTrust:
2148 case aImportOwnerTrust:
2149 case aRebuildKeydbCaches:
2150 set_cmd (&cmd, pargs.r_opt);
2151 break;
2153 case aKeygen:
2154 case aEditKey:
2155 case aDeleteSecretKeys:
2156 case aDeleteSecretAndPublicKeys:
2157 case aDeleteKeys:
2158 set_cmd (&cmd, pargs.r_opt);
2159 greeting=1;
2160 break;
2162 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2164 case aDecryptFiles: multifile=1; /* fall through */
2165 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2167 case aEncrFiles: multifile=1; /* fall through */
2168 case aEncr: set_cmd( &cmd, aEncr); break;
2170 case aVerifyFiles: multifile=1; /* fall through */
2171 case aVerify: set_cmd( &cmd, aVerify); break;
2173 case aServer:
2174 set_cmd (&cmd, pargs.r_opt);
2175 opt.batch = 1;
2176 break;
2178 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2179 case oOutput: opt.outfile = pargs.r.ret_str; break;
2180 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2181 case oQuiet: opt.quiet = 1; break;
2182 case oNoTTY: tty_no_terminal(1); break;
2183 case oDryRun: opt.dry_run = 1; break;
2184 case oInteractive: opt.interactive = 1; break;
2185 case oVerbose:
2186 opt.verbose++;
2187 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2188 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2189 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2190 break;
2192 case oBatch:
2193 opt.batch = 1;
2194 nogreeting = 1;
2195 break;
2197 case oUseAgent: /* Dummy. */
2198 break;
2199 case oNoUseAgent:
2200 obsolete_option (configname, configlineno, "--no-use-agent");
2201 break;
2202 case oGpgAgentInfo:
2203 obsolete_option (configname, configlineno, "--gpg-agent-info");
2204 break;
2206 case oAnswerYes: opt.answer_yes = 1; break;
2207 case oAnswerNo: opt.answer_no = 1; break;
2208 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2209 case oPrimaryKeyring:
2210 sl=append_to_strlist( &nrings, pargs.r.ret_str);
2211 sl->flags=2;
2212 break;
2213 case oShowKeyring:
2214 deprecated_warning(configname,configlineno,"--show-keyring",
2215 "--list-options ","show-keyring");
2216 opt.list_options|=LIST_SHOW_KEYRING;
2217 break;
2219 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2220 case oDebugAll: opt.debug = ~0; break;
2221 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2223 case oStatusFD:
2224 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2225 break;
2226 case oStatusFile:
2227 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2228 break;
2229 case oAttributeFD:
2230 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2231 break;
2232 case oAttributeFile:
2233 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2234 break;
2235 case oLoggerFD:
2236 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2237 break;
2238 case oLoggerFile:
2239 logfile = pargs.r.ret_str;
2240 break;
2242 case oWithFingerprint:
2243 opt.with_fingerprint = 1;
2244 opt.fingerprint++;
2245 break;
2246 case oFingerprint:
2247 opt.fingerprint++;
2248 fpr_maybe_cmd = 1;
2249 break;
2251 case oSecretKeyring:
2252 append_to_strlist( &sec_nrings, pargs.r.ret_str);
2253 break;
2254 case oOptions:
2255 /* config files may not be nested (silently ignore them) */
2256 if( !configfp ) {
2257 xfree(configname);
2258 configname = xstrdup(pargs.r.ret_str);
2259 goto next_pass;
2261 break;
2262 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2263 case oNoDefKeyring: default_keyring = 0; break;
2264 case oNoGreeting: nogreeting = 1; break;
2265 case oNoVerbose:
2266 opt.verbose = 0;
2267 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2268 opt.list_sigs=0;
2269 break;
2270 case oQuickRandom:
2271 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2272 break;
2273 case oEmitVersion: opt.no_version=0; break;
2274 case oNoEmitVersion: opt.no_version=1; break;
2275 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2276 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2277 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2278 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2279 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2280 case oDefRecipient:
2281 if( *pargs.r.ret_str )
2282 opt.def_recipient = make_username(pargs.r.ret_str);
2283 break;
2284 case oDefRecipientSelf:
2285 xfree(opt.def_recipient); opt.def_recipient = NULL;
2286 opt.def_recipient_self = 1;
2287 break;
2288 case oNoDefRecipient:
2289 xfree(opt.def_recipient); opt.def_recipient = NULL;
2290 opt.def_recipient_self = 0;
2291 break;
2292 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2293 case oHomedir: break;
2294 case oNoBatch: opt.batch = 0; break;
2296 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2297 case oWithColons: opt.with_colons=':'; break;
2299 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2300 case oWithSigList: opt.list_sigs = 1; break;
2302 case oSkipVerify: opt.skip_verify=1; break;
2303 case oCompressKeys: opt.compress_keys = 1; break;
2304 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2305 /* There are many programs (like mutt) that call gpg with
2306 --always-trust so keep this option around for a long
2307 time. */
2308 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2309 case oTrustModel:
2310 parse_trust_model(pargs.r.ret_str);
2311 break;
2312 case oForceOwnertrust:
2313 log_info(_("NOTE: %s is not for normal use!\n"),
2314 "--force-ownertrust");
2315 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2316 if(opt.force_ownertrust==-1)
2318 log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
2319 opt.force_ownertrust=0;
2321 break;
2322 case oLoadExtension:
2323 /* Dummy so that gpg 1.4 conf files can work. Should
2324 eventually be removed. */
2325 break;
2326 case oRFC1991:
2327 opt.compliance = CO_RFC1991;
2328 opt.force_v4_certs = 0;
2329 opt.escape_from = 1;
2330 break;
2331 case oOpenPGP:
2332 case oRFC4880:
2333 /* This is effectively the same as RFC2440, but with
2334 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2335 --require-cross-certification". */
2336 opt.compliance = CO_RFC4880;
2337 opt.flags.dsa2 = 1;
2338 opt.flags.require_cross_cert = 1;
2339 opt.rfc2440_text = 0;
2340 opt.allow_non_selfsigned_uid = 1;
2341 opt.allow_freeform_uid = 1;
2342 opt.pgp2_workarounds = 0;
2343 opt.escape_from = 1;
2344 opt.force_v3_sigs = 0;
2345 opt.compress_keys = 0; /* not mandated, but we do it */
2346 opt.compress_sigs = 0; /* ditto. */
2347 opt.not_dash_escaped = 0;
2348 opt.def_cipher_algo = 0;
2349 opt.def_digest_algo = 0;
2350 opt.cert_digest_algo = 0;
2351 opt.compress_algo = -1;
2352 opt.s2k_mode = 3; /* iterated+salted */
2353 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2354 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2355 break;
2356 case oRFC2440:
2357 opt.compliance = CO_RFC2440;
2358 opt.flags.dsa2 = 0;
2359 opt.rfc2440_text = 1;
2360 opt.allow_non_selfsigned_uid = 1;
2361 opt.allow_freeform_uid = 1;
2362 opt.pgp2_workarounds = 0;
2363 opt.escape_from = 0;
2364 opt.force_v3_sigs = 0;
2365 opt.compress_keys = 0; /* not mandated, but we do it */
2366 opt.compress_sigs = 0; /* ditto. */
2367 opt.not_dash_escaped = 0;
2368 opt.def_cipher_algo = 0;
2369 opt.def_digest_algo = 0;
2370 opt.cert_digest_algo = 0;
2371 opt.compress_algo = -1;
2372 opt.s2k_mode = 3; /* iterated+salted */
2373 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2374 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2375 break;
2376 case oPGP2: opt.compliance = CO_PGP2; break;
2377 case oPGP6: opt.compliance = CO_PGP6; break;
2378 case oPGP7: opt.compliance = CO_PGP7; break;
2379 case oPGP8: opt.compliance = CO_PGP8; break;
2380 case oGnuPG: opt.compliance = CO_GNUPG; break;
2381 case oCompressSigs: opt.compress_sigs = 1; break;
2382 case oRFC2440Text: opt.rfc2440_text=1; break;
2383 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2384 case oSetFilename:
2385 if(utf8_strings)
2386 opt.set_filename = pargs.r.ret_str;
2387 else
2388 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2389 break;
2390 case oForYourEyesOnly: eyes_only = 1; break;
2391 case oNoForYourEyesOnly: eyes_only = 0; break;
2392 case oSetPolicyURL:
2393 add_policy_url(pargs.r.ret_str,0);
2394 add_policy_url(pargs.r.ret_str,1);
2395 break;
2396 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2397 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2398 case oShowPolicyURL:
2399 deprecated_warning(configname,configlineno,"--show-policy-url",
2400 "--list-options ","show-policy-urls");
2401 deprecated_warning(configname,configlineno,"--show-policy-url",
2402 "--verify-options ","show-policy-urls");
2403 opt.list_options|=LIST_SHOW_POLICY_URLS;
2404 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2405 break;
2406 case oNoShowPolicyURL:
2407 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2408 "--list-options ","no-show-policy-urls");
2409 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2410 "--verify-options ","no-show-policy-urls");
2411 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2412 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2413 break;
2414 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2415 case oUseEmbeddedFilename:
2416 opt.flags.use_embedded_filename=1;
2417 break;
2418 case oNoUseEmbeddedFilename:
2419 opt.flags.use_embedded_filename=0;
2420 break;
2421 case oComment:
2422 if(pargs.r.ret_str[0])
2423 append_to_strlist(&opt.comments,pargs.r.ret_str);
2424 break;
2425 case oDefaultComment:
2426 deprecated_warning(configname,configlineno,
2427 "--default-comment","--no-comments","");
2428 /* fall through */
2429 case oNoComments:
2430 free_strlist(opt.comments);
2431 opt.comments=NULL;
2432 break;
2433 case oThrowKeyids: opt.throw_keyid = 1; break;
2434 case oNoThrowKeyids: opt.throw_keyid = 0; break;
2435 case oShowPhotos:
2436 deprecated_warning(configname,configlineno,"--show-photos",
2437 "--list-options ","show-photos");
2438 deprecated_warning(configname,configlineno,"--show-photos",
2439 "--verify-options ","show-photos");
2440 opt.list_options|=LIST_SHOW_PHOTOS;
2441 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2442 break;
2443 case oNoShowPhotos:
2444 deprecated_warning(configname,configlineno,"--no-show-photos",
2445 "--list-options ","no-show-photos");
2446 deprecated_warning(configname,configlineno,"--no-show-photos",
2447 "--verify-options ","no-show-photos");
2448 opt.list_options&=~LIST_SHOW_PHOTOS;
2449 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2450 break;
2451 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2452 case oForceV3Sigs: opt.force_v3_sigs = 1; break;
2453 case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
2454 case oForceV4Certs: opt.force_v4_certs = 1; break;
2455 case oNoForceV4Certs: opt.force_v4_certs = 0; break;
2456 case oForceMDC: opt.force_mdc = 1; break;
2457 case oNoForceMDC: opt.force_mdc = 0; break;
2458 case oDisableMDC: opt.disable_mdc = 1; break;
2459 case oNoDisableMDC: opt.disable_mdc = 0; break;
2460 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2461 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2462 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2463 case oS2KCount:
2464 opt.s2k_count=encode_s2k_iterations(pargs.r.ret_int);
2465 break;
2466 case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
2467 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2468 case oEncryptTo: /* store the recipient in the second list */
2469 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2470 sl->flags = 1;
2471 break;
2472 case oHiddenEncryptTo: /* store the recipient in the second list */
2473 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2474 sl->flags = 1|2;
2475 break;
2476 case oRecipient: /* store the recipient */
2477 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2478 any_explicit_recipient = 1;
2479 break;
2480 case oHiddenRecipient: /* store the recipient with a flag */
2481 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2482 sl->flags = 2;
2483 any_explicit_recipient = 1;
2484 break;
2485 case oTextmodeShort: opt.textmode = 2; break;
2486 case oTextmode: opt.textmode=1; break;
2487 case oNoTextmode: opt.textmode=0; break;
2488 case oExpert: opt.expert = 1; break;
2489 case oNoExpert: opt.expert = 0; break;
2490 case oDefSigExpire:
2491 if(*pargs.r.ret_str!='\0')
2493 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2494 log_error(_("`%s' is not a valid signature expiration\n"),
2495 pargs.r.ret_str);
2496 else
2497 opt.def_sig_expire=pargs.r.ret_str;
2499 break;
2500 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2501 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2502 case oDefCertExpire:
2503 if(*pargs.r.ret_str!='\0')
2505 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2506 log_error(_("`%s' is not a valid signature expiration\n"),
2507 pargs.r.ret_str);
2508 else
2509 opt.def_cert_expire=pargs.r.ret_str;
2511 break;
2512 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2513 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2514 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2515 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2516 case oAskCertLevel: opt.ask_cert_level = 1; break;
2517 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2518 case oLocalUser: /* store the local users */
2519 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2520 break;
2521 case oCompress:
2522 /* this is the -z command line option */
2523 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2524 break;
2525 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2526 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2527 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2528 case oPasswd:
2529 set_passphrase_from_string(pargs.r.ret_str);
2530 break;
2531 case oPasswdFD:
2532 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2533 break;
2534 case oPasswdFile:
2535 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
2536 break;
2537 case oPasswdRepeat: opt.passwd_repeat=pargs.r.ret_int; break;
2538 case oCommandFD:
2539 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2540 break;
2541 case oCommandFile:
2542 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
2543 break;
2544 case oCipherAlgo:
2545 def_cipher_string = xstrdup(pargs.r.ret_str);
2546 break;
2547 case oDigestAlgo:
2548 def_digest_string = xstrdup(pargs.r.ret_str);
2549 break;
2550 case oCompressAlgo:
2551 /* If it is all digits, stick a Z in front of it for
2552 later. This is for backwards compatibility with
2553 versions that took the compress algorithm number. */
2555 char *pt=pargs.r.ret_str;
2556 while(*pt)
2558 if (!isascii (*pt) || !isdigit (*pt))
2559 break;
2561 pt++;
2564 if(*pt=='\0')
2566 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2567 strcpy(compress_algo_string,"Z");
2568 strcat(compress_algo_string,pargs.r.ret_str);
2570 else
2571 compress_algo_string = xstrdup(pargs.r.ret_str);
2573 break;
2574 case oCertDigestAlgo:
2575 cert_digest_string = xstrdup(pargs.r.ret_str);
2576 break;
2578 case oNoSecmemWarn:
2579 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
2580 break;
2582 case oRequireSecmem: require_secmem=1; break;
2583 case oNoRequireSecmem: require_secmem=0; break;
2584 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2585 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2586 case oDisplayCharset:
2587 if( set_native_charset( pargs.r.ret_str ) )
2588 log_error(_("`%s' is not a valid character set\n"),
2589 pargs.r.ret_str);
2590 break;
2591 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2592 case oEscapeFrom: opt.escape_from = 1; break;
2593 case oNoEscapeFrom: opt.escape_from = 0; break;
2594 case oLockOnce: opt.lock_once = 1; break;
2595 case oLockNever:
2596 disable_dotlock ();
2597 break;
2598 case oLockMultiple:
2599 #ifndef __riscos__
2600 opt.lock_once = 0;
2601 #else /* __riscos__ */
2602 riscos_not_implemented("lock-multiple");
2603 #endif /* __riscos__ */
2604 break;
2605 case oKeyServer:
2607 struct keyserver_spec *keyserver;
2608 keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
2609 configname,configlineno);
2610 if(!keyserver)
2611 log_error(_("could not parse keyserver URL\n"));
2612 else
2614 keyserver->next=opt.keyserver;
2615 opt.keyserver=keyserver;
2618 break;
2619 case oKeyServerOptions:
2620 if(!parse_keyserver_options(pargs.r.ret_str))
2622 if(configname)
2623 log_error(_("%s:%d: invalid keyserver options\n"),
2624 configname,configlineno);
2625 else
2626 log_error(_("invalid keyserver options\n"));
2628 break;
2629 case oImportOptions:
2630 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2632 if(configname)
2633 log_error(_("%s:%d: invalid import options\n"),
2634 configname,configlineno);
2635 else
2636 log_error(_("invalid import options\n"));
2638 break;
2639 case oExportOptions:
2640 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2642 if(configname)
2643 log_error(_("%s:%d: invalid export options\n"),
2644 configname,configlineno);
2645 else
2646 log_error(_("invalid export options\n"));
2648 break;
2649 case oListOptions:
2650 if(!parse_list_options(pargs.r.ret_str))
2652 if(configname)
2653 log_error(_("%s:%d: invalid list options\n"),
2654 configname,configlineno);
2655 else
2656 log_error(_("invalid list options\n"));
2658 break;
2659 case oVerifyOptions:
2661 struct parse_options vopts[]=
2663 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2664 N_("display photo IDs during signature verification")},
2665 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2666 N_("show policy URLs during signature verification")},
2667 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2668 N_("show all notations during signature verification")},
2669 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2670 N_("show IETF standard notations during signature verification")},
2671 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2672 NULL},
2673 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2674 N_("show user-supplied notations during signature verification")},
2675 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2676 N_("show preferred keyserver URLs during signature verification")},
2677 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2678 N_("show user ID validity during signature verification")},
2679 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2680 N_("show revoked and expired user IDs in signature verification")},
2681 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
2682 N_("show only the primary user ID in signature verification")},
2683 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2684 N_("validate signatures with PKA data")},
2685 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2686 N_("elevate the trust of signatures with valid PKA data")},
2687 {NULL,0,NULL,NULL}
2690 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2692 if(configname)
2693 log_error(_("%s:%d: invalid verify options\n"),
2694 configname,configlineno);
2695 else
2696 log_error(_("invalid verify options\n"));
2699 break;
2700 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2701 case oExecPath:
2702 if(set_exec_path(pargs.r.ret_str))
2703 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2704 else
2705 opt.exec_path_set=1;
2706 break;
2707 case oSetNotation:
2708 add_notation_data( pargs.r.ret_str, 0 );
2709 add_notation_data( pargs.r.ret_str, 1 );
2710 break;
2711 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2712 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2713 case oShowNotation:
2714 deprecated_warning(configname,configlineno,"--show-notation",
2715 "--list-options ","show-notations");
2716 deprecated_warning(configname,configlineno,"--show-notation",
2717 "--verify-options ","show-notations");
2718 opt.list_options|=LIST_SHOW_NOTATIONS;
2719 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2720 break;
2721 case oNoShowNotation:
2722 deprecated_warning(configname,configlineno,"--no-show-notation",
2723 "--list-options ","no-show-notations");
2724 deprecated_warning(configname,configlineno,"--no-show-notation",
2725 "--verify-options ","no-show-notations");
2726 opt.list_options&=~LIST_SHOW_NOTATIONS;
2727 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2728 break;
2729 case oUtf8Strings: utf8_strings = 1; break;
2730 case oNoUtf8Strings: utf8_strings = 0; break;
2731 case oDisableCipherAlgo:
2733 int algo = string_to_cipher_algo (pargs.r.ret_str);
2734 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2736 break;
2737 case oDisablePubkeyAlgo:
2739 int algo = gcry_pk_map_name (pargs.r.ret_str);
2740 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2742 break;
2743 case oNoSigCache: opt.no_sig_cache = 1; break;
2744 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2745 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2746 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2747 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2748 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2749 case oNoLiteral: opt.no_literal = 1; break;
2750 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2751 case oHonorHttpProxy:
2752 add_to_strlist(&opt.keyserver_options.other,"http-proxy");
2753 deprecated_warning(configname,configlineno,
2754 "--honor-http-proxy",
2755 "--keyserver-options ","http-proxy");
2756 break;
2757 case oFastListMode: opt.fast_list_mode = 1; break;
2758 case oFixedListMode: /* Dummy */ break;
2759 case oListOnly: opt.list_only=1; break;
2760 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2761 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2762 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2763 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2764 case oNoRandomSeedFile: use_random_seed = 0; break;
2765 case oAutoKeyRetrieve:
2766 case oNoAutoKeyRetrieve:
2767 if(pargs.r_opt==oAutoKeyRetrieve)
2768 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
2769 else
2770 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
2772 deprecated_warning(configname,configlineno,
2773 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
2774 "--no-auto-key-retrieve","--keyserver-options ",
2775 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
2776 "no-auto-key-retrieve");
2777 break;
2778 case oShowSessionKey: opt.show_session_key = 1; break;
2779 case oOverrideSessionKey:
2780 opt.override_session_key = pargs.r.ret_str;
2781 break;
2782 case oMergeOnly:
2783 deprecated_warning(configname,configlineno,"--merge-only",
2784 "--import-options ","merge-only");
2785 opt.import_options|=IMPORT_MERGE_ONLY;
2786 break;
2787 case oAllowSecretKeyImport: /* obsolete */ break;
2788 case oTryAllSecrets: opt.try_all_secrets = 1; break;
2789 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
2790 case oEnableSpecialFilenames:
2791 iobuf_enable_special_filenames (1);
2792 break;
2793 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
2794 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
2795 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
2796 case oPreservePermissions: opt.preserve_permissions=1; break;
2797 case oDefaultPreferenceList:
2798 opt.def_preference_list = pargs.r.ret_str;
2799 break;
2800 case oDefaultKeyserverURL:
2802 struct keyserver_spec *keyserver;
2803 keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
2804 configname,configlineno);
2805 if(!keyserver)
2806 log_error(_("could not parse keyserver URL\n"));
2807 else
2808 free_keyserver_spec(keyserver);
2810 opt.def_keyserver_url = pargs.r.ret_str;
2812 break;
2813 case oPersonalCipherPreferences:
2814 pers_cipher_list=pargs.r.ret_str;
2815 break;
2816 case oPersonalDigestPreferences:
2817 pers_digest_list=pargs.r.ret_str;
2818 break;
2819 case oPersonalCompressPreferences:
2820 pers_compress_list=pargs.r.ret_str;
2821 break;
2822 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
2823 case oDisplay: opt.display = pargs.r.ret_str; break;
2824 case oTTYname: opt.ttyname = pargs.r.ret_str; break;
2825 case oTTYtype: opt.ttytype = pargs.r.ret_str; break;
2826 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
2827 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
2828 case oXauthority: opt.xauthority = pargs.r.ret_str; break;
2829 case oGroup: add_group(pargs.r.ret_str); break;
2830 case oUnGroup: rm_group(pargs.r.ret_str); break;
2831 case oNoGroups:
2832 while(opt.grouplist)
2834 struct groupitem *iter=opt.grouplist;
2835 free_strlist(iter->values);
2836 opt.grouplist=opt.grouplist->next;
2837 xfree(iter);
2839 break;
2841 case oStrict:
2842 case oNoStrict:
2843 /* Not used */
2844 break;
2846 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
2847 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
2848 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
2849 case oMultifile: multifile=1; break;
2850 case oKeyidFormat:
2851 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
2852 opt.keyid_format=KF_SHORT;
2853 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
2854 opt.keyid_format=KF_LONG;
2855 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
2856 opt.keyid_format=KF_0xSHORT;
2857 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
2858 opt.keyid_format=KF_0xLONG;
2859 else
2860 log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
2861 break;
2863 case oExitOnStatusWriteError:
2864 opt.exit_on_status_write_error = 1;
2865 break;
2867 case oLimitCardInsertTries:
2868 opt.limit_card_insert_tries = pargs.r.ret_int;
2869 break;
2871 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
2872 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
2874 case oAutoKeyLocate:
2875 if(!parse_auto_key_locate(pargs.r.ret_str))
2877 if(configname)
2878 log_error(_("%s:%d: invalid auto-key-locate list\n"),
2879 configname,configlineno);
2880 else
2881 log_error(_("invalid auto-key-locate list\n"));
2883 break;
2884 case oNoAutoKeyLocate:
2885 release_akl();
2886 break;
2888 case oEnableDSA2: opt.flags.dsa2=1; break;
2889 case oDisableDSA2: opt.flags.dsa2=0; break;
2891 case oAllowMultisigVerification:
2892 case oAllowMultipleMessages:
2893 opt.flags.allow_multiple_messages=1;
2894 break;
2896 case oNoAllowMultipleMessages:
2897 opt.flags.allow_multiple_messages=0;
2898 break;
2900 case oNoop: break;
2902 default:
2903 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
2904 break;
2909 if( configfp ) {
2910 fclose( configfp );
2911 configfp = NULL;
2912 /* Remember the first config file name. */
2913 if (!save_configname)
2914 save_configname = configname;
2915 else
2916 xfree(configname);
2917 configname = NULL;
2918 goto next_pass;
2920 xfree( configname ); configname = NULL;
2921 if( log_get_errorcount(0) )
2922 g10_exit(2);
2924 /* The command --gpgconf-list is pretty simple and may be called
2925 directly after the option parsing. */
2926 if (cmd == aGPGConfList)
2928 gpgconf_list (save_configname ? save_configname : default_configname);
2929 g10_exit (0);
2931 xfree (save_configname);
2932 xfree (default_configname);
2934 if( nogreeting )
2935 greeting = 0;
2937 if( greeting ) {
2938 fprintf(stderr, "%s %s; %s\n",
2939 strusage(11), strusage(13), strusage(14) );
2940 fprintf(stderr, "%s\n", strusage(15) );
2942 #ifdef IS_DEVELOPMENT_VERSION
2943 if (!opt.batch)
2945 const char *s;
2947 if((s=strusage(25)))
2948 log_info("%s\n",s);
2949 if((s=strusage(26)))
2950 log_info("%s\n",s);
2951 if((s=strusage(27)))
2952 log_info("%s\n",s);
2954 #endif
2956 /* FIXME: We should use logging to a file only in server mode;
2957 however we have not yet implemetyed that. Thus we try to get
2958 away with --batch as indication for logging to file
2959 required. */
2960 if (logfile && opt.batch)
2962 log_set_file (logfile);
2963 log_set_prefix (NULL, 1|2|4);
2966 #ifdef USE_CAMELLIA
2967 /* We better also print a runtime warning if people build it with
2968 support for Camellia (which is not yet defined by OpenPGP). */
2969 log_info ("WARNING: This version has been built with support for the "
2970 "Camellia cipher.\n");
2971 log_info (" It is for testing only and is NOT for production "
2972 "use!\n");
2973 #endif
2975 /* Older Libgcrypts fail with an assertion during DSA key
2976 generation. Better disable DSA2 entirely. */
2977 if (opt.flags.dsa2 && !gcry_check_version ("1.4.0") )
2979 log_info ("WARNING: "
2980 "DSA2 is only available with Libgcrypt 1.4 and later\n");
2981 opt.flags.dsa2 = 0;
2984 if (opt.verbose > 2)
2985 log_info ("using character set `%s'\n", get_native_charset ());
2987 if( may_coredump && !opt.quiet )
2988 log_info(_("WARNING: program may create a core file!\n"));
2990 if (eyes_only) {
2991 if (opt.set_filename)
2992 log_info(_("WARNING: %s overrides %s\n"),
2993 "--for-your-eyes-only","--set-filename");
2995 opt.set_filename="_CONSOLE";
2998 if (opt.no_literal) {
2999 log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
3000 if (opt.textmode)
3001 log_error(_("%s not allowed with %s!\n"),
3002 "--textmode", "--no-literal" );
3003 if (opt.set_filename)
3004 log_error(_("%s makes no sense with %s!\n"),
3005 eyes_only?"--for-your-eyes-only":"--set-filename",
3006 "--no-literal" );
3010 if (opt.set_filesize)
3011 log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
3012 if( opt.batch )
3013 tty_batchmode( 1 );
3015 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3017 if(require_secmem && !got_secmem)
3019 log_info(_("will not run with insecure memory due to %s\n"),
3020 "--require-secmem");
3021 g10_exit(2);
3024 set_debug (debug_level);
3026 /* Do these after the switch(), so they can override settings. */
3027 if(PGP2)
3029 int unusable=0;
3031 if(cmd==aSign && !detached_sig)
3033 log_info(_("you can only make detached or clear signatures "
3034 "while in --pgp2 mode\n"));
3035 unusable=1;
3037 else if(cmd==aSignEncr || cmd==aSignSym)
3039 log_info(_("you can't sign and encrypt at the "
3040 "same time while in --pgp2 mode\n"));
3041 unusable=1;
3043 else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
3045 log_info(_("you must use files (and not a pipe) when "
3046 "working with --pgp2 enabled.\n"));
3047 unusable=1;
3049 else if(cmd==aEncr || cmd==aSym)
3051 /* Everything else should work without IDEA (except using
3052 a secret key encrypted with IDEA and setting an IDEA
3053 preference, but those have their own error
3054 messages). */
3056 if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
3058 log_info(_("encrypting a message in --pgp2 mode requires "
3059 "the IDEA cipher\n"));
3060 idea_cipher_warn(1);
3061 unusable=1;
3063 else if(cmd==aSym)
3065 /* This only sets IDEA for symmetric encryption
3066 since it is set via select_algo_from_prefs for
3067 pk encryption. */
3068 xfree(def_cipher_string);
3069 def_cipher_string = xstrdup("idea");
3072 /* PGP2 can't handle the output from the textmode
3073 filter, so we disable it for anything that could
3074 create a literal packet (only encryption and
3075 symmetric encryption, since we disable signing
3076 above). */
3077 if(!unusable)
3078 opt.textmode=0;
3081 if(unusable)
3082 compliance_failure();
3083 else
3085 opt.force_v4_certs = 0;
3086 opt.escape_from = 1;
3087 opt.force_v3_sigs = 1;
3088 opt.pgp2_workarounds = 1;
3089 opt.ask_sig_expire = 0;
3090 opt.ask_cert_expire = 0;
3091 xfree(def_digest_string);
3092 def_digest_string = xstrdup("md5");
3093 xfree(s2k_digest_string);
3094 s2k_digest_string = xstrdup("md5");
3095 opt.compress_algo = COMPRESS_ALGO_ZIP;
3098 else if(PGP6)
3100 opt.escape_from=1;
3101 opt.force_v3_sigs=1;
3102 opt.ask_sig_expire=0;
3104 else if(PGP7)
3106 opt.escape_from=1;
3107 opt.force_v3_sigs=1;
3108 opt.ask_sig_expire=0;
3110 else if(PGP8)
3112 opt.escape_from=1;
3116 if( def_cipher_string ) {
3117 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3118 if(opt.def_cipher_algo==0 &&
3119 (ascii_strcasecmp(def_cipher_string,"idea")==0
3120 || ascii_strcasecmp(def_cipher_string,"s1")==0))
3121 idea_cipher_warn(1);
3122 xfree(def_cipher_string); def_cipher_string = NULL;
3123 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3124 log_error(_("selected cipher algorithm is invalid\n"));
3126 if( def_digest_string ) {
3127 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3128 xfree(def_digest_string); def_digest_string = NULL;
3129 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3130 log_error(_("selected digest algorithm is invalid\n"));
3132 if( compress_algo_string ) {
3133 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3134 xfree(compress_algo_string); compress_algo_string = NULL;
3135 if( check_compress_algo(opt.compress_algo) )
3136 log_error(_("selected compression algorithm is invalid\n"));
3138 if( cert_digest_string ) {
3139 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3140 xfree(cert_digest_string); cert_digest_string = NULL;
3141 if (openpgp_md_test_algo(opt.cert_digest_algo))
3142 log_error(_("selected certification digest algorithm is invalid\n"));
3144 if( s2k_cipher_string ) {
3145 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3146 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3147 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3148 log_error(_("selected cipher algorithm is invalid\n"));
3150 if( s2k_digest_string ) {
3151 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3152 xfree(s2k_digest_string); s2k_digest_string = NULL;
3153 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3154 log_error(_("selected digest algorithm is invalid\n"));
3156 if( opt.completes_needed < 1 )
3157 log_error(_("completes-needed must be greater than 0\n"));
3158 if( opt.marginals_needed < 2 )
3159 log_error(_("marginals-needed must be greater than 1\n"));
3160 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3161 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3162 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3163 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3164 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3165 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3166 switch( opt.s2k_mode ) {
3167 case 0:
3168 log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
3169 break;
3170 case 1: case 3: break;
3171 default:
3172 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3175 /* This isn't actually needed, but does serve to error out if the
3176 string is invalid. */
3177 if(opt.def_preference_list &&
3178 keygen_set_std_prefs(opt.def_preference_list,0))
3179 log_error(_("invalid default preferences\n"));
3181 /* We provide defaults for the personal digest list. This is
3182 SHA-1. */
3183 if(!pers_digest_list)
3184 pers_digest_list="h2";
3186 if(pers_cipher_list &&
3187 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3188 log_error(_("invalid personal cipher preferences\n"));
3190 if(pers_digest_list &&
3191 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3192 log_error(_("invalid personal digest preferences\n"));
3194 if(pers_compress_list &&
3195 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3196 log_error(_("invalid personal compress preferences\n"));
3198 /* We don't support all possible commands with multifile yet */
3199 if(multifile)
3201 char *cmdname;
3203 switch(cmd)
3205 case aSign:
3206 cmdname="--sign";
3207 break;
3208 case aClearsign:
3209 cmdname="--clearsign";
3210 break;
3211 case aDetachedSign:
3212 cmdname="--detach-sign";
3213 break;
3214 case aSym:
3215 cmdname="--symmetric";
3216 break;
3217 case aEncrSym:
3218 cmdname="--symmetric --encrypt";
3219 break;
3220 case aStore:
3221 cmdname="--store";
3222 break;
3223 default:
3224 cmdname=NULL;
3225 break;
3228 if(cmdname)
3229 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3232 if( log_get_errorcount(0) )
3233 g10_exit(2);
3235 if(opt.compress_level==0)
3236 opt.compress_algo=COMPRESS_ALGO_NONE;
3238 /* Check our chosen algorithms against the list of legal
3239 algorithms. */
3241 if(!GNUPG)
3243 const char *badalg=NULL;
3244 preftype_t badtype=PREFTYPE_NONE;
3246 if(opt.def_cipher_algo
3247 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3249 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3250 badtype = PREFTYPE_SYM;
3252 else if(opt.def_digest_algo
3253 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3255 badalg = gcry_md_algo_name (opt.def_digest_algo);
3256 badtype = PREFTYPE_HASH;
3258 else if(opt.cert_digest_algo
3259 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3261 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3262 badtype = PREFTYPE_HASH;
3264 else if(opt.compress_algo!=-1
3265 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3267 badalg = compress_algo_to_string(opt.compress_algo);
3268 badtype = PREFTYPE_ZIP;
3271 if(badalg)
3273 switch(badtype)
3275 case PREFTYPE_SYM:
3276 log_info(_("you may not use cipher algorithm `%s'"
3277 " while in %s mode\n"),
3278 badalg,compliance_option_string());
3279 break;
3280 case PREFTYPE_HASH:
3281 log_info(_("you may not use digest algorithm `%s'"
3282 " while in %s mode\n"),
3283 badalg,compliance_option_string());
3284 break;
3285 case PREFTYPE_ZIP:
3286 log_info(_("you may not use compression algorithm `%s'"
3287 " while in %s mode\n"),
3288 badalg,compliance_option_string());
3289 break;
3290 default:
3291 BUG();
3294 compliance_failure();
3298 /* Set the random seed file. */
3299 if( use_random_seed ) {
3300 char *p = make_filename(opt.homedir, "random_seed", NULL );
3301 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3302 if (!access (p, F_OK))
3303 register_secured_file (p);
3304 xfree(p);
3307 /* If there is no command but the --fingerprint is given, default
3308 to the --list-keys command. */
3309 if (!cmd && fpr_maybe_cmd)
3311 set_cmd (&cmd, aListKeys);
3315 if( opt.verbose > 1 )
3316 set_packet_list_mode(1);
3318 /* Add the keyrings, but not for some special commands. Also
3319 avoid adding the secret keyring for a couple of commands to
3320 avoid unneeded access in case the secrings are stored on a
3321 floppy.
3323 We always need to add the keyrings if we are running under
3324 SELinux, this is so that the rings are added to the list of
3325 secured files. */
3326 if( ALWAYS_ADD_KEYRINGS
3327 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) )
3329 if (ALWAYS_ADD_KEYRINGS
3330 || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
3331 && cmd != aVerify && cmd != aSym && cmd != aLocateKeys))
3333 if (!sec_nrings || default_keyring) /* add default secret rings */
3334 keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
3335 for (sl = sec_nrings; sl; sl = sl->next)
3336 keydb_add_resource ( sl->d, 0, 1 );
3338 if( !nrings || default_keyring ) /* add default ring */
3339 keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
3340 for(sl = nrings; sl; sl = sl->next )
3341 keydb_add_resource ( sl->d, sl->flags, 0 );
3343 FREE_STRLIST(nrings);
3344 FREE_STRLIST(sec_nrings);
3346 if (cmd == aGPGConfTest)
3347 g10_exit(0);
3350 if( pwfd != -1 ) /* Read the passphrase now. */
3351 read_passphrase_from_fd( pwfd );
3353 fname = argc? *argv : NULL;
3355 if(fname && utf8_strings)
3356 opt.flags.utf8_filename=1;
3358 switch( cmd ) {
3359 case aPrimegen:
3360 case aPrintMD:
3361 case aPrintMDs:
3362 case aGenRandom:
3363 case aDeArmor:
3364 case aEnArmor:
3365 case aFixTrustDB:
3366 break;
3367 case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
3368 case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
3369 default: rc = setup_trustdb(1, trustdb_name ); break;
3371 if( rc )
3372 log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
3375 switch (cmd)
3377 case aStore:
3378 case aSym:
3379 case aSign:
3380 case aSignSym:
3381 case aClearsign:
3382 if (!opt.quiet && any_explicit_recipient)
3383 log_info (_("WARNING: recipients (-r) given "
3384 "without using public key encryption\n"));
3385 break;
3386 default:
3387 break;
3390 switch( cmd )
3392 case aServer:
3394 ctrl_t ctrl = xtrycalloc (1, sizeof *ctrl);
3395 gpg_init_default_ctrl (ctrl);
3396 gpg_server (ctrl);
3397 gpg_deinit_default_ctrl (ctrl);
3398 xfree (ctrl);
3400 break;
3402 case aStore: /* only store the file */
3403 if( argc > 1 )
3404 wrong_args(_("--store [filename]"));
3405 if( (rc = encode_store(fname)) )
3406 log_error ("storing `%s' failed: %s\n",
3407 print_fname_stdin(fname),g10_errstr(rc) );
3408 break;
3409 case aSym: /* encrypt the given file only with the symmetric cipher */
3410 if( argc > 1 )
3411 wrong_args(_("--symmetric [filename]"));
3412 if( (rc = encode_symmetric(fname)) )
3413 log_error (_("symmetric encryption of `%s' failed: %s\n"),
3414 print_fname_stdin(fname),g10_errstr(rc) );
3415 break;
3417 case aEncr: /* encrypt the given file */
3418 if(multifile)
3419 encode_crypt_files(argc, argv, remusr);
3420 else
3422 if( argc > 1 )
3423 wrong_args(_("--encrypt [filename]"));
3424 if( (rc = encode_crypt(fname,remusr,0)) )
3425 log_error("%s: encryption failed: %s\n",
3426 print_fname_stdin(fname), g10_errstr(rc) );
3428 break;
3430 case aEncrSym:
3431 /* This works with PGP 8 in the sense that it acts just like a
3432 symmetric message. It doesn't work at all with 2 or 6. It
3433 might work with 7, but alas, I don't have a copy to test
3434 with right now. */
3435 if( argc > 1 )
3436 wrong_args(_("--symmetric --encrypt [filename]"));
3437 else if(opt.s2k_mode==0)
3438 log_error(_("you cannot use --symmetric --encrypt"
3439 " with --s2k-mode 0\n"));
3440 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3441 log_error(_("you cannot use --symmetric --encrypt"
3442 " while in %s mode\n"),compliance_option_string());
3443 else
3445 if( (rc = encode_crypt(fname,remusr,1)) )
3446 log_error("%s: encryption failed: %s\n",
3447 print_fname_stdin(fname), g10_errstr(rc) );
3449 break;
3451 case aSign: /* sign the given file */
3452 sl = NULL;
3453 if( detached_sig ) { /* sign all files */
3454 for( ; argc; argc--, argv++ )
3455 add_to_strlist( &sl, *argv );
3457 else {
3458 if( argc > 1 )
3459 wrong_args(_("--sign [filename]"));
3460 if( argc ) {
3461 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3462 strcpy(sl->d, fname);
3465 if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
3466 log_error("signing failed: %s\n", g10_errstr(rc) );
3467 free_strlist(sl);
3468 break;
3470 case aSignEncr: /* sign and encrypt the given file */
3471 if( argc > 1 )
3472 wrong_args(_("--sign --encrypt [filename]"));
3473 if( argc ) {
3474 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3475 strcpy(sl->d, fname);
3477 else
3478 sl = NULL;
3479 if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
3480 log_error("%s: sign+encrypt failed: %s\n",
3481 print_fname_stdin(fname), g10_errstr(rc) );
3482 free_strlist(sl);
3483 break;
3485 case aSignEncrSym: /* sign and encrypt the given file */
3486 if( argc > 1 )
3487 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3488 else if(opt.s2k_mode==0)
3489 log_error(_("you cannot use --symmetric --sign --encrypt"
3490 " with --s2k-mode 0\n"));
3491 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3492 log_error(_("you cannot use --symmetric --sign --encrypt"
3493 " while in %s mode\n"),compliance_option_string());
3494 else
3496 if( argc )
3498 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3499 strcpy(sl->d, fname);
3501 else
3502 sl = NULL;
3503 if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
3504 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3505 print_fname_stdin(fname), g10_errstr(rc) );
3506 free_strlist(sl);
3508 break;
3510 case aSignSym: /* sign and conventionally encrypt the given file */
3511 if (argc > 1)
3512 wrong_args(_("--sign --symmetric [filename]"));
3513 rc = sign_symencrypt_file (fname, locusr);
3514 if (rc)
3515 log_error("%s: sign+symmetric failed: %s\n",
3516 print_fname_stdin(fname), g10_errstr(rc) );
3517 break;
3519 case aClearsign: /* make a clearsig */
3520 if( argc > 1 )
3521 wrong_args(_("--clearsign [filename]"));
3522 if( (rc = clearsign_file(fname, locusr, NULL)) )
3523 log_error("%s: clearsign failed: %s\n",
3524 print_fname_stdin(fname), g10_errstr(rc) );
3525 break;
3527 case aVerify:
3528 if(multifile)
3530 if( (rc = verify_files( argc, argv ) ))
3531 log_error("verify files failed: %s\n", g10_errstr(rc) );
3533 else
3535 if( (rc = verify_signatures( argc, argv ) ))
3536 log_error("verify signatures failed: %s\n", g10_errstr(rc) );
3538 break;
3540 case aDecrypt:
3541 if(multifile)
3542 decrypt_messages(argc, argv);
3543 else
3545 if( argc > 1 )
3546 wrong_args(_("--decrypt [filename]"));
3547 if( (rc = decrypt_message( fname ) ))
3548 log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
3550 break;
3552 case aSignKey:
3553 if( argc != 1 )
3554 wrong_args(_("--sign-key user-id"));
3555 /* fall through */
3556 case aLSignKey:
3557 if( argc != 1 )
3558 wrong_args(_("--lsign-key user-id"));
3559 /* fall through */
3561 sl=NULL;
3563 if(cmd==aSignKey)
3564 append_to_strlist(&sl,"sign");
3565 else if(cmd==aLSignKey)
3566 append_to_strlist(&sl,"lsign");
3567 else
3568 BUG();
3570 append_to_strlist( &sl, "save" );
3571 username = make_username( fname );
3572 keyedit_menu (username, locusr, sl, 0, 0 );
3573 xfree(username);
3574 free_strlist(sl);
3575 break;
3577 case aEditKey: /* Edit a key signature */
3578 if( !argc )
3579 wrong_args(_("--edit-key user-id [commands]"));
3580 username = make_username( fname );
3581 if( argc > 1 ) {
3582 sl = NULL;
3583 for( argc--, argv++ ; argc; argc--, argv++ )
3584 append_to_strlist( &sl, *argv );
3585 keyedit_menu( username, locusr, sl, 0, 1 );
3586 free_strlist(sl);
3588 else
3589 keyedit_menu(username, locusr, NULL, 0, 1 );
3590 xfree(username);
3591 break;
3593 case aDeleteKeys:
3594 case aDeleteSecretKeys:
3595 case aDeleteSecretAndPublicKeys:
3596 sl = NULL;
3597 /* I'm adding these in reverse order as add_to_strlist2
3598 reverses them again, and it's easier to understand in the
3599 proper order :) */
3600 for( ; argc; argc-- )
3601 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3602 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3603 free_strlist(sl);
3604 break;
3606 case aCheckKeys:
3607 opt.check_sigs = 1;
3608 case aListSigs:
3609 opt.list_sigs = 1;
3610 case aListKeys:
3611 sl = NULL;
3612 for( ; argc; argc--, argv++ )
3613 add_to_strlist2( &sl, *argv, utf8_strings );
3614 public_key_list( sl, 0 );
3615 free_strlist(sl);
3616 break;
3617 case aListSecretKeys:
3618 sl = NULL;
3619 for( ; argc; argc--, argv++ )
3620 add_to_strlist2( &sl, *argv, utf8_strings );
3621 secret_key_list( sl );
3622 free_strlist(sl);
3623 break;
3624 case aLocateKeys:
3625 sl = NULL;
3626 for (; argc; argc--, argv++)
3627 add_to_strlist2( &sl, *argv, utf8_strings );
3628 public_key_list (sl, 1);
3629 free_strlist (sl);
3630 break;
3632 case aKeygen: /* generate a key */
3633 if( opt.batch ) {
3634 if( argc > 1 )
3635 wrong_args("--gen-key [parameterfile]");
3636 generate_keypair( argc? *argv : NULL, NULL, NULL );
3638 else {
3639 if( argc )
3640 wrong_args("--gen-key");
3641 generate_keypair(NULL, NULL, NULL);
3643 break;
3645 case aFastImport:
3646 opt.import_options |= IMPORT_FAST;
3647 case aImport:
3648 import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
3649 break;
3651 /* TODO: There are a number of command that use this same
3652 "make strlist, call function, report error, free strlist"
3653 pattern. Join them together here and avoid all that
3654 duplicated code. */
3656 case aExport:
3657 case aSendKeys:
3658 case aRecvKeys:
3659 sl = NULL;
3660 for( ; argc; argc--, argv++ )
3661 append_to_strlist2( &sl, *argv, utf8_strings );
3662 if( cmd == aSendKeys )
3663 rc=keyserver_export( sl );
3664 else if( cmd == aRecvKeys )
3665 rc=keyserver_import( sl );
3666 else
3667 rc=export_pubkeys( sl, opt.export_options );
3668 if(rc)
3670 if(cmd==aSendKeys)
3671 log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
3672 else if(cmd==aRecvKeys)
3673 log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
3674 else
3675 log_error(_("key export failed: %s\n"),g10_errstr(rc));
3677 free_strlist(sl);
3678 break;
3680 case aSearchKeys:
3681 sl = NULL;
3682 for( ; argc; argc--, argv++ )
3683 append_to_strlist2( &sl, *argv, utf8_strings );
3684 rc=keyserver_search( sl );
3685 if(rc)
3686 log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
3687 free_strlist(sl);
3688 break;
3690 case aRefreshKeys:
3691 sl = NULL;
3692 for( ; argc; argc--, argv++ )
3693 append_to_strlist2( &sl, *argv, utf8_strings );
3694 rc=keyserver_refresh(sl);
3695 if(rc)
3696 log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
3697 free_strlist(sl);
3698 break;
3700 case aFetchKeys:
3701 sl = NULL;
3702 for( ; argc; argc--, argv++ )
3703 append_to_strlist2( &sl, *argv, utf8_strings );
3704 rc=keyserver_fetch(sl);
3705 if(rc)
3706 log_error("key fetch failed: %s\n",g10_errstr(rc));
3707 free_strlist(sl);
3708 break;
3710 case aExportSecret:
3711 sl = NULL;
3712 for( ; argc; argc--, argv++ )
3713 add_to_strlist2( &sl, *argv, utf8_strings );
3714 export_seckeys( sl );
3715 free_strlist(sl);
3716 break;
3718 case aExportSecretSub:
3719 sl = NULL;
3720 for( ; argc; argc--, argv++ )
3721 add_to_strlist2( &sl, *argv, utf8_strings );
3722 export_secsubkeys( sl );
3723 free_strlist(sl);
3724 break;
3726 case aGenRevoke:
3727 if( argc != 1 )
3728 wrong_args("--gen-revoke user-id");
3729 username = make_username(*argv);
3730 gen_revoke( username );
3731 xfree( username );
3732 break;
3734 case aDesigRevoke:
3735 if( argc != 1 )
3736 wrong_args("--desig-revoke user-id");
3737 username = make_username(*argv);
3738 gen_desig_revoke( username, locusr );
3739 xfree( username );
3740 break;
3742 case aDeArmor:
3743 if( argc > 1 )
3744 wrong_args("--dearmor [file]");
3745 rc = dearmor_file( argc? *argv: NULL );
3746 if( rc )
3747 log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
3748 break;
3750 case aEnArmor:
3751 if( argc > 1 )
3752 wrong_args("--enarmor [file]");
3753 rc = enarmor_file( argc? *argv: NULL );
3754 if( rc )
3755 log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
3756 break;
3759 case aPrimegen:
3760 #if 0 /*FIXME*/
3761 { int mode = argc < 2 ? 0 : atoi(*argv);
3763 if( mode == 1 && argc == 2 ) {
3764 mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
3766 else if( mode == 2 && argc == 3 ) {
3767 mpi_print( stdout, generate_elg_prime(
3768 0, atoi(argv[1]),
3769 atoi(argv[2]), NULL,NULL ), 1);
3771 else if( mode == 3 && argc == 3 ) {
3772 MPI *factors;
3773 mpi_print( stdout, generate_elg_prime(
3774 1, atoi(argv[1]),
3775 atoi(argv[2]), NULL,&factors ), 1);
3776 putchar('\n');
3777 mpi_print( stdout, factors[0], 1 ); /* print q */
3779 else if( mode == 4 && argc == 3 ) {
3780 MPI g = mpi_alloc(1);
3781 mpi_print( stdout, generate_elg_prime(
3782 0, atoi(argv[1]),
3783 atoi(argv[2]), g, NULL ), 1);
3784 putchar('\n');
3785 mpi_print( stdout, g, 1 );
3786 mpi_free(g);
3788 else
3789 wrong_args("--gen-prime mode bits [qbits] ");
3790 putchar('\n');
3792 #endif
3793 wrong_args("--gen-prime not yet supported ");
3794 break;
3796 case aGenRandom:
3798 int level = argc ? atoi(*argv):0;
3799 int count = argc > 1 ? atoi(argv[1]): 0;
3800 int endless = !count;
3802 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
3803 wrong_args("--gen-random 0|1|2 [count]");
3805 while( endless || count ) {
3806 byte *p;
3807 /* Wee need a multiple of 3, so that in case of
3808 armored output we get a correct string. No
3809 linefolding is done, as it is best to levae this to
3810 other tools */
3811 size_t n = !endless && count < 99? count : 99;
3813 p = gcry_random_bytes (n, level);
3814 #ifdef HAVE_DOSISH_SYSTEM
3815 setmode ( fileno(stdout), O_BINARY );
3816 #endif
3817 if (opt.armor) {
3818 char *tmp = make_radix64_string (p, n);
3819 fputs (tmp, stdout);
3820 xfree (tmp);
3821 if (n%3 == 1)
3822 putchar ('=');
3823 if (n%3)
3824 putchar ('=');
3825 } else {
3826 fwrite( p, n, 1, stdout );
3828 xfree(p);
3829 if( !endless )
3830 count -= n;
3832 if (opt.armor)
3833 putchar ('\n');
3835 break;
3837 case aPrintMD:
3838 if( argc < 1)
3839 wrong_args("--print-md algo [files]");
3841 int all_algos = (**argv=='*' && !(*argv)[1]);
3842 int algo = all_algos? 0 : gcry_md_map_name (*argv);
3844 if( !algo && !all_algos )
3845 log_error(_("invalid hash algorithm `%s'\n"), *argv );
3846 else {
3847 argc--; argv++;
3848 if( !argc )
3849 print_mds(NULL, algo);
3850 else {
3851 for(; argc; argc--, argv++ )
3852 print_mds(*argv, algo);
3856 break;
3858 case aPrintMDs: /* old option */
3859 if( !argc )
3860 print_mds(NULL,0);
3861 else {
3862 for(; argc; argc--, argv++ )
3863 print_mds(*argv,0);
3865 break;
3867 case aListTrustDB:
3868 if( !argc )
3869 list_trustdb(NULL);
3870 else {
3871 for( ; argc; argc--, argv++ )
3872 list_trustdb( *argv );
3874 break;
3876 case aUpdateTrustDB:
3877 if( argc )
3878 wrong_args("--update-trustdb");
3879 update_trustdb();
3880 break;
3882 case aCheckTrustDB:
3883 /* Old versions allowed for arguments - ignore them */
3884 check_trustdb();
3885 break;
3887 case aFixTrustDB:
3888 log_error("this command is not yet implemented.\n");
3889 log_error("A workaround is to use \"--export-ownertrust\", remove\n");
3890 log_error("the trustdb file and do an \"--import-ownertrust\".\n" );
3891 break;
3893 case aListTrustPath:
3894 if( !argc )
3895 wrong_args("--list-trust-path <user-ids>");
3896 for( ; argc; argc--, argv++ ) {
3897 username = make_username( *argv );
3898 list_trust_path( username );
3899 xfree(username);
3901 break;
3903 case aExportOwnerTrust:
3904 if( argc )
3905 wrong_args("--export-ownertrust");
3906 export_ownertrust();
3907 break;
3909 case aImportOwnerTrust:
3910 if( argc > 1 )
3911 wrong_args("--import-ownertrust [file]");
3912 import_ownertrust( argc? *argv:NULL );
3913 break;
3915 case aRebuildKeydbCaches:
3916 if (argc)
3917 wrong_args ("--rebuild-keydb-caches");
3918 keydb_rebuild_caches (1);
3919 break;
3921 #ifdef ENABLE_CARD_SUPPORT
3922 case aCardStatus:
3923 if (argc)
3924 wrong_args ("--card-status");
3925 card_status (stdout, NULL, 0);
3926 break;
3928 case aCardEdit:
3929 if (argc) {
3930 sl = NULL;
3931 for (argc--, argv++ ; argc; argc--, argv++)
3932 append_to_strlist (&sl, *argv);
3933 card_edit (sl);
3934 free_strlist (sl);
3936 else
3937 card_edit (NULL);
3938 break;
3940 case aChangePIN:
3941 if (!argc)
3942 change_pin (0,1);
3943 else if (argc == 1)
3944 change_pin (atoi (*argv),1);
3945 else
3946 wrong_args ("--change-pin [no]");
3947 break;
3948 #endif /* ENABLE_CARD_SUPPORT*/
3950 case aListConfig:
3952 char *str=collapse_args(argc,argv);
3953 list_config(str);
3954 xfree(str);
3956 break;
3958 case aListPackets:
3959 opt.list_packets=2;
3960 default:
3961 if( argc > 1 )
3962 wrong_args(_("[filename]"));
3963 /* Issue some output for the unix newbie */
3964 if( !fname && !opt.outfile && isatty( fileno(stdin) )
3965 && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
3966 log_info(_("Go ahead and type your message ...\n"));
3968 a = iobuf_open(fname);
3969 if (a && is_secured_file (iobuf_get_fd (a)))
3971 iobuf_close (a);
3972 a = NULL;
3973 errno = EPERM;
3975 if( !a )
3976 log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
3977 else {
3979 if( !opt.no_armor ) {
3980 if( use_armor_filter( a ) ) {
3981 afx = new_armor_context ();
3982 push_armor_filter (afx, a);
3985 if( cmd == aListPackets ) {
3986 set_packet_list_mode(1);
3987 opt.list_packets=1;
3989 rc = proc_packets(NULL, a );
3990 if( rc )
3991 log_error("processing message failed: %s\n", g10_errstr(rc) );
3992 iobuf_close(a);
3994 break;
3997 /* cleanup */
3998 release_armor_context (afx);
3999 FREE_STRLIST(remusr);
4000 FREE_STRLIST(locusr);
4001 g10_exit(0);
4002 return 8; /*NEVER REACHED*/
4006 /* Note: This function is used by signal handlers!. */
4007 static void
4008 emergency_cleanup (void)
4010 gcry_control (GCRYCTL_TERM_SECMEM );
4014 void
4015 g10_exit( int rc )
4017 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
4018 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
4020 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
4021 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
4023 if (opt.debug)
4024 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
4026 emergency_cleanup ();
4028 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
4029 exit (rc);
4033 /* Pretty-print hex hashes. This assumes at least an 80-character
4034 display, but there are a few other similar assumptions in the
4035 display code. */
4036 static void
4037 print_hex( gcry_md_hd_t md, int algo, const char *fname )
4039 int i,n,count,indent=0;
4040 const byte *p;
4042 if(fname)
4043 indent=printf("%s: ",fname);
4045 if(indent>40)
4047 printf("\n");
4048 indent=0;
4051 if(algo==DIGEST_ALGO_RMD160)
4052 indent+=printf("RMD160 = ");
4053 else if(algo>0)
4054 indent+=printf("%6s = ", gcry_md_algo_name (algo));
4055 else
4056 algo=abs(algo);
4058 count=indent;
4060 p = gcry_md_read (md, algo);
4061 n = gcry_md_get_algo_dlen (algo);
4063 count += printf ("%02X",*p++);
4065 for(i=1;i<n;i++,p++)
4067 if(n==16)
4069 if(count+2>79)
4071 printf("\n%*s",indent," ");
4072 count=indent;
4074 else
4075 count+=printf(" ");
4077 if(!(i%8))
4078 count+=printf(" ");
4080 else if (n==20)
4082 if(!(i%2))
4084 if(count+4>79)
4086 printf("\n%*s",indent," ");
4087 count=indent;
4089 else
4090 count+=printf(" ");
4093 if(!(i%10))
4094 count+=printf(" ");
4096 else
4098 if(!(i%4))
4100 if(count+8>79)
4102 printf("\n%*s",indent," ");
4103 count=indent;
4105 else
4106 count+=printf(" ");
4110 count+=printf("%02X",*p);
4113 printf("\n");
4116 static void
4117 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
4119 int i, n;
4120 const byte *p;
4122 if ( fname ) {
4123 for (p = fname; *p; p++ ) {
4124 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
4125 printf("%%%02X", *p );
4126 else
4127 putchar( *p );
4130 putchar(':');
4131 printf("%d:", algo );
4132 p = gcry_md_read (md, algo);
4133 n = gcry_md_get_algo_dlen (algo);
4134 for(i=0; i < n ; i++, p++ )
4135 printf("%02X", *p );
4136 putchar(':');
4137 putchar('\n');
4140 static void
4141 print_mds( const char *fname, int algo )
4143 FILE *fp;
4144 char buf[1024];
4145 size_t n;
4146 gcry_md_hd_t md;
4148 if( !fname ) {
4149 fp = stdin;
4150 #ifdef HAVE_DOSISH_SYSTEM
4151 setmode ( fileno(fp) , O_BINARY );
4152 #endif
4154 else {
4155 fp = fopen( fname, "rb" );
4156 if (fp && is_secured_file (fileno (fp)))
4158 fclose (fp);
4159 fp = NULL;
4160 errno = EPERM;
4163 if( !fp ) {
4164 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4165 return;
4168 gcry_md_open (&md, 0, 0);
4169 if( algo )
4170 gcry_md_enable (md, algo);
4171 else {
4172 gcry_md_enable (md, GCRY_MD_MD5);
4173 gcry_md_enable (md, GCRY_MD_SHA1);
4174 gcry_md_enable (md, GCRY_MD_RMD160);
4175 if (!openpgp_md_test_algo (GCRY_MD_SHA224))
4176 gcry_md_enable (md, GCRY_MD_SHA224);
4177 if (!openpgp_md_test_algo (GCRY_MD_SHA256))
4178 gcry_md_enable (md, GCRY_MD_SHA256);
4179 if (!openpgp_md_test_algo (GCRY_MD_SHA384))
4180 gcry_md_enable (md, GCRY_MD_SHA384);
4181 if (!openpgp_md_test_algo (GCRY_MD_SHA512))
4182 gcry_md_enable (md, GCRY_MD_SHA512);
4185 while( (n=fread( buf, 1, DIM(buf), fp )) )
4186 gcry_md_write (md, buf, n);
4187 if( ferror(fp) )
4188 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4189 else {
4190 gcry_md_final (md);
4191 if ( opt.with_colons ) {
4192 if ( algo )
4193 print_hashline( md, algo, fname );
4194 else {
4195 print_hashline( md, GCRY_MD_MD5, fname );
4196 print_hashline( md, GCRY_MD_SHA1, fname );
4197 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4198 print_hashline( md, GCRY_MD_RMD160, fname );
4199 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4200 print_hashline (md, GCRY_MD_SHA224, fname);
4201 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4202 print_hashline( md, GCRY_MD_SHA256, fname );
4203 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4204 print_hashline ( md, GCRY_MD_SHA384, fname );
4205 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4206 print_hashline ( md, GCRY_MD_SHA512, fname );
4209 else {
4210 if( algo )
4211 print_hex(md,-algo,fname);
4212 else {
4213 print_hex( md, GCRY_MD_MD5, fname );
4214 print_hex( md, GCRY_MD_SHA1, fname );
4215 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4216 print_hex( md, GCRY_MD_RMD160, fname );
4217 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4218 print_hex (md, GCRY_MD_SHA224, fname);
4219 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4220 print_hex( md, GCRY_MD_SHA256, fname );
4221 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4222 print_hex( md, GCRY_MD_SHA384, fname );
4223 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4224 print_hex( md, GCRY_MD_SHA512, fname );
4228 gcry_md_close(md);
4230 if( fp != stdin )
4231 fclose(fp);
4235 /****************
4236 * Check the supplied name,value string and add it to the notation
4237 * data to be used for signatures. which==0 for sig notations, and 1
4238 * for cert notations.
4240 static void
4241 add_notation_data( const char *string, int which )
4243 struct notation *notation;
4245 notation=string_to_notation(string,utf8_strings);
4246 if(notation)
4248 if(which)
4250 notation->next=opt.cert_notations;
4251 opt.cert_notations=notation;
4253 else
4255 notation->next=opt.sig_notations;
4256 opt.sig_notations=notation;
4261 static void
4262 add_policy_url( const char *string, int which )
4264 unsigned int i,critical=0;
4265 strlist_t sl;
4267 if(*string=='!')
4269 string++;
4270 critical=1;
4273 for(i=0;i<strlen(string);i++)
4274 if( !isascii (string[i]) || iscntrl(string[i]))
4275 break;
4277 if(i==0 || i<strlen(string))
4279 if(which)
4280 log_error(_("the given certification policy URL is invalid\n"));
4281 else
4282 log_error(_("the given signature policy URL is invalid\n"));
4285 if(which)
4286 sl=add_to_strlist( &opt.cert_policy_url, string );
4287 else
4288 sl=add_to_strlist( &opt.sig_policy_url, string );
4290 if(critical)
4291 sl->flags |= 1;
4294 static void
4295 add_keyserver_url( const char *string, int which )
4297 unsigned int i,critical=0;
4298 strlist_t sl;
4300 if(*string=='!')
4302 string++;
4303 critical=1;
4306 for(i=0;i<strlen(string);i++)
4307 if( !isascii (string[i]) || iscntrl(string[i]))
4308 break;
4310 if(i==0 || i<strlen(string))
4312 if(which)
4313 BUG();
4314 else
4315 log_error(_("the given preferred keyserver URL is invalid\n"));
4318 if(which)
4319 BUG();
4320 else
4321 sl=add_to_strlist( &opt.sig_keyserver_url, string );
4323 if(critical)
4324 sl->flags |= 1;