~ubuntu-branches/ubuntu/precise/gnupg2/precise-proposed

« back to all changes in this revision

Viewing changes to g10/g10.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Mueller
  • Date: 2005-03-29 10:30:32 UTC
  • Revision ID: james.westby@ubuntu.com-20050329103032-sj42n2ain3ipx310
Tags: upstream-1.9.15
ImportĀ upstreamĀ versionĀ 1.9.15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* g10.c - The GnuPG utility (main for gpg)
 
2
 * Copyright (C) 1998,1999,2000,2001,2002,2003
 
3
 *               2004 Free Software Foundation, Inc.
 
4
 *
 
5
 * This file is part of GnuPG.
 
6
 *
 
7
 * GnuPG is free software; you can redistribute it and/or modify
 
8
 * it under the terms of the GNU General Public License as published by
 
9
 * the Free Software Foundation; either version 2 of the License, or
 
10
 * (at your option) any later version.
 
11
 *
 
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.
 
16
 *
 
17
 * You should have received a copy of the GNU General Public License
 
18
 * along with this program; if not, write to the Free Software
 
19
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
20
 */
 
21
 
 
22
#include <config.h>
 
23
#include <errno.h>
 
24
#include <stdio.h>
 
25
#include <stdlib.h>
 
26
#include <string.h>
 
27
#include <ctype.h>
 
28
#include <unistd.h>
 
29
#include <assert.h>
 
30
#ifdef HAVE_DOSISH_SYSTEM
 
31
#include <fcntl.h> /* for setmode() */
 
32
#endif
 
33
#ifdef HAVE_STAT
 
34
#include <sys/stat.h> /* for stat() */
 
35
#endif
 
36
#include <assuan.h>
 
37
 
 
38
#define INCLUDED_BY_MAIN_MODULE 1
 
39
#include "gpg.h"
 
40
#include "packet.h"
 
41
#include "iobuf.h"
 
42
#include "memory.h"
 
43
#include "util.h"
 
44
#include "main.h"
 
45
#include "options.h"
 
46
#include "keydb.h"
 
47
#include "trustdb.h"
 
48
#include "mpi.h"
 
49
#include "cipher.h"
 
50
#include "filter.h"
 
51
#include "ttyio.h"
 
52
#include "i18n.h"
 
53
#include "status.h"
 
54
#include "keyserver-internal.h"
 
55
#include "exec.h"
 
56
 
 
57
enum cmd_and_opt_values { aNull = 0,
 
58
    oArmor        = 'a',
 
59
    aDetachedSign = 'b',
 
60
    aSym          = 'c',
 
61
    aDecrypt      = 'd',
 
62
    aEncr         = 'e',
 
63
    oInteractive  = 'i',
 
64
    aListKeys     = 'k',
 
65
    aListSecretKeys = 'K',
 
66
    oDryRun       = 'n',
 
67
    oOutput       = 'o',
 
68
    oQuiet        = 'q',
 
69
    oRecipient    = 'r',
 
70
    oHiddenRecipient = 'R',
 
71
    aSign         = 's',
 
72
    oTextmodeShort= 't',
 
73
    oUser         = 'u',
 
74
    oVerbose      = 'v',
 
75
    oCompress     = 'z',
 
76
    oSetNotation  = 'N',
 
77
    oBatch        = 500,
 
78
    aGPGConfList,
 
79
    oSigNotation,
 
80
    oCertNotation,
 
81
    oShowNotation,
 
82
    oNoShowNotation,
 
83
    aEncrFiles,
 
84
    aDecryptFiles,                          
 
85
    aClearsign,
 
86
    aStore,
 
87
    aKeygen,
 
88
    aSignEncr,
 
89
    aSignSym,
 
90
    aSignKey,
 
91
    aLSignKey,
 
92
    aNRSignKey,
 
93
    aNRLSignKey,
 
94
    aListPackets,
 
95
    aEditKey,
 
96
    aDeleteKeys,
 
97
    aDeleteSecretKeys,
 
98
    aDeleteSecretAndPublicKeys,
 
99
    aImport,
 
100
    aFastImport,
 
101
    aVerify,
 
102
    aVerifyFiles,
 
103
    aListSigs,
 
104
    aSendKeys,
 
105
    aRecvKeys,
 
106
    aSearchKeys,
 
107
    aExport,
 
108
    aExportAll,
 
109
    aExportSecret,
 
110
    aExportSecretSub,
 
111
    aCheckKeys,
 
112
    aGenRevoke,
 
113
    aDesigRevoke,
 
114
    aPrimegen,
 
115
    aPrintMD,
 
116
    aPrintMDs,
 
117
    aCheckTrustDB,
 
118
    aUpdateTrustDB,
 
119
    aFixTrustDB,
 
120
    aListTrustDB,
 
121
    aListTrustPath,
 
122
    aExportOwnerTrust,
 
123
    aListOwnerTrust,
 
124
    aImportOwnerTrust,
 
125
    aDeArmor,
 
126
    aEnArmor,
 
127
    aGenRandom,
 
128
    aPipeMode,
 
129
    aRebuildKeydbCaches,
 
130
    aRefreshKeys,
 
131
    aCardStatus,
 
132
    aCardEdit,
 
133
    aChangePIN,
 
134
 
 
135
    oTextmode,
 
136
    oNoTextmode,
 
137
    oExpert,
 
138
    oNoExpert,
 
139
    oAskSigExpire,
 
140
    oNoAskSigExpire,
 
141
    oAskCertExpire,
 
142
    oNoAskCertExpire,
 
143
    oFingerprint,
 
144
    oWithFingerprint,
 
145
    oAnswerYes,
 
146
    oAnswerNo,
 
147
    oDefCertCheckLevel,
 
148
    oKeyring,
 
149
    oPrimaryKeyring,
 
150
    oSecretKeyring,
 
151
    oShowKeyring,
 
152
    oDefaultKey,
 
153
    oDefRecipient,
 
154
    oDefRecipientSelf,
 
155
    oNoDefRecipient,
 
156
    oOptions,
 
157
    oDebug,
 
158
    oDebugLevel,
 
159
    oDebugAll,
 
160
    oStatusFD,
 
161
#ifdef __riscos__
 
162
    oStatusFile,
 
163
#endif /* __riscos__ */
 
164
    oAttributeFD,
 
165
#ifdef __riscos__
 
166
    oAttributeFile,
 
167
#endif /* __riscos__ */
 
168
    oSKComments,
 
169
    oNoSKComments,
 
170
    oEmitVersion,
 
171
    oNoEmitVersion,
 
172
    oCompletesNeeded,
 
173
    oMarginalsNeeded,
 
174
    oMaxCertDepth,
 
175
    oLoadExtension,
 
176
    oGnuPG,
 
177
    oRFC1991,
 
178
    oRFC2440,
 
179
    oOpenPGP,
 
180
    oPGP2,
 
181
    oPGP6,
 
182
    oPGP7,
 
183
    oPGP8,
 
184
    oCipherAlgo,
 
185
    oDigestAlgo,
 
186
    oCertDigestAlgo,
 
187
    oCompressAlgo,
 
188
    oPasswdFD,
 
189
#ifdef __riscos__
 
190
    oPasswdFile,
 
191
#endif /* __riscos__ */
 
192
    oCommandFD,
 
193
#ifdef __riscos__
 
194
    oCommandFile,
 
195
#endif /* __riscos__ */
 
196
    oQuickRandom,
 
197
    oNoVerbose,
 
198
    oTrustDBName,
 
199
    oNoSecmemWarn,
 
200
    oNoPermissionWarn,
 
201
    oNoMDCWarn,
 
202
    oNoArmor,
 
203
    oNoDefKeyring,
 
204
    oNoGreeting,
 
205
    oNoTTY,
 
206
    oNoOptions,
 
207
    oNoBatch,
 
208
    oHomedir,
 
209
    oWithColons,
 
210
    oWithKeyData,
 
211
    oSkipVerify,
 
212
    oCompressKeys,
 
213
    oCompressSigs,
 
214
    oAlwaysTrust,
 
215
    oTrustModel,
 
216
    oForceOwnertrust,
 
217
    oEmuChecksumBug,
 
218
    oSetFilename,
 
219
    oForYourEyesOnly,
 
220
    oNoForYourEyesOnly,
 
221
    oSetPolicyURL,
 
222
    oSigPolicyURL,
 
223
    oCertPolicyURL,
 
224
    oShowPolicyURL,
 
225
    oNoShowPolicyURL,
 
226
    oSigKeyserverURL,
 
227
    oUseEmbeddedFilename,
 
228
    oComment,
 
229
    oDefaultComment,
 
230
    oNoComments,
 
231
    oThrowKeyid,
 
232
    oNoThrowKeyid,
 
233
    oShowPhotos,
 
234
    oNoShowPhotos,
 
235
    oPhotoViewer,
 
236
    oForceV3Sigs,
 
237
    oNoForceV3Sigs,
 
238
    oForceV4Certs,
 
239
    oNoForceV4Certs,
 
240
    oForceMDC,
 
241
    oNoForceMDC,
 
242
    oDisableMDC,
 
243
    oNoDisableMDC,
 
244
    oS2KMode,
 
245
    oS2KDigest,
 
246
    oS2KCipher,
 
247
    oSimpleSKChecksum,                          
 
248
    oCharset,
 
249
    oNotDashEscaped,
 
250
    oEscapeFrom,
 
251
    oNoEscapeFrom,
 
252
    oLockOnce,
 
253
    oLockMultiple,
 
254
    oLockNever,
 
255
    oKeyServer,
 
256
    oKeyServerOptions,
 
257
    oImportOptions,
 
258
    oExportOptions,
 
259
    oListOptions,
 
260
    oVerifyOptions,
 
261
    oTempDir,
 
262
    oExecPath,
 
263
    oEncryptTo,
 
264
    oHiddenEncryptTo,
 
265
    oNoEncryptTo,
 
266
    oLogFile,
 
267
    oLoggerFD,
 
268
#ifdef __riscos__
 
269
    oLoggerFile,
 
270
#endif /* __riscos__ */
 
271
    oUtf8Strings,
 
272
    oNoUtf8Strings,
 
273
    oDisableCipherAlgo,
 
274
    oDisablePubkeyAlgo,
 
275
    oAllowNonSelfsignedUID,
 
276
    oNoAllowNonSelfsignedUID,
 
277
    oAllowFreeformUID,
 
278
    oNoAllowFreeformUID,
 
279
    oAllowSecretKeyImport,                      
 
280
    oEnableSpecialFilenames,
 
281
    oNoLiteral,
 
282
    oSetFilesize,
 
283
    oHonorHttpProxy,
 
284
    oFastListMode,
 
285
    oListOnly,
 
286
    oIgnoreTimeConflict,
 
287
    oIgnoreValidFrom,
 
288
    oIgnoreCrcError,
 
289
    oIgnoreMDCError,
 
290
    oShowSessionKey,
 
291
    oOverrideSessionKey,
 
292
    oNoRandomSeedFile,
 
293
    oAutoKeyRetrieve,
 
294
    oNoAutoKeyRetrieve,
 
295
    oUseAgent,
 
296
    oNoUseAgent,
 
297
    oGpgAgentInfo,
 
298
    oMergeOnly,
 
299
    oTryAllSecrets,
 
300
    oTrustedKey,
 
301
    oNoExpensiveTrustChecks,
 
302
    oFixedListMode,
 
303
    oNoSigCache,
 
304
    oNoSigCreateCheck,
 
305
    oAutoCheckTrustDB,
 
306
    oNoAutoCheckTrustDB,
 
307
    oPreservePermissions,
 
308
    oDefaultPreferenceList,
 
309
    oPersonalCipherPreferences,
 
310
    oPersonalDigestPreferences,
 
311
    oPersonalCompressPreferences,
 
312
    oEmuMDEncodeBug,
 
313
    oAgentProgram,
 
314
    oDisplay,
 
315
    oTTYname,
 
316
    oTTYtype,
 
317
    oLCctype,
 
318
    oLCmessages,
 
319
    oGroup,
 
320
    oStrict,
 
321
    oNoStrict,
 
322
    oMangleDosFilenames,
 
323
    oNoMangleDosFilenames,
 
324
    oEnableProgressFilter,                          
 
325
    oMultifile,
 
326
aTest };
 
