##// END OF EJS Templates
url: limit expansion to safe auth keys (Issue2328)...
Martin Geisler -
r11838:d4bfa07f default
parent child Browse files
Show More
@@ -1,1056 +1,1059 b''
1 1 ======
2 2 hgrc
3 3 ======
4 4
5 5 ---------------------------------
6 6 configuration files for Mercurial
7 7 ---------------------------------
8 8
9 9 :Author: Bryan O'Sullivan <bos@serpentine.com>
10 10 :Organization: Mercurial
11 11 :Manual section: 5
12 12 :Manual group: Mercurial Manual
13 13
14 14 .. contents::
15 15 :backlinks: top
16 16 :class: htmlonly
17 17
18 18
19 19 Synopsis
20 20 --------
21 21
22 22 The Mercurial system uses a set of configuration files to control
23 23 aspects of its behavior.
24 24
25 25 Files
26 26 -----
27 27
28 28 Mercurial reads configuration data from several files, if they exist.
29 29 The names of these files depend on the system on which Mercurial is
30 30 installed. ``*.rc`` files from a single directory are read in
31 31 alphabetical order, later ones overriding earlier ones. Where multiple
32 32 paths are given below, settings from earlier paths override later
33 33 ones.
34 34
35 35 | (Unix, Windows) ``<repo>/.hg/hgrc``
36 36
37 37 Per-repository configuration options that only apply in a
38 38 particular repository. This file is not version-controlled, and
39 39 will not get transferred during a "clone" operation. Options in
40 40 this file override options in all other configuration files. On
41 41 Unix, most of this file will be ignored if it doesn't belong to a
42 42 trusted user or to a trusted group. See the documentation for the
43 43 trusted_ section below for more details.
44 44
45 45 | (Unix) ``$HOME/.hgrc``
46 46 | (Windows) ``%USERPROFILE%\.hgrc``
47 47 | (Windows) ``%USERPROFILE%\Mercurial.ini``
48 48 | (Windows) ``%HOME%\.hgrc``
49 49 | (Windows) ``%HOME%\Mercurial.ini``
50 50
51 51 Per-user configuration file(s), for the user running Mercurial. On
52 52 Windows 9x, ``%HOME%`` is replaced by ``%APPDATA%``. Options in these
53 53 files apply to all Mercurial commands executed by this user in any
54 54 directory. Options in these files override per-system and per-installation
55 55 options.
56 56
57 57 | (Unix) ``/etc/mercurial/hgrc``
58 58 | (Unix) ``/etc/mercurial/hgrc.d/*.rc``
59 59
60 60 Per-system configuration files, for the system on which Mercurial
61 61 is running. Options in these files apply to all Mercurial commands
62 62 executed by any user in any directory. Options in these files
63 63 override per-installation options.
64 64
65 65 | (Unix) ``<install-root>/etc/mercurial/hgrc``
66 66 | (Unix) ``<install-root>/etc/mercurial/hgrc.d/*.rc``
67 67
68 68 Per-installation configuration files, searched for in the
69 69 directory where Mercurial is installed. ``<install-root>`` is the
70 70 parent directory of the **hg** executable (or symlink) being run. For
71 71 example, if installed in ``/shared/tools/bin/hg``, Mercurial will look
72 72 in ``/shared/tools/etc/mercurial/hgrc``. Options in these files apply
73 73 to all Mercurial commands executed by any user in any directory.
74 74
75 75 | (Windows) ``<install-dir>\Mercurial.ini``
76 76 | (Windows) ``<install-dir>\hgrc.d\*.rc``
77 77 | (Windows) ``HKEY_LOCAL_MACHINE\SOFTWARE\Mercurial``
78 78
79 79 Per-installation/system configuration files, for the system on
80 80 which Mercurial is running. Options in these files apply to all
81 81 Mercurial commands executed by any user in any directory. Registry
82 82 keys contain PATH-like strings, every part of which must reference
83 83 a ``Mercurial.ini`` file or be a directory where ``*.rc`` files will
84 84 be read. Mercurial checks each of these locations in the specified
85 85 order until one or more configuration files are detected. If the
86 86 pywin32 extensions are not installed, Mercurial will only look for
87 87 site-wide configuration in ``C:\Mercurial\Mercurial.ini``.
88 88
89 89 Syntax
90 90 ------
91 91
92 92 A configuration file consists of sections, led by a ``[section]`` header
93 93 and followed by ``name = value`` entries (sometimes called
94 94 ``configuration keys``)::
95 95
96 96 [spam]
97 97 eggs=ham
98 98 green=
99 99 eggs
100 100
101 101 Each line contains one entry. If the lines that follow are indented,
102 102 they are treated as continuations of that entry. Leading whitespace is
103 103 removed from values. Empty lines are skipped. Lines beginning with
104 104 ``#`` or ``;`` are ignored and may be used to provide comments.
105 105
106 106 Configuration keys can be set multiple times, in which case mercurial
107 107 will use the value that was configured last. As an example::
108 108
109 109 [spam]
110 110 eggs=large
111 111 ham=serrano
112 112 eggs=small
113 113
114 114 This would set the configuration key named ``eggs`` to ``small``.
115 115
116 116 It is also possible to define a section multiple times. A section can
117 117 be redefined on the same and/or on different hgrc files. For example::
118 118
119 119 [foo]
120 120 eggs=large
121 121 ham=serrano
122 122 eggs=small
123 123
124 124 [bar]
125 125 eggs=ham
126 126 green=
127 127 eggs
128 128
129 129 [foo]
130 130 ham=prosciutto
131 131 eggs=medium
132 132 bread=toasted
133 133
134 134 This would set the ``eggs``, ``ham``, and ``bread`` configuration keys
135 135 of the ``foo`` section to ``medium``, ``prosciutto``, and ``toasted``,
136 136 respectively. As you can see there only thing that matters is the last
137 137 value that was set for each of the configuration keys.
138 138
139 139 If a configuration key is set multiple times in different
140 140 configuration files the final value will depend on the order in which
141 141 the different configuration files are read, with settings from earlier
142 142 paths overriding later ones as described on the ``Files`` section
143 143 above.
144 144
145 145 A line of the form ``%include file`` will include ``file`` into the
146 146 current configuration file. The inclusion is recursive, which means
147 147 that included files can include other files. Filenames are relative to
148 148 the configuration file in which the ``%include`` directive is found.
149 149 Environment variables and ``~user`` constructs are expanded in
150 150 ``file``. This lets you do something like::
151 151
152 152 %include ~/.hgrc.d/$HOST.rc
153 153
154 154 to include a different configuration file on each computer you use.
155 155
156 156 A line with ``%unset name`` will remove ``name`` from the current
157 157 section, if it has been set previously.
158 158
159 159 The values are either free-form text strings, lists of text strings,
160 160 or Boolean values. Boolean values can be set to true using any of "1",
161 161 "yes", "true", or "on" and to false using "0", "no", "false", or "off"
162 162 (all case insensitive).
163 163
164 164 List values are separated by whitespace or comma, except when values are
165 165 placed in double quotation marks::
166 166
167 167 allow_read = "John Doe, PhD", brian, betty
168 168
169 169 Quotation marks can be escaped by prefixing them with a backslash. Only
170 170 quotation marks at the beginning of a word is counted as a quotation
171 171 (e.g., ``foo"bar baz`` is the list of ``foo"bar`` and ``baz``).
172 172
173 173 Sections
174 174 --------
175 175
176 176 This section describes the different sections that may appear in a
177 177 Mercurial "hgrc" file, the purpose of each section, its possible keys,
178 178 and their possible values.
179 179
180 180 ``alias``
181 181 """""""""
182 182 Defines command aliases.
183 183 Aliases allow you to define your own commands in terms of other
184 184 commands (or aliases), optionally including arguments.
185 185
186 186 Alias definitions consist of lines of the form::
187 187
188 188 <alias> = <command> [<argument]...
189 189
190 190 For example, this definition::
191 191
192 192 latest = log --limit 5
193 193
194 194 creates a new command ``latest`` that shows only the five most recent
195 195 changesets. You can define subsequent aliases using earlier ones::
196 196
197 197 stable5 = latest -b stable
198 198
199 199 .. note:: It is possible to create aliases with the same names as
200 200 existing commands, which will then override the original
201 201 definitions. This is almost always a bad idea!
202 202
203 203
204 204 ``auth``
205 205 """"""""
206 206 Authentication credentials for HTTP authentication. Each line has
207 207 the following format::
208 208
209 209 <name>.<argument> = <value>
210 210
211 211 where ``<name>`` is used to group arguments into authentication
212 212 entries. Example::
213 213
214 214 foo.prefix = hg.intevation.org/mercurial
215 215 foo.username = foo
216 216 foo.password = bar
217 217 foo.schemes = http https
218 218
219 219 bar.prefix = secure.example.org
220 220 bar.key = path/to/file.key
221 221 bar.cert = path/to/file.cert
222 222 bar.schemes = https
223 223
224 224 Supported arguments:
225 225
226 226 ``prefix``
227 227 Either ``*`` or a URI prefix with or without the scheme part.
228 228 The authentication entry with the longest matching prefix is used
229 229 (where ``*`` matches everything and counts as a match of length
230 230 1). If the prefix doesn't include a scheme, the match is performed
231 231 against the URI with its scheme stripped as well, and the schemes
232 232 argument, q.v., is then subsequently consulted.
233 233 ``username``
234 234 Optional. Username to authenticate with. If not given, and the
235 remote site requires basic or digest authentication, the user
236 will be prompted for it.
235 remote site requires basic or digest authentication, the user will
236 be prompted for it. Environment variables are expanded in the
237 username letting you do ``foo.username = $USER``.
237 238 ``password``
238 239 Optional. Password to authenticate with. If not given, and the
239 240 remote site requires basic or digest authentication, the user
240 241 will be prompted for it.
241 242 ``key``
242 Optional. PEM encoded client certificate key file.
243 Optional. PEM encoded client certificate key file. Environment
244 variables are expanded in the filename.
243 245 ``cert``
244 Optional. PEM encoded client certificate chain file.
246 Optional. PEM encoded client certificate chain file. Environment
247 variables are expanded in the filename.
245 248 ``schemes``
246 249 Optional. Space separated list of URI schemes to use this
247 250 authentication entry with. Only used if the prefix doesn't include
248 251 a scheme. Supported schemes are http and https. They will match
249 252 static-http and static-https respectively, as well.
250 253 Default: https.
251 254
252 255 If no suitable authentication entry is found, the user is prompted
253 256 for credentials as usual if required by the remote.
254 257
255 258
256 259 ``decode/encode``
257 260 """""""""""""""""
258 261 Filters for transforming files on checkout/checkin. This would
259 262 typically be used for newline processing or other
260 263 localization/canonicalization of files.
261 264
262 265 Filters consist of a filter pattern followed by a filter command.
263 266 Filter patterns are globs by default, rooted at the repository root.
264 267 For example, to match any file ending in ``.txt`` in the root
265 268 directory only, use the pattern ``*.txt``. To match any file ending
266 269 in ``.c`` anywhere in the repository, use the pattern ``**.c``.
267 270 For each file only the first matching filter applies.
268 271
269 272 The filter command can start with a specifier, either ``pipe:`` or
270 273 ``tempfile:``. If no specifier is given, ``pipe:`` is used by default.
271 274
272 275 A ``pipe:`` command must accept data on stdin and return the transformed
273 276 data on stdout.
274 277
275 278 Pipe example::
276 279
277 280 [encode]
278 281 # uncompress gzip files on checkin to improve delta compression
279 282 # note: not necessarily a good idea, just an example
280 283 *.gz = pipe: gunzip
281 284
282 285 [decode]
283 286 # recompress gzip files when writing them to the working dir (we
284 287 # can safely omit "pipe:", because it's the default)
285 288 *.gz = gzip
286 289
287 290 A ``tempfile:`` command is a template. The string ``INFILE`` is replaced
288 291 with the name of a temporary file that contains the data to be
289 292 filtered by the command. The string ``OUTFILE`` is replaced with the name
290 293 of an empty temporary file, where the filtered data must be written by
291 294 the command.
292 295
293 296 .. note:: The tempfile mechanism is recommended for Windows systems,
294 297 where the standard shell I/O redirection operators often have
295 298 strange effects and may corrupt the contents of your files.
296 299
297 300 This filter mechanism is used internally by the ``eol`` extension to
298 301 translate line ending characters between Windows (CRLF) and Unix (LF)
299 302 format. We suggest you use the ``eol`` extension for convenience.
300 303
301 304
302 305 ``defaults``
303 306 """"""""""""
304 307
305 308 (defaults are deprecated. Don't use them. Use aliases instead)
306 309
307 310 Use the ``[defaults]`` section to define command defaults, i.e. the
308 311 default options/arguments to pass to the specified commands.
309 312
310 313 The following example makes :hg:`log` run in verbose mode, and
311 314 :hg:`status` show only the modified files, by default::
312 315
313 316 [defaults]
314 317 log = -v
315 318 status = -m
316 319
317 320 The actual commands, instead of their aliases, must be used when
318 321 defining command defaults. The command defaults will also be applied
319 322 to the aliases of the commands defined.
320 323
321 324
322 325 ``diff``
323 326 """"""""
324 327
325 328 Settings used when displaying diffs. They are all Boolean and
326 329 defaults to False.
327 330
328 331 ``git``
329 332 Use git extended diff format.
330 333 ``nodates``
331 334 Don't include dates in diff headers.
332 335 ``showfunc``
333 336 Show which function each change is in.
334 337 ``ignorews``
335 338 Ignore white space when comparing lines.
336 339 ``ignorewsamount``
337 340 Ignore changes in the amount of white space.
338 341 ``ignoreblanklines``
339 342 Ignore changes whose lines are all blank.
340 343
341 344 ``email``
342 345 """""""""
343 346 Settings for extensions that send email messages.
344 347
345 348 ``from``
346 349 Optional. Email address to use in "From" header and SMTP envelope
347 350 of outgoing messages.
348 351 ``to``
349 352 Optional. Comma-separated list of recipients' email addresses.
350 353 ``cc``
351 354 Optional. Comma-separated list of carbon copy recipients'
352 355 email addresses.
353 356 ``bcc``
354 357 Optional. Comma-separated list of blind carbon copy recipients'
355 358 email addresses.
356 359 ``method``
357 360 Optional. Method to use to send email messages. If value is ``smtp``
358 361 (default), use SMTP (see the SMTP_ section for configuration).
359 362 Otherwise, use as name of program to run that acts like sendmail
360 363 (takes ``-f`` option for sender, list of recipients on command line,
361 364 message on stdin). Normally, setting this to ``sendmail`` or
362 365 ``/usr/sbin/sendmail`` is enough to use sendmail to send messages.
363 366 ``charsets``
364 367 Optional. Comma-separated list of character sets considered
365 368 convenient for recipients. Addresses, headers, and parts not
366 369 containing patches of outgoing messages will be encoded in the
367 370 first character set to which conversion from local encoding
368 371 (``$HGENCODING``, ``ui.fallbackencoding``) succeeds. If correct
369 372 conversion fails, the text in question is sent as is. Defaults to
370 373 empty (explicit) list.
371 374
372 375 Order of outgoing email character sets:
373 376
374 377 1. ``us-ascii``: always first, regardless of settings
375 378 2. ``email.charsets``: in order given by user
376 379 3. ``ui.fallbackencoding``: if not in email.charsets
377 380 4. ``$HGENCODING``: if not in email.charsets
378 381 5. ``utf-8``: always last, regardless of settings
379 382
380 383 Email example::
381 384
382 385 [email]
383 386 from = Joseph User <joe.user@example.com>
384 387 method = /usr/sbin/sendmail
385 388 # charsets for western Europeans
386 389 # us-ascii, utf-8 omitted, as they are tried first and last
387 390 charsets = iso-8859-1, iso-8859-15, windows-1252
388 391
389 392
390 393 ``extensions``
391 394 """"""""""""""
392 395
393 396 Mercurial has an extension mechanism for adding new features. To
394 397 enable an extension, create an entry for it in this section.
395 398
396 399 If you know that the extension is already in Python's search path,
397 400 you can give the name of the module, followed by ``=``, with nothing
398 401 after the ``=``.
399 402
400 403 Otherwise, give a name that you choose, followed by ``=``, followed by
401 404 the path to the ``.py`` file (including the file name extension) that
402 405 defines the extension.
403 406
404 407 To explicitly disable an extension that is enabled in an hgrc of
405 408 broader scope, prepend its path with ``!``, as in
406 409 ``hgext.foo = !/ext/path`` or ``hgext.foo = !`` when path is not
407 410 supplied.
408 411
409 412 Example for ``~/.hgrc``::
410 413
411 414 [extensions]
412 415 # (the mq extension will get loaded from Mercurial's path)
413 416 hgext.mq =
414 417 # (this extension will get loaded from the file specified)
415 418 myfeature = ~/.hgext/myfeature.py
416 419
417 420
418 421 ``format``
419 422 """"""""""
420 423
421 424 ``usestore``
422 425 Enable or disable the "store" repository format which improves
423 426 compatibility with systems that fold case or otherwise mangle
424 427 filenames. Enabled by default. Disabling this option will allow
425 428 you to store longer filenames in some situations at the expense of
426 429 compatibility and ensures that the on-disk format of newly created
427 430 repositories will be compatible with Mercurial before version 0.9.4.
428 431
429 432 ``usefncache``
430 433 Enable or disable the "fncache" repository format which enhances
431 434 the "store" repository format (which has to be enabled to use
432 435 fncache) to allow longer filenames and avoids using Windows
433 436 reserved names, e.g. "nul". Enabled by default. Disabling this
434 437 option ensures that the on-disk format of newly created
435 438 repositories will be compatible with Mercurial before version 1.1.
436 439
437 440 ``merge-patterns``
438 441 """"""""""""""""""
439 442
440 443 This section specifies merge tools to associate with particular file
441 444 patterns. Tools matched here will take precedence over the default
442 445 merge tool. Patterns are globs by default, rooted at the repository
443 446 root.
444 447
445 448 Example::
446 449
447 450 [merge-patterns]
448 451 **.c = kdiff3
449 452 **.jpg = myimgmerge
450 453
451 454 ``merge-tools``
452 455 """""""""""""""
453 456
454 457 This section configures external merge tools to use for file-level
455 458 merges.
456 459
457 460 Example ``~/.hgrc``::
458 461
459 462 [merge-tools]
460 463 # Override stock tool location
461 464 kdiff3.executable = ~/bin/kdiff3
462 465 # Specify command line
463 466 kdiff3.args = $base $local $other -o $output
464 467 # Give higher priority
465 468 kdiff3.priority = 1
466 469
467 470 # Define new tool
468 471 myHtmlTool.args = -m $local $other $base $output
469 472 myHtmlTool.regkey = Software\FooSoftware\HtmlMerge
470 473 myHtmlTool.priority = 1
471 474
472 475 Supported arguments:
473 476
474 477 ``priority``
475 478 The priority in which to evaluate this tool.
476 479 Default: 0.
477 480 ``executable``
478 481 Either just the name of the executable or its pathname. On Windows,
479 482 the path can use environment variables with ${ProgramFiles} syntax.
480 483 Default: the tool name.
481 484 ``args``
482 485 The arguments to pass to the tool executable. You can refer to the
483 486 files being merged as well as the output file through these
484 487 variables: ``$base``, ``$local``, ``$other``, ``$output``.
485 488 Default: ``$local $base $other``
486 489 ``premerge``
487 490 Attempt to run internal non-interactive 3-way merge tool before
488 491 launching external tool. Options are ``true``, ``false``, or ``keep``
489 492 to leave markers in the file if the premerge fails.
490 493 Default: True
491 494 ``binary``
492 495 This tool can merge binary files. Defaults to False, unless tool
493 496 was selected by file pattern match.
494 497 ``symlink``
495 498 This tool can merge symlinks. Defaults to False, even if tool was
496 499 selected by file pattern match.
497 500 ``check``
498 501 A list of merge success-checking options:
499 502
500 503 ``changed``
501 504 Ask whether merge was successful when the merged file shows no changes.
502 505 ``conflicts``
503 506 Check whether there are conflicts even though the tool reported success.
504 507 ``prompt``
505 508 Always prompt for merge success, regardless of success reported by tool.
506 509
507 510 ``checkchanged``
508 511 True is equivalent to ``check = changed``.
509 512 Default: False
510 513 ``checkconflicts``
511 514 True is equivalent to ``check = conflicts``.
512 515 Default: False
513 516 ``fixeol``
514 517 Attempt to fix up EOL changes caused by the merge tool.
515 518 Default: False
516 519 ``gui``
517 520 This tool requires a graphical interface to run. Default: False
518 521 ``regkey``
519 522 Windows registry key which describes install location of this
520 523 tool. Mercurial will search for this key first under
521 524 ``HKEY_CURRENT_USER`` and then under ``HKEY_LOCAL_MACHINE``.
522 525 Default: None
523 526 ``regname``
524 527 Name of value to read from specified registry key. Defaults to the
525 528 unnamed (default) value.
526 529 ``regappend``
527 530 String to append to the value read from the registry, typically
528 531 the executable name of the tool.
529 532 Default: None
530 533
531 534
532 535 ``hooks``
533 536 """""""""
534 537 Commands or Python functions that get automatically executed by
535 538 various actions such as starting or finishing a commit. Multiple
536 539 hooks can be run for the same action by appending a suffix to the
537 540 action. Overriding a site-wide hook can be done by changing its
538 541 value or setting it to an empty string.
539 542
540 543 Example ``.hg/hgrc``::
541 544
542 545 [hooks]
543 546 # update working directory after adding changesets
544 547 changegroup.update = hg update
545 548 # do not use the site-wide hook
546 549 incoming =
547 550 incoming.email = /my/email/hook
548 551 incoming.autobuild = /my/build/hook
549 552
550 553 Most hooks are run with environment variables set that give useful
551 554 additional information. For each hook below, the environment
552 555 variables it is passed are listed with names of the form ``$HG_foo``.
553 556
554 557 ``changegroup``
555 558 Run after a changegroup has been added via push, pull or unbundle.
556 559 ID of the first new changeset is in ``$HG_NODE``. URL from which
557 560 changes came is in ``$HG_URL``.
558 561 ``commit``
559 562 Run after a changeset has been created in the local repository. ID
560 563 of the newly created changeset is in ``$HG_NODE``. Parent changeset
561 564 IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
562 565 ``incoming``
563 566 Run after a changeset has been pulled, pushed, or unbundled into
564 567 the local repository. The ID of the newly arrived changeset is in
565 568 ``$HG_NODE``. URL that was source of changes came is in ``$HG_URL``.
566 569 ``outgoing``
567 570 Run after sending changes from local repository to another. ID of
568 571 first changeset sent is in ``$HG_NODE``. Source of operation is in
569 572 ``$HG_SOURCE``; see "preoutgoing" hook for description.
570 573 ``post-<command>``
571 574 Run after successful invocations of the associated command. The
572 575 contents of the command line are passed as ``$HG_ARGS`` and the result
573 576 code in ``$HG_RESULT``. Parsed command line arguments are passed as
574 577 ``$HG_PATS`` and ``$HG_OPTS``. These contain string representations of
575 578 the python data internally passed to <command>. ``$HG_OPTS`` is a
576 579 dictionary of options (with unspecified options set to their defaults).
577 580 ``$HG_PATS`` is a list of arguments. Hook failure is ignored.
578 581 ``pre-<command>``
579 582 Run before executing the associated command. The contents of the
580 583 command line are passed as ``$HG_ARGS``. Parsed command line arguments
581 584 are passed as ``$HG_PATS`` and ``$HG_OPTS``. These contain string
582 585 representations of the data internally passed to <command>. ``$HG_OPTS``
583 586 is a dictionary of options (with unspecified options set to their
584 587 defaults). ``$HG_PATS`` is a list of arguments. If the hook returns
585 588 failure, the command doesn't execute and Mercurial returns the failure
586 589 code.
587 590 ``prechangegroup``
588 591 Run before a changegroup is added via push, pull or unbundle. Exit
589 592 status 0 allows the changegroup to proceed. Non-zero status will
590 593 cause the push, pull or unbundle to fail. URL from which changes
591 594 will come is in ``$HG_URL``.
592 595 ``precommit``
593 596 Run before starting a local commit. Exit status 0 allows the
594 597 commit to proceed. Non-zero status will cause the commit to fail.
595 598 Parent changeset IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
596 599 ``preoutgoing``
597 600 Run before collecting changes to send from the local repository to
598 601 another. Non-zero status will cause failure. This lets you prevent
599 602 pull over HTTP or SSH. Also prevents against local pull, push
600 603 (outbound) or bundle commands, but not effective, since you can
601 604 just copy files instead then. Source of operation is in
602 605 ``$HG_SOURCE``. If "serve", operation is happening on behalf of remote
603 606 SSH or HTTP repository. If "push", "pull" or "bundle", operation
604 607 is happening on behalf of repository on same system.
605 608 ``pretag``
606 609 Run before creating a tag. Exit status 0 allows the tag to be
607 610 created. Non-zero status will cause the tag to fail. ID of
608 611 changeset to tag is in ``$HG_NODE``. Name of tag is in ``$HG_TAG``. Tag is
609 612 local if ``$HG_LOCAL=1``, in repository if ``$HG_LOCAL=0``.
610 613 ``pretxnchangegroup``
611 614 Run after a changegroup has been added via push, pull or unbundle,
612 615 but before the transaction has been committed. Changegroup is
613 616 visible to hook program. This lets you validate incoming changes
614 617 before accepting them. Passed the ID of the first new changeset in
615 618 ``$HG_NODE``. Exit status 0 allows the transaction to commit. Non-zero
616 619 status will cause the transaction to be rolled back and the push,
617 620 pull or unbundle will fail. URL that was source of changes is in
618 621 ``$HG_URL``.
619 622 ``pretxncommit``
620 623 Run after a changeset has been created but the transaction not yet
621 624 committed. Changeset is visible to hook program. This lets you
622 625 validate commit message and changes. Exit status 0 allows the
623 626 commit to proceed. Non-zero status will cause the transaction to
624 627 be rolled back. ID of changeset is in ``$HG_NODE``. Parent changeset
625 628 IDs are in ``$HG_PARENT1`` and ``$HG_PARENT2``.
626 629 ``preupdate``
627 630 Run before updating the working directory. Exit status 0 allows
628 631 the update to proceed. Non-zero status will prevent the update.
629 632 Changeset ID of first new parent is in ``$HG_PARENT1``. If merge, ID
630 633 of second new parent is in ``$HG_PARENT2``.
631 634 ``tag``
632 635 Run after a tag is created. ID of tagged changeset is in ``$HG_NODE``.
633 636 Name of tag is in ``$HG_TAG``. Tag is local if ``$HG_LOCAL=1``, in
634 637 repository if ``$HG_LOCAL=0``.
635 638 ``update``
636 639 Run after updating the working directory. Changeset ID of first
637 640 new parent is in ``$HG_PARENT1``. If merge, ID of second new parent is
638 641 in ``$HG_PARENT2``. If the update succeeded, ``$HG_ERROR=0``. If the
639 642 update failed (e.g. because conflicts not resolved), ``$HG_ERROR=1``.
640 643
641 644 .. note:: It is generally better to use standard hooks rather than the
642 645 generic pre- and post- command hooks as they are guaranteed to be
643 646 called in the appropriate contexts for influencing transactions.
644 647 Also, hooks like "commit" will be called in all contexts that
645 648 generate a commit (e.g. tag) and not just the commit command.
646 649
647 650 .. note:: Environment variables with empty values may not be passed to
648 651 hooks on platforms such as Windows. As an example, ``$HG_PARENT2``
649 652 will have an empty value under Unix-like platforms for non-merge
650 653 changesets, while it will not be available at all under Windows.
651 654
652 655 The syntax for Python hooks is as follows::
653 656
654 657 hookname = python:modulename.submodule.callable
655 658 hookname = python:/path/to/python/module.py:callable
656 659
657 660 Python hooks are run within the Mercurial process. Each hook is
658 661 called with at least three keyword arguments: a ui object (keyword
659 662 ``ui``), a repository object (keyword ``repo``), and a ``hooktype``
660 663 keyword that tells what kind of hook is used. Arguments listed as
661 664 environment variables above are passed as keyword arguments, with no
662 665 ``HG_`` prefix, and names in lower case.
663 666
664 667 If a Python hook returns a "true" value or raises an exception, this
665 668 is treated as a failure.
666 669
667 670
668 671 ``http_proxy``
669 672 """"""""""""""
670 673 Used to access web-based Mercurial repositories through a HTTP
671 674 proxy.
672 675
673 676 ``host``
674 677 Host name and (optional) port of the proxy server, for example
675 678 "myproxy:8000".
676 679 ``no``
677 680 Optional. Comma-separated list of host names that should bypass
678 681 the proxy.
679 682 ``passwd``
680 683 Optional. Password to authenticate with at the proxy server.
681 684 ``user``
682 685 Optional. User name to authenticate with at the proxy server.
683 686 ``always``
684 687 Optional. Always use the proxy, even for localhost and any entries
685 688 in ``http_proxy.no``. True or False. Default: False.
686 689
687 690 ``smtp``
688 691 """"""""
689 692 Configuration for extensions that need to send email messages.
690 693
691 694 ``host``
692 695 Host name of mail server, e.g. "mail.example.com".
693 696 ``port``
694 697 Optional. Port to connect to on mail server. Default: 25.
695 698 ``tls``
696 699 Optional. Whether to connect to mail server using TLS. True or
697 700 False. Default: False.
698 701 ``username``
699 702 Optional. User name to authenticate to SMTP server with. If
700 703 username is specified, password must also be specified.
701 704 Default: none.
702 705 ``password``
703 706 Optional. Password to authenticate to SMTP server with. If
704 707 username is specified, password must also be specified.
705 708 Default: none.
706 709 ``local_hostname``
707 710 Optional. It's the hostname that the sender can use to identify
708 711 itself to the MTA.
709 712
710 713
711 714 ``patch``
712 715 """""""""
713 716 Settings used when applying patches, for instance through the 'import'
714 717 command or with Mercurial Queues extension.
715 718
716 719 ``eol``
717 720 When set to 'strict' patch content and patched files end of lines
718 721 are preserved. When set to ``lf`` or ``crlf``, both files end of
719 722 lines are ignored when patching and the result line endings are
720 723 normalized to either LF (Unix) or CRLF (Windows). When set to
721 724 ``auto``, end of lines are again ignored while patching but line
722 725 endings in patched files are normalized to their original setting
723 726 on a per-file basis. If target file does not exist or has no end
724 727 of line, patch line endings are preserved.
725 728 Default: strict.
726 729
727 730
728 731 ``paths``
729 732 """""""""
730 733 Assigns symbolic names to repositories. The left side is the
731 734 symbolic name, and the right gives the directory or URL that is the
732 735 location of the repository. Default paths can be declared by setting
733 736 the following entries.
734 737
735 738 ``default``
736 739 Directory or URL to use when pulling if no source is specified.
737 740 Default is set to repository from which the current repository was
738 741 cloned.
739 742 ``default-push``
740 743 Optional. Directory or URL to use when pushing if no destination
741 744 is specified.
742 745
743 746
744 747 ``profiling``
745 748 """""""""""""
746 749 Specifies profiling format and file output. In this section
747 750 description, 'profiling data' stands for the raw data collected
748 751 during profiling, while 'profiling report' stands for a statistical
749 752 text report generated from the profiling data. The profiling is done
750 753 using lsprof.
751 754
752 755 ``format``
753 756 Profiling format.
754 757 Default: text.
755 758
756 759 ``text``
757 760 Generate a profiling report. When saving to a file, it should be
758 761 noted that only the report is saved, and the profiling data is
759 762 not kept.
760 763 ``kcachegrind``
761 764 Format profiling data for kcachegrind use: when saving to a
762 765 file, the generated file can directly be loaded into
763 766 kcachegrind.
764 767 ``output``
765 768 File path where profiling data or report should be saved. If the
766 769 file exists, it is replaced. Default: None, data is printed on
767 770 stderr
768 771
769 772 ``server``
770 773 """"""""""
771 774 Controls generic server settings.
772 775
773 776 ``uncompressed``
774 777 Whether to allow clients to clone a repository using the
775 778 uncompressed streaming protocol. This transfers about 40% more
776 779 data than a regular clone, but uses less memory and CPU on both
777 780 server and client. Over a LAN (100 Mbps or better) or a very fast
778 781 WAN, an uncompressed streaming clone is a lot faster (~10x) than a
779 782 regular clone. Over most WAN connections (anything slower than
780 783 about 6 Mbps), uncompressed streaming is slower, because of the
781 784 extra data transfer overhead. This mode will also temporarily hold
782 785 the write lock while determining what data to transfer.
783 786 Default is True.
784 787
785 788 ``validate``
786 789 Whether to validate the completeness of pushed changesets by
787 790 checking that all new file revisions specified in manifests are
788 791 present. Default is False.
789 792
790 793 ``trusted``
791 794 """""""""""
792 795
793 796 Mercurial will not use the settings in the
794 797 ``.hg/hgrc`` file from a repository if it doesn't belong to a trusted
795 798 user or to a trusted group, as various hgrc features allow arbitrary
796 799 commands to be run. This issue is often encountered when configuring
797 800 hooks or extensions for shared repositories or servers. However,
798 801 the web interface will use some safe settings from the ``[web]``
799 802 section.
800 803
801 804 This section specifies what users and groups are trusted. The
802 805 current user is always trusted. To trust everybody, list a user or a
803 806 group with name ``*``. These settings must be placed in an
804 807 *already-trusted file* to take effect, such as ``$HOME/.hgrc`` of the
805 808 user or service running Mercurial.
806 809
807 810 ``users``
808 811 Comma-separated list of trusted users.
809 812 ``groups``
810 813 Comma-separated list of trusted groups.
811 814
812 815
813 816 ``ui``
814 817 """"""
815 818
816 819 User interface controls.
817 820
818 821 ``archivemeta``
819 822 Whether to include the .hg_archival.txt file containing meta data
820 823 (hashes for the repository base and for tip) in archives created
821 824 by the :hg:`archive` command or downloaded via hgweb.
822 825 Default is True.
823 826 ``askusername``
824 827 Whether to prompt for a username when committing. If True, and
825 828 neither ``$HGUSER`` nor ``$EMAIL`` has been specified, then the user will
826 829 be prompted to enter a username. If no username is entered, the
827 830 default ``USER@HOST`` is used instead.
828 831 Default is False.
829 832 ``debug``
830 833 Print debugging information. True or False. Default is False.
831 834 ``editor``
832 835 The editor to use during a commit. Default is ``$EDITOR`` or ``vi``.
833 836 ``fallbackencoding``
834 837 Encoding to try if it's not possible to decode the changelog using
835 838 UTF-8. Default is ISO-8859-1.
836 839 ``ignore``
837 840 A file to read per-user ignore patterns from. This file should be
838 841 in the same format as a repository-wide .hgignore file. This
839 842 option supports hook syntax, so if you want to specify multiple
840 843 ignore files, you can do so by setting something like
841 844 ``ignore.other = ~/.hgignore2``. For details of the ignore file
842 845 format, see the |hgignore(5)|_ man page.
843 846 ``interactive``
844 847 Allow to prompt the user. True or False. Default is True.
845 848 ``logtemplate``
846 849 Template string for commands that print changesets.
847 850 ``merge``
848 851 The conflict resolution program to use during a manual merge.
849 852 There are some internal tools available:
850 853
851 854 ``internal:local``
852 855 keep the local version
853 856 ``internal:other``
854 857 use the other version
855 858 ``internal:merge``
856 859 use the internal non-interactive merge tool
857 860 ``internal:fail``
858 861 fail to merge
859 862
860 863 For more information on configuring merge tools see the
861 864 merge-tools_ section.
862 865
863 866 ``patch``
864 867 command to use to apply patches. Look for ``gpatch`` or ``patch`` in
865 868 PATH if unset.
866 869 ``quiet``
867 870 Reduce the amount of output printed. True or False. Default is False.
868 871 ``remotecmd``
869 872 remote command to use for clone/push/pull operations. Default is ``hg``.
870 873 ``report_untrusted``
871 874 Warn if a ``.hg/hgrc`` file is ignored due to not being owned by a
872 875 trusted user or group. True or False. Default is True.
873 876 ``slash``
874 877 Display paths using a slash (``/``) as the path separator. This
875 878 only makes a difference on systems where the default path
876 879 separator is not the slash character (e.g. Windows uses the
877 880 backslash character (``\``)).
878 881 Default is False.
879 882 ``ssh``
880 883 command to use for SSH connections. Default is ``ssh``.
881 884 ``strict``
882 885 Require exact command names, instead of allowing unambiguous
883 886 abbreviations. True or False. Default is False.
884 887 ``style``
885 888 Name of style to use for command output.
886 889 ``timeout``
887 890 The timeout used when a lock is held (in seconds), a negative value
888 891 means no timeout. Default is 600.
889 892 ``traceback``
890 893 Mercurial always prints a traceback when an unknown exception
891 894 occurs. Setting this to True will make Mercurial print a traceback
892 895 on all exceptions, even those recognized by Mercurial (such as
893 896 IOError or MemoryError). Default is False.
894 897 ``username``
895 898 The committer of a changeset created when running "commit".
896 899 Typically a person's name and email address, e.g. ``Fred Widget
897 900 <fred@example.com>``. Default is ``$EMAIL`` or ``username@hostname``. If
898 901 the username in hgrc is empty, it has to be specified manually or
899 902 in a different hgrc file (e.g. ``$HOME/.hgrc``, if the admin set
900 903 ``username =`` in the system hgrc). Environment variables in the
901 904 username are expanded.
902 905 ``verbose``
903 906 Increase the amount of output printed. True or False. Default is False.
904 907
905 908
906 909 ``web``
907 910 """""""
908 911 Web interface configuration.
909 912
910 913 ``accesslog``
911 914 Where to output the access log. Default is stdout.
912 915 ``address``
913 916 Interface address to bind to. Default is all.
914 917 ``allow_archive``
915 918 List of archive format (bz2, gz, zip) allowed for downloading.
916 919 Default is empty.
917 920 ``allowbz2``
918 921 (DEPRECATED) Whether to allow .tar.bz2 downloading of repository
919 922 revisions.
920 923 Default is False.
921 924 ``allowgz``
922 925 (DEPRECATED) Whether to allow .tar.gz downloading of repository
923 926 revisions.
924 927 Default is False.
925 928 ``allowpull``
926 929 Whether to allow pulling from the repository. Default is True.
927 930 ``allow_push``
928 931 Whether to allow pushing to the repository. If empty or not set,
929 932 push is not allowed. If the special value ``*``, any remote user can
930 933 push, including unauthenticated users. Otherwise, the remote user
931 934 must have been authenticated, and the authenticated user name must
932 935 be present in this list. The contents of the allow_push list are
933 936 examined after the deny_push list.
934 937 ``allow_read``
935 938 If the user has not already been denied repository access due to
936 939 the contents of deny_read, this list determines whether to grant
937 940 repository access to the user. If this list is not empty, and the
938 941 user is unauthenticated or not present in the list, then access is
939 942 denied for the user. If the list is empty or not set, then access
940 943 is permitted to all users by default. Setting allow_read to the
941 944 special value ``*`` is equivalent to it not being set (i.e. access
942 945 is permitted to all users). The contents of the allow_read list are
943 946 examined after the deny_read list.
944 947 ``allowzip``
945 948 (DEPRECATED) Whether to allow .zip downloading of repository
946 949 revisions. Default is False. This feature creates temporary files.
947 950 ``baseurl``
948 951 Base URL to use when publishing URLs in other locations, so
949 952 third-party tools like email notification hooks can construct
950 953 URLs. Example: ``http://hgserver/repos/``.
951 954 ``cacerts``
952 955 Path to file containing a list of PEM encoded certificate authorities
953 956 that may be used to verify an SSL server's identity. The form must be
954 957 as follows::
955 958
956 959 -----BEGIN CERTIFICATE-----
957 960 ... (certificate in base64 PEM encoding) ...
958 961 -----END CERTIFICATE-----
959 962 -----BEGIN CERTIFICATE-----
960 963 ... (certificate in base64 PEM encoding) ...
961 964 -----END CERTIFICATE-----
962 965
963 966 This feature is only supported when using Python 2.6. If you wish to
964 967 use it with earlier versions of Python, install the backported
965 968 version of the ssl library that is available from
966 969 ``http://pypi.python.org``.
967 970
968 971 You can use OpenSSL's CA certificate file if your platform has one.
969 972 On most Linux systems this will be ``/etc/ssl/certs/ca-certificates.crt``.
970 973 Otherwise you will have to generate this file manually.
971 974 ``contact``
972 975 Name or email address of the person in charge of the repository.
973 976 Defaults to ui.username or ``$EMAIL`` or "unknown" if unset or empty.
974 977 ``deny_push``
975 978 Whether to deny pushing to the repository. If empty or not set,
976 979 push is not denied. If the special value ``*``, all remote users are
977 980 denied push. Otherwise, unauthenticated users are all denied, and
978 981 any authenticated user name present in this list is also denied. The
979 982 contents of the deny_push list are examined before the allow_push list.
980 983 ``deny_read``
981 984 Whether to deny reading/viewing of the repository. If this list is
982 985 not empty, unauthenticated users are all denied, and any
983 986 authenticated user name present in this list is also denied access to
984 987 the repository. If set to the special value ``*``, all remote users
985 988 are denied access (rarely needed ;). If deny_read is empty or not set,
986 989 the determination of repository access depends on the presence and
987 990 content of the allow_read list (see description). If both
988 991 deny_read and allow_read are empty or not set, then access is
989 992 permitted to all users by default. If the repository is being
990 993 served via hgwebdir, denied users will not be able to see it in
991 994 the list of repositories. The contents of the deny_read list have
992 995 priority over (are examined before) the contents of the allow_read
993 996 list.
994 997 ``descend``
995 998 hgwebdir indexes will not descend into subdirectories. Only repositories
996 999 directly in the current path will be shown (other repositories are still
997 1000 available from the index corresponding to their containing path).
998 1001 ``description``
999 1002 Textual description of the repository's purpose or contents.
1000 1003 Default is "unknown".
1001 1004 ``encoding``
1002 1005 Character encoding name. Default is the current locale charset.
1003 1006 Example: "UTF-8"
1004 1007 ``errorlog``
1005 1008 Where to output the error log. Default is stderr.
1006 1009 ``hidden``
1007 1010 Whether to hide the repository in the hgwebdir index.
1008 1011 Default is False.
1009 1012 ``ipv6``
1010 1013 Whether to use IPv6. Default is False.
1011 1014 ``name``
1012 1015 Repository name to use in the web interface. Default is current
1013 1016 working directory.
1014 1017 ``maxchanges``
1015 1018 Maximum number of changes to list on the changelog. Default is 10.
1016 1019 ``maxfiles``
1017 1020 Maximum number of files to list per changeset. Default is 10.
1018 1021 ``port``
1019 1022 Port to listen on. Default is 8000.
1020 1023 ``prefix``
1021 1024 Prefix path to serve from. Default is '' (server root).
1022 1025 ``push_ssl``
1023 1026 Whether to require that inbound pushes be transported over SSL to
1024 1027 prevent password sniffing. Default is True.
1025 1028 ``staticurl``
1026 1029 Base URL to use for static files. If unset, static files (e.g. the
1027 1030 hgicon.png favicon) will be served by the CGI script itself. Use
1028 1031 this setting to serve them directly with the HTTP server.
1029 1032 Example: ``http://hgserver/static/``.
1030 1033 ``stripes``
1031 1034 How many lines a "zebra stripe" should span in multiline output.
1032 1035 Default is 1; set to 0 to disable.
1033 1036 ``style``
1034 1037 Which template map style to use.
1035 1038 ``templates``
1036 1039 Where to find the HTML templates. Default is install path.
1037 1040
1038 1041
1039 1042 Author
1040 1043 ------
1041 1044 Bryan O'Sullivan <bos@serpentine.com>.
1042 1045
1043 1046 Mercurial was written by Matt Mackall <mpm@selenic.com>.
1044 1047
1045 1048 See Also
1046 1049 --------
1047 1050 |hg(1)|_, |hgignore(5)|_
1048 1051
1049 1052 Copying
1050 1053 -------
1051 1054 This manual page is copyright 2005 Bryan O'Sullivan.
1052 1055 Mercurial is copyright 2005-2010 Matt Mackall.
1053 1056 Free use of this software is granted under the terms of the GNU General
1054 1057 Public License version 2 or any later version.
1055 1058
1056 1059 .. include:: common.txt
@@ -1,640 +1,641 b''
1 1 # url.py - HTTP handling for mercurial
2 2 #
3 3 # Copyright 2005, 2006, 2007, 2008 Matt Mackall <mpm@selenic.com>
4 4 # Copyright 2006, 2007 Alexis S. L. Carvalho <alexis@cecm.usp.br>
5 5 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
6 6 #
7 7 # This software may be used and distributed according to the terms of the
8 8 # GNU General Public License version 2 or any later version.
9 9
10 10 import urllib, urllib2, urlparse, httplib, os, re, socket, cStringIO
11 11 from i18n import _
12 12 import keepalive, util
13 13
14 14 def _urlunparse(scheme, netloc, path, params, query, fragment, url):
15 15 '''Handle cases where urlunparse(urlparse(x://)) doesn't preserve the "//"'''
16 16 result = urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
17 17 if (scheme and
18 18 result.startswith(scheme + ':') and
19 19 not result.startswith(scheme + '://') and
20 20 url.startswith(scheme + '://')
21 21 ):
22 22 result = scheme + '://' + result[len(scheme + ':'):]
23 23 return result
24 24
25 25 def hidepassword(url):
26 26 '''hide user credential in a url string'''
27 27 scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
28 28 netloc = re.sub('([^:]*):([^@]*)@(.*)', r'\1:***@\3', netloc)
29 29 return _urlunparse(scheme, netloc, path, params, query, fragment, url)
30 30
31 31 def removeauth(url):
32 32 '''remove all authentication information from a url string'''
33 33 scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
34 34 netloc = netloc[netloc.find('@')+1:]
35 35 return _urlunparse(scheme, netloc, path, params, query, fragment, url)
36 36
37 37 def netlocsplit(netloc):
38 38 '''split [user[:passwd]@]host[:port] into 4-tuple.'''
39 39
40 40 a = netloc.find('@')
41 41 if a == -1:
42 42 user, passwd = None, None
43 43 else:
44 44 userpass, netloc = netloc[:a], netloc[a + 1:]
45 45 c = userpass.find(':')
46 46 if c == -1:
47 47 user, passwd = urllib.unquote(userpass), None
48 48 else:
49 49 user = urllib.unquote(userpass[:c])
50 50 passwd = urllib.unquote(userpass[c + 1:])
51 51 c = netloc.find(':')
52 52 if c == -1:
53 53 host, port = netloc, None
54 54 else:
55 55 host, port = netloc[:c], netloc[c + 1:]
56 56 return host, port, user, passwd
57 57
58 58 def netlocunsplit(host, port, user=None, passwd=None):
59 59 '''turn host, port, user, passwd into [user[:passwd]@]host[:port].'''
60 60 if port:
61 61 hostport = host + ':' + port
62 62 else:
63 63 hostport = host
64 64 if user:
65 65 quote = lambda s: urllib.quote(s, safe='')
66 66 if passwd:
67 67 userpass = quote(user) + ':' + quote(passwd)
68 68 else:
69 69 userpass = quote(user)
70 70 return userpass + '@' + hostport
71 71 return hostport
72 72
73 73 _safe = ('abcdefghijklmnopqrstuvwxyz'
74 74 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
75 75 '0123456789' '_.-/')
76 76 _safeset = None
77 77 _hex = None
78 78 def quotepath(path):
79 79 '''quote the path part of a URL
80 80
81 81 This is similar to urllib.quote, but it also tries to avoid
82 82 quoting things twice (inspired by wget):
83 83
84 84 >>> quotepath('abc def')
85 85 'abc%20def'
86 86 >>> quotepath('abc%20def')
87 87 'abc%20def'
88 88 >>> quotepath('abc%20 def')
89 89 'abc%20%20def'
90 90 >>> quotepath('abc def%20')
91 91 'abc%20def%20'
92 92 >>> quotepath('abc def%2')
93 93 'abc%20def%252'
94 94 >>> quotepath('abc def%')
95 95 'abc%20def%25'
96 96 '''
97 97 global _safeset, _hex
98 98 if _safeset is None:
99 99 _safeset = set(_safe)
100 100 _hex = set('abcdefABCDEF0123456789')
101 101 l = list(path)
102 102 for i in xrange(len(l)):
103 103 c = l[i]
104 104 if (c == '%' and i + 2 < len(l) and
105 105 l[i + 1] in _hex and l[i + 2] in _hex):
106 106 pass
107 107 elif c not in _safeset:
108 108 l[i] = '%%%02X' % ord(c)
109 109 return ''.join(l)
110 110
111 111 class passwordmgr(urllib2.HTTPPasswordMgrWithDefaultRealm):
112 112 def __init__(self, ui):
113 113 urllib2.HTTPPasswordMgrWithDefaultRealm.__init__(self)
114 114 self.ui = ui
115 115
116 116 def find_user_password(self, realm, authuri):
117 117 authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(
118 118 self, realm, authuri)
119 119 user, passwd = authinfo
120 120 if user and passwd:
121 121 self._writedebug(user, passwd)
122 122 return (user, passwd)
123 123
124 124 if not user:
125 125 auth = self.readauthtoken(authuri)
126 126 if auth:
127 127 user, passwd = auth.get('username'), auth.get('password')
128 128 if not user or not passwd:
129 129 if not self.ui.interactive():
130 130 raise util.Abort(_('http authorization required'))
131 131
132 132 self.ui.write(_("http authorization required\n"))
133 133 self.ui.status(_("realm: %s\n") % realm)
134 134 if user:
135 135 self.ui.status(_("user: %s\n") % user)
136 136 else:
137 137 user = self.ui.prompt(_("user:"), default=None)
138 138
139 139 if not passwd:
140 140 passwd = self.ui.getpass()
141 141
142 142 self.add_password(realm, authuri, user, passwd)
143 143 self._writedebug(user, passwd)
144 144 return (user, passwd)
145 145
146 146 def _writedebug(self, user, passwd):
147 147 msg = _('http auth: user %s, password %s\n')
148 148 self.ui.debug(msg % (user, passwd and '*' * len(passwd) or 'not set'))
149 149
150 150 def readauthtoken(self, uri):
151 151 # Read configuration
152 152 config = dict()
153 153 for key, val in self.ui.configitems('auth'):
154 154 if '.' not in key:
155 155 self.ui.warn(_("ignoring invalid [auth] key '%s'\n") % key)
156 156 continue
157 157 group, setting = key.split('.', 1)
158 158 gdict = config.setdefault(group, dict())
159 if setting in ('username', 'cert', 'key'):
159 160 val = util.expandpath(val)
160 161 gdict[setting] = val
161 162
162 163 # Find the best match
163 164 scheme, hostpath = uri.split('://', 1)
164 165 bestlen = 0
165 166 bestauth = None
166 167 for auth in config.itervalues():
167 168 prefix = auth.get('prefix')
168 169 if not prefix:
169 170 continue
170 171 p = prefix.split('://', 1)
171 172 if len(p) > 1:
172 173 schemes, prefix = [p[0]], p[1]
173 174 else:
174 175 schemes = (auth.get('schemes') or 'https').split()
175 176 if (prefix == '*' or hostpath.startswith(prefix)) and \
176 177 len(prefix) > bestlen and scheme in schemes:
177 178 bestlen = len(prefix)
178 179 bestauth = auth
179 180 return bestauth
180 181
181 182 class proxyhandler(urllib2.ProxyHandler):
182 183 def __init__(self, ui):
183 184 proxyurl = ui.config("http_proxy", "host") or os.getenv('http_proxy')
184 185 # XXX proxyauthinfo = None
185 186
186 187 if proxyurl:
187 188 # proxy can be proper url or host[:port]
188 189 if not (proxyurl.startswith('http:') or
189 190 proxyurl.startswith('https:')):
190 191 proxyurl = 'http://' + proxyurl + '/'
191 192 snpqf = urlparse.urlsplit(proxyurl)
192 193 proxyscheme, proxynetloc, proxypath, proxyquery, proxyfrag = snpqf
193 194 hpup = netlocsplit(proxynetloc)
194 195
195 196 proxyhost, proxyport, proxyuser, proxypasswd = hpup
196 197 if not proxyuser:
197 198 proxyuser = ui.config("http_proxy", "user")
198 199 proxypasswd = ui.config("http_proxy", "passwd")
199 200
200 201 # see if we should use a proxy for this url
201 202 no_list = ["localhost", "127.0.0.1"]
202 203 no_list.extend([p.lower() for
203 204 p in ui.configlist("http_proxy", "no")])
204 205 no_list.extend([p.strip().lower() for
205 206 p in os.getenv("no_proxy", '').split(',')
206 207 if p.strip()])
207 208 # "http_proxy.always" config is for running tests on localhost
208 209 if ui.configbool("http_proxy", "always"):
209 210 self.no_list = []
210 211 else:
211 212 self.no_list = no_list
212 213
213 214 proxyurl = urlparse.urlunsplit((
214 215 proxyscheme, netlocunsplit(proxyhost, proxyport,
215 216 proxyuser, proxypasswd or ''),
216 217 proxypath, proxyquery, proxyfrag))
217 218 proxies = {'http': proxyurl, 'https': proxyurl}
218 219 ui.debug('proxying through http://%s:%s\n' %
219 220 (proxyhost, proxyport))
220 221 else:
221 222 proxies = {}
222 223
223 224 # urllib2 takes proxy values from the environment and those
224 225 # will take precedence if found, so drop them
225 226 for env in ["HTTP_PROXY", "http_proxy", "no_proxy"]:
226 227 try:
227 228 if env in os.environ:
228 229 del os.environ[env]
229 230 except OSError:
230 231 pass
231 232
232 233 urllib2.ProxyHandler.__init__(self, proxies)
233 234 self.ui = ui
234 235
235 236 def proxy_open(self, req, proxy, type_):
236 237 host = req.get_host().split(':')[0]
237 238 if host in self.no_list:
238 239 return None
239 240
240 241 # work around a bug in Python < 2.4.2
241 242 # (it leaves a "\n" at the end of Proxy-authorization headers)
242 243 baseclass = req.__class__
243 244 class _request(baseclass):
244 245 def add_header(self, key, val):
245 246 if key.lower() == 'proxy-authorization':
246 247 val = val.strip()
247 248 return baseclass.add_header(self, key, val)
248 249 req.__class__ = _request
249 250
250 251 return urllib2.ProxyHandler.proxy_open(self, req, proxy, type_)
251 252
252 253 class httpsendfile(file):
253 254 def __len__(self):
254 255 return os.fstat(self.fileno()).st_size
255 256
256 257 def _gen_sendfile(connection):
257 258 def _sendfile(self, data):
258 259 # send a file
259 260 if isinstance(data, httpsendfile):
260 261 # if auth required, some data sent twice, so rewind here
261 262 data.seek(0)
262 263 for chunk in util.filechunkiter(data):
263 264 connection.send(self, chunk)
264 265 else:
265 266 connection.send(self, data)
266 267 return _sendfile
267 268
268 269 has_https = hasattr(urllib2, 'HTTPSHandler')
269 270 if has_https:
270 271 try:
271 272 # avoid using deprecated/broken FakeSocket in python 2.6
272 273 import ssl
273 274 _ssl_wrap_socket = ssl.wrap_socket
274 275 CERT_REQUIRED = ssl.CERT_REQUIRED
275 276 except ImportError:
276 277 CERT_REQUIRED = 2
277 278
278 279 def _ssl_wrap_socket(sock, key_file, cert_file,
279 280 cert_reqs=CERT_REQUIRED, ca_certs=None):
280 281 if ca_certs:
281 282 raise util.Abort(_(
282 283 'certificate checking requires Python 2.6'))
283 284
284 285 ssl = socket.ssl(sock, key_file, cert_file)
285 286 return httplib.FakeSocket(sock, ssl)
286 287
287 288 try:
288 289 _create_connection = socket.create_connection
289 290 except AttributeError:
290 291 _GLOBAL_DEFAULT_TIMEOUT = object()
291 292
292 293 def _create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
293 294 source_address=None):
294 295 # lifted from Python 2.6
295 296
296 297 msg = "getaddrinfo returns an empty list"
297 298 host, port = address
298 299 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
299 300 af, socktype, proto, canonname, sa = res
300 301 sock = None
301 302 try:
302 303 sock = socket.socket(af, socktype, proto)
303 304 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
304 305 sock.settimeout(timeout)
305 306 if source_address:
306 307 sock.bind(source_address)
307 308 sock.connect(sa)
308 309 return sock
309 310
310 311 except socket.error, msg:
311 312 if sock is not None:
312 313 sock.close()
313 314
314 315 raise socket.error, msg
315 316
316 317 class httpconnection(keepalive.HTTPConnection):
317 318 # must be able to send big bundle as stream.
318 319 send = _gen_sendfile(keepalive.HTTPConnection)
319 320
320 321 def connect(self):
321 322 if has_https and self.realhostport: # use CONNECT proxy
322 323 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
323 324 self.sock.connect((self.host, self.port))
324 325 if _generic_proxytunnel(self):
325 326 # we do not support client x509 certificates
326 327 self.sock = _ssl_wrap_socket(self.sock, None, None)
327 328 else:
328 329 keepalive.HTTPConnection.connect(self)
329 330
330 331 def getresponse(self):
331 332 proxyres = getattr(self, 'proxyres', None)
332 333 if proxyres:
333 334 if proxyres.will_close:
334 335 self.close()
335 336 self.proxyres = None
336 337 return proxyres
337 338 return keepalive.HTTPConnection.getresponse(self)
338 339
339 340 # general transaction handler to support different ways to handle
340 341 # HTTPS proxying before and after Python 2.6.3.
341 342 def _generic_start_transaction(handler, h, req):
342 343 if hasattr(req, '_tunnel_host') and req._tunnel_host:
343 344 tunnel_host = req._tunnel_host
344 345 if tunnel_host[:7] not in ['http://', 'https:/']:
345 346 tunnel_host = 'https://' + tunnel_host
346 347 new_tunnel = True
347 348 else:
348 349 tunnel_host = req.get_selector()
349 350 new_tunnel = False
350 351
351 352 if new_tunnel or tunnel_host == req.get_full_url(): # has proxy
352 353 urlparts = urlparse.urlparse(tunnel_host)
353 354 if new_tunnel or urlparts[0] == 'https': # only use CONNECT for HTTPS
354 355 realhostport = urlparts[1]
355 356 if realhostport[-1] == ']' or ':' not in realhostport:
356 357 realhostport += ':443'
357 358
358 359 h.realhostport = realhostport
359 360 h.headers = req.headers.copy()
360 361 h.headers.update(handler.parent.addheaders)
361 362 return
362 363
363 364 h.realhostport = None
364 365 h.headers = None
365 366
366 367 def _generic_proxytunnel(self):
367 368 proxyheaders = dict(
368 369 [(x, self.headers[x]) for x in self.headers
369 370 if x.lower().startswith('proxy-')])
370 371 self._set_hostport(self.host, self.port)
371 372 self.send('CONNECT %s HTTP/1.0\r\n' % self.realhostport)
372 373 for header in proxyheaders.iteritems():
373 374 self.send('%s: %s\r\n' % header)
374 375 self.send('\r\n')
375 376
376 377 # majority of the following code is duplicated from
377 378 # httplib.HTTPConnection as there are no adequate places to
378 379 # override functions to provide the needed functionality
379 380 res = self.response_class(self.sock,
380 381 strict=self.strict,
381 382 method=self._method)
382 383
383 384 while True:
384 385 version, status, reason = res._read_status()
385 386 if status != httplib.CONTINUE:
386 387 break
387 388 while True:
388 389 skip = res.fp.readline().strip()
389 390 if not skip:
390 391 break
391 392 res.status = status
392 393 res.reason = reason.strip()
393 394
394 395 if res.status == 200:
395 396 while True:
396 397 line = res.fp.readline()
397 398 if line == '\r\n':
398 399 break
399 400 return True
400 401
401 402 if version == 'HTTP/1.0':
402 403 res.version = 10
403 404 elif version.startswith('HTTP/1.'):
404 405 res.version = 11
405 406 elif version == 'HTTP/0.9':
406 407 res.version = 9
407 408 else:
408 409 raise httplib.UnknownProtocol(version)
409 410
410 411 if res.version == 9:
411 412 res.length = None
412 413 res.chunked = 0
413 414 res.will_close = 1
414 415 res.msg = httplib.HTTPMessage(cStringIO.StringIO())
415 416 return False
416 417
417 418 res.msg = httplib.HTTPMessage(res.fp)
418 419 res.msg.fp = None
419 420
420 421 # are we using the chunked-style of transfer encoding?
421 422 trenc = res.msg.getheader('transfer-encoding')
422 423 if trenc and trenc.lower() == "chunked":
423 424 res.chunked = 1
424 425 res.chunk_left = None
425 426 else:
426 427 res.chunked = 0
427 428
428 429 # will the connection close at the end of the response?
429 430 res.will_close = res._check_close()
430 431
431 432 # do we have a Content-Length?
432 433 # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
433 434 length = res.msg.getheader('content-length')
434 435 if length and not res.chunked:
435 436 try:
436 437 res.length = int(length)
437 438 except ValueError:
438 439 res.length = None
439 440 else:
440 441 if res.length < 0: # ignore nonsensical negative lengths
441 442 res.length = None
442 443 else:
443 444 res.length = None
444 445
445 446 # does the body have a fixed length? (of zero)
446 447 if (status == httplib.NO_CONTENT or status == httplib.NOT_MODIFIED or
447 448 100 <= status < 200 or # 1xx codes
448 449 res._method == 'HEAD'):
449 450 res.length = 0
450 451
451 452 # if the connection remains open, and we aren't using chunked, and
452 453 # a content-length was not provided, then assume that the connection
453 454 # WILL close.
454 455 if (not res.will_close and
455 456 not res.chunked and
456 457 res.length is None):
457 458 res.will_close = 1
458 459
459 460 self.proxyres = res
460 461
461 462 return False
462 463
463 464 class httphandler(keepalive.HTTPHandler):
464 465 def http_open(self, req):
465 466 return self.do_open(httpconnection, req)
466 467
467 468 def _start_transaction(self, h, req):
468 469 _generic_start_transaction(self, h, req)
469 470 return keepalive.HTTPHandler._start_transaction(self, h, req)
470 471
471 472 def __del__(self):
472 473 self.close_all()
473 474
474 475 if has_https:
475 476 class BetterHTTPS(httplib.HTTPSConnection):
476 477 send = keepalive.safesend
477 478
478 479 def connect(self):
479 480 if hasattr(self, 'ui'):
480 481 cacerts = self.ui.config('web', 'cacerts')
481 482 else:
482 483 cacerts = None
483 484
484 485 if cacerts:
485 486 sock = _create_connection((self.host, self.port))
486 487 self.sock = _ssl_wrap_socket(sock, self.key_file,
487 488 self.cert_file, cert_reqs=CERT_REQUIRED,
488 489 ca_certs=cacerts)
489 490 self.ui.debug(_('server identity verification succeeded\n'))
490 491 else:
491 492 httplib.HTTPSConnection.connect(self)
492 493
493 494 class httpsconnection(BetterHTTPS):
494 495 response_class = keepalive.HTTPResponse
495 496 # must be able to send big bundle as stream.
496 497 send = _gen_sendfile(BetterHTTPS)
497 498 getresponse = keepalive.wrapgetresponse(httplib.HTTPSConnection)
498 499
499 500 def connect(self):
500 501 if self.realhostport: # use CONNECT proxy
501 502 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
502 503 self.sock.connect((self.host, self.port))
503 504 if _generic_proxytunnel(self):
504 505 self.sock = _ssl_wrap_socket(self.sock, self.cert_file,
505 506 self.key_file)
506 507 else:
507 508 BetterHTTPS.connect(self)
508 509
509 510 class httpshandler(keepalive.KeepAliveHandler, urllib2.HTTPSHandler):
510 511 def __init__(self, ui):
511 512 keepalive.KeepAliveHandler.__init__(self)
512 513 urllib2.HTTPSHandler.__init__(self)
513 514 self.ui = ui
514 515 self.pwmgr = passwordmgr(self.ui)
515 516
516 517 def _start_transaction(self, h, req):
517 518 _generic_start_transaction(self, h, req)
518 519 return keepalive.KeepAliveHandler._start_transaction(self, h, req)
519 520
520 521 def https_open(self, req):
521 522 self.auth = self.pwmgr.readauthtoken(req.get_full_url())
522 523 return self.do_open(self._makeconnection, req)
523 524
524 525 def _makeconnection(self, host, port=None, *args, **kwargs):
525 526 keyfile = None
526 527 certfile = None
527 528
528 529 if len(args) >= 1: # key_file
529 530 keyfile = args[0]
530 531 if len(args) >= 2: # cert_file
531 532 certfile = args[1]
532 533 args = args[2:]
533 534
534 535 # if the user has specified different key/cert files in
535 536 # hgrc, we prefer these
536 537 if self.auth and 'key' in self.auth and 'cert' in self.auth:
537 538 keyfile = self.auth['key']
538 539 certfile = self.auth['cert']
539 540
540 541 conn = httpsconnection(host, port, keyfile, certfile, *args, **kwargs)
541 542 conn.ui = self.ui
542 543 return conn
543 544
544 545 class httpdigestauthhandler(urllib2.HTTPDigestAuthHandler):
545 546 def __init__(self, *args, **kwargs):
546 547 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)
547 548 self.retried_req = None
548 549
549 550 def reset_retry_count(self):
550 551 # Python 2.6.5 will call this on 401 or 407 errors and thus loop
551 552 # forever. We disable reset_retry_count completely and reset in
552 553 # http_error_auth_reqed instead.
553 554 pass
554 555
555 556 def http_error_auth_reqed(self, auth_header, host, req, headers):
556 557 # Reset the retry counter once for each request.
557 558 if req is not self.retried_req:
558 559 self.retried_req = req
559 560 self.retried = 0
560 561 # In python < 2.5 AbstractDigestAuthHandler raises a ValueError if
561 562 # it doesn't know about the auth type requested. This can happen if
562 563 # somebody is using BasicAuth and types a bad password.
563 564 try:
564 565 return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(
565 566 self, auth_header, host, req, headers)
566 567 except ValueError, inst:
567 568 arg = inst.args[0]
568 569 if arg.startswith("AbstractDigestAuthHandler doesn't know "):
569 570 return
570 571 raise
571 572
572 573 def getauthinfo(path):
573 574 scheme, netloc, urlpath, query, frag = urlparse.urlsplit(path)
574 575 if not urlpath:
575 576 urlpath = '/'
576 577 if scheme != 'file':
577 578 # XXX: why are we quoting the path again with some smart
578 579 # heuristic here? Anyway, it cannot be done with file://
579 580 # urls since path encoding is os/fs dependent (see
580 581 # urllib.pathname2url() for details).
581 582 urlpath = quotepath(urlpath)
582 583 host, port, user, passwd = netlocsplit(netloc)
583 584
584 585 # urllib cannot handle URLs with embedded user or passwd
585 586 url = urlparse.urlunsplit((scheme, netlocunsplit(host, port),
586 587 urlpath, query, frag))
587 588 if user:
588 589 netloc = host
589 590 if port:
590 591 netloc += ':' + port
591 592 # Python < 2.4.3 uses only the netloc to search for a password
592 593 authinfo = (None, (url, netloc), user, passwd or '')
593 594 else:
594 595 authinfo = None
595 596 return url, authinfo
596 597
597 598 handlerfuncs = []
598 599
599 600 def opener(ui, authinfo=None):
600 601 '''
601 602 construct an opener suitable for urllib2
602 603 authinfo will be added to the password manager
603 604 '''
604 605 handlers = [httphandler()]
605 606 if has_https:
606 607 handlers.append(httpshandler(ui))
607 608
608 609 handlers.append(proxyhandler(ui))
609 610
610 611 passmgr = passwordmgr(ui)
611 612 if authinfo is not None:
612 613 passmgr.add_password(*authinfo)
613 614 user, passwd = authinfo[2:4]
614 615 ui.debug('http auth: user %s, password %s\n' %
615 616 (user, passwd and '*' * len(passwd) or 'not set'))
616 617
617 618 handlers.extend((urllib2.HTTPBasicAuthHandler(passmgr),
618 619 httpdigestauthhandler(passmgr)))
619 620 handlers.extend([h(ui, passmgr) for h in handlerfuncs])
620 621 opener = urllib2.build_opener(*handlers)
621 622
622 623 # 1.0 here is the _protocol_ version
623 624 opener.addheaders = [('User-agent', 'mercurial/proto-1.0')]
624 625 opener.addheaders.append(('Accept', 'application/mercurial-0.1'))
625 626 return opener
626 627
627 628 scheme_re = re.compile(r'^([a-zA-Z0-9+-.]+)://')
628 629
629 630 def open(ui, url, data=None):
630 631 scheme = None
631 632 m = scheme_re.search(url)
632 633 if m:
633 634 scheme = m.group(1).lower()
634 635 if not scheme:
635 636 path = util.normpath(os.path.abspath(url))
636 637 url = 'file://' + urllib.pathname2url(path)
637 638 authinfo = None
638 639 else:
639 640 url, authinfo = getauthinfo(url)
640 641 return opener(ui, authinfo).open(url, data)
General Comments 0
You need to be logged in to leave comments. Login now