327
 
 
328
 
 
329
static ARGPARSE_OPTS opts[] = {
 
330
 
 
331
    { 300, NULL, 0, N_("@Commands:\n ") },
 
332
 
 
333
    { aSign, "sign",      256, N_("|[file]|make a signature")},
 
334
    { aClearsign, "clearsign", 256, N_("|[file]|make a clear text signature") },
 
335
    { aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
 
336
    { aEncr, "encrypt",   256, N_("encrypt data")},
 
337
    { aEncrFiles, "encrypt-files", 256, "@"},
 
338
    { aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
 
339
    { aStore, "store",     256, "@"},
 
340
    { aDecrypt, "decrypt",   256, N_("decrypt data (default)")},
 
341
    { aDecryptFiles, "decrypt-files", 256, "@"},
 
342
    { aVerify, "verify"   , 256, N_("verify a signature")},
 
343
    { aVerifyFiles, "verify-files" , 256, "@" },
 
344
    { aListKeys, "list-keys", 256, N_("list keys")},
 
345
    { aListKeys, "list-public-keys", 256, "@" },
 
346
    { aListSigs, "list-sigs", 256, N_("list keys and signatures")},
 
347
    { aCheckKeys, "check-sigs",256, N_("list and check key signatures")},
 
348
    { oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
 
349
    { aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
 
350
    { aKeygen,     "gen-key",  256, N_("generate a new key pair")},
 
351
    { aDeleteKeys,"delete-keys",256,N_("remove keys from the public keyring")},
 
352
    { aDeleteSecretKeys, "delete-secret-keys",256,
 
353
                                    N_("remove keys from the secret keyring")},
 
354
    { aSignKey,  "sign-key"   ,256, N_("sign a key")},
 
355
    { aLSignKey, "lsign-key"  ,256, N_("sign a key locally")},
 
356
    { aNRSignKey, "nrsign-key"  ,256, "@"},
 
357
    { aNRLSignKey, "nrlsign-key"  ,256, "@"},
 
358
    { aEditKey,  "edit-key"   ,256, N_("sign or edit a key")},
 
359
    { aGenRevoke, "gen-revoke",256, N_("generate a revocation certificate")},
 
360
    { aDesigRevoke, "desig-revoke",256, "@" },
 
361
    { aExport, "export"           , 256, N_("export keys") },
 
362
    { aSendKeys, "send-keys"     , 256, N_("export keys to a key server") },
 
363
    { aRecvKeys, "recv-keys"     , 256, N_("import keys from a key server") },
 
364
    { aSearchKeys, "search-keys" , 256,
 
365
                                    N_("search for keys on a key server") },
 
366
    { aRefreshKeys, "refresh-keys", 256,
 
367
                                    N_("update all keys from a keyserver")},
 
368
    { aExportAll, "export-all"    , 256, "@" },
 
369
    { aExportSecret, "export-secret-keys" , 256, "@" },
 
370
    { aExportSecretSub, "export-secret-subkeys" , 256, "@" },
 
371
    { aImport, "import",      256     , N_("import/merge keys")},
 
372
    { aFastImport, "fast-import",  256 , "@"},
 
373
    { aCardStatus,  "card-status", 256, N_("print the card status")},
 
374
    { aCardEdit,   "card-edit",  256, N_("change data on a card")},
 
375
    { aChangePIN,  "change-pin", 256, N_("change a card's PIN")},
 
376
 
 
377
    { aListPackets, "list-packets",256, "@"},
 
378
    { aExportOwnerTrust, "export-ownertrust", 256, "@"},
 
379
    { aImportOwnerTrust, "import-ownertrust", 256, "@"},
 
380
    { aUpdateTrustDB, "update-trustdb",0 , N_("update the trust database")},
 
381
    { aCheckTrustDB,  "check-trustdb",0 , "@"},
 
382
    { aFixTrustDB, "fix-trustdb",0 , N_("fix a corrupted trust database")},
 
383
    { aDeArmor, "dearmor", 256, "@" },
 
384
    { aDeArmor, "dearmour", 256, "@" },
 
385
    { aEnArmor, "enarmor", 256, "@" },
 
386
    { aEnArmor, "enarmour", 256, "@" },
 
387
    { aPrintMD,  "print-md" , 256, N_("|algo [files]|print message digests")},
 
388
    { aPrimegen, "gen-prime" , 256, "@" },
 
389
    { aGenRandom, "gen-random" , 256, "@" },
 
390
    { aGPGConfList, "gpgconf-list", 256, "@" },
 
391
 
 
392
    { 301, NULL, 0, N_("@\nOptions:\n ") },
 
393
 
 
394
    { oArmor, "armor",     0, N_("create ascii armored output")},
 
395
    { oArmor, "armour",     0, "@" },
 
396
    { oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
 
397
    { oHiddenRecipient, "hidden-recipient", 2, "@" },
 
398
    { oRecipient, "remote-user", 2, "@"},  /* old option name */
 
399
    { oDefRecipient, "default-recipient" ,2, "@" },
 
400
    { oDefRecipientSelf, "default-recipient-self" ,0, "@" },
 
401
    { oNoDefRecipient, "no-default-recipient", 0, "@" },
 
402
    { oTempDir, "temp-directory", 2, "@" },
 
403
    { oExecPath, "exec-path", 2, "@" },
 
404
    { oEncryptTo, "encrypt-to", 2, "@" },
 
405
    { oHiddenEncryptTo, "hidden-encrypt-to", 2, "@" },
 
406
    { oNoEncryptTo, "no-encrypt-to", 0, "@" },
 
407
    { oUser, "local-user",2, N_("use this user-id to sign or decrypt")},
 
408
    { oCompress, NULL,        1, N_("|N|set compress level N (0 disables)") },
 
409
    { oTextmodeShort, NULL,   0, "@"},
 
410
    { oTextmode, "textmode",  0, N_("use canonical text mode")},
 
411
    { oNoTextmode, "no-textmode",  0, "@"},
 
412
    { oExpert, "expert",   0, "@"},
 
413
    { oNoExpert, "no-expert",   0, "@"},
 
414
    { oAskSigExpire, "ask-sig-expire",   0, "@"},
 
415
    { oNoAskSigExpire, "no-ask-sig-expire",   0, "@"},
 
416
    { oAskCertExpire, "ask-cert-expire",   0, "@"},
 
417
    { oNoAskCertExpire, "no-ask-cert-expire",   0, "@"},
 
418
    { oOutput, "output",    2, N_("use as output file")},
 
419
    { oVerbose, "verbose",   0, N_("verbose") },
 
420
    { oQuiet,   "quiet",     0, "@" },
 
421
    { oNoTTY,   "no-tty",    0, "@" },
 
422
    { oLogFile, "log-file"   ,2, "@" },
 
423
    { oForceV3Sigs, "force-v3-sigs", 0, "@" },
 
424
    { oNoForceV3Sigs, "no-force-v3-sigs", 0, "@" },
 
425
    { oForceV4Certs, "force-v4-certs", 0, "@" },
 
426
    { oNoForceV4Certs, "no-force-v4-certs", 0, "@" },
 
427
    { oForceMDC, "force-mdc", 0, "@" },
 
428
    { oNoForceMDC, "no-force-mdc", 0, "@" },
 
429
    { oDisableMDC, "disable-mdc", 0, "@" },
 
430
    { oNoDisableMDC, "no-disable-mdc", 0, "@" },
 
431
    { oDryRun, "dry-run",   0, N_("do not make any changes") },
 
432
    { oInteractive, "interactive", 0, N_("prompt before overwriting") },
 
433
    { oUseAgent, "use-agent",0, "@"},
 
434
    { oNoUseAgent, "no-use-agent",0, "@"},
 
435
    { oGpgAgentInfo, "gpg-agent-info",2, "@"},
 
436
    { oBatch, "batch",     0, "@"},
 
437
    { oAnswerYes, "yes",       0, "@"},
 
438
    { oAnswerNo,  "no",        0, "@"},
 
439
    { oKeyring, "keyring"   ,  2, "@"},
 
440
    { oPrimaryKeyring, "primary-keyring",2, "@" },
 
441
    { oSecretKeyring, "secret-keyring" ,2, "@"},
 
442
    { oShowKeyring, "show-keyring", 0, "@"},
 
443
    { oDefaultKey, "default-key" ,  2, "@"},
 
444
    { oKeyServer, "keyserver",      2, "@"},
 
445
    { oKeyServerOptions, "keyserver-options",2,"@"},
 
446
    { oImportOptions, "import-options",2,"@"},
 
447
    { oExportOptions, "export-options",2,"@"},
 
448
    { oListOptions, "list-options",2,"@"},
 
449
    { oVerifyOptions, "verify-options",2,"@"},
 
450
    { oCharset, "charset"   , 2, "@" },
 
451
    { oOptions, "options"   , 2, "@"},
 
452
 
 
453
    { oDebug, "debug"     ,4|16, "@"},
 
454
    { oDebugLevel, "debug-level" ,2, "@"},
 
455
    { oDebugAll, "debug-all" ,0, "@"},
 
456
    { oStatusFD, "status-fd" ,1, "@" },
 
457
#ifdef __riscos__
 
458
    { oStatusFile, "status-file" ,2, "@" },
 
459
#endif /* __riscos__ */
 
460
    { oAttributeFD, "attribute-fd" ,1, "@" },
 
461
#ifdef __riscos__
 
462
    { oAttributeFile, "attribute-file" ,2, "@" },
 
463
#endif /* __riscos__ */
 
464
    { oNoSKComments, "no-sk-comments", 0,   "@"},
 
465
    { oSKComments, "sk-comments", 0,   "@"},
 
466
    { oCompletesNeeded, "completes-needed", 1, "@"},
 
467
    { oMarginalsNeeded, "marginals-needed", 1, "@"},
 
468
    { oMaxCertDepth,    "max-cert-depth", 1, "@" },
 
469
    { oTrustedKey, "trusted-key", 2, "@"},
 
470
    { oLoadExtension, "load-extension" ,2, "@"},
 
471
    { oGnuPG, "gnupg",   0, "@"},
 
472
    { oGnuPG, "no-pgp2", 0, "@"},
 
473
    { oGnuPG, "no-pgp6", 0, "@"},
 
474
    { oGnuPG, "no-pgp7", 0, "@"},
 
475
    { oGnuPG, "no-pgp8", 0, "@"},
 
476
    { oRFC1991, "rfc1991",   0, "@"},
 
477
    { oRFC2440, "rfc2440",   0, "@"},
 
478
    { oOpenPGP, "openpgp", 0, N_("use strict OpenPGP behavior")},
 
479
    { oPGP2, "pgp2", 0, N_("generate PGP 2.x compatible messages")},
 
480
    { oPGP6, "pgp6", 0, "@"},
 
481
    { oPGP7, "pgp7", 0, "@"},
 
482
    { oPGP8, "pgp8", 0, "@"},
 
483
    { oS2KMode, "s2k-mode",  1, "@"},
 
484
    { oS2KDigest, "s2k-digest-algo",2, "@"},
 
485
    { oS2KCipher, "s2k-cipher-algo",2, "@"},
 
486
    { oSimpleSKChecksum, "simple-sk-checksum", 0, "@"},
 
487
    { oCipherAlgo, "cipher-algo", 2 , "@"},
 
488
    { oDigestAlgo, "digest-algo", 2 , "@"},
 
489
    { oCertDigestAlgo, "cert-digest-algo", 2 , "@" },
 
490
    { oCompressAlgo,"compress-algo",2, "@"},
 
491
    { oThrowKeyid, "throw-keyid", 0,  "@"},
 
492
    { oNoThrowKeyid, "no-throw-keyid", 0, "@" },
 
493
    { oShowPhotos,   "show-photos", 0, "@" },
 
494
    { oNoShowPhotos, "no-show-photos", 0, "@" },
 
495
    { oPhotoViewer,  "photo-viewer", 2, "@" },
 
496
    { oSetNotation,  "set-notation", 2, "@" },
 
497
    { oSetNotation,  "notation-data", 2, "@" }, /* Alias */
 
498
    { oSigNotation,   "sig-notation", 2, "@" },
 
499
    { oCertNotation,  "cert-notation", 2, "@" },
 
500
 
 
501
    { 302, NULL, 0, N_(
 
502
  "@\n(See the man page for a complete listing of all commands and options)\n"
 
503
                      )},
 
504
 
 
505
    { 303, NULL, 0, N_("@\nExamples:\n\n"
 
506
    " -se -r Bob [file]          sign and encrypt for user Bob\n"
 
507
    " --clearsign [file]         make a clear text signature\n"
 
508
    " --detach-sign [file]       make a detached signature\n"
 
509
    " --list-keys [names]        show keys\n"
 
510
    " --fingerprint [names]      show fingerprints\n"  ) },
 
511
 
 
512
  /* hidden options */
 
513
    { aListOwnerTrust, "list-ownertrust", 256, "@"}, /* deprecated */
 
514
    { oCompressAlgo, "compression-algo", 1, "@"}, /* alias */
 
515
    { aPrintMDs, "print-mds" , 256, "@"}, /* old */
 
516
    { aListTrustDB, "list-trustdb",0 , "@"},
 
517
    /* Not yet used */
 
518
    /* { aListTrustPath, "list-trust-path",0, "@"}, */
 
519
    { aPipeMode,  "pipemode", 0, "@" },
 
520
    { oPasswdFD, "passphrase-fd",1, "@" },
 
521
#ifdef __riscos__
 
522
    { oPasswdFile, "passphrase-file",2, "@" },
 
523
#endif /* __riscos__ */
 
524
    { oCommandFD, "command-fd",1, "@" },
 
525
#ifdef __riscos__
 
526
    { oCommandFile, "command-file",2, "@" },
 
527
#endif /* __riscos__ */
 
528
    { oQuickRandom, "quick-random", 0, "@"},
 
529
    { oNoVerbose, "no-verbose", 0, "@"},
 
530
    { oTrustDBName, "trustdb-name", 2, "@" },
 
531
    { oNoSecmemWarn, "no-secmem-warning", 0, "@" }, /* used only by regression tests */
 
532
    { oNoPermissionWarn, "no-permission-warning", 0, "@" },
 
533
    { oNoMDCWarn, "no-mdc-warning", 0, "@" },
 
534
    { oNoArmor, "no-armor",   0, "@"},
 
535
    { oNoArmor, "no-armour",   0, "@"},
 
536
    { oNoDefKeyring, "no-default-keyring", 0, "@" },
 
537
    { oNoGreeting, "no-greeting", 0, "@" },
 
538
    { oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
 
539
    { oHomedir, "homedir", 2, "@" },   /* defaults to "~/.gnupg" */
 
540
    { oNoBatch, "no-batch", 0, "@" },
 
541
    { oWithColons, "with-colons", 0, "@"},
 
542
    { oWithKeyData,"with-key-data", 0, "@"},
 
543
    { aListKeys, "list-key", 0, "@" }, /* alias */
 
544
    { aListSigs, "list-sig", 0, "@" }, /* alias */
 
545
    { aCheckKeys, "check-sig",0, "@" }, /* alias */
 
546
    { oSkipVerify, "skip-verify",0, "@" },
 
547
    { oCompressKeys, "compress-keys",0, "@"},
 
548
    { oCompressSigs, "compress-sigs",0, "@"},
 
549
    { oDefCertCheckLevel, "default-cert-check-level", 1, "@"},
 
550
    { oAlwaysTrust, "always-trust", 0, "@"},
 
551
    { oTrustModel, "trust-model", 2, "@"},
 
552
    { oForceOwnertrust, "force-ownertrust", 2, "@"},
 
553
    { oEmuChecksumBug, "emulate-checksum-bug", 0, "@"},
 
554
    { oSetFilename, "set-filename", 2, "@" },
 
555
    { oForYourEyesOnly, "for-your-eyes-only", 0, "@" },
 
556
    { oNoForYourEyesOnly, "no-for-your-eyes-only", 0, "@" },
 
557
    { oSetPolicyURL, "set-policy-url", 2, "@" },
 
558
    { oSigPolicyURL, "sig-policy-url", 2, "@" },
 
559
    { oCertPolicyURL, "cert-policy-url", 2, "@" },
 
560
    { oShowPolicyURL, "show-policy-url", 0, "@" },
 
561
    { oNoShowPolicyURL, "no-show-policy-url", 0, "@" },
 
562
    { oShowNotation, "show-notation", 0, "@" },
 
563
    { oNoShowNotation, "no-show-notation", 0, "@" },
 
564
    { oSigKeyserverURL, "sig-keyserver-url", 2, "@" },
 
565
    { oComment, "comment", 2, "@" },
 
566
    { oDefaultComment, "default-comment", 0, "@" },
 
567
    { oNoComments, "no-comments", 0, "@" },
 
568
    { oEmitVersion, "emit-version", 0, "@"},
 
569
    { oNoEmitVersion, "no-emit-version", 0, "@"},
 
570
    { oNoEmitVersion, "no-version", 0, "@"}, /* alias */
 
571
    { oNotDashEscaped, "not-dash-escaped", 0, "@" },
 
572
    { oEscapeFrom, "escape-from-lines", 0, "@" },
 
573
    { oNoEscapeFrom, "no-escape-from-lines", 0, "@" },
 
574
    { oLockOnce, "lock-once", 0, "@" },
 
575
    { oLockMultiple, "lock-multiple", 0, "@" },
 
576
    { oLockNever, "lock-never", 0, "@" },
 
577
    { oLoggerFD, "logger-fd",1, "@" },
 
578
#ifdef __riscos__
 
579
    { oLoggerFile, "logger-file",2, "@" },
 
580
#endif /* __riscos__ */
 
581
    { oUseEmbeddedFilename, "use-embedded-filename", 0, "@" },
 
582
    { oUtf8Strings, "utf8-strings", 0, "@" },
 
583
    { oNoUtf8Strings, "no-utf8-strings", 0, "@" },
 
584
    { oWithFingerprint, "with-fingerprint", 0, "@" },
 
585
    { oDisableCipherAlgo,  "disable-cipher-algo", 2, "@" },
 
586
    { oDisablePubkeyAlgo,  "disable-pubkey-algo", 2, "@" },
 
587
    { oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", 0, "@" },
 
588
    { oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", 0, "@" },
 
589
    { oAllowFreeformUID, "allow-freeform-uid", 0, "@" },
 
590
    { oNoAllowFreeformUID, "no-allow-freeform-uid", 0, "@" },
 
591
    { oNoLiteral, "no-literal", 0, "@" },
 
592
    { oSetFilesize, "set-filesize", 20, "@" },
 
593
    { oHonorHttpProxy,"honor-http-proxy", 0, "@" },
 
594
    { oFastListMode,"fast-list-mode", 0, "@" },
 
595
    { oFixedListMode,"fixed-list-mode", 0, "@" },
 
596
    { oListOnly, "list-only", 0, "@"},
 
597
    { oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
 
598
    { oIgnoreValidFrom,    "ignore-valid-from",    0, "@" },
 
599
    { oIgnoreCrcError, "ignore-crc-error", 0,"@" },
 
600
    { oIgnoreMDCError, "ignore-mdc-error", 0,"@" },
 
601
    { oShowSessionKey, "show-session-key", 0, "@" },
 
602
    { oOverrideSessionKey, "override-session-key", 2, "@" },
 
603
    { oNoRandomSeedFile,  "no-random-seed-file", 0, "@" },
 
604
    { oAutoKeyRetrieve, "auto-key-retrieve", 0, "@" },
 
605
    { oNoAutoKeyRetrieve, "no-auto-key-retrieve", 0, "@" },
 
606
    { oNoSigCache,         "no-sig-cache", 0, "@" },
 
607
    { oNoSigCreateCheck,   "no-sig-create-check", 0, "@" },
 
608
    { oAutoCheckTrustDB, "auto-check-trustdb", 0, "@"},
 
609
    { oNoAutoCheckTrustDB, "no-auto-check-trustdb", 0, "@"},
 
610
    { oMergeOnly,         "merge-only", 0, "@" },
 
611
    { oAllowSecretKeyImport, "allow-secret-key-import", 0, "@" },
 
612
    { oTryAllSecrets,  "try-all-secrets", 0, "@" },
 
613
    { oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
 
614
    { oNoExpensiveTrustChecks, "no-expensive-trust-checks", 0, "@" },
 
615
    { aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys",256, "@" },
 
616
    { aRebuildKeydbCaches, "rebuild-keydb-caches", 256, "@"},
 
617
    { oPreservePermissions, "preserve-permissions", 0, "@"},
 
618
    { oDefaultPreferenceList,  "default-preference-list", 2, "@"},
 
619
    { oPersonalCipherPreferences,  "personal-cipher-preferences", 2, "@"},
 
620
    { oPersonalDigestPreferences,  "personal-digest-preferences", 2, "@"},
 
621
    { oPersonalCompressPreferences,  "personal-compress-preferences", 2, "@"},
 
622
    { oEmuMDEncodeBug,  "emulate-md-encode-bug", 0, "@"},
 
623
    { oAgentProgram, "agent-program", 2 , "@" },
 
624
    { oDisplay,    "display",     2, "@" },
 
625
    { oTTYname,    "ttyname",     2, "@" },
 
626
    { oTTYtype,    "ttytype",     2, "@" },
 
627
    { oLCctype,    "lc-ctype",    2, "@" },
 
628
    { oLCmessages, "lc-messages", 2, "@" },
 
629
    { oGroup,      "group",       2, "@" },
 
630
    { oStrict,     "strict",      0, "@" },
 
631
    { oNoStrict,   "no-strict",   0, "@" },
 
632
    { oMangleDosFilenames, "mangle-dos-filenames", 0, "@" },
 
633
    { oNoMangleDosFilenames, "no-mangle-dos-filenames", 0, "@" },
 
634
    { oEnableProgressFilter, "enable-progress-filter", 0, "@" },
 
635
    { oMultifile, "multifile", 0, "@" },
 
636
{0} };
 
637
 
 
638
 
 
639
 
 
640
int g10_errors_seen = 0;
 
641
 
 
642
static int utf8_strings = 0;
 
643
static int maybe_setuid = 1;
 
644
 
 
645
static char *build_list( const char *text, char letter,
 
646
                         const char *(*mapf)(int), int (*chkf)(int) );
 
647
static void set_cmd( enum cmd_and_opt_values *ret_cmd,
 
648
                        enum cmd_and_opt_values new_cmd );
 
649
static void print_mds( const char *fname, int algo );
 
650
static void add_notation_data( const char *string, int which );
 
651
static void add_policy_url( const char *string, int which );
 
652
static void add_keyserver_url( const char *string, int which );
 
653
static void emergency_cleanup (void);
 
654
 
 
655
#ifdef __riscos__
 
656
RISCOS_GLOBAL_STATICS("GnuPG Heap")
 
657
#endif /* __riscos__ */
 
658
 
 
659
static int
 
660
pk_test_algo (int algo)
 
661
{
 
662
  return openpgp_pk_test_algo (algo, 0);
 
663
}
 
664
 
 
665
 
 
666
static const char *
 
667
my_strusage( int level )
 
668
{
 
669
  static char *digests, *pubkeys, *ciphers, *zips;
 
670
    const char *p;
 
671
    switch( level ) {
 
672
      case 11: p = "gpg (GnuPG)";
 
673
        break;
 
674
      case 13: p = VERSION; break;
 
675
      case 17: p = PRINTABLE_OS_NAME; break;
 
676
      case 19: p =
 
677
            _("Please report bugs to <gnupg-bugs@gnu.org>.\n");
 
678
        break;
 
679
      case 1:
 
680
      case 40:  p =
 
681
            _("Usage: gpg [options] [files] (-h for help)");
 
682
        break;
 
683
      case 41:  p =
 
684
            _("Syntax: gpg [options] [files]\n"
 
685
              "sign, check, encrypt or decrypt\n"
 
686
              "default operation depends on the input data\n");
 
687
        break;
 
688
 
 
689
      case 31: p = "\nHome: "; break;
 
690
#ifndef __riscos__
 
691
      case 32: p = opt.homedir; break;
 
692
#else /* __riscos__ */
 
693
      case 32: p = make_filename(opt.homedir, NULL); break;
 
694
#endif /* __riscos__ */
 
695
      case 33: p = _("\nSupported algorithms:\n"); break;
 
696
      case 34:
 
697
        if( !pubkeys )
 
698
            pubkeys = build_list(_("Pubkey: "), 0, gcry_pk_algo_name,
 
699
                                 pk_test_algo );
 
700
        p = pubkeys;
 
701
        break;
 
702
      case 35:
 
703
        if( !ciphers )
 
704
            ciphers = build_list(_("Cipher: "), 'S', gcry_cipher_algo_name,
 
705
                                 openpgp_cipher_test_algo );
 
706
        p = ciphers;
 
707
        break;
 
708
      case 36:
 
709
        if( !digests )
 
710
            digests = build_list(_("Hash: "), 'H', gcry_md_algo_name,
 
711
                                        openpgp_md_test_algo );
 
712
        p = digests;
 
713
        break;
 
714
      case 37:
 
715
        if( !zips )
 
716
            zips = build_list(_("Compression: "),'Z',compress_algo_to_string,
 
717
                                                        check_compress_algo);
 
718
        p = zips;
 
719
        break;
 
720
 
 
721
      default:  p = NULL;
 
722
    }
 
723
    return p;
 
724
}
 
725
 
 
726
 
 
727
static char *
 
728
build_list( const char *text, char letter,
 
729
            const char * (*mapf)(int), int (*chkf)(int) )
 
730
{
 
731
    int i;
 
732
    const char *s;
 
733
    size_t n=strlen(text)+2;
 
734
    char *list, *p, *line=NULL;
 
735
 
 
736
    if( maybe_setuid )
 
737
        gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* drop setuid */
 
738
 
 
739
    for(i=0; i <= 110; i++ )
 
740
        if( !chkf(i) && (s=mapf(i)) )
 
741
            n += strlen(s) + 7 + 2;
 
742
    list = xmalloc ( 21 + n ); *list = 0;
 
743
    for(p=NULL, i=0; i <= 110; i++ ) {
 
744
        if( !chkf(i) && (s=mapf(i)) ) {
 
745
            if( !p ) {
 
746
                p = stpcpy( list, text );
 
747
                line=p;
 
748
            }
 
749
            else
 
750
                p = stpcpy( p, ", ");
 
751
 
 
752
            if(strlen(line)>60) {
 
753
              int spaces=strlen(text);
 
754
 
 
755
              list = xrealloc(list,n+spaces+1);
 
756
              /* realloc could move the block, so find the end again */
 
757
              p=list;
 
758
              while(*p)
 
759
                p++;
 
760
 
 
761
              p=stpcpy(p, "\n");
 
762
              line=p;
 
763
              for(;spaces;spaces--)
 
764
                p=stpcpy(p, " ");
 
765
            }
 
766
 
 
767
            p = stpcpy(p, s );
 
768
            if(opt.verbose && letter)
 
769
              {
 
770
                char num[8];
 
771
                sprintf(num," (%c%d)",letter,i);
 
772
                p = stpcpy(p,num);
 
773
              }
 
774
        }
 
775
    }
 
776
    if( p )
 
777
        p = stpcpy(p, "\n" );
 
778
    return list;
 
779
}
 
780
 
 
781
 
 
782
static void
 
783
i18n_init(void)
 
784
{
 
785
#ifdef USE_SIMPLE_GETTEXT
 
786
    set_gettext_file( PACKAGE_GT );
 
787
#else
 
788
#ifdef ENABLE_NLS
 
789
    setlocale( LC_ALL, "" );
 
790
    bindtextdomain( PACKAGE_GT, LOCALEDIR );
 
791
    textdomain( PACKAGE_GT );
 
792
#endif
 
793
#endif
 
794
}
 
795
 
 
796
static void
 
797
wrong_args( const char *text)
 
798
{
 
799
    fputs(_("usage: gpg [options] "),stderr);
 
800
    fputs(text,stderr);
 
801
    putc('\n',stderr);
 
802
    g10_exit(2);
 
803
}
 
804
 
 
805
 
 
806
static void
 
807
log_set_strict (int yesno)
 
808
{
 
809
  /* FIXME-XXX*/
 
810
}
 
811
 
 
812
static char *
 
813
make_username( const char *string )
 
814
{
 
815
  char *p;
 
816
  if( utf8_strings )
 
817
    p = xstrdup (string);
 
818
  else
 
819
    p = native_to_utf8( string );
 
820
  return p;
 
821
}
 
822
 
 
823
 
 
824
/*
 
825
 * same as add_to_strlist() but if is_utf8 is *not* set a conversion
 
826
 * to UTF8 is done  
 
827
 */
 
828
static STRLIST
 
829
add_to_strlist2 ( STRLIST *list, const char *string, int is_utf8)
 
830
{
 
831
  STRLIST sl;
 
832
  
 
833
  if (is_utf8)
 
834
    sl = add_to_strlist( list, string );
 
835
  else 
 
836
    {
 
837
      char *p = native_to_utf8( string );
 
838
      sl = add_to_strlist( list, p );
 
839
      xfree( p );
 
840
    }
 
841
  return sl;
 
842
}
 
843
 
 
844
 
 
845
/* Setup the debugging.  With a LEVEL of NULL only the active debug
 
846
   flags are propagated to the subsystems.  With LEVEL set, a specific
 
847
   set of debug flags is set; thus overriding all flags already
 
848
   set. */
 
849
static void
 
850
set_debug (const char *level)
 
851
{
 
852
  if (!level)
 
853
    ;
 
854
  else if (!strcmp (level, "none"))
 
855
    opt.debug = 0;
 
856
  else if (!strcmp (level, "basic"))
 
857
    opt.debug = DBG_MEMSTAT_VALUE;
 
858
  else if (!strcmp (level, "advanced"))
 
859
    opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
 
860
  else if (!strcmp (level, "expert"))
 
861
    opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
 
862
                 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
 
863
  else if (!strcmp (level, "guru"))
 
864
    opt.debug = ~0;
 
865
  else
 
866
    {
 
867
      log_error (_("invalid debug-level `%s' given\n"), level);
 
868
      g10_exit (2);
 
869
    }
 
870
 
 
871
  if (opt.debug & DBG_MEMORY_VALUE )
 
872
    memory_debug_mode = 1;
 
873
  if (opt.debug & DBG_MEMSTAT_VALUE )
 
874
    memory_stat_debug_mode = 1;
 
875
  if (opt.debug & DBG_MPI_VALUE)
 
876
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
 
877
  if (opt.debug & DBG_CIPHER_VALUE )
 
878
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
 
879
  if (opt.debug & DBG_IOBUF_VALUE )
 
880
    iobuf_debug_mode = 1;
 
881
}
 
882
 
 
883
 
 
884
/* We need the home directory also in some other directories, so make
 
885
   sure that both variables are always in sync. */
 
886
static void
 
887
set_homedir (const char *dir)
 
888
{
 
889
  if (!dir)
 
890
    dir = "";
 
891
  g10_opt_homedir = opt.homedir = dir;
 
892
}
 
893
 
 
894
 
 
895
static void
 
896
set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
 
897
{
 
898
    enum cmd_and_opt_values cmd = *ret_cmd;
 
899
 
 
900
    if( !cmd || cmd == new_cmd )
 
901
        cmd = new_cmd;
 
902
    else if( cmd == aSign && new_cmd == aEncr )
 
903
        cmd = aSignEncr;
 
904
    else if( cmd == aEncr && new_cmd == aSign )
 
905
        cmd = aSignEncr;
 
906
    else if( cmd == aSign && new_cmd == aSym )
 
907
        cmd = aSignSym;
 
908
    else if( cmd == aSym && new_cmd == aSign )
 
909
        cmd = aSignSym;
 
910
    else if(    ( cmd == aSign     && new_cmd == aClearsign )
 
911
             || ( cmd == aClearsign && new_cmd == aSign )  )
 
912
        cmd = aClearsign;
 
913
    else {
 
914
        log_error(_("conflicting commands\n"));
 
915
        g10_exit(2);
 
916
    }
 
917
 
 
918
    *ret_cmd = cmd;
 
919
}
 
920
 
 
921
 
 
922
static void add_group(char *string)
 
923
{
 
924
  char *name,*value;
 
925
  struct groupitem *item;
 
926
  STRLIST values=NULL;
 
927
 
 
928
  /* Break off the group name */
 
929
  name=strsep(&string,"=");
 
930
  if(string==NULL)
 
931
    {
 
932
      log_error(_("no = sign found in group definition \"%s\"\n"),name);
 
933
      return;
 
934
    }
 
935
 
 
936
  trim_trailing_ws(name,strlen(name));
 
937
 
 
938
  /* Break apart the values */
 
939
  while ((value= strsep(&string," \t")))
 
940
    {
 
941
      if (*value)
 
942
        add_to_strlist2 (&values,value,utf8_strings);
 
943
    }
 
944
 
 
945
  item=xmalloc (sizeof(struct groupitem));
 
946
  item->name=name;
 
947
  item->values=values;
 
948
  item->next=opt.grouplist;
 
949
 
 
950
  opt.grouplist=item;
 
951
}
 
952
 
 
953
/* We need to check three things.
 
954
 
 
955
   0) The homedir.  It must be x00, a directory, and owned by the
 
956
   user.
 
957
 
 
958
   1) The options file.  Okay unless it or its containing directory is
 
959
   group or other writable or not owned by us.  disable exec in this
 
960
   case.
 
961
 
 
962
   2) Extensions.  Same as #2.
 
963
 
 
964
   Returns true if the item is unsafe. */
 
965
static int
 
966
check_permissions(const char *path,int item)
 
967
{
 
968
#if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
 
969
  static int homedir_cache=-1;
 
970
  char *tmppath,*dir;
 
971
  struct stat statbuf,dirbuf;
 
972
  int homedir=0,ret=0,checkonly=0;
 
973
  int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
 
974
 
 
975
  if(opt.no_perm_warn)
 
976
    return 0;
 
977
 
 
978
  assert(item==0 || item==1 || item==2);
 
979
 
 
980
  /* extensions may attach a path */
 
981
  if(item==2 && path[0]!=DIRSEP_C)
 
982
    {
 
983
      if(strchr(path,DIRSEP_C))
 
984
        tmppath=make_filename(path,NULL);
 
985
      else
 
986
        tmppath=make_filename(GNUPG_LIBDIR,path,NULL);
 
987
    }
 
988
  else
 
989
    tmppath=xstrdup (path);
 
990
 
 
991
  /* If the item is located in the homedir, but isn't the homedir,
 
992
     don't continue if we already checked the homedir itself.  This is
 
993
     to avoid user confusion with an extra options file warning which
 
994
     could be rectified if the homedir itself had proper
 
995
     permissions. */
 
996
  if(item!=0 && homedir_cache>-1
 
997
     && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
 
998
    {
 
999
      ret=homedir_cache;
 
1000
      goto end;
 
1001
    }
 
1002
 
 
1003
  /* It's okay if the file or directory doesn't exist */
 
1004
  if(stat(tmppath,&statbuf)!=0)
 
1005
    {
 
1006
      ret=0;
 
1007
      goto end;
 
1008
    }
 
1009
 
 
1010
  /* Now check the enclosing directory.  Theoretically, we could walk
 
1011
     this test up to the root directory /, but for the sake of sanity,
 
1012
     I'm stopping at one level down. */
 
1013
  dir=make_dirname(tmppath);
 
1014
 
 
1015
  if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
 
1016
    {
 
1017
      /* Weird error */
 
1018
      ret=1;
 
1019
      goto end;
 
1020
    }
 
1021
 
 
1022
  xfree (dir);
 
1023
 
 
1024
  /* Assume failure */
 
1025
  ret=1;
 
1026
 
 
1027
  if(item==0)
 
1028
    {
 
1029
      /* The homedir must be x00, a directory, and owned by the user. */
 
1030
 
 
1031
      if(S_ISDIR(statbuf.st_mode))
 
1032
        {
 
1033
          if(statbuf.st_uid==getuid())
 
1034
            {
 
1035
              if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
 
1036
                ret=0;
 
1037
              else
 
1038
                perm=1;
 
1039
            }
 
1040
          else
 
1041
            own=1;
 
1042
 
 
1043
          homedir_cache=ret;
 
1044
        }
 
1045
    }
 
1046
  else if(item==1 || item==2)
 
1047
    {
 
1048
      /* The options or extension file.  Okay unless it or its
 
1049
         containing directory is group or other writable or not owned
 
1050
         by us or root. */
 
1051
 
 
1052
      if(S_ISREG(statbuf.st_mode))
 
1053
        {
 
1054
          if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
 
1055
            {
 
1056
              if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
 
1057
                {
 
1058
                  /* it's not writable, so make sure the enclosing
 
1059
                     directory is also not writable */
 
1060
                  if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
 
1061
                    {
 
1062
                      if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
 
1063
                        ret=0;
 
1064
                      else
 
1065
                        enc_dir_perm=1;
 
1066
                    }
 
1067
                  else
 
1068
                    enc_dir_own=1;
 
1069
                }
 
1070
              else
 
1071
                {
 
1072
                  /* it's writable, so the enclosing directory had
 
1073
                     better not let people get to it. */
 
1074
                  if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
 
1075
                    {
 
1076
                      if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
 
1077
                        ret=0;
 
1078
                      else
 
1079
                        perm=enc_dir_perm=1; /* unclear which one to fix! */
 
1080
                    }
 
1081
                  else
 
1082
                    enc_dir_own=1;
 
1083
                }
 
1084
            }
 
1085
          else
 
1086
            own=1;
 
1087
        }
 
1088
    }
 
1089
  else
 
1090
    BUG();
 
1091
 
 
1092
  if(!checkonly)
 
1093
    {
 
1094
      if(own)
 
1095
        {
 
1096
          if(item==0)
 
1097
            log_info(_("WARNING: unsafe ownership on "
 
1098
                       "homedir \"%s\"\n"),tmppath);
 
1099
          else if(item==1)
 
1100
            log_info(_("WARNING: unsafe ownership on "
 
1101
                       "configuration file \"%s\"\n"),tmppath);
 
1102
          else
 
1103
            log_info(_("WARNING: unsafe ownership on "
 
1104
                       "extension \"%s\"\n"),tmppath);
 
1105
        }
 
1106
      if(perm)
 
1107
        {
 
1108
          if(item==0)
 
1109
            log_info(_("WARNING: unsafe permissions on "
 
1110
                       "homedir \"%s\"\n"),tmppath);
 
1111
          else if(item==1)
 
1112
            log_info(_("WARNING: unsafe permissions on "
 
1113
                       "configuration file \"%s\"\n"),tmppath);
 
1114
          else
 
1115
            log_info(_("WARNING: unsafe permissions on "
 
1116
                       "extension \"%s\"\n"),tmppath);
 
1117
        }
 
1118
      if(enc_dir_own)
 
1119
        {
 
1120
          if(item==0)
 
1121
            log_info(_("WARNING: unsafe enclosing directory ownership on "
 
1122
                       "homedir \"%s\"\n"),tmppath);
 
1123
          else if(item==1)
 
1124
            log_info(_("WARNING: unsafe enclosing directory ownership on "
 
1125
                       "configuration file \"%s\"\n"),tmppath);
 
1126
          else
 
1127
            log_info(_("WARNING: unsafe enclosing directory ownership on "
 
1128
                       "extension \"%s\"\n"),tmppath);
 
1129
        }
 
1130
      if(enc_dir_perm)
 
1131
        {
 
1132
          if(item==0)
 
1133
            log_info(_("WARNING: unsafe enclosing directory permissions on "
 
1134
                       "homedir \"%s\"\n"),tmppath);
 
1135
          else if(item==1)
 
1136
            log_info(_("WARNING: unsafe enclosing directory permissions on "
 
1137
                       "configuration file \"%s\"\n"),tmppath);
 
1138
          else
 
1139
            log_info(_("WARNING: unsafe enclosing directory permissions on "
 
1140
                       "extension \"%s\"\n"),tmppath);
 
1141
        }
 
1142
    }
 
1143
 
 
1144
 end:
 
1145
  xfree (tmppath);
 
1146
 
 
1147
  if(homedir)
 
1148
    homedir_cache=ret;
 
1149
 
 
1150
  return ret;
 
1151
 
 
1152
#endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
 
1153
 
 
1154
  return 0;
 
1155
}
 
1156
 
 
1157
int
 
1158
main( int argc, char **argv )
 
1159
{
 
1160
    ARGPARSE_ARGS pargs;
 
1161
    iobuf_t a;
 
1162
    int rc=0;
 
1163
    int orig_argc;
 
1164
    char **orig_argv;
 
1165
    const char *fname;
 
1166
    char *username;
 
1167
    int may_coredump;
 
1168
    STRLIST sl, remusr= NULL, locusr=NULL;
 
1169
    STRLIST nrings=NULL, sec_nrings=NULL;
 
1170
    armor_filter_context_t afx;
 
1171
    int detached_sig = 0;
 
1172
    FILE *configfp = NULL;
 
1173
    char *configname = NULL;
 
1174
    const char *config_filename = NULL;
 
1175
    unsigned configlineno;
 
1176
    int parse_debug = 0;
 
1177
    int default_config = 1;
 
1178
    int default_keyring = 1;
 
1179
    int greeting = 0;
 
1180
    int nogreeting = 0;
 
1181
    char *logfile = NULL;
 
1182
    int use_random_seed = 1;
 
1183
    enum cmd_and_opt_values cmd = 0;
 
1184
    const char *debug_level = NULL;
 
1185
    const char *trustdb_name = NULL;
 
1186
    char *def_cipher_string = NULL;
 
1187
    char *def_digest_string = NULL;
 
1188
    char *def_compress_string = NULL;
 
1189
    char *cert_digest_string = NULL;
 
1190
    char *s2k_cipher_string = NULL;
 
1191
    char *s2k_digest_string = NULL;
 
1192
    char *pers_cipher_list = NULL;
 
1193
    char *pers_digest_list = NULL;
 
1194
    char *pers_compress_list = NULL;
 
1195
    int eyes_only=0;
 
1196
    int multifile=0;
 
1197
    int pwfd = -1;
 
1198
    int with_fpr = 0; /* make an option out of --fingerprint */
 
1199
    int any_explicit_recipient = 0;
 
1200
 
 
1201
#ifdef __riscos__
 
1202
    riscos_global_defaults();
 
1203
    opt.lock_once = 1;
 
1204
#endif /* __riscos__ */
 
1205
 
 
1206
    trap_unaligned();
 
1207
    set_strusage (my_strusage);
 
1208
    gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
 
1209
    /* We don't need any locking in libgcrypt unless we use any kind of
 
1210
       threading. */
 
1211
    gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
 
1212
    /* Please note that we may running SUID(ROOT), so be very CAREFUL
 
1213
     * when adding any stuff between here and the call to
 
1214
     * secmem_init()  somewhere after the option parsing
 
1215
     */
 
1216
    log_set_prefix ("gpg", 1);
 
1217
    /* check that the libraries are suitable.  Do it here because the
 
1218
       option parse may need services of the library */
 
1219
    if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
 
1220
      {
 
1221
        log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
 
1222
                   NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
 
1223
      }
 
1224
 
 
1225
    gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
 
1226
 
 
1227
    may_coredump = disable_core_dumps();
 
1228
    gnupg_init_signals (0, emergency_cleanup);
 
1229
    create_dotlock (NULL); /* register locking cleanup */
 
1230
    i18n_init();
 
1231
 
 
1232
    opt.command_fd = -1; /* no command fd */
 
1233
    opt.compress = -1; /* defaults to standard compress level */
 
1234
    /* note: if you change these lines, look at oOpenPGP */
 
1235
    opt.def_cipher_algo = 0;
 
1236
    opt.def_digest_algo = 0;
 
1237
    opt.cert_digest_algo = 0;
 
1238
    opt.def_compress_algo = -1;
 
1239
    opt.s2k_mode = 3; /* iterated+salted */
 
1240
    opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
 
1241
#ifdef USE_CAST5
 
1242
    opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
 
1243
#else
 
1244
    opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
 
1245
#endif
 
1246
    opt.completes_needed = 1;
 
1247
    opt.marginals_needed = 3;
 
1248
    opt.max_cert_depth = 5;
 
1249
    opt.pgp2_workarounds = 1;
 
1250
    opt.force_v3_sigs = 1;
 
1251
    opt.escape_from = 1;
 
1252
    opt.import_options=IMPORT_SK2PK;
 
1253
    opt.export_options=
 
1254
      EXPORT_INCLUDE_NON_RFC|EXPORT_INCLUDE_ATTRIBUTES;
 
1255
    opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
 
1256
    opt.keyserver_options.export_options=
 
1257
      EXPORT_INCLUDE_NON_RFC|EXPORT_INCLUDE_ATTRIBUTES;
 
1258
    opt.keyserver_options.include_subkeys=1;
 
1259
    opt.keyserver_options.include_revoked=1;
 
1260
    opt.keyserver_options.try_dns_srv=1;
 
1261
    opt.verify_options=
 
1262
      VERIFY_SHOW_POLICY|VERIFY_SHOW_NOTATION|VERIFY_SHOW_KEYSERVER;
 
1263
    opt.trust_model=TM_AUTO;
 
1264
    opt.mangle_dos_filenames = 1;
 
1265
    opt.use_agent = 1;
 
1266
 
 
1267
    set_homedir ( default_homedir () );
 
1268
 
 
1269
    /* Check whether we have a config file on the commandline */
 
1270
    orig_argc = argc;
 
1271
    orig_argv = argv;
 
1272
    pargs.argc = &argc;
 
1273
    pargs.argv = &argv;
 
1274
    pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
 
1275
    while( arg_parse( &pargs, opts) ) {
 
1276
        if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
 
1277
            parse_debug++;
 
1278
        else if( pargs.r_opt == oOptions ) {
 
1279
            /* yes there is one, so we do not try the default one, but
 
1280
             * read the option file when it is encountered at the commandline
 
1281
             */
 
1282
            default_config = 0;
 
1283
        }
 
1284
        else if( pargs.r_opt == oNoOptions )
 
1285
            default_config = 0; /* --no-options */
 
1286
        else if( pargs.r_opt == oHomedir )
 
1287
            set_homedir ( pargs.r.ret_str );
 
1288
        else if( pargs.r_opt == oNoPermissionWarn )
 
1289
            opt.no_perm_warn=1;
 
1290
        else if (pargs.r_opt == oStrict )
 
1291
          {
 
1292
            opt.strict=1;
 
1293
            log_set_strict(1);
 
1294
          }
 
1295
        else if (pargs.r_opt == oNoStrict )
 
1296
          {
 
1297
            opt.strict=0;
 
1298
            log_set_strict(0);
 
1299
          }
 
1300
    }
 
1301
 
 
1302
#ifdef HAVE_DOSISH_SYSTEM
 
1303
    if ( strchr (opt.homedir,'\\') ) {
 
1304
        char *d, *buf = xmalloc (strlen (opt.homedir)+1);
 
1305
        const char *s = opt.homedir;
 
1306
        for (d=buf,s=opt.homedir; *s; s++)
 
1307
            *d++ = *s == '\\'? '/': *s;
 
1308
        *d = 0;
 
1309
        set_homedir (buf);
 
1310
    }
 
1311
#endif
 
1312
 
 
1313
    /* Initialize the secure memory. */
 
1314
    gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
 
1315
    maybe_setuid = 0;
 
1316
    /* Okay, we are now working under our real uid */
 
1317
 
 
1318
    /* malloc hooks go here ... */
 
1319
    assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
 
1320
 
 
1321
    set_native_charset (NULL); /* Try to auto set the character set */
 
1322
 
 
1323
    /* Try for a version specific config file first */
 
1324
    if( default_config )
 
1325
      {
 
1326
        char *name = xstrdup ("gpg" EXTSEP_S "conf-" SAFE_VERSION);
 
1327
        char *ver  = name + strlen("gpg" EXTSEP_S "conf-");
 
1328
 
 
1329
        do
 
1330
          {
 
1331
            if(configname)
 
1332
              {
 
1333
                char *tok;
 
1334
 
 
1335
                xfree (configname);
 
1336
                configname=NULL;
 
1337
 
 
1338
                if((tok=strrchr (ver,SAFE_VERSION_DASH)))
 
1339
                  *tok='\0';
 
1340
                else if((tok=strrchr (ver,SAFE_VERSION_DOT)))
 
1341
                  *tok='\0';
 
1342
                else
 
1343
                  break;
 
1344
              }
 
1345
 
 
1346
            configname = make_filename (opt.homedir, name, NULL);
 
1347
          }
 
1348
        while ( access(configname,R_OK) );
 
1349
        xfree(name);
 
1350
 
 
1351
        if (!access (configname, R_OK))
 
1352
          { /* Print a warning when both config files are present. */
 
1353
            char *p = make_filename(opt.homedir, "options", NULL );
 
1354
            if (!access (p, R_OK))
 
1355
              log_info (_("NOTE: old default options file `%s' ignored\n"), p);
 
1356
            xfree (p);
 
1357
          }
 
1358
        else
 
1359
          { /* Keep on using the old default one. */
 
1360
            xfree (configname);
 
1361
            configname = make_filename(opt.homedir, "options", NULL );
 
1362
          }
 
1363
      }
 
1364
    argc = orig_argc;
 
1365
    argv = orig_argv;
 
1366
    pargs.argc = &argc;
 
1367
    pargs.argv = &argv;
 
1368
    pargs.flags=  1;  /* do not remove the args */
 
1369
 
 
1370
    /* By this point we have a homedir, and cannot change it. */
 
1371
    check_permissions(opt.homedir,0);
 
1372
 
 
1373
  next_pass:
 
1374
    if( configname ) {
 
1375
      if(check_permissions(configname,1))
 
1376
        {
 
1377
          /* If any options file is unsafe, then disable any external
 
1378
             programs for keyserver calls or photo IDs.  Since the
 
1379
             external program to call is set in the options file, a
 
1380
             unsafe options file can lead to an arbitrary program
 
1381
             being run. */
 
1382
 
 
1383
          opt.exec_disable=1;
 
1384
        }
 
1385
 
 
1386
        configlineno = 0;
 
1387
        configfp = fopen( configname, "r" );
 
1388
        if( !configfp ) {
 
1389
            if( default_config ) {
 
1390
                if( parse_debug )
 
1391
                    log_info(_("NOTE: no default option file `%s'\n"),
 
1392
                                                            configname );
 
1393
            }
 
1394
            else {
 
1395
                log_error(_("option file `%s': %s\n"),
 
1396
                                    configname, strerror(errno) );
 
1397
                g10_exit(2);
 
1398
            }
 
1399
            xfree (configname); configname = NULL;
 
1400
        }
 
1401
        if( parse_debug && configname )
 
1402
            log_info(_("reading options from `%s'\n"), configname );
 
1403
        default_config = 0;
 
1404
    }
 
1405
 
 
1406
    while( optfile_parse( configfp, configname, &configlineno,
 
1407
                                                &pargs, opts) ) {
 
1408
        switch( pargs.r_opt ) {
 
1409
          case aCheckKeys: set_cmd( &cmd, aCheckKeys); break;
 
1410
          case aListPackets: set_cmd( &cmd, aListPackets); break;
 
1411
          case aImport: set_cmd( &cmd, aImport); break;
 
1412
          case aFastImport: set_cmd( &cmd, aFastImport); break;
 
1413
          case aSendKeys: set_cmd( &cmd, aSendKeys); break;
 
1414
          case aRecvKeys: set_cmd( &cmd, aRecvKeys); break;
 
1415
          case aSearchKeys: set_cmd( &cmd, aSearchKeys); break;
 
1416
          case aRefreshKeys: set_cmd( &cmd, aRefreshKeys); break;
 
1417
          case aExport: set_cmd( &cmd, aExport); break;
 
1418
          case aExportAll: set_cmd( &cmd, aExportAll); break;
 
1419
          case aListKeys: set_cmd( &cmd, aListKeys); break;
 
1420
          case aListSigs: set_cmd( &cmd, aListSigs); break;
 
1421
          case aExportSecret: set_cmd( &cmd, aExportSecret); break;
 
1422
          case aExportSecretSub: set_cmd( &cmd, aExportSecretSub); break;
 
1423
          case aDeleteSecretKeys: set_cmd( &cmd, aDeleteSecretKeys);
 
1424
                                                        greeting=1; break;
 
1425
          case aDeleteSecretAndPublicKeys:
 
1426
            set_cmd( &cmd, aDeleteSecretAndPublicKeys);
 
1427
            greeting=1; 
 
1428
            break;
 
1429
          case aDeleteKeys: set_cmd( &cmd, aDeleteKeys); greeting=1; break;
 
1430
 
 
1431
          case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
 
1432
          case aSym: set_cmd( &cmd, aSym); break;
 
1433
 
 
1434
          case aDecryptFiles: multifile=1; /* fall through */
 
1435
          case aDecrypt: set_cmd( &cmd, aDecrypt); break;
 
1436
 
 
1437
          case aEncrFiles: multifile=1; /* fall through */
 
1438
          case aEncr: set_cmd( &cmd, aEncr); break;
 
1439
 
 
1440
          case aVerifyFiles: multifile=1; /* fall through */
 
1441
          case aVerify: set_cmd( &cmd, aVerify); break;
 
1442
 
 
1443
          case aSign: set_cmd( &cmd, aSign );  break;
 
1444
          case aKeygen: set_cmd( &cmd, aKeygen); greeting=1; break;
 
1445
          case aSignKey: set_cmd( &cmd, aSignKey); break;
 
1446
          case aLSignKey: set_cmd( &cmd, aLSignKey); break;
 
1447
          case aNRSignKey: set_cmd( &cmd, aNRSignKey); break;
 
1448
          case aNRLSignKey: set_cmd( &cmd, aNRLSignKey); break;
 
1449
          case aStore: set_cmd( &cmd, aStore); break;
 
1450
          case aEditKey: set_cmd( &cmd, aEditKey); greeting=1; break;
 
1451
          case aClearsign: set_cmd( &cmd, aClearsign); break;
 
1452
          case aGenRevoke: set_cmd( &cmd, aGenRevoke); break;
 
1453
          case aDesigRevoke: set_cmd( &cmd, aDesigRevoke); break;
 
1454
 
 
1455
          case aPrimegen: set_cmd( &cmd, aPrimegen); break;
 
1456
          case aGenRandom: set_cmd( &cmd, aGenRandom); break;
 
1457
          case aPrintMD: set_cmd( &cmd, aPrintMD); break;
 
1458
          case aPrintMDs: set_cmd( &cmd, aPrintMDs); break;
 
1459
          case aListTrustDB: set_cmd( &cmd, aListTrustDB); break;
 
1460
          case aCheckTrustDB: set_cmd( &cmd, aCheckTrustDB); break;
 
1461
          case aUpdateTrustDB: set_cmd( &cmd, aUpdateTrustDB); break;
 
1462
          case aFixTrustDB: set_cmd( &cmd, aFixTrustDB); break;
 
1463
          case aListTrustPath: set_cmd( &cmd, aListTrustPath); break;
 
1464
          case aDeArmor: set_cmd( &cmd, aDeArmor); break;
 
1465
          case aEnArmor: set_cmd( &cmd, aEnArmor); break;
 
1466
          case aListOwnerTrust:
 
1467
            deprecated_warning(configname,configlineno,
 
1468
                               "--list-ownertrust","--export-ownertrust","");
 
1469
          case aExportOwnerTrust: set_cmd( &cmd, aExportOwnerTrust); break;
 
1470
          case aImportOwnerTrust: set_cmd( &cmd, aImportOwnerTrust); break;
 
1471
          case aPipeMode: set_cmd( &cmd, aPipeMode); break;
 
1472
          case aRebuildKeydbCaches: set_cmd( &cmd, aRebuildKeydbCaches); break;
 
1473
 
 
1474
          case aCardStatus: set_cmd (&cmd, aCardStatus); break;
 
1475
          case aCardEdit: set_cmd (&cmd, aCardEdit); break;
 
1476
          case aChangePIN: set_cmd (&cmd, aChangePIN); break;
 
1477
          case aGPGConfList: 
 
1478
            set_cmd (&cmd, aGPGConfList);
 
1479
            nogreeting = 1;
 
1480
            break;
 
1481
 
 
1482
          case oArmor: opt.armor = 1; opt.no_armor=0; break;
 
1483
          case oOutput: opt.outfile = pargs.r.ret_str; break;
 
1484
          case oQuiet: opt.quiet = 1; break;
 
1485
          case oNoTTY: tty_no_terminal(1); break;
 
1486
          case oDryRun: opt.dry_run = 1; break;
 
1487
          case oInteractive: opt.interactive = 1; break;
 
1488
          case oVerbose: g10_opt_verbose++;
 
1489
                    opt.verbose++; opt.list_sigs=1; break;
 
1490
 
 
1491
          case oLogFile: logfile = pargs.r.ret_str; break;
 
1492
    
 
1493
          case oBatch: opt.batch = 1; nogreeting = 1; break;
 
1494
          case oUseAgent:
 
1495
#ifndef __riscos__
 
1496
            opt.use_agent = 1;
 
1497
#else /* __riscos__ */
 
1498
            opt.use_agent = 0;
 
1499
            riscos_not_implemented("use-agent");
 
1500
#endif /* __riscos__ */
 
1501
            break;
 
1502
          case oNoUseAgent: opt.use_agent = 0; break;
 
1503
          case oGpgAgentInfo: opt.gpg_agent_info = pargs.r.ret_str; break;
 
1504
          case oAnswerYes: opt.answer_yes = 1; break;
 
1505
          case oAnswerNo: opt.answer_no = 1; break;
 
1506
          case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
 
1507
          case oPrimaryKeyring:
 
1508
            sl=append_to_strlist( &nrings, pargs.r.ret_str);
 
1509
            sl->flags=2;
 
1510
            break;
 
1511
          case oShowKeyring: opt.list_options|=LIST_SHOW_KEYRING; break;
 
1512
          case oDebug: opt.debug |= pargs.r.ret_ulong; break;
 
1513
          case oDebugAll: opt.debug = ~0; break;
 
1514
          case oDebugLevel: debug_level = pargs.r.ret_str; break;
 
1515
          case oStatusFD:
 
1516
            set_status_fd( iobuf_translate_file_handle (pargs.r.ret_int, 1) );
 
1517
            break;
 
1518
#ifdef __riscos__
 
1519
          case oStatusFile:
 
1520
            set_status_fd( iobuf_translate_file_handle ( riscos_fdopenfile (pargs.r.ret_str, 1), 1) );
 
1521
            break;
 
1522
#endif /* __riscos__ */
 
1523
          case oAttributeFD:
 
1524
            set_attrib_fd(iobuf_translate_file_handle (pargs.r.ret_int, 1));
 
1525
            break;
 
1526
#ifdef __riscos__
 
1527
          case oAttributeFile:
 
1528
            set_attrib_fd(iobuf_translate_file_handle ( riscos_fdopenfile (pargs.r.ret_str, 1), 1) );
 
1529
            break;
 
1530
#endif /* __riscos__ */
 
1531
          case oLoggerFD:
 
1532
            log_set_fd (iobuf_translate_file_handle (pargs.r.ret_int, 1));
 
1533
            break;
 
1534
#ifdef __riscos__
 
1535
          case oLoggerFile:
 
1536
            log_set_logfile( NULL,
 
1537
                             iobuf_translate_file_handle ( riscos_fdopenfile (pargs.r.ret_str, 1), 1) );
 
1538
            break;
 
1539
#endif /* __riscos__ */
 
1540
          case oWithFingerprint:
 
1541
            opt.with_fingerprint = 1;
 
1542
            with_fpr=1; /*fall thru*/
 
1543
          case oFingerprint: opt.fingerprint++; break;
 
1544
          case oSecretKeyring: append_to_strlist( &sec_nrings, pargs.r.ret_str); break;
 
1545
          case oOptions:
 
1546
            /* config files may not be nested (silently ignore them) */
 
1547
            if( !configfp ) {
 
1548
                xfree (configname);
 
1549
                configname = xstrdup (pargs.r.ret_str);
 
1550
                goto next_pass;
 
1551
            }
 
1552
            break;
 
1553
          case oNoArmor: opt.no_armor=1; opt.armor=0; break;
 
1554
          case oNoDefKeyring: default_keyring = 0; break;
 
1555
          case oDefCertCheckLevel: opt.def_cert_check_level=pargs.r.ret_int; break;
 
1556
          case oNoGreeting: nogreeting = 1; break;
 
1557
          case oNoVerbose: g10_opt_verbose = 0;
 
1558
                           opt.verbose = 0; opt.list_sigs=0; break;
 
1559
      /* disabled for now: 
 
1560
          case oQuickRandom: quick_random_gen(1); break; */
 
1561
          case oSKComments: opt.sk_comments=1; break;
 
1562
          case oNoSKComments: opt.sk_comments=0; break;
 
1563
          case oEmitVersion: opt.no_version=0; break;
 
1564
          case oNoEmitVersion: opt.no_version=1; break;
 
1565
          case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
 
1566
          case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
 
1567
          case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
 
1568
          case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
 
1569
          case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
 
1570
          case oDefRecipient:
 
1571
                    if( *pargs.r.ret_str )
 
1572
                        opt.def_recipient = make_username(pargs.r.ret_str);
 
1573
                    break;
 
1574
          case oDefRecipientSelf:
 
1575
                    xfree (opt.def_recipient); opt.def_recipient = NULL;
 
1576
                    opt.def_recipient_self = 1;
 
1577
                    break;
 
1578
          case oNoDefRecipient:
 
1579
                    xfree (opt.def_recipient); opt.def_recipient = NULL;
 
1580
                    opt.def_recipient_self = 0;
 
1581
                    break;
 
1582
          case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
 
1583
          case oHomedir: break;
 
1584
          case oNoBatch: opt.batch = 0; break;
 
1585
          case oWithKeyData: opt.with_key_data=1; /* fall thru */
 
1586
          case oWithColons: opt.with_colons=':'; break;
 
1587
 
 
1588
          case oSkipVerify: opt.skip_verify=1; break;
 
1589
          case oCompressKeys: opt.compress_keys = 1; break;
 
1590
          case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
 
1591
            /* There are many programs (like mutt) that call gpg with
 
1592
               --always-trust so keep this option around for a long
 
1593
               time. */
 
1594
          case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
 
1595
          case oTrustModel:
 
1596
            if(ascii_strcasecmp(pargs.r.ret_str,"pgp")==0)
 
1597
              opt.trust_model=TM_PGP;
 
1598
            else if(ascii_strcasecmp(pargs.r.ret_str,"classic")==0)
 
1599
              opt.trust_model=TM_CLASSIC;
 
1600
            else if(ascii_strcasecmp(pargs.r.ret_str,"always")==0)
 
1601
              opt.trust_model=TM_ALWAYS;
 
1602
            else if(ascii_strcasecmp(pargs.r.ret_str,"auto")==0)
 
1603
              opt.trust_model=TM_AUTO;
 
1604
            else
 
1605
              log_error("unknown trust model \"%s\"\n",pargs.r.ret_str);
 
1606
            break;
 
1607
          case oForceOwnertrust:
 
1608
            log_info(_("NOTE: %s is not for normal use!\n"),
 
1609
                     "--force-ownertrust");
 
1610
            opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
 
1611
            if(opt.force_ownertrust==-1)
 
1612
              {
 
1613
                log_error("invalid ownertrust \"%s\"\n",pargs.r.ret_str);
 
1614
                opt.force_ownertrust=0;
 
1615
              }
 
1616
            break;
 
1617
          case oLoadExtension:
 
1618
#ifndef __riscos__
 
1619
#if defined(USE_DYNAMIC_LINKING) || defined(_WIN32)
 
1620
            if(check_permissions(pargs.r.ret_str,2))
 
1621
              log_info(_("cipher extension \"%s\" not loaded due to "
 
1622
                         "unsafe permissions\n"),pargs.r.ret_str);
 
1623
            else
 
1624
              register_cipher_extension(orig_argc? *orig_argv:NULL,
 
1625
                                        pargs.r.ret_str);
 
1626
#endif
 
1627
#else /* __riscos__ */
 
1628
            riscos_not_implemented("load-extension");
 
1629
#endif /* __riscos__ */
 
1630
            break;
 
1631
          case oRFC1991:
 
1632
            opt.compliance = CO_RFC1991;
 
1633
            opt.force_v4_certs = 0;
 
1634
            opt.escape_from = 1;
 
1635
            break;
 
1636
          case oRFC2440:
 
1637
          case oOpenPGP:
 
1638
            /* TODO: When 2440bis becomes a RFC, these may need
 
1639
               changing. */
 
1640
            opt.compliance = CO_RFC2440;
 
1641
            opt.allow_non_selfsigned_uid = 1;
 
1642
            opt.allow_freeform_uid = 1;
 
1643
            opt.pgp2_workarounds = 0;
 
1644
            opt.escape_from = 0;
 
1645
            opt.force_v3_sigs = 0;
 
1646
            opt.compress_keys = 0;          /* not mandated  but we do it */
 
1647
            opt.compress_sigs = 0;          /* ditto. */
 
1648
            opt.not_dash_escaped = 0;
 
1649
            opt.def_cipher_algo = 0;
 
1650
            opt.def_digest_algo = 0;
 
1651
            opt.cert_digest_algo = 0;
 
1652
            opt.def_compress_algo = -1;
 
1653
            opt.s2k_mode = 3; /* iterated+salted */
 
1654
            opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
 
1655
            opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
 
1656
            break;
 
1657
          case oPGP2:  opt.compliance = CO_PGP2;  break;
 
1658
          case oPGP6:  opt.compliance = CO_PGP6;  break;
 
1659
          case oPGP7:  opt.compliance = CO_PGP7;  break;
 
1660
          case oPGP8:  opt.compliance = CO_PGP8;  break;
 
1661
          case oGnuPG: opt.compliance = CO_GNUPG; break;
 
1662
          case oEmuMDEncodeBug: opt.emulate_bugs |= EMUBUG_MDENCODE; break;
 
1663
          case oCompressSigs: opt.compress_sigs = 1; break;
 
1664
          case oSetFilename: opt.set_filename = pargs.r.ret_str; break;
 
1665
          case oForYourEyesOnly: eyes_only = 1; break;
 
1666
          case oNoForYourEyesOnly: eyes_only = 0; break;
 
1667
          case oSetPolicyURL:
 
1668
            add_policy_url(pargs.r.ret_str,0);
 
1669
            add_policy_url(pargs.r.ret_str,1);
 
1670
            break;
 
1671
          case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
 
1672
          case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
 
1673
          case oShowPolicyURL:
 
1674
            opt.list_options|=LIST_SHOW_POLICY;
 
1675
            opt.verify_options|=VERIFY_SHOW_POLICY;
 
1676
            break;
 
1677
          case oNoShowPolicyURL:
 
1678
            opt.list_options&=~LIST_SHOW_POLICY;
 
1679
            opt.verify_options&=~VERIFY_SHOW_POLICY;
 
1680
            break;
 
1681
          case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
 
1682
          case oUseEmbeddedFilename: opt.use_embedded_filename = 1; break;
 
1683
 
 
1684
          case oComment: add_to_strlist(&opt.comments,pargs.r.ret_str); break;
 
1685
          case oDefaultComment:
 
1686
            deprecated_warning(configname,configlineno,
 
1687
                               "--default-comment","--no-comments","");
 
1688
            /* fall through */
 
1689
          case oNoComments:
 
1690
            free_strlist(opt.comments);
 
1691
            opt.comments=NULL;
 
1692
            break;
 
1693
 
 
1694
          case oThrowKeyid: opt.throw_keyid = 1; break;
 
1695
          case oNoThrowKeyid: opt.throw_keyid = 0; break;
 
1696
          case oShowPhotos: 
 
1697
            opt.list_options|=LIST_SHOW_PHOTOS;
 
1698
            opt.verify_options|=VERIFY_SHOW_PHOTOS;
 
1699
            break;
 
1700
          case oNoShowPhotos:
 
1701
            opt.list_options&=~LIST_SHOW_PHOTOS;
 
1702
            opt.verify_options&=~VERIFY_SHOW_PHOTOS;
 
1703
            break;
 
1704
          case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
 
1705
          case oForceV3Sigs: opt.force_v3_sigs = 1; break;
 
1706
          case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
 
1707
          case oForceV4Certs: opt.force_v4_certs = 1; break;
 
1708
          case oNoForceV4Certs: opt.force_v4_certs = 0; break;
 
1709
          case oForceMDC: opt.force_mdc = 1; break;
 
1710
          case oNoForceMDC: opt.force_mdc = 0; break;
 
1711
          case oDisableMDC: opt.disable_mdc = 1; break;
 
1712
          case oNoDisableMDC: opt.disable_mdc = 0; break;
 
1713
          case oS2KMode:   opt.s2k_mode = pargs.r.ret_int; break;
 
1714
          case oS2KDigest: s2k_digest_string = xstrdup (pargs.r.ret_str); break;
 
1715
          case oS2KCipher: s2k_cipher_string = xstrdup (pargs.r.ret_str); break;
 
1716
          case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
 
1717
          case oNoEncryptTo: opt.no_encrypt_to = 1; break;
 
1718
          case oEncryptTo: /* store the recipient in the second list */
 
1719
            sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
 
1720
            sl->flags = 1;
 
1721
            break;
 
1722
          case oHiddenEncryptTo: /* store the recipient in the second list */
 
1723
            sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
 
1724
            sl->flags = 1|2;
 
1725
            break;
 
1726
          case oRecipient: /* store the recipient */
 
1727
            add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
 
1728
            any_explicit_recipient = 1;
 
1729
            break;
 
1730
          case oHiddenRecipient: /* store the recipient with a flag */
 
1731
            sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
 
1732
            sl->flags = 2;
 
1733
            any_explicit_recipient = 1;
 
1734
            break;
 
1735
          case oTextmodeShort: opt.textmode = 2; break;
 
1736
          case oTextmode: opt.textmode=1;  break;
 
1737
          case oNoTextmode: opt.textmode=0;  break;
 
1738
          case oExpert: opt.expert = 1; break;
 
1739
          case oNoExpert: opt.expert = 0; break;
 
1740
          case oAskSigExpire: opt.ask_sig_expire = 1; break;
 
1741
          case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
 
1742
          case oAskCertExpire: opt.ask_cert_expire = 1; break;
 
1743
          case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
 
1744
          case oUser: /* store the local users */
 
1745
            add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
 
1746
            break;
 
1747
          case oCompress: opt.compress = pargs.r.ret_int; break;
 
1748
          case oPasswdFD:
 
1749
            pwfd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
 
1750
            opt.use_agent = 0;
 
1751
            break;
 
1752
#ifdef __riscos__
 
1753
          case oPasswdFile:
 
1754
            pwfd = iobuf_translate_file_handle ( riscos_fdopenfile (pargs.r.ret_str, 0), 0);
 
1755
            break;
 
1756
#endif /* __riscos__ */
 
1757
          case oCommandFD:
 
1758
            opt.command_fd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
 
1759
            break;
 
1760
#ifdef __riscos__
 
1761
          case oCommandFile:
 
1762
            opt.command_fd = iobuf_translate_file_handle ( riscos_fdopenfile (pargs.r.ret_str, 0), 0);
 
1763
            break;
 
1764
#endif /* __riscos__ */
 
1765
          case oCipherAlgo: def_cipher_string = xstrdup (pargs.r.ret_str); break;
 
1766
          case oDigestAlgo: def_digest_string = xstrdup (pargs.r.ret_str); break;
 
1767
          case oCompressAlgo:
 
1768
            /* If it is all digits, stick a Z in front of it for
 
1769
               later.  This is for backwards compatibility with
 
1770
               versions that took the compress algorithm number. */
 
1771
            {
 
1772
              char *pt=pargs.r.ret_str;
 
1773
              while(*pt)
 
1774
                {
 
1775
                  if(!isdigit(*pt))
 
1776
                    break;
 
1777
 
 
1778
                  pt++;
 
1779
                }
 
1780
 
 
1781
              if(*pt=='\0')
 
1782
                {
 
1783
                  def_compress_string=xmalloc (strlen(pargs.r.ret_str)+2);
 
1784
                  strcpy(def_compress_string,"Z");
 
1785
                  strcat(def_compress_string,pargs.r.ret_str);
 
1786
                }
 
1787
              else
 
1788
                def_compress_string = xstrdup (pargs.r.ret_str);
 
1789
            }
 
1790
            break;
 
1791
          case oCertDigestAlgo: cert_digest_string = xstrdup (pargs.r.ret_str); break;
 
1792
          case oNoSecmemWarn:
 
1793
            gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); 
 
1794
            break;
 
1795
          case oNoPermissionWarn: opt.no_perm_warn=1; break;
 
1796
          case oNoMDCWarn: opt.no_mdc_warn=1; break;
 
1797
          case oCharset:
 
1798
            if( set_native_charset( pargs.r.ret_str ) )
 
1799
                log_error(_("%s is not a valid character set\n"),
 
1800
                                                    pargs.r.ret_str);
 
1801
            break;
 
1802
          case oNotDashEscaped: opt.not_dash_escaped = 1; break;
 
1803
          case oEscapeFrom: opt.escape_from = 1; break;
 
1804
          case oNoEscapeFrom: opt.escape_from = 0; break;
 
1805
          case oLockOnce: opt.lock_once = 1; break;
 
1806
          case oLockNever: disable_dotlock(); break;
 
1807
          case oLockMultiple:
 
1808
#ifndef __riscos__
 
1809
            opt.lock_once = 0;
 
1810
#else /* __riscos__ */
 
1811
            riscos_not_implemented("lock-multiple");
 
1812
#endif /* __riscos__ */
 
1813
            break;
 
1814
          case oKeyServer:
 
1815
            opt.keyserver_uri=xstrdup (pargs.r.ret_str);
 
1816
            if(parse_keyserver_uri(pargs.r.ret_str,configname,configlineno))
 
1817
              log_error(_("could not parse keyserver URI\n"));
 
1818
            break;
 
1819
          case oKeyServerOptions:
 
1820
            parse_keyserver_options(pargs.r.ret_str);
 
1821
            break;
 
1822
          case oImportOptions:
 
1823
            if(!parse_import_options(pargs.r.ret_str,&opt.import_options))
 
1824
              {
 
1825
                if(configname)
 
1826
                  log_error(_("%s:%d: invalid import options\n"),
 
1827
                            configname,configlineno);
 
1828
                else
 
1829
                  log_error(_("invalid import options\n"));
 
1830
              }
 
1831
            break;
 
1832
          case oExportOptions:
 
1833
            if(!parse_export_options(pargs.r.ret_str,&opt.export_options))
 
1834
              {
 
1835
                if(configname)
 
1836
                  log_error(_("%s:%d: invalid export options\n"),
 
1837
                            configname,configlineno);
 
1838
                else
 
1839
                  log_error(_("invalid export options\n"));
 
1840
              }
 
1841
            break;
 
1842
          case oListOptions:
 
1843
            {
 
1844
              struct parse_options lopts[]=
 
1845
                {
 
1846
                  {"show-photos",LIST_SHOW_PHOTOS},
 
1847
                  {"show-policy-url",LIST_SHOW_POLICY},
 
1848
                  {"show-notation",LIST_SHOW_NOTATION},
 
1849
                  {"show-keyserver-url",LIST_SHOW_KEYSERVER},
 
1850
                  {"show-validity",LIST_SHOW_VALIDITY},
 
1851
                  {"show-long-keyid",LIST_SHOW_LONG_KEYID},
 
1852
                  {"show-keyring",LIST_SHOW_KEYRING},
 
1853
                  {"show-sig-expire",LIST_SHOW_SIG_EXPIRE},
 
1854
                  {NULL,0}
 
1855
                };
 
1856
 
 
1857
              if(!parse_options(pargs.r.ret_str,&opt.list_options,lopts))
 
1858
                {
 
1859
                  if(configname)
 
1860
                    log_error(_("%s:%d: invalid list options\n"),
 
1861
                              configname,configlineno);
 
1862
                  else
 
1863
                    log_error(_("invalid list options\n"));
 
1864
                }
 
1865
            }
 
1866
            break;
 
1867
          case oVerifyOptions:
 
1868
            {
 
1869
              struct parse_options vopts[]=
 
1870
                {
 
1871
                  {"show-photos",VERIFY_SHOW_PHOTOS},
 
1872
                  {"show-policy-url",VERIFY_SHOW_POLICY},
 
1873
                  {"show-notation",VERIFY_SHOW_NOTATION},
 
1874
                  {"show-keyserver-url",VERIFY_SHOW_KEYSERVER},
 
1875
                  {"show-validity",VERIFY_SHOW_VALIDITY},
 
1876
                  {"show-long-keyid",VERIFY_SHOW_LONG_KEYID},
 
1877
                  {NULL,0}
 
1878
                };
 
1879
 
 
1880
              if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts))
 
1881
                {
 
1882
                  if(configname)
 
1883
                    log_error(_("%s:%d: invalid verify options\n"),
 
1884
                              configname,configlineno);
 
1885
                  else
 
1886
                    log_error(_("invalid verify options\n"));
 
1887
                }
 
1888
            }
 
1889
            break;
 
1890
          case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
 
1891
          case oExecPath:
 
1892
            if(set_exec_path(pargs.r.ret_str,0))
 
1893
              log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
 
1894
            else
 
1895
              opt.exec_path_set=1;
 
1896
            break;
 
1897
          case oSetNotation:
 
1898
            add_notation_data( pargs.r.ret_str, 0 );
 
1899
            add_notation_data( pargs.r.ret_str, 1 );
 
1900
            break;
 
1901
          case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
 
1902
          case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
 
1903
          case oShowNotation:
 
1904
            opt.list_options|=LIST_SHOW_NOTATION;
 
1905
            opt.verify_options|=VERIFY_SHOW_NOTATION;
 
1906
            break;
 
1907
          case oNoShowNotation:
 
1908
            opt.list_options&=~LIST_SHOW_NOTATION;
 
1909
            opt.verify_options&=~VERIFY_SHOW_NOTATION;
 
1910
            break;
 
1911
          case oUtf8Strings: utf8_strings = 1; break;
 
1912
          case oNoUtf8Strings: utf8_strings = 0; break;
 
1913
          case oDisableCipherAlgo:
 
1914
            {
 
1915
              int algo = gcry_cipher_map_name (pargs.r.ret_str);
 
1916
              gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO,
 
1917
                               &algo, sizeof algo);
 
1918
            }
 
1919
            break;
 
1920
          case oDisablePubkeyAlgo:
 
1921
            {
 
1922
              int algo = gcry_pk_map_name (pargs.r.ret_str);
 
1923
              gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,
 
1924
                           &algo, sizeof algo );
 
1925
            }
 
1926
            break;
 
1927
          case oNoSigCache: opt.no_sig_cache = 1; break;
 
1928
          case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
 
1929
          case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
 
1930
          case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
 
1931
          case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
 
1932
          case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
 
1933
          case oNoLiteral: opt.no_literal = 1; break;
 
1934
          case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
 
1935
          case oHonorHttpProxy:
 
1936
                opt.keyserver_options.honor_http_proxy = 1;
 
1937
                deprecated_warning(configname,configlineno,
 
1938
                                   "--honor-http-proxy",
 
1939
                                   "--keyserver-options ",
 
1940
                                   "honor-http-proxy");
 
1941
                break;
 
1942
          case oFastListMode: opt.fast_list_mode = 1; break;
 
1943
          case oFixedListMode: opt.fixed_list_mode = 1; break;
 
1944
          case oListOnly: opt.list_only=1; break;
 
1945
          case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
 
1946
          case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
 
1947
          case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
 
1948
          case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
 
1949
          case oNoRandomSeedFile: use_random_seed = 0; break;
 
1950
          case oAutoKeyRetrieve:
 
1951
          case oNoAutoKeyRetrieve:
 
1952
                opt.keyserver_options.auto_key_retrieve=
 
1953
                                             (pargs.r_opt==oAutoKeyRetrieve);
 
1954
                deprecated_warning(configname,configlineno,
 
1955
                           pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
 
1956
                               "--no-auto-key-retrieve","--keyserver-options ",
 
1957
                           pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
 
1958
                               "no-auto-key-retrieve");
 
1959
                break;
 
1960
          case oShowSessionKey: opt.show_session_key = 1; break;
 
1961
          case oOverrideSessionKey:
 
1962
                opt.override_session_key = pargs.r.ret_str;
 
1963
                break;
 
1964
          case oMergeOnly: opt.merge_only = 1; break;
 
1965
          case oAllowSecretKeyImport: /* obsolete */ break;
 
1966
          case oTryAllSecrets: opt.try_all_secrets = 1; break;
 
1967
          case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
 
1968
          case oEnableSpecialFilenames:
 
1969
            iobuf_enable_special_filenames (1);
 
1970
            break;
 
1971
          case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
 
1972
          case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
 
1973
          case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
 
1974
          case oPreservePermissions: opt.preserve_permissions=1; break;
 
1975
          case oDefaultPreferenceList:
 
1976
            opt.def_preference_list = pargs.r.ret_str;
 
1977
            break;
 
1978
          case oPersonalCipherPreferences:
 
1979
            pers_cipher_list=pargs.r.ret_str;
 
1980
            break;
 
1981
          case oPersonalDigestPreferences:
 
1982
            pers_digest_list=pargs.r.ret_str;
 
1983
            break;
 
1984
          case oPersonalCompressPreferences:
 
1985
            pers_compress_list=pargs.r.ret_str;
 
1986
            break;
 
1987
          case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
 
1988
          case oDisplay: opt.display = pargs.r.ret_str; break;
 
1989
          case oTTYname: opt.ttyname = pargs.r.ret_str; break;
 
1990
          case oTTYtype: opt.ttytype = pargs.r.ret_str; break;
 
1991
          case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
 
1992
          case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
 
1993
          case oGroup: add_group(pargs.r.ret_str); break;
 
1994
          case oStrict: opt.strict=1; log_set_strict(1); break;
 
1995
          case oNoStrict: opt.strict=0; log_set_strict(0); break;
 
1996
 
 
1997
          case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
 
1998
          case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
 
1999
 
 
2000
          case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
 
2001
          case oMultifile: multifile=1; break;
 
2002
 
 
2003
          default : pargs.err = configfp? 1:2; break;
 
2004
        }
 
2005
    }
 
2006
 
 
2007
    if( configfp ) {
 
2008
        fclose( configfp );
 
2009
        configfp = NULL;
 
2010
        config_filename = configname; /* Keep a copy of the config
 
2011
                                         file name. */
 
2012
        configname = NULL;
 
2013
        goto next_pass;
 
2014
    }
 
2015
    xfree ( configname ); configname = NULL;
 
2016
    if( log_get_errorcount(0) )
 
2017
        g10_exit(2);
 
2018
    if( nogreeting )
 
2019
        greeting = 0;
 
2020
 
 
2021
    if( greeting ) {
 
2022
        fprintf(stderr, "%s %s; %s\n",
 
2023
                        strusage(11), strusage(13), strusage(14) );
 
2024
        fprintf(stderr, "%s\n", strusage(15) );
 
2025
    }
 
2026
#ifdef IS_DEVELOPMENT_VERSION
 
2027
    if( !opt.batch ) {
 
2028
        log_info("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
 
2029
        log_info("It is only intended for test purposes and should NOT be\n");
 
2030
        log_info("used in a production environment or with production keys!\n");
 
2031
    }
 
2032
#endif
 
2033
 
 
2034
    log_info ("WARNING: This version of gpg is not very matured and\n");
 
2035
    log_info ("WARNING: only intended for testing.  Please keep using\n");
 
2036
    log_info ("WARNING: gpg 1.2.x, 1.3.x or 1.4.x for OpenPGP\n");
 
2037
 
 
2038
    /* FIXME: We should use the lggging to a file only in server mode;
 
2039
       however we have not yet implemetyed that thus we try to get
 
2040
       away with --batch as indication for logging to file required. */
 
2041
    if (logfile && opt.batch)
 
2042
      {
 
2043
        log_set_file (logfile);
 
2044
        log_set_prefix (NULL, 1|2|4);
 
2045
      }
 
2046
 
 
2047
    if (opt.verbose > 2)
 
2048
        log_info ("using character set `%s'\n", get_native_charset ());
 
2049
 
 
2050
    if( may_coredump && !opt.quiet )
 
2051
        log_info(_("WARNING: program may create a core file!\n"));
 
2052
 
 
2053
    if (eyes_only) {
 
2054
      if (opt.set_filename)
 
2055
          log_info(_("WARNING: %s overrides %s\n"),
 
2056
                   "--for-your-eyes-only","--set-filename");
 
2057
 
 
2058
      opt.set_filename="_CONSOLE";
 
2059
    }
 
2060
 
 
2061
    if (opt.no_literal) {
 
2062
        log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
 
2063
        if (opt.textmode)
 
2064
            log_error(_("%s not allowed with %s!\n"),
 
2065
                       "--textmode", "--no-literal" );
 
2066
        if (opt.set_filename)
 
2067
            log_error(_("%s makes no sense with %s!\n"),
 
2068
                        eyes_only?"--for-your-eyes-only":"--set-filename",
 
2069
                        "--no-literal" );
 
2070
    }
 
2071
 
 
2072
    if (opt.set_filesize)
 
2073
        log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
 
2074
    if( opt.batch )
 
2075
        tty_batchmode( 1 );
 
2076
 
 
2077
    gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
 
2078
    set_debug (debug_level);
 
2079
 
 
2080
    /* Do these after the switch(), so they can override settings. */
 
2081
    if(PGP2)
 
2082
      {
 
2083
        int unusable=0;
 
2084
 
 
2085
        if(cmd==aSign && !detached_sig)
 
2086
          {
 
2087
            log_info(_("you can only make detached or clear signatures "
 
2088
                       "while in --pgp2 mode\n"));
 
2089
            unusable=1;
 
2090
          }
 
2091
        else if(cmd==aSignEncr || cmd==aSignSym)
 
2092
          {
 
2093
            log_info(_("you can't sign and encrypt at the "
 
2094
                       "same time while in --pgp2 mode\n"));
 
2095
            unusable=1;
 
2096
          }
 
2097
        else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
 
2098
          {
 
2099
            log_info(_("you must use files (and not a pipe) when "
 
2100
                       "working with --pgp2 enabled.\n"));
 
2101
            unusable=1;
 
2102
          }
 
2103
        else if(cmd==aEncr || cmd==aSym)
 
2104
          {
 
2105
            /* Everything else should work without IDEA (except using
 
2106
               a secret key encrypted with IDEA and setting an IDEA
 
2107
               preference, but those have their own error
 
2108
               messages). */
 
2109
 
 
2110
            if(openpgp_cipher_test_algo (CIPHER_ALGO_IDEA))
 
2111
              {
 
2112
                log_info(_("encrypting a message in --pgp2 mode requires "
 
2113
                           "the IDEA cipher\n"));
 
2114
                idea_cipher_warn(1);
 
2115
                unusable=1;
 
2116
              }
 
2117
            else if(cmd==aSym)
 
2118
              {
 
2119
                /* This only sets IDEA for symmetric encryption
 
2120
                   since it is set via select_algo_from_prefs for
 
2121
                   pk encryption. */
 
2122
                xfree (def_cipher_string);
 
2123
                def_cipher_string = xstrdup ("idea");
 
2124
              }
 
2125
 
 
2126
            /* PGP2 can't handle the output from the textmode
 
2127
               filter, so we disable it for anything that could
 
2128
               create a literal packet (only encryption and
 
2129
               symmetric encryption, since we disable signing
 
2130
               above). */
 
2131
            if(!unusable)
 
2132
              opt.textmode=0;
 
2133
          }
 
2134
 
 
2135
        if(unusable)
 
2136
          compliance_failure();
 
2137
        else
 
2138
          {
 
2139
            opt.force_v4_certs = 0;
 
2140
            opt.sk_comments = 0;
 
2141
            opt.escape_from = 1;
 
2142
            opt.force_v3_sigs = 1;
 
2143
            opt.pgp2_workarounds = 1;
 
2144
            opt.ask_sig_expire = 0;
 
2145
            opt.ask_cert_expire = 0;
 
2146
            xfree (def_digest_string);
 
2147
            def_digest_string = xstrdup ("md5");
 
2148
            opt.def_compress_algo = 1;
 
2149
          }
 
2150
      }
 
2151
    else if(PGP6)
 
2152
      {
 
2153
        opt.sk_comments=0;
 
2154
        opt.escape_from=1;
 
2155
        opt.force_v3_sigs=1;
 
2156
        opt.ask_sig_expire=0;
 
2157
      }
 
2158
    else if(PGP7)
 
2159
      {
 
2160
        opt.sk_comments=0;
 
2161
        opt.escape_from=1;
 
2162
        opt.force_v3_sigs=1;
 
2163
        opt.ask_sig_expire=0;
 
2164
      }
 
2165
    else if(PGP8)
 
2166
      {
 
2167
        opt.escape_from=1;
 
2168
      }
 
2169
 
 
2170
    /* must do this after dropping setuid, because string_to...
 
2171
     * may try to load an module */
 
2172
    if( def_cipher_string ) {
 
2173
        opt.def_cipher_algo = gcry_cipher_map_name (def_cipher_string);
 
2174
        if(opt.def_cipher_algo==0 &&
 
2175
           (ascii_strcasecmp(def_cipher_string,"idea")==0
 
2176
            || ascii_strcasecmp(def_cipher_string,"s1")==0))
 
2177
          idea_cipher_warn(1);
 
2178
        xfree (def_cipher_string); def_cipher_string = NULL;
 
2179
        if( openpgp_cipher_test_algo (opt.def_cipher_algo) )
 
2180
            log_error(_("selected cipher algorithm is invalid\n"));
 
2181
    }
 
2182
    if( def_digest_string ) {
 
2183
        opt.def_digest_algo = gcry_md_map_name (def_digest_string);
 
2184
        xfree (def_digest_string); def_digest_string = NULL;
 
2185
        if( openpgp_md_test_algo (opt.def_digest_algo) )
 
2186
            log_error(_("selected digest algorithm is invalid\n"));
 
2187
    }
 
2188
    if( def_compress_string ) {
 
2189
        opt.def_compress_algo = string_to_compress_algo(def_compress_string);
 
2190
        xfree (def_compress_string); def_compress_string = NULL;
 
2191
        if( check_compress_algo(opt.def_compress_algo) )
 
2192
            log_error(_("selected compression algorithm is invalid\n"));
 
2193
    }
 
2194
    if( cert_digest_string ) {
 
2195
        opt.cert_digest_algo = gcry_md_map_name (cert_digest_string);
 
2196
        xfree (cert_digest_string); cert_digest_string = NULL;
 
2197
        if( openpgp_md_test_algo(opt.cert_digest_algo) )
 
2198
            log_error(_("selected certification digest algorithm is invalid\n"));
 
2199
    }
 
2200
    if( s2k_cipher_string ) {
 
2201
        opt.s2k_cipher_algo = gcry_cipher_map_name (s2k_cipher_string);
 
2202
        xfree (s2k_cipher_string); s2k_cipher_string = NULL;
 
2203
        if( openpgp_cipher_test_algo (opt.s2k_cipher_algo) )
 
2204
            log_error(_("selected cipher algorithm is invalid\n"));
 
2205
    }
 
2206
    if( s2k_digest_string ) {
 
2207
        opt.s2k_digest_algo = gcry_md_map_name (s2k_digest_string);
 
2208
        xfree (s2k_digest_string); s2k_digest_string = NULL;
 
2209
        if( openpgp_md_test_algo (opt.s2k_digest_algo) )
 
2210
            log_error(_("selected digest algorithm is invalid\n"));
 
2211
    }
 
2212
    if( opt.completes_needed < 1 )
 
2213
        log_error(_("completes-needed must be greater than 0\n"));
 
2214
    if( opt.marginals_needed < 2 )
 
2215
        log_error(_("marginals-needed must be greater than 1\n"));
 
2216
    if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
 
2217
        log_error(_("max-cert-depth must be in range 1 to 255\n"));
 
2218
    switch( opt.s2k_mode ) {
 
2219
      case 0:
 
2220
        log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
 
2221
        break;
 
2222
      case 1: case 3: break;
 
2223
      default:
 
2224
        log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
 
2225
    }
 
2226
 
 
2227
    if(opt.def_cert_check_level<0 || opt.def_cert_check_level>3)
 
2228
      log_error(_("invalid default-check-level; must be 0, 1, 2, or 3\n"));
 
2229
 
 
2230
    /* This isn't actually needed, but does serve to error out if the
 
2231
       string is invalid. */
 
2232
    if(opt.def_preference_list &&
 
2233
        keygen_set_std_prefs(opt.def_preference_list,0))
 
2234
      log_error(_("invalid default preferences\n"));
 
2235
 
 
2236
    /* We provide defaults for the personal digest list */
 
2237
    if(!pers_digest_list)
 
2238
      pers_digest_list="h2";
 
2239
 
 
2240
    if(pers_cipher_list &&
 
2241
       keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
 
2242
      log_error(_("invalid personal cipher preferences\n"));
 
2243
 
 
2244
    if(pers_digest_list &&
 
2245
       keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
 
2246
      log_error(_("invalid personal digest preferences\n"));
 
2247
 
 
2248
    if(pers_compress_list &&
 
2249
       keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
 
2250
      log_error(_("invalid personal compress preferences\n"));
 
2251
 
 
2252
    /* We don't support all possible commands with multifile yet */
 
2253
    if(multifile)
 
2254
      {
 
2255
        char *cmdname;
 
2256
        
 
2257
        switch(cmd)
 
2258
          {
 
2259
          case aSign:
 
2260
            cmdname="--sign";
 
2261
            break;
 
2262
          case aClearsign:
 
2263
            cmdname="--clearsign";
 
2264
            break;
 
2265
          case aDetachedSign:
 
2266
            cmdname="--detach-sign";
 
2267
            break;
 
2268
          case aSym:
 
2269
            cmdname="--symmetric";
 
2270
            break;
 
2271
          case aStore:
 
2272
            cmdname="--store";
 
2273
            break;
 
2274
          default:
 
2275
            cmdname=NULL;
 
2276
            break;
 
2277
          }
 
2278
 
 
2279
        if(cmdname)
 
2280
          log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
 
2281
      }
 
2282
 
 
2283
    if( log_get_errorcount(0) )
 
2284
        g10_exit(2);
 
2285
 
 
2286
    /* Check our chosen algorithms against the list of legal
 
2287
       algorithms. */
 
2288
 
 
2289
    if(!GNUPG)
 
2290
      {
 
2291
        const char *badalg=NULL;
 
2292
        preftype_t badtype=PREFTYPE_NONE;
 
2293
 
 
2294
        if (opt.def_cipher_algo
 
2295
            && !algo_available (PREFTYPE_SYM,opt.def_cipher_algo,NULL))
 
2296
          {
 
2297
            badalg = gcry_cipher_algo_name (opt.def_cipher_algo);
 
2298
            badtype = PREFTYPE_SYM;
 
2299
          }
 
2300
        else if (opt.def_digest_algo
 
2301
                && !algo_available (PREFTYPE_HASH,opt.def_digest_algo,NULL))
 
2302
          {
 
2303
            badalg = gcry_md_algo_name (opt.def_digest_algo);
 
2304
            badtype = PREFTYPE_HASH;
 
2305
          }
 
2306
        else if (opt.cert_digest_algo
 
2307
                 && !algo_available (PREFTYPE_HASH,opt.cert_digest_algo,NULL))
 
2308
          {
 
2309
            badalg = gcry_md_algo_name (opt.cert_digest_algo);
 
2310
            badtype = PREFTYPE_HASH;
 
2311
          }
 
2312
        else if (opt.def_compress_algo!=-1
 
2313
                 && !algo_available (PREFTYPE_ZIP,opt.def_compress_algo,NULL))
 
2314
          {
 
2315
            badalg = compress_algo_to_string (opt.def_compress_algo);
 
2316
            badtype = PREFTYPE_ZIP;
 
2317
          }
 
2318
 
 
2319
        if (badalg)
 
2320
          {
 
2321
            switch(badtype)
 
2322
              {
 
2323
              case PREFTYPE_SYM:
 
2324
                log_info(_("you may not use cipher algorithm \"%s\" "
 
2325
                           "while in %s mode\n"),
 
2326
                         badalg,compliance_option_string());
 
2327
                break;
 
2328
              case PREFTYPE_HASH:
 
2329
                log_info(_("you may not use digest algorithm \"%s\" "
 
2330
                           "while in %s mode\n"),
 
2331
                         badalg,compliance_option_string());
 
2332
                break;
 
2333
              case PREFTYPE_ZIP:
 
2334
                log_info(_("you may not use compression algorithm \"%s\" "
 
2335
                           "while in %s mode\n"),
 
2336
                         badalg,compliance_option_string());
 
2337
                break;
 
2338
              default:
 
2339
                BUG();
 
2340
              }
 
2341
 
 
2342
            compliance_failure();
 
2343
          }
 
2344
      }
 
2345
 
 
2346
    /* set the random seed file */
 
2347
    if( use_random_seed ) {
 
2348
        char *p = make_filename(opt.homedir, "random_seed", NULL );
 
2349
        gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
 
2350
        xfree (p);
 
2351
    }
 
2352
 
 
2353
    if( !cmd && opt.fingerprint && !with_fpr ) {
 
2354
        set_cmd( &cmd, aListKeys);
 
2355
    }
 
2356
 
 
2357
    /* Compression algorithm 0 means no compression at all */
 
2358
    if( opt.def_compress_algo == 0)
 
2359
        opt.compress = 0;
 
2360
 
 
2361
    /* kludge to let -sat generate a clear text signature */
 
2362
    if( opt.textmode == 2 && !detached_sig && opt.armor && cmd == aSign )
 
2363
        cmd = aClearsign;
 
2364
 
 
2365
    if( opt.verbose > 1 )
 
2366
        set_packet_list_mode(1);
 
2367
 
 
2368
    /* Add the keyrings, but not for some special commands.  Also
 
2369
       avoid adding the secret keyring for a couple of commands to
 
2370
       avoid unneeded access in case the secrings are stored on a
 
2371
       floppy */
 
2372
    if( cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfList )
 
2373
      {
 
2374
        if (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
 
2375
            && cmd != aVerify && cmd != aSym)
 
2376
          {
 
2377
            if (!sec_nrings || default_keyring) /* add default secret rings */
 
2378
              keydb_add_resource ("secring" EXTSEP_S "gpg", 0, 1);
 
2379
            for (sl = sec_nrings; sl; sl = sl->next)
 
2380
              keydb_add_resource ( sl->d, 0, 1 );
 
2381
          }
 
2382
        if( !nrings || default_keyring )  /* add default ring */
 
2383
            keydb_add_resource ("pubring" EXTSEP_S "gpg", 0, 0);
 
2384
        for(sl = nrings; sl; sl = sl->next )
 
2385
            keydb_add_resource ( sl->d, sl->flags, 0 );
 
2386
      }
 
2387
    FREE_STRLIST(nrings);
 
2388
    FREE_STRLIST(sec_nrings);
 
2389
 
 
2390
 
 
2391
    if( pwfd != -1 )  /* read the passphrase now. */
 
2392
        read_passphrase_from_fd( pwfd );
 
2393
 
 
2394
    fname = argc? *argv : NULL;
 
2395
 
 
2396
    switch( cmd ) {
 
2397
      case aPrimegen:
 
2398
      case aPrintMD:
 
2399
      case aPrintMDs:
 
2400
      case aGenRandom:
 
2401
      case aDeArmor:
 
2402
      case aEnArmor:
 
2403
      case aFixTrustDB:
 
2404
      case aCardStatus:
 
2405
      case aCardEdit:
 
2406
      case aChangePIN:
 
2407
      case aGPGConfList:
 
2408
        break;
 
2409
      case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
 
2410
      case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
 
2411
      default: rc = setup_trustdb(1, trustdb_name ); break;
 
2412
    }
 
2413
    if( rc )
 
2414
        log_error(_("failed to initialize the TrustDB: %s\n"), gpg_strerror (rc));
 
2415
 
 
2416
 
 
2417
    switch (cmd) {
 
2418
      case aStore: 
 
2419
      case aSym:  
 
2420
      case aSign: 
 
2421
      case aSignSym: 
 
2422
      case aClearsign: 
 
2423
        if (!opt.quiet && any_explicit_recipient)
 
2424
          log_info (_("WARNING: recipients (-r) given "
 
2425
                      "without using public key encryption\n"));
 
2426
        break;
 
2427
      default:
 
2428
        break;
 
2429
    }
 
2430
 
 
2431
    switch( cmd ) {
 
2432
      case aStore: /* only store the file */
 
2433
        if( argc > 1 )
 
2434
            wrong_args(_("--store [filename]"));
 
2435
        if( (rc = encode_store(fname)) )
 
2436
            log_error ("\b%s: store failed: %s\n",
 
2437
                       print_fname_stdin(fname), gpg_strerror (rc) );
 
2438
        break;
 
2439
      case aSym: /* encrypt the given file only with the symmetric cipher */
 
2440
        if( argc > 1 )
 
2441
            wrong_args(_("--symmetric [filename]"));
 
2442
        if( (rc = encode_symmetric(fname)) )
 
2443
            log_error ("\b%s: symmetric encryption failed: %s\n",
 
2444
                       print_fname_stdin(fname), gpg_strerror (rc) );
 
2445
        break;
 
2446
 
 
2447
      case aEncr: /* encrypt the given file */
 
2448
        if(multifile)
 
2449
          encode_crypt_files(argc, argv, remusr);
 
2450
        else
 
2451
          {
 
2452
            if( argc > 1 )
 
2453
              wrong_args(_("--encrypt [filename]"));
 
2454
            if( (rc = encode_crypt(fname,remusr)) )
 
2455
              log_error("%s: encryption failed: %s\n",
 
2456
                        print_fname_stdin(fname), gpg_strerror (rc) );
 
2457
          }
 
2458
        break;
 
2459
 
 
2460
      case aSign: /* sign the given file */
 
2461
        sl = NULL;
 
2462
        if( detached_sig ) { /* sign all files */
 
2463
            for( ; argc; argc--, argv++ )
 
2464
                add_to_strlist( &sl, *argv );
 
2465
        }
 
2466
        else {
 
2467
            if( argc > 1 )
 
2468
                wrong_args(_("--sign [filename]"));
 
2469
            if( argc ) {
 
2470
                sl = xcalloc (1, sizeof *sl + strlen(fname));
 
2471
                strcpy(sl->d, fname);
 
2472
            }
 
2473
        }
 
2474
        if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
 
2475
            log_error("signing failed: %s\n", gpg_strerror (rc) );
 
2476
        free_strlist(sl);
 
2477
        break;
 
2478
 
 
2479
      case aSignEncr: /* sign and encrypt the given file */
 
2480
        if( argc > 1 )
 
2481
            wrong_args(_("--sign --encrypt [filename]"));
 
2482
        if( argc ) {
 
2483
            sl = xcalloc (1, sizeof *sl + strlen(fname));
 
2484
            strcpy(sl->d, fname);
 
2485
        }
 
2486
        else
 
2487
            sl = NULL;
 
2488
        if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
 
2489
            log_error("%s: sign+encrypt failed: %s\n", print_fname_stdin(fname), gpg_strerror (rc) );
 
2490
        free_strlist(sl);
 
2491
        break;
 
2492
 
 
2493
      case aSignSym: /* sign and conventionally encrypt the given file */
 
2494
        if (argc > 1)
 
2495
            wrong_args(_("--sign --symmetric [filename]"));
 
2496
        rc = sign_symencrypt_file (fname, locusr);
 
2497
        if (rc)
 
2498
            log_error("%s: sign+symmetric failed: %s\n",
 
2499
                      print_fname_stdin(fname), gpg_strerror (rc) );
 
2500
        break;
 
2501
 
 
2502
      case aClearsign: /* make a clearsig */
 
2503
        if( argc > 1 )
 
2504
            wrong_args(_("--clearsign [filename]"));
 
2505
        if( (rc = clearsign_file(fname, locusr, NULL)) )
 
2506
            log_error("%s: clearsign failed: %s\n",
 
2507
                      print_fname_stdin(fname), gpg_strerror (rc) );
 
2508
        break;
 
2509
 
 
2510
      case aVerify:
 
2511
        if(multifile)
 
2512
          {
 
2513
            if( (rc = verify_files( argc, argv ) ))
 
2514
              log_error("verify files failed: %s\n", gpg_strerror (rc) );
 
2515
          }
 
2516
        else
 
2517
          {
 
2518
            if( (rc = verify_signatures( argc, argv ) ))
 
2519
              log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
 
2520
          }
 
2521
        break;
 
2522
 
 
2523
      case aDecrypt:
 
2524
        if(multifile)
 
2525
          decrypt_messages(argc, argv);
 
2526
        else
 
2527
          {
 
2528
            if( argc > 1 )
 
2529
              wrong_args(_("--decrypt [filename]"));
 
2530
            if( (rc = decrypt_message( fname ) ))
 
2531
              log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
 
2532
          }
 
2533
        break;
 
2534
 
 
2535
      case aSignKey: /* sign the key given as argument */
 
2536
        if( argc != 1 )
 
2537
            wrong_args(_("--sign-key user-id"));
 
2538
        username = make_username( fname );
 
2539
        keyedit_menu(fname, locusr, NULL, 1 );
 
2540
        xfree (username);
 
2541
        break;
 
2542
 
 
2543
      case aLSignKey:
 
2544
        if( argc != 1 )
 
2545
            wrong_args(_("--lsign-key user-id"));
 
2546
        username = make_username( fname );
 
2547
        keyedit_menu(fname, locusr, NULL, 2 );
 
2548
        xfree (username);
 
2549
        break;
 
2550
 
 
2551
      case aNRSignKey:
 
2552
        if( argc != 1 )
 
2553
            wrong_args(_("--nrsign-key user-id"));
 
2554
        username = make_username( fname );
 
2555
        keyedit_menu(fname, locusr, NULL, 3 );
 
2556
        xfree (username);
 
2557
        break;
 
2558
 
 
2559
      case aNRLSignKey:
 
2560
        if( argc != 1 )
 
2561
            wrong_args(_("--nrlsign-key user-id"));
 
2562
        username = make_username( fname );
 
2563
        keyedit_menu(fname, locusr, NULL, 4 );
 
2564
        xfree (username);
 
2565
        break;
 
2566
 
 
2567
      case aEditKey: /* Edit a key signature */
 
2568
        if( !argc )
 
2569
            wrong_args(_("--edit-key user-id [commands]"));
 
2570
        username = make_username( fname );
 
2571
        if( argc > 1 ) {
 
2572
            sl = NULL;
 
2573
            for( argc--, argv++ ; argc; argc--, argv++ )
 
2574
                append_to_strlist( &sl, *argv );
 
2575
            keyedit_menu( username, locusr, sl, 0 );
 
2576
            free_strlist(sl);
 
2577
        }
 
2578
        else
 
2579
            keyedit_menu(username, locusr, NULL, 0 );
 
2580
        xfree (username);
 
2581
        break;
 
2582
 
 
2583
      case aDeleteKeys:
 
2584
      case aDeleteSecretKeys:
 
2585
      case aDeleteSecretAndPublicKeys:
 
2586
        sl = NULL;
 
2587
        /* I'm adding these in reverse order as add_to_strlist2
 
2588
           reverses them again, and it's easier to understand in the
 
2589
           proper order :) */
 
2590
        for( ; argc; argc-- )
 
2591
          add_to_strlist2( &sl, argv[argc-1], utf8_strings );
 
2592
        delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
 
2593
        free_strlist(sl);
 
2594
        break;
 
2595
 
 
2596
      case aCheckKeys:
 
2597
        opt.check_sigs = 1;
 
2598
      case aListSigs:
 
2599
        opt.list_sigs = 1;
 
2600
      case aListKeys:
 
2601
        sl = NULL;
 
2602
        for( ; argc; argc--, argv++ )
 
2603
            add_to_strlist2( &sl, *argv, utf8_strings );
 
2604
        public_key_list( sl );
 
2605
        free_strlist(sl);
 
2606
        break;
 
2607
      case aListSecretKeys:
 
2608
        sl = NULL;
 
2609
        for( ; argc; argc--, argv++ )
 
2610
            add_to_strlist2( &sl, *argv, utf8_strings );
 
2611
        secret_key_list( sl );
 
2612
        free_strlist(sl);
 
2613
        break;
 
2614
 
 
2615
      case aKeygen: /* generate a key */
 
2616
        if( opt.batch ) {
 
2617
            if( argc > 1 )
 
2618
                wrong_args("--gen-key [parameterfile]");
 
2619
            generate_keypair( argc? *argv : NULL, NULL );
 
2620
        }
 
2621
        else {
 
2622
            if( argc )
 
2623
                wrong_args("--gen-key");
 
2624
            generate_keypair(NULL, NULL);
 
2625
        }
 
2626
        break;
 
2627
 
 
2628
      case aFastImport:
 
2629
        opt.import_options |= IMPORT_FAST_IMPORT;
 
2630
      case aImport:
 
2631
        import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
 
2632
        break;
 
2633
 
 
2634
      case aExport:
 
2635
      case aExportAll:
 
2636
      case aSendKeys:
 
2637
      case aRecvKeys:
 
2638
        sl = NULL;
 
2639
        for( ; argc; argc--, argv++ )
 
2640
            add_to_strlist2( &sl, *argv, utf8_strings );
 
2641
        if( cmd == aSendKeys )
 
2642
            rc=keyserver_export( sl );
 
2643
        else if( cmd == aRecvKeys )
 
2644
            rc=keyserver_import( sl );
 
2645
        else
 
2646
            rc=export_pubkeys( sl, opt.export_options );
 
2647
        if(rc)
 
2648
          {
 
2649
            if(cmd==aSendKeys)
 
2650
              log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
 
2651
            else if(cmd==aRecvKeys)
 
2652
              log_error(_("keyserver receive failed: %s\n"),gpg_strerror (rc));
 
2653
            else
 
2654
              log_error(_("key export failed: %s\n"),gpg_strerror (rc));
 
2655
          }
 
2656
        free_strlist(sl);
 
2657
        break;
 
2658
 
 
2659
     case aSearchKeys:
 
2660
        sl = NULL;
 
2661
        for( ; argc; argc--, argv++ )
 
2662
          {
 
2663
            if (utf8_strings)
 
2664
              sl = append_to_strlist ( &sl, *argv );
 
2665
            else
 
2666
              {
 
2667
                char *p = native_to_utf8 ( *argv );
 
2668
                sl = append_to_strlist( &sl, p );
 
2669
                xfree( p );
 
2670
              }
 
2671
          }
 
2672
 
 
2673
        rc=keyserver_search( sl );
 
2674
        if(rc)
 
2675
          log_error(_("keyserver search failed: %s\n"),gpg_strerror (rc));
 
2676
        free_strlist(sl);
 
2677
        break;
 
2678
 
 
2679
      case aRefreshKeys:
 
2680
        sl = NULL;
 
2681
        for( ; argc; argc--, argv++ )
 
2682
            add_to_strlist2( &sl, *argv, utf8_strings );
 
2683
        rc=keyserver_refresh(sl);
 
2684
        if(rc)
 
2685
          log_error(_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
 
2686
        free_strlist(sl);
 
2687
        break;
 
2688
 
 
2689
      case aExportSecret:
 
2690
        sl = NULL;
 
2691
        for( ; argc; argc--, argv++ )
 
2692
            add_to_strlist2( &sl, *argv, utf8_strings );
 
2693
        export_seckeys( sl );
 
2694
        free_strlist(sl);
 
2695
        break;
 
2696
 
 
2697
      case aExportSecretSub:
 
2698
        sl = NULL;
 
2699
        for( ; argc; argc--, argv++ )
 
2700
            add_to_strlist2( &sl, *argv, utf8_strings );
 
2701
        export_secsubkeys( sl );
 
2702
        free_strlist(sl);
 
2703
        break;
 
2704
 
 
2705
      case aGenRevoke:
 
2706
        if( argc != 1 )
 
2707
            wrong_args("--gen-revoke user-id");
 
2708
        username =  make_username(*argv);
 
2709
        gen_revoke( username );
 
2710
        xfree ( username );
 
2711
        break;
 
2712
 
 
2713
      case aDesigRevoke:
 
2714
        if( argc != 1 )
 
2715
            wrong_args("--desig-revoke user-id");
 
2716
        username =  make_username(*argv);
 
2717
        gen_desig_revoke( username );
 
2718
        xfree ( username );
 
2719
        break;
 
2720
 
 
2721
      case aDeArmor:
 
2722
        if( argc > 1 )
 
2723
            wrong_args("--dearmor [file]");
 
2724
        rc = dearmor_file( argc? *argv: NULL );
 
2725
        if( rc )
 
2726
            log_error(_("dearmoring failed: %s\n"), gpg_strerror (rc));
 
2727
        break;
 
2728
 
 
2729
      case aEnArmor:
 
2730
        if( argc > 1 )
 
2731
            wrong_args("--enarmor [file]");
 
2732
        rc = enarmor_file( argc? *argv: NULL );
 
2733
        if( rc )
 
2734
            log_error(_("enarmoring failed: %s\n"), gpg_strerror (rc));
 
2735
        break;
 
2736
 
 
2737
 
 
2738
      case aPrimegen:
 
2739
#if 0 /*FIXME-XXX*/
 
2740
        {   int mode = argc < 2 ? 0 : atoi(*argv);
 
2741
 
 
2742
            if( mode == 1 && argc == 2 ) {
 
2743
                mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
 
2744
            }
 
2745
            else if( mode == 2 && argc == 3 ) {
 
2746
                mpi_print( stdout, generate_elg_prime(
 
2747
                                             0, atoi(argv[1]),
 
2748
                                             atoi(argv[2]), NULL,NULL ), 1);
 
2749
            }
 
2750
            else if( mode == 3 && argc == 3 ) {
 
2751
                gcry_mpi_t *factors;
 
2752
                mpi_print( stdout, generate_elg_prime(
 
2753
                                             1, atoi(argv[1]),
 
2754
                                             atoi(argv[2]), NULL,&factors ), 1);
 
2755
                putchar('\n');
 
2756
                mpi_print( stdout, factors[0], 1 ); /* print q */
 
2757
            }
 
2758
            else if( mode == 4 && argc == 3 ) {
 
2759
                gcry_mpi_t g = mpi_alloc(1);
 
2760
                mpi_print( stdout, generate_elg_prime(
 
2761
                                                 0, atoi(argv[1]),
 
2762
                                                 atoi(argv[2]), g, NULL ), 1);
 
2763
                putchar('\n');
 
2764
                mpi_print( stdout, g, 1 );
 
2765
                mpi_free(g);
 
2766
            }
 
2767
            else
 
2768
                wrong_args("--gen-prime mode bits [qbits] ");
 
2769
            putchar('\n');
 
2770
        }
 
2771
#endif
 
2772
        break;
 
2773
 
 
2774
      case aGenRandom:
 
2775
        {
 
2776
            int level = argc ? atoi(*argv):0;
 
2777
            int count = argc > 1 ? atoi(argv[1]): 0;
 
2778
            int endless = !count;
 
2779
 
 
2780
            if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
 
2781
                wrong_args("--gen-random 0|1|2 [count]");
 
2782
 
 
2783
            while( endless || count ) {
 
2784
                byte *p;
 
2785
                /* Wee need a multiple of 3, so that in case of
 
2786
                   armored output we get a correct string.  No
 
2787
                   linefolding is done, as it is best to levae this to
 
2788
                   other tools */
 
2789
                size_t n = !endless && count < 99? count : 99;
 
2790
 
 
2791
                p = gcry_random_bytes (n, level);
 
2792
#ifdef HAVE_DOSISH_SYSTEM
 
2793
                setmode ( fileno(stdout), O_BINARY );
 
2794
#endif
 
2795
                if (opt.armor) {
 
2796
                    char *tmp = make_radix64_string (p, n);
 
2797
                    fputs (tmp, stdout);
 
2798
                    xfree (tmp);
 
2799
                    if (n%3 == 1)
 
2800
                      putchar ('=');
 
2801
                    if (n%3)
 
2802
                      putchar ('=');
 
2803
                } else {
 
2804
                    fwrite( p, n, 1, stdout );
 
2805
                }
 
2806
                xfree (p);
 
2807
                if( !endless )
 
2808
                    count -= n;
 
2809
            }
 
2810
            if (opt.armor)
 
2811
                putchar ('\n');
 
2812
        }
 
2813
        break;
 
2814
 
 
2815
      case aPrintMD:
 
2816
        if( argc < 1)
 
2817
            wrong_args("--print-md algo [files]");
 
2818
        {
 
2819
            int all_algos = (**argv=='*' && !(*argv)[1]);
 
2820
            int algo = all_algos? 0 : gcry_md_map_name (*argv);
 
2821
 
 
2822
            if( !algo && !all_algos )
 
2823
                log_error(_("invalid hash algorithm `%s'\n"), *argv );
 
2824
            else {
 
2825
                argc--; argv++;
 
2826
                if( !argc )
 
2827
                    print_mds(NULL, algo);
 
2828
                else {
 
2829
                    for(; argc; argc--, argv++ )
 
2830
                        print_mds(*argv, algo);
 
2831
                }
 
2832
            }
 
2833
        }
 
2834
        break;
 
2835
 
 
2836
      case aPrintMDs: /* old option */
 
2837
        if( !argc )
 
2838
            print_mds(NULL,0);
 
2839
        else {
 
2840
            for(; argc; argc--, argv++ )
 
2841
                print_mds(*argv,0);
 
2842
        }
 
2843
        break;
 
2844
 
 
2845
      case aListTrustDB:
 
2846
        if( !argc )
 
2847
            list_trustdb(NULL);
 
2848
        else {
 
2849
            for( ; argc; argc--, argv++ )
 
2850
                list_trustdb( *argv );
 
2851
        }
 
2852
        break;
 
2853
 
 
2854
      case aUpdateTrustDB:
 
2855
        if( argc )
 
2856
            wrong_args("--update-trustdb");
 
2857
        update_trustdb();
 
2858
        break;
 
2859
 
 
2860
      case aCheckTrustDB:
 
2861
        /* Old versions allowed for arguments - ignore them */
 
2862
        check_trustdb();
 
2863
        break;
 
2864
 
 
2865
      case aFixTrustDB:
 
2866
        log_error("this command is not yet implemented.\n");
 
2867
        log_error("A workaround is to use \"--export-ownertrust\", remove\n");
 
2868
        log_error("the trustdb file and do an \"--import-ownertrust\".\n" );
 
2869
        break;
 
2870
 
 
2871
      case aListTrustPath:
 
2872
        if( !argc )
 
2873
            wrong_args("--list-trust-path <user-ids>");
 
2874
        for( ; argc; argc--, argv++ ) {
 
2875
            username = make_username( *argv );
 
2876
            list_trust_path( username );
 
2877
            xfree (username);
 
2878
        }
 
2879
        break;
 
2880
 
 
2881
      case aExportOwnerTrust:
 
2882
        if( argc )
 
2883
            wrong_args("--export-ownertrust");
 
2884
        export_ownertrust();
 
2885
        break;
 
2886
 
 
2887
      case aImportOwnerTrust:
 
2888
        if( argc > 1 )
 
2889
            wrong_args("--import-ownertrust [file]");
 
2890
        import_ownertrust( argc? *argv:NULL );
 
2891
        break;
 
2892
      
 
2893
      case aPipeMode:
 
2894
        if ( argc )
 
2895
            wrong_args ("--pipemode");
 
2896
        run_in_pipemode ();
 
2897
        break;
 
2898
 
 
2899
      case aRebuildKeydbCaches:
 
2900
        if (argc)
 
2901
            wrong_args ("--rebuild-keydb-caches");
 
2902
        keydb_rebuild_caches ();
 
2903
        break;
 
2904
 
 
2905
    case aCardStatus:
 
2906
      if (argc)
 
2907
        wrong_args ("--card-status");
 
2908
      card_status (stdout, NULL, 0);
 
2909
      break;
 
2910
 
 
2911
    case aCardEdit:
 
2912
      if (argc)
 
2913
        {
 
2914
          sl = NULL;
 
2915
          for (argc--, argv++ ; argc; argc--, argv++)
 
2916
            append_to_strlist (&sl, *argv);
 
2917
          card_edit (sl);
 
2918
          free_strlist (sl);
 
2919
        }
 
2920
      else
 
2921
        card_edit (NULL);
 
2922
      break;
 
2923
 
 
2924
    case aChangePIN:
 
2925
      if (!argc)
 
2926
        change_pin (0,1);
 
2927
      else if (argc == 1)
 
2928
        change_pin ( atoi (*argv), 1);
 
2929
      else
 
2930
        wrong_args ("--change-pin [no]");
 
2931
      break;
 
2932
 
 
2933
    case aGPGConfList: 
 
2934
      { /* List options and default values in the GPG Conf format.  */
 
2935
 
 
2936
        /* The following list is taken from gnupg/tools/gpgconf-comp.c.  */
 
2937
        /* Option flags.  YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING
 
2938
           FLAGS, AS THEY ARE PART OF THE EXTERNAL INTERFACE.  */
 
2939
#define GC_OPT_FLAG_NONE        0UL
 
2940
        /* The RUNTIME flag for an option indicates that the option can be
 
2941
           changed at runtime.  */
 
2942
#define GC_OPT_FLAG_RUNTIME     (1UL << 3)
 
2943
        /* The DEFAULT flag for an option indicates that the option has a
 
2944
           default value.  */
 
2945
#define GC_OPT_FLAG_DEFAULT     (1UL << 4)
 
2946
        /* The DEF_DESC flag for an option indicates that the option has a
 
2947
           default, which is described by the value of the default field.  */
 
2948
#define GC_OPT_FLAG_DEF_DESC    (1UL << 5)
 
2949
        /* The NO_ARG_DESC flag for an option indicates that the argument has
 
2950
           a default, which is described by the value of the ARGDEF field.  */
 
2951
#define GC_OPT_FLAG_NO_ARG_DESC (1UL << 6)
 
2952
 
 
2953
        if (!config_filename)
 
2954
          config_filename = make_filename (opt.homedir, "gpg.conf", NULL);
 
2955
 
 
2956
        printf ("gpgconf-gpg.conf:%lu:\"%s\n",
 
2957
                GC_OPT_FLAG_DEFAULT, config_filename);
 
2958
        
 
2959
        printf ("verbose:%lu:\n"
 
2960
                "quiet:%lu:\n"
 
2961
                "debug-level:%lu:\"none:\n"
 
2962
                "log-file:%lu:\n",
 
2963
                GC_OPT_FLAG_NONE,
 
2964
                GC_OPT_FLAG_NONE,
 
2965
                GC_OPT_FLAG_DEFAULT,
 
2966
                GC_OPT_FLAG_NONE );
 
2967
        printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
 
2968
 
 
2969
      }
 
2970
      break;
 
2971
 
 
2972
      case aListPackets:
 
2973
        opt.list_packets=2;
 
2974
      default:
 
2975
        if( argc > 1 )
 
2976
            wrong_args(_("[filename]"));
 
2977
        /* Issue some output for the unix newbie */
 
2978
        if( !fname && !opt.outfile && isatty( fileno(stdin) )
 
2979
                && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
 
2980
            log_info(_("Go ahead and type your message ...\n"));
 
2981
 
 
2982
        if( !(a = iobuf_open(fname)) )
 
2983
            log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
 
2984
        else {
 
2985
 
 
2986
            if( !opt.no_armor ) {
 
2987
                if( use_armor_filter( a ) ) {
 
2988
                    memset( &afx, 0, sizeof afx);
 
2989
                    iobuf_push_filter( a, armor_filter, &afx );
 
2990
                }
 
2991
            }
 
2992
            if( cmd == aListPackets ) {
 
2993
                set_packet_list_mode(1);
 
2994
                opt.list_packets=1;
 
2995
            }
 
2996
            rc = proc_packets(NULL, a );
 
2997
            if( rc )
 
2998
                log_error("processing message failed: %s\n", gpg_strerror (rc) );
 
2999
            iobuf_close(a);
 
3000
        }
 
3001
        break;
 
3002
    }
 
3003
 
 
3004
    /* cleanup */
 
3005
    FREE_STRLIST(remusr);
 
3006
    FREE_STRLIST(locusr);
 
3007
    g10_exit(0);
 
3008
    return 8; /*NEVER REACHED*/
 
3009
}
 
3010
 
 
3011
/* Note: This function is used by signal handlers!. */
 
3012
static void
 
3013
emergency_cleanup (void)
 
3014
{
 
3015
  gcry_control (GCRYCTL_TERM_SECMEM );
 
3016
}
 
3017
 
 
3018
 
 
3019
void
 
3020
g10_exit( int rc )
 
3021
{
 
3022
  gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
 
3023
  if (opt.debug & DBG_MEMSTAT_VALUE)
 
3024
    {
 
3025
      gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
 
3026
      gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
 
3027
    }
 
3028
  if (opt.debug)
 
3029
    gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
 
3030
  emergency_cleanup ();
 
3031
  rc = rc? rc : log_get_errorcount(0)? 2 :
 
3032
       g10_errors_seen? 1 : 0;
 
3033
  exit (rc );
 
3034
}
 
3035
 
 
3036
 
 
3037
/* Pretty-print hex hashes.  This assumes at least an 80-character
 
3038
   display, but there are a few other similar assumptions in the
 
3039
   display code. */
 
3040
static void
 
3041
print_hex( MD_HANDLE md, int algo, const char *fname )
 
3042
{
 
3043
  int i,n,count,indent=0;
 
3044
  const byte *p;
 
3045
 
 
3046
  if(fname)
 
3047
    indent=printf("%s: ",fname);
 
3048
 
 
3049
  if(indent>40)
 
3050
    {
 
3051
      printf("\n");
 
3052
      indent=0;
 
3053
    }
 
3054
 
 
3055
  if(algo==DIGEST_ALGO_RMD160)
 
3056
    indent+=printf("RMD160 = ");
 
3057
  else if(algo>0)
 
3058
    indent+=printf("%6s = ", gcry_md_algo_name (algo));
 
3059
  else
 
3060
    algo=abs(algo);
 
3061
 
 
3062
  count=indent;
 
3063
 
 
3064
  p = gcry_md_read (md, algo);
 
3065
  n = gcry_md_get_algo_dlen (algo);
 
3066
 
 
3067
  count+=printf("%02X",*p++);
 
3068
 
 
3069
  for(i=1;i<n;i++,p++)
 
3070
    {
 
3071
      if(n==16)
 
3072
        {
 
3073
          if(count+2>79)
 
3074
            {
 
3075
              printf("\n%*s",indent," ");
 
3076
              count=indent;
 
3077
            }
 
3078
          else
 
3079
            count+=printf(" ");
 
3080
 
 
3081
          if(!(i%8))
 
3082
            count+=printf(" ");
 
3083
        }
 
3084
      else if (n==20)
 
3085
        {
 
3086
          if(!(i%2))
 
3087
            {
 
3088
              if(count+4>79)
 
3089
                {
 
3090
                  printf("\n%*s",indent," ");
 
3091
                  count=indent;
 
3092
                }
 
3093
              else
 
3094
                count+=printf(" ");
 
3095
            }
 
3096
 
 
3097
          if(!(i%10))
 
3098
            count+=printf(" ");
 
3099
        }
 
3100
      else
 
3101
        {
 
3102
          if(!(i%4))
 
3103
            {
 
3104
              if(count+8>79)
 
3105
                {
 
3106
                  printf("\n%*s",indent," ");
 
3107
                  count=indent;
 
3108
                }
 
3109
              else
 
3110
                count+=printf(" ");
 
3111
            }
 
3112
        }
 
3113
 
 
3114
      count+=printf("%02X",*p);
 
3115
    }
 
3116
 
 
3117
  printf("\n");
 
3118
}
 
3119
 
 
3120
static void
 
3121
print_hashline( MD_HANDLE md, int algo, const char *fname )
 
3122
{
 
3123
    int i, n;
 
3124
    const byte *p;
 
3125
    
 
3126
    if ( fname ) {
 
3127
        for (p = fname; *p; p++ ) {
 
3128
            if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
 
3129
                printf("%%%02X", *p );
 
3130
            else 
 
3131
                putchar( *p );
 
3132
        }
 
3133
    }
 
3134
    putchar(':');
 
3135
    printf("%d:", algo );
 
3136
    p = gcry_md_read (md, algo );
 
3137
    n = gcry_md_get_algo_dlen (algo);
 
3138
    for(i=0; i < n ; i++, p++ ) 
 
3139
        printf("%02X", *p );
 
3140
    putchar(':');
 
3141
    putchar('\n');
 
3142
}
 
3143
 
 
3144
static void
 
3145
print_mds( const char *fname, int algo )
 
3146
{
 
3147
    FILE *fp;
 
3148
    char buf[1024];
 
3149
    size_t n;
 
3150
    MD_HANDLE md;
 
3151
 
 
3152
    if( !fname ) {
 
3153
        fp = stdin;
 
3154
#ifdef HAVE_DOSISH_SYSTEM
 
3155
        setmode ( fileno(fp) , O_BINARY );
 
3156
#endif
 
3157
    }
 
3158
    else {
 
3159
        fp = fopen( fname, "rb" );
 
3160
    }
 
3161
    if( !fp ) {
 
3162
        log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
 
3163
        return;
 
3164
    }
 
3165
 
 
3166
    gcry_md_open (&md, 0, 0 );
 
3167
    if( algo )
 
3168
        gcry_md_enable ( md, algo );
 
3169
    else {
 
3170
        gcry_md_enable (md, GCRY_MD_MD5 );
 
3171
        gcry_md_enable (md, GCRY_MD_SHA1 );
 
3172
        gcry_md_enable (md, GCRY_MD_RMD160 );
 
3173
#ifdef USE_SHA256
 
3174
        gcry_md_enable (md, GCRY_MD_SHA256 );
 
3175
#endif
 
3176
#ifdef USE_SHA512
 
3177
        gcry_md_enable (md, GCRY_MD_SHA384 );
 
3178
        gcry_md_enable (md, GCRY_MD_SHA512 );
 
3179
#endif
 
3180
    }
 
3181
 
 
3182
    while( (n=fread( buf, 1, DIM(buf), fp )) )
 
3183
        gcry_md_write (md, buf, n);
 
3184
    if( ferror(fp) )
 
3185
        log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
 
3186
    else {
 
3187
        gcry_md_final (md);
 
3188
        if ( opt.with_colons ) {
 
3189
            if ( algo ) 
 
3190
                print_hashline( md, algo, fname );
 
3191
            else {
 
3192
                print_hashline( md, GCRY_MD_MD5, fname );
 
3193
                print_hashline( md, GCRY_MD_SHA1, fname );
 
3194
                print_hashline( md, GCRY_MD_RMD160, fname );
 
3195
#ifdef USE_SHA256
 
3196
                print_hashline( md, GCRY_MD_SHA256, fname );
 
3197
#endif
 
3198
#ifdef USE_SHA512
 
3199
                print_hashline( md, GCRY_MD_SHA384, fname );
 
3200
                print_hashline( md, GCRY_MD_SHA512, fname );
 
3201
#endif
 
3202
            }
 
3203
        }
 
3204
        else {
 
3205
            if( algo )
 
3206
               print_hex(md,-algo,fname);
 
3207
            else {
 
3208
                print_hex( md, GCRY_MD_MD5, fname );
 
3209
                print_hex( md, GCRY_MD_SHA1, fname );
 
3210
                print_hex( md, GCRY_MD_RMD160, fname );
 
3211
#ifdef USE_SHA256
 
3212
                print_hex( md, GCRY_MD_SHA256, fname );
 
3213
#endif
 
3214
#ifdef USE_SHA512
 
3215
                print_hex( md, GCRY_MD_SHA384, fname );
 
3216
                print_hex( md, GCRY_MD_SHA512, fname );
 
3217
#endif
 
3218
            }
 
3219
        }
 
3220
    }
 
3221
    gcry_md_close (md);
 
3222
 
 
3223
    if( fp != stdin )
 
3224
        fclose(fp);
 
3225
}
 
3226
 
 
3227
 
 
3228
/****************
 
3229
 * Check the supplied name,value string and add it to the notation
 
3230
 * data to be used for signatures.  which==0 for sig notations, and 1
 
3231
 * for cert notations.
 
3232
*/
 
3233
static void
 
3234
add_notation_data( const char *string, int which )
 
3235
{
 
3236
    const char *s;
 
3237
    STRLIST sl,*notation_data;
 
3238
    int critical=0;
 
3239
    int highbit=0;
 
3240
    int saw_at=0;
 
3241
 
 
3242
    if(which)
 
3243
      notation_data=&opt.cert_notation_data;
 
3244
    else
 
3245
      notation_data=&opt.sig_notation_data;
 
3246
 
 
3247
    if( *string == '!' ) {
 
3248
        critical = 1;
 
3249
        string++;
 
3250
    }
 
3251
 
 
3252
    /* If and when the IETF assigns some official name tags, we'll
 
3253
       have to add them here. */
 
3254
 
 
3255
    for( s=string ; *s != '='; s++ )
 
3256
      {
 
3257
        if( *s=='@')
 
3258
          saw_at=1;
 
3259
 
 
3260
        if( !*s || (*s & 0x80) || (!isgraph(*s) && !isspace(*s)) )
 
3261
          {
 
3262
            log_error(_("a notation name must have only printable characters "
 
3263
                        "or spaces, and end with an '='\n") );
 
3264
            return;
 
3265
          }
 
3266
      }
 
3267
 
 
3268
    if(!saw_at && !opt.expert)
 
3269
      {
 
3270
        log_error(
 
3271
                _("a user notation name must contain the '@' character\n"));
 
3272
        return;
 
3273
      }
 
3274
 
 
3275
    /* we only support printable text - therefore we enforce the use
 
3276
     * of only printable characters (an empty value is valid) */
 
3277
    for( s++; *s ; s++ ) {
 
3278
        if( *s & 0x80 )
 
3279
            highbit = 1;
 
3280
        else if( iscntrl(*s) ) {
 
3281
            log_error(_("a notation value must not use "
 
3282
                        "any control characters\n") );
 
3283
            return;
 
3284
        }
 
3285
    }
 
3286
 
 
3287
    if( highbit )   /* must use UTF8 encoding */
 
3288
        sl = add_to_strlist2( notation_data, string, utf8_strings );
 
3289
    else
 
3290
        sl = add_to_strlist( notation_data, string );
 
3291
 
 
3292
    if( critical )
 
3293
        sl->flags |= 1;
 
3294
}
 
3295
 
 
3296
 
 
3297
static void
 
3298
add_policy_url( const char *string, int which )
 
3299
{
 
3300
  int i,critical=0;
 
3301
  STRLIST sl;
 
3302
 
 
3303
  if(*string=='!')
 
3304
    {
 
3305
      string++;
 
3306
      critical=1;
 
3307
    }
 
3308
 
 
3309
  for(i=0;i<strlen(string);i++)
 
3310
    if(string[i]&0x80 || iscntrl(string[i]))
 
3311
      break;
 
3312
 
 
3313
  if(i==0 || i<strlen(string))
 
3314
    {
 
3315
      if(which)
 
3316
        log_error(_("the given certification policy URL is invalid\n"));
 
3317
      else
 
3318
        log_error(_("the given signature policy URL is invalid\n"));
 
3319
    }
 
3320
 
 
3321
  if(which)
 
3322
    sl=add_to_strlist( &opt.cert_policy_url, string );
 
3323
  else
 
3324
    sl=add_to_strlist( &opt.sig_policy_url, string );
 
3325
 
 
3326
  if(critical)
 
3327
    sl->flags |= 1;    
 
3328
}
 
3329
 
 
3330
 
 
3331
static void
 
3332
add_keyserver_url( const char *string, int which )
 
3333
{
 
3334
  int i,critical=0;
 
3335
  STRLIST sl;
 
3336
 
 
3337
  if(*string=='!')
 
3338
    {
 
3339
      string++;
 
3340
      critical=1;
 
3341
    }
 
3342
 
 
3343
  for(i=0;i<strlen(string);i++)
 
3344
    if(string[i]&0x80 || iscntrl(string[i]))
 
3345
      break;
 
3346
 
 
3347
  if(i==0 || i<strlen(string))
 
3348
    {
 
3349
      if(which)
 
3350
        BUG();
 
3351
      else
 
3352
        log_error(_("the given signature preferred"
 
3353
                    " keyserver URL is invalid\n"));
 
3354
    }
 
3355
 
 
3356
  if(which)
 
3357
    BUG();
 
3358
  else
 
3359
    sl=add_to_strlist( &opt.sig_keyserver_url, string );
 
3360
 
 
3361
  if(critical)
 
3362
    sl->flags |= 1;    
 
3363
}
 
3364