diff --git a/pl_PL.ISO8859-2/books/handbook/boot/chapter.xml b/pl_PL.ISO8859-2/books/handbook/boot/chapter.xml
index 96f10dce02..2e89b1e7cf 100644
--- a/pl_PL.ISO8859-2/books/handbook/boot/chapter.xml
+++ b/pl_PL.ISO8859-2/books/handbook/boot/chapter.xml
@@ -1,814 +1,809 @@
The FreeBSD Booting ProcessSynopsisbootingbootstrapThe process of starting a computer and loading the operating system
is referred to as the bootstrap process, or simply
booting. FreeBSD's boot process provides a great deal of
flexibility in customizing what happens when you start the system,
allowing you to select from different operating systems installed on the
same computer, or even different versions of the same operating system
or installed kernel.This chapter details the configuration options you can set and how
to customize the FreeBSD boot process. This includes everything that
happens until the FreeBSD kernel has started, probed for devices, and
started &man.init.8;. If you are not quite sure when this happens, it
occurs when the text color changes from bright white to grey.After reading this chapter, you will know:What the components of the FreeBSD bootstrap system are, and how
they interact.The options you can give to the components in the FreeBSD
bootstrap to control the boot process.The basics of &man.device.hints.5;.x86 OnlyThis chapter only describes the boot process for FreeBSD running
on Intel x86 systems.The Booting ProblemTurning on a computer and starting the operating system poses an
interesting dilemma. By definition, the computer does not know how to
do anything until the operating system is started. This includes
running programs from the disk. So if the computer can not run a
program from the disk without the operating system, and the operating
system programs are on the disk, how is the operating system
started?This problem parallels one in the book The Adventures of
Baron Munchausen. A character had fallen part way down a
manhole, and pulled himself out by grabbing his bootstraps, and
lifting. In the early days of computing the term
bootstrap was applied to the mechanism used to
load the operating system, which has become shortened to
booting.BIOSBasic Input/Output SystemBIOSOn x86 hardware the Basic Input/Output System (BIOS) is responsible
for loading the operating system. To do this, the BIOS looks on the
hard disk for the Master Boot Record (MBR), which must be located on a
specific place on the disk. The BIOS has enough knowledge to load and
run the MBR, and assumes that the MBR can then carry out the rest of the
tasks involved in loading the operating system,
possibly with the help of the BIOS.Master Boot Record (MBR)Boot ManagerBoot LoaderThe code within the MBR is usually referred to as a boot
manager, especially when it interacts with the user. In this case
the boot manager usually has more code in the first
track of the disk or within some OS's file system. (A
boot manager is sometimes also called a boot loader,
but FreeBSD uses that term for a later stage of booting.) Popular boot
managers include boot0 (a.k.a. Boot
Easy, the standard &os; boot manager),
Grub, GAG, and
LILO.
(Only boot0 fits within the MBR.)If you have only one operating system installed on your disks then
a standard PC MBR will suffice. This MBR searches for the first bootable
(a.k.a. active) slice on the disk, and then runs the code on that slice to
load the remainder of the operating system. The MBR installed by
&man.fdisk.8;, by default, is such an MBR. It is based on
/boot/mbr.If you have installed multiple operating systems on your disks then
you can install a different boot manager, one that can display a list of
different operating systems, and allows you to choose the one to boot
from. Two of these are discussed in the next subsection.The remainder of the FreeBSD bootstrap system is divided into three
stages. The first stage is run by the MBR, which knows just enough to
get the computer into a specific state and run the second stage. The
second stage can do a little bit more, before running the third stage.
The third stage finishes the task of loading the operating system. The
work is split into these three stages because the PC standards put
limits on the size of the programs that can be run at stages one and
two. Chaining the tasks together allows FreeBSD to provide a more
flexible loader.kernelinitThe kernel is then started and it begins to probe for devices
and initialize them for use. Once the kernel boot
process is finished, the kernel passes control to the user process
&man.init.8;, which then makes sure the disks are in a usable state.
&man.init.8; then starts the user-level resource configuration which
mounts file systems, sets up network cards to communicate on the
network, and generally starts all the processes that usually
are run on a FreeBSD system at startup.The Boot Manager and Boot StagesBoot ManagerThe Boot ManagerMaster Boot Record (MBR)The code in the MBR or boot manager is sometimes referred to as
stage zero of the boot process. This subsection
discusses two of the boot managers previously mentioned:
boot0 and LILO.The boot0 Boot Manager:The MBR installed by FreeBSD's installer or &man.boot0cfg.8;, by
default, is based on /boot/boot0.
(The boot0 program is very simple, since the
program in the MBR can only be 446 bytes long because of the slice
table and 0x55AA identifier at the end of the MBR.)
If you have installed boot0 and
multiple operating systems on your hard disks, then you will see a
display similar to this one at boot time:boot0 ScreenshotF1 DOS
F2 FreeBSD
F3 Linux
F4 ??
F5 Drive 1
Default: F2Other operating systems, in particular &windows;, have been known
to overwrite an existing MBR with their own. If this happens to you,
or you want to replace your existing MBR with the FreeBSD MBR then use
the following command:&prompt.root; fdisk -B -b /boot/boot0 devicewhere device is the device that you
boot from, such as ad0 for the first IDE
disk, ad2 for the first IDE disk on a second
IDE controller, da0 for the first SCSI disk,
and so on. Or, if you want a custom configuration of the MBR,
use &man.boot0cfg.8;.The LILO Boot Manager:To install this boot manager so it will also boot FreeBSD, first
start Linux and add the following to your existing
/etc/lilo.conf configuration file:other=/dev/hdXY
table=/dev/hdX
loader=/boot/chain.b
label=FreeBSDIn the above, specify FreeBSD's primary partition and drive using
Linux specifiers, replacing X with the Linux
drive letter and Y with the Linux primary
partition number. If you are using a SCSI drive, you
will need to change /dev/hd to read something
similar to /dev/sd. The
line can be omitted if you have
both operating systems on the same drive. Now run
/sbin/lilo -v to commit your new changes to the
system; this should be verified by checking its screen messages.Stage One, /boot/boot1, and Stage Two,
/boot/boot2Conceptually the first and second stages are part of the same
program, on the same area of the disk. Because of space constraints
they have been split into two, but you would always install them
together. They are copied from the combined file
/boot/boot by the installer or
bsdlabel (see below).They are located outside file systems, in the first track of
the boot slice, starting with the first sector. This is where boot0, or any other boot manager,
expects to find a program to run which will
continue the boot process. The number of sectors used is easily
determined from the size of /boot/boot.boot1 is very simple, since it
can only be 512 bytes
in size, and knows just enough about the FreeBSD
bsdlabel, which stores information
about the slice, to find and execute boot2.boot2 is slightly more sophisticated, and understands
the FreeBSD file system enough to find files on it, and can
provide a simple interface to choose the kernel or loader to
run.Since the loader is
much more sophisticated, and provides a nice easy-to-use
boot configuration, boot2 usually runs
it, but previously it
was tasked to run the kernel directly.boot2 Screenshot>> FreeBSD/i386 BOOT
Default: 0:ad(0,a)/boot/loader
boot:If you ever need to replace the installed
boot1 and boot2 use
&man.bsdlabel.8;:&prompt.root; bsdlabel -B diskslicewhere diskslice is the disk and slice
you boot from, such as ad0s1 for the first
slice on the first IDE disk.Dangerously Dedicated ModeIf you use just the disk name, such as
ad0, in the &man.bsdlabel.8; command you
will create a dangerously dedicated disk, without slices. This is
almost certainly not what you want to do, so make sure you double
check the &man.bsdlabel.8; command before you press
Return.Stage Three, /boot/loaderboot-loaderThe loader is the final stage of the three-stage
bootstrap, and is located on the file system, usually as
/boot/loader.The loader is intended as a user-friendly method for
configuration, using an easy-to-use built-in command set,
backed up by a more powerful interpreter, with a more complex
command set.Loader Program FlowDuring initialization, the loader will probe for a
console and for disks, and figure out what disk it is
booting from. It will set variables accordingly, and an
interpreter is started where user commands can be passed from
a script or interactively.loaderloader configurationThe loader will then read
/boot/loader.rc, which by default reads
in /boot/defaults/loader.conf which
sets reasonable defaults for variables and reads
/boot/loader.conf for local changes to
those variables. loader.rc then acts
on these variables, loading whichever modules and kernel are
selected.Finally, by default, the loader issues a 10 second wait
for key presses, and boots the kernel if it is not interrupted.
If interrupted, the user is presented with a prompt which
understands the easy-to-use command set, where the user may
adjust variables, unload all modules, load modules, and then
finally boot or reboot.Loader Built-In CommandsThese are the most commonly used loader commands. For a
complete discussion of all available commands, please see
&man.loader.8;.autoboot secondsProceeds to boot the kernel if not interrupted
within the time span given, in seconds. It displays a
countdown, and the default time span is 10
seconds.boot
-optionskernelnameImmediately proceeds to boot the kernel, with the
given options, if any, and with the kernel name given,
if it is.boot-confGoes through the same automatic configuration of
modules based on variables as what happens at boot.
This only makes sense if you use
unload first, and change some
variables, most commonly kernel.help
topicShows help messages read from
/boot/loader.help. If the topic
given is index, then the list of
available topics is given.include filename
…Processes the file with the given filename. The
file is read in, and interpreted line by line. An
error immediately stops the include command.load typefilenameLoads the kernel, kernel module, or file of the
type given, with the filename given. Any arguments
after filename are passed to the file.ls pathDisplays a listing of files in the given path, or
the root directory, if the path is not specified. If
is specified, file sizes will be
shown too.lsdev Lists all of the devices from which it may be
possible to load modules. If is
specified, more details are printed.lsmod Displays loaded modules. If is
specified, more details are shown.more filenameDisplays the files specified, with a pause at each
LINES displayed.rebootImmediately reboots the system.set variableset
variable=valueSets the loader's environment variables.unloadRemoves all loaded modules.Loader ExamplesHere are some practical examples of loader usage:
- single-user modeTo simply boot your usual kernel, but in single-user
- mode:
+ mode:single-user modeboot -sTo unload your usual kernel and modules, and then
load just your old (or another) kernel:
-
- kernel.old
-
-
unloadload kernel.oldYou can use kernel.GENERIC to
refer to the generic kernel that comes on the install
- disk, or kernel.old to refer to
+ disk, or kernel.oldkernel.old to refer to
your previously installed kernel (when you have upgraded
or configured your own kernel, for example).Use the following to load your usual modules with
another kernel:unloadset kernel="kernel.old"boot-confTo load a kernel configuration script (an automated
script which does the things you would normally do in the
kernel boot-time configurator):load -t userconfig_script /boot/kernel.confKernel Interaction During Bootkernelboot interactionOnce the kernel is loaded by either loader (as usual) or boot2 (bypassing the loader), it
examines its boot flags, if any, and adjusts its behavior as
necessary.Kernel Boot FlagskernelbootflagsHere are the more common boot flags:during kernel initialization, ask for the device
to mount as the root file system.boot from CDROM.run UserConfig, the boot-time kernel
configuratorboot into single-user modebe more verbose during kernel startupThere are other boot flags, read &man.boot.8; for more
information on them.TomRhodesContributed by Device Hintsdevice.hintsThis is a FreeBSD 5.0 and later feature which does not
exist in earlier versions.During initial system startup, the boot &man.loader.8; will read the
&man.device.hints.5; file. This file stores kernel boot information
known as variables, sometimes referred to as device hints.
These device hints are used by device drivers for device
configuration.Device hints may also be specified at the
Stage 3 boot loader prompt. Variables can be added using
set, removed with unset, and viewed
with the show commands. Variables set in the
/boot/device.hints file can be overridden here also. Device hints entered at
the boot loader are not permanent and will be forgotten on the next
reboot.Once the system is booted, the &man.kenv.1; command can be used to
dump all of the variables.The syntax for the /boot/device.hints file is one variable per line, using
the standard hash # as comment markers. Lines are
constructed as follows:hint.driver.unit.keyword="value"The syntax for the Stage 3 boot loader is:set hint.driver.unit.keyword=valuedriver is the device driver name, unit
is the device driver unit number, and keyword is the hint
keyword. The keyword may consist of the following options:at: specifies the bus which the device is attached to.port: specifies the start address of the I/O
to be used.irq: specifies the interrupt request number to be used.drq: specifies the DMA channel number.maddr: specifies the physical memory address occupied by the
device.flags: sets various flag bits for the device.disabled: if set to 1 the device is disabled.Device drivers may accept (or require) more hints not listed here, viewing
their manual page is recommended. For more information, consult the
&man.device.hints.5;, &man.kenv.1;, &man.loader.conf.5;, and &man.loader.8;
manual pages.Init: Process Control InitializationinitOnce the kernel has finished booting, it passes control to
the user process &man.init.8;, which is located at
/sbin/init, or the program path specified
in the init_path variable in
loader.Automatic Reboot SequenceThe automatic reboot sequence makes sure that the
file systems available on the system are consistent. If they
are not, and &man.fsck.8; cannot fix the
inconsistencies, &man.init.8; drops the system
into single-user mode
for the system administrator to take care of the problems
directly.Single-User Modesingle-user modeconsoleThis mode can be reached through the automatic reboot
sequence, or by the user booting with the
option or setting the
boot_single variable in
loader.It can also be reached by calling
&man.shutdown.8; without the reboot
() or halt () options,
from multi-user
mode.If the system console is set
to insecure in /etc/ttys,
then the system prompts for the root password
before initiating single-user mode.An Insecure Console in /etc/ttys# name getty type status comments
#
# If console is marked "insecure", then init will ask for the root password
# when going to single-user mode.
console none unknown off insecureAn insecure console means that you
consider your physical security to the console to be
insecure, and want to make sure only someone who knows the
root password may use single-user mode, and it
does not mean that you want to run your console insecurely. Thus,
if you want security, choose insecure,
not secure.Multi-User Modemulti-user modeIf &man.init.8; finds your file systems to be
in order, or once the user has finished in single-user mode, the
system enters multi-user mode, in which it starts the
resource configuration of the system.Resource Configuration (rc)rc filesThe resource configuration system reads in
configuration defaults from
/etc/defaults/rc.conf, and
system-specific details from
/etc/rc.conf, and then proceeds to
mount the system file systems mentioned in
/etc/fstab, start up networking
services, start up miscellaneous system daemons, and
finally runs the startup scripts of locally installed
packages.The &man.rc.8; manual page is a good reference to the resource
configuration system, as is examining the scripts
themselves.Shutdown SequenceshutdownUpon controlled shutdown, via &man.shutdown.8;,
&man.init.8; will attempt to run the script
/etc/rc.shutdown, and then proceed to send
all processes the TERM signal, and subsequently
the KILL signal to any that do not terminate
timely.To power down a FreeBSD machine on architectures and systems
that support power management, simply use the command
shutdown -p now to turn the power off
immediately. To just reboot a FreeBSD system, just use
shutdown -r now. You need to be
root or a member of
operator group to run &man.shutdown.8;.
The &man.halt.8; and &man.reboot.8; commands can also be used,
please refer to their manual pages and to &man.shutdown.8;'s one
for more information.Power management requires &man.acpi.4; support in the kernel
or loaded as module for.
diff --git a/pl_PL.ISO8859-2/books/handbook/cutting-edge/chapter.xml b/pl_PL.ISO8859-2/books/handbook/cutting-edge/chapter.xml
index 09b01dd660..c0f83bd4fd 100644
--- a/pl_PL.ISO8859-2/books/handbook/cutting-edge/chapter.xml
+++ b/pl_PL.ISO8859-2/books/handbook/cutting-edge/chapter.xml
@@ -1,1726 +1,1676 @@
JimMockRestructured, reorganized, and parts updated by JordanHubbardOriginal work by Poul-HenningKampJohnPolstraNikClaytonThe Cutting EdgeSynopsis&os; is under constant development between releases. For
people who want to be on the cutting edge, there are several easy
mechanisms for keeping your system in sync with the latest
developments. Be warned—the cutting edge is not for everyone!
This chapter will help you decide if you want to track the
development system, or stick with one of the released
versions.After reading this chapter, you will know:The difference between the two development
branches: &os.stable; and &os.current;.How to keep your system up to date with
CVSup,
CVS, or
CTM.How to rebuild and reinstall the entire base
system with make buildworld (etc).Before reading this chapter, you should:Properly set up your network connection ().Know how to install additional third-party
software ().&os.current; vs. &os.stable;-CURRENT-STABLEThere are two development branches to FreeBSD: &os.current; and
&os.stable;. This section will explain a bit about each and describe
how to keep your system up-to-date with each respective tree.
&os.current; will be discussed first, then &os.stable;.Staying Current with &os;As you read this, keep in mind that &os.current; is the
bleeding edge of &os; development.
&os.current; users are expected to have a high degree of
technical skill, and should be capable of solving difficult
system problems on their own. If you are new to &os;, think
twice before installing it. What Is &os.current;?snapshot&os.current; is the latest working sources for &os;.
This includes work in progress, experimental changes, and
transitional mechanisms that might or might not be present
in the next official release of the software. While many
&os; developers compile the &os.current; source code daily,
there are periods of time when the sources are not
buildable. These problems are resolved as expeditiously as
possible, but whether or not &os.current; brings disaster or
greatly desired functionality can be a matter of which exact
moment you grabbed the source code in!Who Needs &os.current;?&os.current; is made available for 3 primary
interest groups:Members of the &os; community who are actively working
on some part of the source tree and for whom keeping
current is an absolute
requirement.Members of the &os; community who are active testers,
willing to spend time solving problems in order to
ensure that &os.current; remains as sane as possible.
These are also people who wish to make topical
suggestions on changes and the general direction of
&os;, and submit patches to implement them.Those who merely wish to keep an eye on things, or
to use the current sources for reference purposes
(e.g. for reading, not running).
These people also make the occasional comment or
contribute code.What Is &os.current; Not?A fast-track to getting pre-release bits because you
heard there is some cool new feature in there and you
want to be the first on your block to have it. Being
the first on the block to get the new feature means that
you are the first on the block to get the new
bugs.A quick way of getting bug fixes. Any given version
of &os.current; is just as likely to introduce new bugs
as to fix existing ones.In any way officially supported. We
do our best to help people genuinely in one of the 3
legitimate &os.current; groups, but we
simply do not have the time to
provide tech support. This is not because we are mean
and nasty people who do not like helping people out (we
would not even be doing &os; if we were). We simply
cannot answer hundreds messages a day
and work on FreeBSD! Given the
choice between improving &os; and answering lots of
questions on experimental code, the developers opt for
the former.Using &os.current;
-
- -CURRENT
- using
-
- Join the &a.current.name; and the &a.cvsall.name; lists. This is not
+ Join the &a.current.name;-CURRENTusing and the &a.cvsall.name; lists. This is not
just a good idea, it is essential. If
you are not on the &a.current.name; list,
you will not see the comments that people are
making about the current state of the system and thus will
probably end up stumbling over a lot of problems that others
have already found and solved. Even more importantly, you
will miss out on important bulletins which may be critical
to your system's continued health.The &a.cvsall.name; list will allow you to see the
commit log entry for each change as it is made along with
any pertinent information on possible side-effects.To join these lists, or one of the others available
go to &a.mailman.lists.link; and click on the list that
you wish to subscribe to. Instructions on the rest of
the procedure are available there.Grab the sources from a &os; mirror
site. You can do this in one of two ways:
-
- cvsup
-
-
- cron
-
-
- -CURRENT
- Syncing with CVSup
-
-
- Use the cvsup program
+ Use the cvsupcvsup program
with the supfile named standard-supfile
available from /usr/share/examples/cvsup.
This is the most recommended
method, since it allows you to grab the entire
collection once and then only what has changed from then
on. Many people run cvsup from
- cron and keep their
+ croncron and keep their
sources up-to-date automatically. You have to
customize the sample supfile above, and configure
- cvsup for your environment.
+ cvsup-CURRENTSyncing with CVSup for your environment.
-
- -CURRENT
- Syncing with CTM
-
-
Use the CTM facility. If you
+ linkend="ctm">CTM-CURRENTSyncing with CTM facility. If you
have very bad connectivity (high price connections or
only email access) CTM is an option.
However, it is a lot of hassle and can give you broken files.
This leads to it being rarely used, which again increases
the chance of it not working for fairly long periods of
time. We recommend using
CVSup
for anybody with a 9600 bps modem or faster connection.
If you are grabbing the sources to run, and not just
look at, then grab all of &os.current;, not
just selected portions. The reason for this is that various
parts of the source depend on updates elsewhere, and trying
to compile just a subset is almost guaranteed to get you
into trouble.
-
- -CURRENT
- compiling
-
- Before compiling &os.current;, read the
+ Before compiling &os.current;-CURRENTcompiling, read the
Makefile in /usr/src
carefully. You should at least install a new kernel and rebuild the world the first time through
as part of the upgrading process. Reading the &a.current;
and /usr/src/UPDATING will keep you up-to-date on other bootstrapping procedures
that sometimes become necessary as we move toward the next
release.Be active! If you are running &os.current;, we want
to know what you have to say about it, especially if you
have suggestions for enhancements or bug fixes. Suggestions
with accompanying code are received most
enthusiastically!Staying Stable with &os;What Is &os.stable;?-STABLE&os.stable; is our development branch from which major releases
are made. Changes go into this branch at a different pace, and
with the general assumption that they have first gone into
&os.current; for testing. This is still
a development branch, however, and this means that at any given time,
the sources for &os.stable; may or may not be suitable for any
particular purpose. It is simply another engineering development
track, not a resource for end-users.Who Needs &os.stable;?If you are interested in tracking or contributing to the
FreeBSD development process, especially as it relates to the
next point release of FreeBSD, then you should
consider following &os.stable;.While it is true that security fixes also go into the
&os.stable; branch, you do not need to
track &os.stable; to do this. Every security advisory for
FreeBSD explains how to fix the problem for the releases it
affects
That is not quite true. We can not continue to
support old releases of FreeBSD forever, although we do
support them for many years. For a complete description
of the current security policy for old releases of
FreeBSD, please see http://www.FreeBSD.org/security/.
, and tracking an entire development branch just
for security reasons is likely to bring in a lot of unwanted
changes as well.Although we endeavor to ensure that the &os.stable; branch
compiles and runs at all times, this cannot be guaranteed. In
addition, while code is developed in &os.current; before including
it in &os.stable;, more people run &os.stable; than &os.current;, so
it is inevitable that bugs and corner cases will sometimes be found
in &os.stable; that were not apparent in &os.current;.For these reasons, we do not recommend that
you blindly track &os.stable;, and it is particularly important that
you do not update any production servers to &os.stable; without
first thoroughly testing the code in your development
environment.If you do not have the resources to do this then we recommend
that you run the most recent release of FreeBSD, and use the binary
update mechanism to move from release to release.Using &os.stable;
-
- -STABLE
- using
-
-
- Join the &a.stable.name; list. This will keep you informed of
+ Join the &a.stable.name;-STABLEusing list. This will keep you informed of
build-dependencies that may appear in &os.stable;
or any other issues requiring
special attention. Developers will also make announcements
in this mailing list when they are contemplating some
controversial fix or update, giving the users a chance to
respond if they have any issues to raise concerning the
proposed change.The &a.cvsall.name; list will allow you to see the
commit log entry for each change as it is made along with
any pertinent information on possible side-effects.To join these lists, or one of the others available
go to &a.mailman.lists.link; and click on the list that
you wish to subscribe to. Instructions on the rest of
the procedure are available there.If you are going to install a new system and want it
to run monthly snapshot built from &os.stable;, please
check the
Snapshots web page for more information.
Alternatively, it is possible to
install the most recent &os.stable; release from the
mirror sites and follow
the instructions below to upgrade your system to the
most up to date &os.stable; source code.If you are already running a previous release of &os;
and wish to upgrade via sources then you can easily do so
from &os; mirror site. This can
be done in one of two ways:
-
- cvsup
-
-
- cron
-
-
- -STABLE
- syncing with CVSup
-
-
- Use the cvsup program
+ Use the cvsupcvsup program
with the supfile named stable-supfile
from the directory
/usr/share/examples/cvsup.
This is the most recommended
method, since it allows you to grab the entire
collection once and then only what has changed from then
on. Many people run cvsup from
- cron to keep their
+ croncron to keep their
sources up-to-date automatically. You have to
customize the sample supfile above,
- and configure cvsup for your
+ and configure cvsup-STABLEsyncing with CVSup for your
environment.
-
- -STABLE
- syncing with CTM
-
-
Use the CTM facility. If
+ linkend="ctm">CTM-STABLEsyncing with CTM facility. If
you do not have a fast and inexpensive connection to
the Internet, this is the method you should consider
using.
Essentially, if you need rapid on-demand access to the
source and communications bandwidth is not a consideration,
use cvsup or ftp.
Otherwise, use CTM.
-
- -STABLE
- compiling
-
-
- Before compiling &os.stable;, read the
+ Before compiling &os.stable;-STABLEcompiling, read the
Makefile in /usr/src
carefully. You should at least install a new kernel and rebuild the world the first time through
as part of the upgrading process. Reading the &a.stable; and /usr/src/UPDATING will
keep you up-to-date on other bootstrapping procedures that
sometimes become necessary as we move toward the next
release.Synchronizing Your SourceThere are various ways of using an Internet (or email)
connection to stay up-to-date with any given area of the &os;
project sources, or all areas, depending on what interests you. The
primary services we offer are Anonymous
CVS, CVSup, and CTM.While it is possible to update only parts of your source tree,
the only supported update procedure is to update the entire tree
and recompile both userland (i.e., all the programs that run in
user space, such as those in /bin and
/sbin) and kernel sources. Updating only part
of your source tree, only the kernel, or only userland will often
result in problems. These problems may range from compile errors
to kernel panics or data corruption.CVSanonymousAnonymous CVS and
CVSup use the pull
model of updating sources. In the case of
CVSup the user (or a
cron script) invokes
the cvsup program, and it interacts with a
cvsupd server somewhere to bring your files
up-to-date. The updates you receive are up-to-the-minute and you
get them when, and only when, you want them. You can easily
restrict your updates to the specific files or directories that are
of interest to you. Updates are generated on the fly by the server,
according to what you have and what you want to have.
Anonymous CVS is quite a bit more
simplistic than CVSup in that it is just an extension to
CVS which allows it to pull changes
directly from a remote CVS repository.
CVSup can do this far more efficiently,
but Anonymous CVS is easier to
use.CTMCTM, on the other hand, does not
interactively compare the sources you have with those on the master
archive or otherwise pull them across. Instead, a script which
identifies changes in files since its previous run is executed
several times a day on the master CTM machine, any detected changes
being compressed, stamped with a sequence-number and encoded for
transmission over email (in printable ASCII only). Once received,
these CTM deltas can then be handed to the
&man.ctm.rmail.1; utility which will automatically decode, verify
and apply the changes to the user's copy of the sources. This
process is far more efficient than CVSup,
and places less strain on our server resources since it is a
push rather than a pull
model.There are other trade-offs, of course. If you inadvertently
wipe out portions of your archive, CVSup
will detect and rebuild the damaged portions for you.
CTM will not do this, and if you wipe some
portion of your source tree out (and do not have it backed up) then
you will have to start from scratch (from the most recent CVS
base delta) and rebuild it all with CTM or, with
Anonymous CVS, simply delete the bad bits and resync.Rebuilding worldRebuilding worldOnce you have synchronized your local source tree against a
particular version of &os; (&os.stable;, &os.current;, and so on)
you can then use the source
tree to rebuild the system.Make a BackupIt cannot be stressed enough how important it is to make a
backup of your system before you do this.
While rebuilding the world is (as long as you follow these
instructions) an easy task to do, there will inevitably be times
when you make mistakes, or when mistakes made by others in the
source tree render your system unbootable.Make sure you have taken a backup. And have a fixit floppy or
bootable CD at
hand. You will probably never have to use it, but it is better to be
safe than sorry!Subscribe to the Right Mailing Listmailing listThe &os.stable; and &os.current; branches are, by their
nature, in development. People that
contribute to &os; are human, and mistakes occasionally
happen.Sometimes these mistakes can be quite harmless, just causing
your system to print a new diagnostic warning. Or the change may
be catastrophic, and render your system unbootable or destroy your
file systems (or worse).If problems like these occur, a heads up is
posted to the appropriate mailing list, explaining the nature of
the problem and which systems it affects. And an all
clear announcement is posted when the problem has been
solved.If you try to track &os.stable; or &os.current; and do
not read the &a.stable; or the
&a.current; respectively, then you are
asking for trouble.Do not use make worldA lot of older documentation recommends using
make world for this. Doing that skips
some important steps and should only be used if you are
sure of what you are doing. For almost all circumstances
make world is the wrong thing to do, and
the procedure described here should be used instead.The Canonical Way to Update Your SystemTo update your system, you should check
/usr/src/UPDATING for any pre-buildworld steps
necessary for your version of the sources and then use the following
procedure:&prompt.root; make buildworld
&prompt.root; make buildkernel
&prompt.root; make installkernel
&prompt.root; rebootThere are a few rare cases when an extra run of
mergemaster -p is needed before the
buildworld step. These are
described in UPDATING. In general,
though, you can safely omit this step if you are not
updating across one or more major &os; versions.After installkernel finishes
successfully, you should boot in single user mode
(i.e. using boot -s from the loader
prompt). Then run:&prompt.root; mergemaster -p
&prompt.root; make installworld
&prompt.root; mergemaster
&prompt.root; rebootRead Further ExplanationsThe sequence described above is only a short resume to
help you getting started. You should however read the
following sections to clearly understand each step, especially
if you want to use a custom kernel configuration.Read /usr/src/UPDATINGBefore you do anything else, read
/usr/src/UPDATING (or the equivalent file
wherever you have a copy of the source code). This file should
contain important information about problems you might encounter, or
specify the order in which you might have to run certain commands.
If UPDATING contradicts something you read here,
UPDATING takes precedence.Reading UPDATING is not an acceptable
substitute for subscribing to the correct mailing list, as described
previously. The two requirements are complementary, not
exclusive.Check /etc/make.confmake.confExamine the files
/usr/share/examples/etc/make.conf
and
/etc/make.conf. The first contains some
default defines – most of which are commented out. To
make use of them when you rebuild your system from source, add
them to /etc/make.conf. Keep in mind that
anything you add to /etc/make.conf is also
used every time you run make, so it is a good
idea to set them to something sensible for your system.A typical user will probably want to copy the
CFLAGS and
NO_PROFILE lines found in
/usr/share/examples/etc/make.conf
to
/etc/make.conf and uncomment them.Examine the other definitions (COPTFLAGS,
NOPORTDOCS and so
on) and decide if they are relevant to you.Update the Files in /etcThe /etc directory contains a large part
of your system's configuration information, as well as scripts
that are run at system startup. Some of these scripts change from
version to version of FreeBSD.Some of the configuration files are also used in the day to
day running of the system. In particular,
/etc/group.There have been occasions when the installation part of
make installworld has expected certain usernames or groups
to exist. When performing an upgrade it is likely that these
users or groups did not exist. This caused problems when upgrading.
In some cases make buildworld will check to see if
these users or groups exist.An example of this is when the
smmsp user was added. Users had the
installation process fail for them when
&man.mtree.8; was trying to create
/var/spool/clientmqueue.The solution is to run &man.mergemaster.8; in
pre-buildworld mode by providing the option.
This will compare only those files that are essential for the success
of buildworld or
installworld. If your old version of
mergemaster does not support ,
use the new version in the source tree when running for the first
time:&prompt.root; cd /usr/src/usr.sbin/mergemaster
&prompt.root; ./mergemaster.sh -pIf you are feeling particularly paranoid, you can check your
system to see which files are owned by the group you are
renaming or deleting:&prompt.root; find / -group GID -printwill show all files owned by group
GID (which can be either a group name
or a numeric group ID).Drop to Single User Modesingle-user modeYou may want to compile the system in single user mode. Apart
from the obvious benefit of making things go slightly faster,
reinstalling the system will touch a lot of important system
files, all the standard system binaries, libraries, include files
and so on. Changing these on a running system (particularly if
you have active users on the system at the time) is asking for
trouble.multi-user modeAnother method is to compile the system in multi-user mode, and
then drop into single user mode for the installation. If you would
like to do it this way, simply hold off on the following steps until
the build has completed. You can postpone dropping to single user
mode until you have to installkernel or
installworld.As the superuser, you can execute:&prompt.root; shutdown nowfrom a running system, which will drop it to single user
mode.Alternatively, reboot the system, and at the boot prompt,
select the single user option. The system will then boot
single user. At the shell prompt you should then run:&prompt.root; fsck -p
&prompt.root; mount -u /
&prompt.root; mount -a -t ufs
&prompt.root; swapon -aThis checks the file systems, remounts /
read/write, mounts all the other UFS file systems referenced in
/etc/fstab and then turns swapping on.If your CMOS clock is set to local time and not to GMT
(this is true if the output of the &man.date.1; command
does not show the correct time and zone),
you may also need to run the following command:&prompt.root; adjkerntz -iThis will make sure that your local time-zone settings
get set up correctly — without this, you may later run into some
problems.
Remove /usr/objAs parts of the system are rebuilt they are placed in
directories which (by default) go under
/usr/obj. The directories shadow those under
/usr/src.You can speed up the make buildworld process, and
possibly save yourself some dependency headaches by removing this
directory as well.Some files below /usr/obj may have the
immutable flag set (see &man.chflags.1; for more information)
which must be removed first.&prompt.root; cd /usr/obj
&prompt.root; chflags -R noschg *
&prompt.root; rm -rf *Recompile the Base SystemSaving the OutputIt is a good idea to save the output you get from running
&man.make.1; to another file. If something goes wrong you will
have a copy of the error message. While this might not help you
in diagnosing what has gone wrong, it can help others if you post
your problem to one of the &os; mailing lists.The easiest way to do this is to use the &man.script.1;
command, with a parameter that specifies the name of the file to
save all output to. You would do this immediately before
rebuilding the world, and then type exit
when the process has finished.&prompt.root; script /var/tmp/mw.out
Script started, output file is /var/tmp/mw.out
&prompt.root; make TARGET… compile, compile, compile …
&prompt.root; exit
Script done, …If you do this, do not save the output
in /tmp. This directory may be cleared
next time you reboot. A better place to store it is in
/var/tmp (as in the previous example) or
in root's home directory.Compile the Base SystemYou must be in the /usr/src
directory:&prompt.root; cd /usr/src(unless, of course, your source code is elsewhere, in which
case change to that directory instead).makeTo rebuild the world you use the &man.make.1; command. This
command reads instructions from the Makefile,
which describes how the programs that comprise &os; should be
rebuilt, the order in which they should be built, and so on.The general format of the command line you will type is as
follows:&prompt.root; make -x -DVARIABLEtargetIn this example,
is an option that you would pass to &man.make.1;. See the
&man.make.1; manual page for an example of the options you can
pass.
passes a variable to the Makefile. The
behavior of the Makefile is controlled by
these variables. These are the same variables as are set in
/etc/make.conf, and this provides another
way of setting them.&prompt.root; make -DNO_PROFILE targetis another way of specifying that profiled libraries should
not be built, and corresponds with theNO_PROFILE= true # Avoid compiling profiled librariesline in /etc/make.conf.target tells &man.make.1; what
you want to do. Each Makefile defines a
number of different targets, and your choice of
target determines what happens.Some targets are listed in the
Makefile, but are not meant for you to run.
Instead, they are used by the build process to break out the
steps necessary to rebuild the system into a number of
sub-steps.Most of the time you will not need to pass any parameters to
&man.make.1;, and so your command like will look like
this:&prompt.root; make targetWhere target will be one of
many build options. The first target should always be
buildworld.As the names imply, buildworld
builds a complete new tree under /usr/obj,
and installworld, another target, installs this tree on
the current machine.Having separate options is very useful for two reasons. First, it allows you
to do the build safe in the knowledge that no components of
your running system will be affected. The build is
self hosted. Because of this, you can safely
run buildworld on a machine running
in multi-user mode with no fear of ill-effects. It is still
recommended that you run the
installworld part in single user
mode, though.Secondly, it allows you to use NFS mounts to upgrade
multiple machines on your network. If you have three machines,
A, B and C that you want to upgrade, run make
buildworld and make installworld on
A. B and C should then NFS mount /usr/src
and /usr/obj from A, and you can then run
make installworld to install the results of
the build on B and C.Although the world target still exists,
you are strongly encouraged not to use it.Run&prompt.root; make buildworldIt is possible to specify a option to
make which will cause it to spawn several
simultaneous processes. This is most useful on multi-CPU machines.
However, since much of the compiling process is IO bound rather
than CPU bound it is also useful on single CPU machines.On a typical single-CPU machine you would run:&prompt.root; make -j4 buildworld&man.make.1; will then have up to 4 processes running at any one
time. Empirical evidence posted to the mailing lists shows this
generally gives the best performance benefit.If you have a multi-CPU machine and you are using an SMP
configured kernel try values between 6 and 10 and see how they speed
things up.Timingsrebuilding worldtimingsMany factors influence the build time, but fairly recent
machines may only take a one or two hours to build
the &os.stable; tree, with no tricks or shortcuts used during the
process. A &os.current; tree will take somewhat longer.Compile and Install a New KernelkernelcompilingTo take full advantage of your new system you should recompile the
kernel. This is practically a necessity, as certain memory structures
may have changed, and programs like &man.ps.1; and &man.top.1; will
fail to work until the kernel and source code versions are the
same.The simplest, safest way to do this is to build and install a
kernel based on GENERIC. While
GENERIC may not have all the necessary devices
for your system, it should contain everything necessary to boot your
system back to single user mode. This is a good test that the new
system works properly. After booting from
GENERIC and verifying that your system works you
can then build a new kernel based on your normal kernel configuration
file.On &os; it is important to build world before building a
new kernel.If you want to build a custom kernel, and already have a configuration
file, just use KERNCONF=MYKERNEL
like this:&prompt.root; cd /usr/src
&prompt.root; make buildkernel KERNCONF=MYKERNEL
&prompt.root; make installkernel KERNCONF=MYKERNELNote that if you have raised kern.securelevel
above 1 and you have set either the
noschg or similar flags to your kernel binary, you
might find it necessary to drop into single user mode to use
installkernel. Otherwise you should be able
to run both these commands from multi user mode without
problems. See &man.init.8; for details about
kern.securelevel and &man.chflags.1; for details
about the various file flags.Reboot into Single User Modesingle-user modeYou should reboot into single user mode to test the new kernel
works. Do this by following the instructions in
.Install the New System BinariesIf you were building a version of &os; recent enough to have
used make buildworld then you should now use
installworld to install the new system
binaries.Run&prompt.root; cd /usr/src
&prompt.root; make installworldIf you specified variables on the make
buildworld command line, you must specify the same
variables in the make installworld command
line. This does not necessarily hold true for other options;
for example, must never be used with
installworld.For example, if you ran:&prompt.root; make -DNO_PROFILE buildworldyou must install the results with:&prompt.root; make -DNO_PROFILE installworldotherwise it would try to install profiled libraries that
had not been built during the make buildworld
phase.Update Files Not Updated by make installworldRemaking the world will not update certain directories (in
particular, /etc, /var and
/usr) with new or changed configuration files.The simplest way to update these files is to use
&man.mergemaster.8;, though it is possible to do it manually
if you would prefer to do that. Regardless of which way you
choose, be sure to make a backup of /etc in
case anything goes wrong.TomRhodesContributed by mergemastermergemasterThe &man.mergemaster.8; utility is a Bourne script that will
aid you in determining the differences between your configuration files
in /etc, and the configuration files in
the source tree /usr/src/etc. This is
the recommended solution for keeping the system configuration files up to date
with those located in the source tree.To begin simply type mergemaster at your prompt, and
watch it start going. mergemaster will then build a
temporary root environment, from / down, and populate
it with various system configuration files. Those files are then compared
to the ones currently installed in your system. At this point, files that
differ will be shown in &man.diff.1; format, with the sign
representing added or modified lines, and representing
lines that will be either removed completely, or replaced with a new line.
See the &man.diff.1; manual page for more information about the &man.diff.1;
syntax and how file differences are shown.&man.mergemaster.8; will then show you each file that displays variances,
and at this point you will have the option of either deleting the new file (referred
to as the temporary file), installing the temporary file in its unmodified state,
merging the temporary file with the currently installed file, or viewing the
&man.diff.1; results again.Choosing to delete the temporary file will tell &man.mergemaster.8; that we
wish to keep our current file unchanged, and to delete the new version.
This option is not recommended, unless you see no
reason to change the current file. You can get help at any time by
typing ? at the &man.mergemaster.8; prompt. If the user
chooses to skip a file, it will be presented again after all other files
have been dealt with.Choosing to install the unmodified temporary file will replace the
current file with the new one. For most unmodified files, this is the best
option.Choosing to merge the file will present you with a text editor,
and the contents of both files. You can now merge them by
reviewing both files side by side on the screen, and choosing parts from
both to create a finished product. When the files are compared side by side,
the l key will select the left contents and the
r key will select contents from your right.
The final output will be a file consisting of both parts, which can then be
installed. This option is customarily used for files where settings have been
modified by the user.Choosing to view the &man.diff.1; results again will show you the file differences
just like &man.mergemaster.8; did before prompting you for an option.After &man.mergemaster.8; is done with the system files you will be
prompted for other options. &man.mergemaster.8; may ask if you want to rebuild
the password file and will finish up with an option to
remove left-over temporary files.Manual UpdateIf you wish to do the update manually, however,
you cannot just copy over the files from
/usr/src/etc to /etc and
have it work. Some of these files must be installed
first. This is because the /usr/src/etc
directory is not a copy of what your
/etc directory should look like. In addition,
there are files that should be in /etc that are
not in /usr/src/etc.If you are using &man.mergemaster.8; (as recommended),
you can skip forward to the next
section.The simplest way to do this by hand is to install the
files into a new directory, and then work through them looking
for differences.Backup Your Existing /etcAlthough, in theory, nothing is going to touch this directory
automatically, it is always better to be sure. So copy your
existing /etc directory somewhere safe.
Something like:&prompt.root; cp -Rp /etc /etc.old does a recursive copy,
preserves times, ownerships on files and suchlike.You need to build a dummy set of directories to install the new
/etc and other files into.
/var/tmp/root is a reasonable choice, and
there are a number of subdirectories required under this as
well.&prompt.root; mkdir /var/tmp/root
&prompt.root; cd /usr/src/etc
&prompt.root; make DESTDIR=/var/tmp/root distrib-dirs distributionThis will build the necessary directory structure and install the
files. A lot of the subdirectories that have been created under
/var/tmp/root are empty and should be deleted.
The simplest way to do this is to:&prompt.root; cd /var/tmp/root
&prompt.root; find -d . -type d | xargs rmdir 2>/dev/nullThis will remove all empty directories. (Standard error is
redirected to /dev/null to prevent the warnings
about the directories that are not empty.)/var/tmp/root now contains all the files that
should be placed in appropriate locations below
/. You now have to go through each of these
files, determining how they differ with your existing files.Note that some of the files that will have been installed in
/var/tmp/root have a leading .. At the
time of writing the only files like this are shell startup files in
/var/tmp/root/ and
/var/tmp/root/root/, although there may be others
(depending on when you are reading this). Make sure you use
ls -a to catch them.The simplest way to do this is to use &man.diff.1; to compare the
two files:&prompt.root; diff /etc/shells /var/tmp/root/etc/shellsThis will show you the differences between your
/etc/shells file and the new
/var/tmp/root/etc/shells file. Use these to decide whether to
merge in changes that you have made or whether to copy over your old
file.Name the New Root Directory
(/var/tmp/root) with a Time Stamp, so You Can
Easily Compare Differences Between VersionsFrequently rebuilding the world means that you have to update
/etc frequently as well, which can be a bit of
a chore.You can speed this process up by keeping a copy of the last set
of changed files that you merged into /etc.
The following procedure gives one idea of how to do this.Make the world as normal. When you want to update
/etc and the other directories, give the
target directory a name based on the current date. If you were
doing this on the 14th of February 1998 you could do the
following:&prompt.root; mkdir /var/tmp/root-19980214
&prompt.root; cd /usr/src/etc
&prompt.root; make DESTDIR=/var/tmp/root-19980214 \
distrib-dirs distributionMerge in the changes from this directory as outlined
above.Do not remove the
/var/tmp/root-19980214 directory when you
have finished.When you have downloaded the latest version of the source
and remade it, follow step 1. This will give you a new
directory, which might be called
/var/tmp/root-19980221 (if you wait a week
between doing updates).You can now see the differences that have been made in the
intervening week using &man.diff.1; to create a recursive diff
between the two directories:&prompt.root; cd /var/tmp
&prompt.root; diff -r root-19980214 root-19980221Typically, this will be a much smaller set of differences
than those between
/var/tmp/root-19980221/etc and
/etc. Because the set of differences is
smaller, it is easier to migrate those changes across into your
/etc directory.You can now remove the older of the two
/var/tmp/root-* directories:&prompt.root; rm -rf /var/tmp/root-19980214Repeat this process every time you need to merge in changes
to /etc.You can use &man.date.1; to automate the generation of the
directory names:&prompt.root; mkdir /var/tmp/root-`date "+%Y%m%d"`RebootingYou are now done. After you have verified that everything appears
to be in the right place you can reboot the system. A simple
&man.shutdown.8; should do it:&prompt.root; shutdown -r nowFinishedYou should now have successfully upgraded your &os; system.
Congratulations.If things went slightly wrong, it is easy to rebuild a particular
piece of the system. For example, if you accidentally deleted
/etc/magic as part of the upgrade or merge of
/etc, the &man.file.1; command will stop working.
In this case, the fix would be to run:&prompt.root; cd /usr/src/usr.bin/file
&prompt.root; make all installQuestionsDo I need to re-make the world for every change?There is no easy answer to this one, as it depends on the
nature of the change. For example, if you just ran CVSup, and
it has shown the following files as being updated:src/games/cribbage/instr.csrc/games/sail/pl_main.csrc/release/sysinstall/config.csrc/release/sysinstall/media.csrc/share/mk/bsd.port.mkit probably is not worth rebuilding the entire world.
You could just go to the appropriate sub-directories and
make all install, and that's about it. But
if something major changed, for example
src/lib/libc/stdlib then you should either
re-make the world, or at least those parts of it that are
statically linked (as well as anything else you might have added
that is statically linked).At the end of the day, it is your call. You might be happy
re-making the world every fortnight say, and let changes
accumulate over that fortnight. Or you might want to re-make
just those things that have changed, and be confident you can
spot all the dependencies.And, of course, this all depends on how often you want to
upgrade, and whether you are tracking &os.stable; or
&os.current;.My compile failed with lots of signal 11signal 11 (or other signal
number) errors. What has happened?This is normally indicative of hardware problems.
(Re)making the world is an effective way to stress test your
hardware, and will frequently throw up memory problems. These
normally manifest themselves as the compiler mysteriously dying
on receipt of strange signals.A sure indicator of this is if you can restart the make and
it dies at a different point in the process.In this instance there is little you can do except start
swapping around the components in your machine to determine
which one is failing.Can I remove /usr/obj when I have
finished?The short answer is yes./usr/obj contains all the object files
that were produced during the compilation phase. Normally, one
of the first steps in the make buildworld process is to
remove this directory and start afresh. In this case, keeping
/usr/obj around after you have finished
makes little sense, and will free up a large chunk of disk space
(currently about 340 MB).However, if you know what you are doing you can have
make buildworld skip this step. This will make subsequent
builds run much faster, since most of sources will not need to
be recompiled. The flip side of this is that subtle dependency
problems can creep in, causing your build to fail in odd ways.
This frequently generates noise on the &os; mailing lists,
when one person complains that their build has failed, not
realizing that it is because they have tried to cut
corners.Can interrupted builds be resumed?This depends on how far through the process you got before
you found a problem.In general (and this is not a hard and
fast rule) the make buildworld process builds new
copies of essential tools (such as &man.gcc.1;, and
&man.make.1;) and the system libraries. These tools and
libraries are then installed. The new tools and libraries are
then used to rebuild themselves, and are installed again. The
entire system (now including regular user programs, such as
&man.ls.1; or &man.grep.1;) is then rebuilt with the new
system files.If you are at the last stage, and you know it (because you
have looked through the output that you were storing) then you
can (fairly safely) do:… fix the problem …
&prompt.root; cd /usr/src
&prompt.root; make -DNO_CLEAN allThis will not undo the work of the previous
make buildworld.If you see the message:--------------------------------------------------------------
Building everything..
--------------------------------------------------------------in the make buildworld output then it is
probably fairly safe to do so.If you do not see that message, or you are not sure, then it
is always better to be safe than sorry, and restart the build
from scratch.How can I speed up making the world?Run in single user mode.Put the /usr/src and
/usr/obj directories on separate
file systems held on separate disks. If possible, put these
disks on separate disk controllers.Better still, put these file systems across multiple
disks using the &man.ccd.4; (concatenated disk
driver) device.Turn off profiling (set NO_PROFILE=true in
/etc/make.conf). You almost certainly
do not need it.Also in /etc/make.conf, set
CFLAGS to something like . The optimization is much
slower, and the optimization difference between
and is normally
negligible. lets the compiler use
pipes rather than temporary files for communication, which
saves disk access (at the expense of memory).Pass the option to &man.make.1; to
run multiple processes in parallel. This usually helps
regardless of whether you have a single or a multi processor
machine.The file system holding
/usr/src can be mounted (or remounted)
with the option. This prevents the
file system from recording the file access time. You probably
do not need this information anyway.&prompt.root; mount -u -o noatime /usr/srcThe example assumes /usr/src is
on its own file system. If it is not (if it is a part of
/usr for example) then you will
need to use that file system mount point, and not
/usr/src.The file system holding /usr/obj can
be mounted (or remounted) with the
option. This causes disk writes to happen asynchronously.
In other words, the write completes immediately, and the
data is written to the disk a few seconds later. This
allows writes to be clustered together, and can be a
dramatic performance boost.Keep in mind that this option makes your file system
more fragile. With this option there is an increased
chance that, should power fail, the file system will be in
an unrecoverable state when the machine restarts.If /usr/obj is the only thing on
this file system then it is not a problem. If you have
other, valuable data on the same file system then ensure
your backups are fresh before you enable this
option.&prompt.root; mount -u -o async /usr/objAs above, if /usr/obj is not on
its own file system, replace it in the example with the
name of the appropriate mount point.What do I do if something goes wrong?Make absolutely sure your environment has no
extraneous cruft from earlier builds. This is simple
enough.&prompt.root; chflags -R noschg /usr/obj/usr
&prompt.root; rm -rf /usr/obj/usr
&prompt.root; cd /usr/src
&prompt.root; make cleandir
&prompt.root; make cleandirYes, make cleandir really should
be run twice.Then restart the whole process, starting
with make buildworld.If you still have problems, send the error and the
output of uname -a to &a.questions;.
Be prepared to answer other questions about your
setup!MikeMeyerContributed by Tracking for Multiple MachinesNFSinstalling multiple machinesIf you have multiple machines that you want to track the
same source tree, then having all of them download sources and
rebuild everything seems like a waste of resources: disk space,
network bandwidth, and CPU cycles. It is, and the solution is
to have one machine do most of the work, while the rest of the
machines mount that work via NFS. This section outlines a
method of doing so.PreliminariesFirst, identify a set of machines that is going to run
the same set of binaries, which we will call a
build set. Each machine can have a
custom kernel, but they will be running the same userland
binaries. From that set, choose a machine to be the
build machine. It is going to be the
machine that the world and kernel are built on. Ideally, it
should be a fast machine that has sufficient spare CPU to
run make buildworld and
make buildkernel. You will also want to
choose a machine to be the test
machine, which will test software updates before they
are put into production. This must be a
machine that you can afford to have down for an extended
period of time. It can be the build machine, but need not be.All the machines in this build set need to mount
/usr/obj and
/usr/src from the same machine, and at
the same point. Ideally, those are on two different drives
on the build machine, but they can be NFS mounted on that machine
as well. If you have multiple build sets,
/usr/src should be on one build machine, and
NFS mounted on the rest.Finally make sure that
/etc/make.conf on all the machines in
the build set agrees with the build machine. That means that
the build machine must build all the parts of the base
system that any machine in the build set is going to
install. Also, each build machine should have its kernel
name set with KERNCONF in
/etc/make.conf, and the build machine
should list them all in KERNCONF, listing
its own kernel first. The build machine must have the kernel
configuration files for each machine in
/usr/src/sys/arch/conf
if it is going to build their kernels.The Base SystemNow that all that is done, you are ready to build
everything. Build the kernel and world as described in on the build machine,
but do not install anything. After the build has finished, go
to the test machine, and install the kernel you just
built. If this machine mounts /usr/src
and /usr/obj via NFS, when you reboot
to single user you will need to enable the network and mount
them. The easiest way to do this is to boot to multi-user,
then run shutdown now to go to single user
mode. Once there, you can install the new kernel and world and run
mergemaster just as you normally would. When
done, reboot to return to normal multi-user operations for this
machine.After you are certain that everything on the test
machine is working properly, use the same procedure to
install the new software on each of the other machines in
the build set.PortsThe same ideas can be used for the ports tree. The first
critical step is mounting /usr/ports from
the same machine to all the machines in the build set. You can
then set up /etc/make.conf properly to share
distfiles. You should set DISTDIR to a
common shared directory that is writable by whichever user
root is mapped to by your NFS mounts. Each
machine should set WRKDIRPREFIX to a
local build directory. Finally, if you are going to be
building and distributing packages, you should set
PACKAGES to a directory similar to
DISTDIR.
diff --git a/pl_PL.ISO8859-2/books/handbook/l10n/chapter.xml b/pl_PL.ISO8859-2/books/handbook/l10n/chapter.xml
index 6236701373..d966c29a1a 100644
--- a/pl_PL.ISO8859-2/books/handbook/l10n/chapter.xml
+++ b/pl_PL.ISO8859-2/books/handbook/l10n/chapter.xml
@@ -1,931 +1,928 @@
AndreyChernovContributed by Michael C.WuRewritten by Localization - I18N/L10N Usage and SetupSynopsisFreeBSD is a very distributed project with users and
contributors located all over the world. This chapter discusses
the internationalization and localization features of FreeBSD
that allow non-English speaking users to get real work done.
There are many aspects of the i18n implementation in both the system
and application levels, so where applicable we refer the reader
to more specific sources of documentation.After reading this chapter, you will know:How different languages and locales are encoded
on modern operating systems.How to set the locale for your login
shell.How to configure your console for non-English
languages.How to use X Window System effectively with different
languages.Where to find more information about writing
i18n-compliant applications.Before reading this chapter, you should:Know how to install additional third-party
applications ().The BasicsWhat Is I18N/L10N?internationalizationlocalizationlocalizationDevelopers shortened internationalization into the term I18N,
counting the number of letters between the first and the last
letters of internationalization. L10N uses the same naming
scheme, coming from localization. Combined
together, I18N/L10N methods, protocols, and applications allow
users to use languages of their choice.I18N applications are programmed using I18N kits under
libraries. It allows for developers to write a simple file and
translate displayed menus and texts to each language. We strongly
encourage programmers to follow this convention.Why Should I Use I18N/L10N?I18N/L10N is used whenever you wish to either view, input, or
process data in non-English languages.What Languages Are Supported in the I18N Effort?I18N and L10N are not FreeBSD specific. Currently, one can
choose from most of the major languages of the World, including
but not limited to: Chinese, German, Japanese, Korean, French,
Russian, Vietnamese and others.Using LocalizationIn all its splendor, I18N is not FreeBSD-specific and is a
convention. We encourage you to help FreeBSD in following this
convention.localeLocalization settings are based on three main terms:
Language Code, Country Code, and Encoding. Locale names are
constructed from these parts as follows:LanguageCode_CountryCode.EncodingLanguage and Country Codeslanguage codescountry codesIn order to localize a FreeBSD system to a specific language
(or any other I18N-supporting &unix; like systems), the user needs to find out
the codes for the specify country and language (country
codes tell applications what variation of given
language to use). In addition, web
browsers, SMTP/POP servers, web servers, etc. make decisions based on
them. The following are examples of language/country codes:Language/Country CodeDescriptionen_USEnglish - United Statesru_RURussian for Russiazh_TWTraditional Chinese for TaiwanEncodingsencodingsASCIISome languages use non-ASCII encodings that are 8-bit, wide
or multibyte characters, see &man.multibyte.3; for more
details. Older applications do not recognize them
and mistake them for control characters. Newer applications
usually do recognize 8-bit characters. Depending on the
implementation, users may be required to compile an application
with wide or multibyte characters support, or configure it correctly.
To be able to input and process wide or multibyte characters, the FreeBSD Ports Collection has provided
each language with different programs. Refer to the I18N
documentation in the respective FreeBSD Port.Specifically, the user needs to look at the application
documentation to decide on how to configure it correctly or to
pass correct values into the configure/Makefile/compiler.Some things to keep in mind are:Language specific single C chars character sets
(see &man.multibyte.3;), e.g.
ISO8859-1, ISO8859-15, KOI8-R, CP437.Wide or multibyte encodings, e.g. EUC, Big5.You can check the active list of character sets at the
IANA Registry.&os; use X11-compatible locale encodings instead.I18N ApplicationsIn the FreeBSD Ports and Package system, I18N applications
have been named with I18N in their names for
easy identification. However, they do not always support the
language needed.Setting LocaleUsually it is sufficient to export the value of the locale name
as LANG in the login shell. This could be done in
the user's ~/.login_conf file or in the
startup file of the user's shell (~/.profile,
~/.bashrc, ~/.cshrc).
There is no need to set the locale subsets such as
LC_CTYPE, LC_CTIME. Please
refer to language-specific FreeBSD documentation for more
information.You should set the following two environment variables in your configuration
files:
- POSIX
- LANG for &posix; &man.setlocale.3; family
+ LANG for &posix;POSIX &man.setlocale.3; family
functions
- MIME
-
- MM_CHARSET for applications' MIME character
+ MM_CHARSET for applications' MIMEMIME character
setThis includes the user shell configuration, the specific application
configuration, and the X11 configuration.Setting Locale Methodslocalelogin classThere are two methods for setting locale, and both are
described below. The first (recommended one) is by assigning
the environment variables in login
class, and the second is by adding the environment
variable assignments to the system's shell startup file.Login Classes MethodThis method allows environment variables needed for locale
name and MIME character sets to be assigned once for every
possible shell instead of adding specific shell assignments to
each shell's startup file. User
Level Setup can be done by an user himself and Administrator Level Setup require
superuser privileges.User Level SetupHere is a minimal example of a
.login_conf file in user's home
directory which has both variables set for Latin-1
encoding:me:\
:charset=ISO-8859-1:\
:lang=de_DE.ISO8859-1:Traditional ChineseBIG-5 encodingHere is an example of a
.login_conf that sets the variables
for Traditional Chinese in BIG-5 encoding. Notice the many
more variables set because some software does not respect
locale variables correctly for Chinese, Japanese, and Korean.#Users who do not wish to use monetary units or time formats
#of Taiwan can manually change each variable
me:\
:lang=zh_TW.Big5:\
:lc_all=zh_TW.Big:\
:lc_collate=zh_TW.Big5:\
:lc_ctype=zh_TW.Big5:\
:lc_messages=zh_TW.Big5:\
:lc_monetary=zh_TW.Big5:\
:lc_numeric=zh_TW.Big5:\
:lc_time=zh_TW.Big5:\
:charset=big5:\
:xmodifiers="@im=xcin": #Setting the XIM Input ServerSee Administrator Level
Setup and &man.login.conf.5; for more details.Administrator Level SetupVerify that the user's login class in
/etc/login.conf sets the correct
language. Make sure these settings
appear in /etc/login.conf:language_name:accounts_title:\
:charset=MIME_charset:\
:lang=locale_name:\
:tc=default:So sticking with our previous example using Latin-1, it
would look like this:german:German Users Accounts:\
:charset=ISO-8859-1:\
:lang=de_DE.ISO8859-1:\
:tc=default:Before changing users Login Classes execute
the following command&prompt.root; cap_mkdb /etc/login.confto make new configuration in
/etc/login.conf visible to the system.Changing Login Classes with &man.vipw.8;vipwUse vipw to add new users, and make
the entry look like this:user:password:1111:11:language:0:0:User Name:/home/user:/bin/shChanging Login Classes with &man.adduser.8;adduserlogin classUse adduser to add new users, and do
the following:Set defaultclass =
language in
/etc/adduser.conf. Keep in mind
you must enter a default class for
all users of other languages in this case.An alternative variant is answering the specified
language each time that
Enter login class: default []:
appears from &man.adduser.8;.Another alternative is to use the following for each
user of a different language that you wish to
add:&prompt.root; adduser -class languageChanging Login Classes with &man.pw.8;pwIf you use &man.pw.8; for adding new users, call it in
this form:&prompt.root; pw useradd user_name -L languageShell Startup File MethodThis method is not recommended because it requires a
different setup for each possible shell program chosen. Use
the Login Class Method
instead.MIMElocaleTo add the locale name and MIME character set, just set
the two environment variables shown below in the
/etc/profile and/or
/etc/csh.login shell startup files. We
will use the German language as an example below:In /etc/profile:LANG=de_DE.ISO8859-1; export LANGMM_CHARSET=ISO-8859-1; export MM_CHARSETOr in /etc/csh.login:setenv LANG de_DE.ISO8859-1setenv MM_CHARSET ISO-8859-1Alternatively, you can add the above instructions to
/usr/share/skel/dot.profile (similar to
what was used in /etc/profile above), or
/usr/share/skel/dot.login (similar to
what was used in /etc/csh.login
above).For X11:In $HOME/.xinitrc:LANG=de_DE.ISO8859-1; export LANGOr:setenv LANG de_DE.ISO8859-1Depending on your shell (see above).Console SetupFor all single C chars character sets, set the correct
console fonts in /etc/rc.conf for the
language in question with:font8x16=font_name
font8x14=font_name
font8x8=font_nameThe font_name here is taken from
the /usr/share/syscons/fonts directory,
without the .fnt suffix.sysinstallkeymapscreenmapAlso be sure to set the correct keymap and screenmap for your
single C chars character set through
sysinstall (/stand/sysinstall
in &os; versions older than 5.2).
Once inside sysinstall, choose Configure, then
Console. Alternatively, you can add the
following to /etc/rc.conf:scrnmap=screenmap_name
keymap=keymap_name
keychange="fkey_number sequence"The screenmap_name here is taken
from the /usr/share/syscons/scrnmaps
directory, without the .scm suffix. A
screenmap with a corresponding mapped font is usually needed as a
workaround for expanding bit 8 to bit 9 on a VGA adapter's font
character matrix in pseudographics area, i.e., to move letters out
of that area if screen font uses a bit 8 column.If you have the moused daemon
enabled by setting the following
in your /etc/rc.conf:moused_enable="YES"then examine the mouse cursor information in the next
paragraph.mousedBy default the mouse cursor of the &man.syscons.4; driver occupies the
0xd0-0xd3 range in the character set. If your language uses this
range, you need to move the cursor's range outside of it. To enable
the workaround for &os;, add the following line to
/etc/rc.conf:mousechar_start=3The keymap_name here is taken from
the /usr/share/syscons/keymaps directory,
without the .kbd suffix. If you are
uncertain which keymap to use, you use can &man.kbdmap.1; to test
keymaps without rebooting.The keychange is usually needed to program
function keys to match the selected terminal type because
function key sequences cannot be defined in the key map.Also be sure to set the correct console terminal type in
/etc/ttys for all ttyv*
entries. Current pre-defined correspondences are:Character SetTerminal TypeISO8859-1 or ISO8859-15cons25l1ISO8859-2cons25l2ISO8859-7cons25l7KOI8-Rcons25rKOI8-Ucons25uCP437 (VGA default)cons25US-ASCIIcons25wFor wide or multibyte characters languages, use the correct
FreeBSD port in your
/usr/ports/language
directory. Some ports appear as console while the system sees it
as serial vtty's, hence you must reserve enough vtty's for both
X11 and the pseudo-serial console. Here is a partial list of
applications for using other languages in console:LanguageLocationTraditional Chinese (BIG-5)chinese/big5conJapanesejapanese/kon2-16dot or
japanese/mule-freewnnKoreankorean/hanX11 SetupAlthough X11 is not part of the FreeBSD Project, we have
included some information here for FreeBSD users. For more
details, refer to the &xorg;
web site or whichever X11 Server you use.In ~/.Xresources, you can additionally
tune application specific I18N settings (e.g., fonts, menus,
etc.).Displaying FontsX11 True Type font serverInstall &xorg; server
(x11-servers/xorg-server)
or &xfree86; server
(x11-servers/XFree86-4-Server),
then install the language &truetype; fonts. Setting the correct
locale should allow you to view your selected language in menus
and such.Inputting Non-English CharactersX11 Input Method (XIM)The X11 Input Method (XIM) Protocol is a new standard for
all X11 clients. All X11 applications should be written as XIM
clients that take input from XIM Input servers. There are
several XIM servers available for different languages.Printer SetupSome single C chars character sets are usually hardware
coded into printers. Wide or multibyte
character sets require special setup and we recommend using
apsfilter. You may also convert the
document to &postscript; or PDF formats using language specific
converters.Kernel and File SystemsThe FreeBSD fast filesystem (FFS) is 8-bit clean, so it can be used
with any single C chars character set (see &man.multibyte.3;),
but there is no character set
name stored in the filesystem; i.e., it is raw 8-bit and does not
know anything about encoding order. Officially, FFS does not
support any form of wide or multibyte character sets yet. However, some
wide or multibyte character sets have independent patches for FFS
enabling such support. They are only temporary unportable
solutions or hacks and we have decided to not include them in the
source tree. Refer to respective languages' web sites for more
information and the patch files.DOSUnicodeThe FreeBSD &ms-dos; filesystem has the configurable ability to
convert between &ms-dos;, Unicode character sets and chosen
FreeBSD filesystem character sets. See &man.mount.msdos.8; for
details.Compiling I18N ProgramsMany FreeBSD Ports have been ported with I18N support. Some
of them are marked with -I18N in the port name. These and many
other programs have built in support for I18N and need no special
consideration.MySQLHowever, some applications such as
MySQL need to be have the
Makefile configured with the specific
charset. This is usually done in the
Makefile or done by passing a value to
configure in the source.Localizing FreeBSD to Specific LanguagesAndreyChernovOriginally contributed by Russian Language (KOI8-R Encoding)localizationRussianFor more information about KOI8-R encoding, see the KOI8-R References
(Russian Net Character Set).Locale SetupPut the following lines into your
~/.login_conf file:me:My Account:\
:charset=KOI8-R:\
:lang=ru_RU.KOI8-R:See earlier in this chapter for examples of setting up the
locale.Console SetupAdd the following line
to your /etc/rc.conf file:mousechar_start=3Also, use following settings in
/etc/rc.conf:keymap="ru.koi8-r"
scrnmap="koi8-r2cp866"
font8x16="cp866b-8x16"
font8x14="cp866-8x14"
font8x8="cp866-8x8"For each ttyv* entry in
/etc/ttys, use
cons25r as the terminal type.See earlier in this chapter for examples of setting up the
console.Printer SetupprintersSince most printers with Russian characters come with
hardware code page CP866, a special output filter is needed
to convert from KOI8-R to CP866. Such a filter is installed by
default as /usr/libexec/lpr/ru/koi2alt.
A Russian printer /etc/printcap entry
should look like:lp|Russian local line printer:\
:sh:of=/usr/libexec/lpr/ru/koi2alt:\
:lp=/dev/lpt0:sd=/var/spool/output/lpd:lf=/var/log/lpd-errs:See &man.printcap.5; for a detailed description.&ms-dos; FS and Russian FilenamesThe following example &man.fstab.5; entry enables support
for Russian filenames in mounted &ms-dos; filesystems:/dev/ad0s2 /dos/c msdos rw,-Wkoi2dos,-Lru_RU.KOI8-R 0 0The option selects the locale name
used, and sets the character conversion
table. To use the option, be sure to
mount /usr before the &ms-dos; partition
because the conversion tables are located in
/usr/libdata/msdosfs. For more
information, see the &man.mount.msdos.8; manual
page.X11 SetupDo non-X locale
setup first as described.If you use &xorg;,
install
x11-fonts/xorg-fonts-cyrillic
package.Check the "Files" section
in your /etc/X11/xorg.conf file.
The following
lines must be added before any other
FontPath entries:FontPath "/usr/X11R6/lib/X11/fonts/cyrillic/misc"
FontPath "/usr/X11R6/lib/X11/fonts/cyrillic/75dpi"
FontPath "/usr/X11R6/lib/X11/fonts/cyrillic/100dpi"If you use a high resolution video mode, swap the 75 dpi
and 100 dpi lines.To activate a Russian keyboard, add the following to the
"Keyboard" section of your
xorg.conf file.Option "XkbLayout" "us,ru"
Option "XkbOptions" "grp:toggle"Also make sure that XkbDisable is
turned off (commented out) there.For grp:caps_toggle
the RUS/LAT switch will be CapsLock.
The old CapsLock function is still
available via ShiftCapsLock (in LAT mode
only). For grp:toggle
the RUS/LAT switch will be Right Alt.
grp:caps_toggle does not work in
&xorg; for unknown reason.If you have &windows; keys on your keyboard,
and notice that some non-alphabetical keys are mapped
incorrectly in RUS mode, add the following line in your
xorg.conf file.Option "XkbVariant" ",winkeys"The Russian XKB keyboard may not work with non-localized
applications.Minimally localized applications
should call a XtSetLanguageProc (NULL, NULL,
NULL); function early in the program.See
KOI8-R for X Window for more instructions on
localizing X11 applications.Traditional Chinese Localization for TaiwanlocalizationTraditional ChineseThe FreeBSD-Taiwan Project has an Chinese HOWTO for
FreeBSD at
using many Chinese ports.
Current editor for the FreeBSD Chinese HOWTO is
Shen Chuan-Hsing statue@freebsd.sinica.edu.tw.
Chuan-Hsing Shen statue@freebsd.sinica.edu.tw has
created the
Chinese FreeBSD Collection (CFC) using FreeBSD-Taiwan's
zh-L10N-tut. The packages and the script files
are available at .German Language Localization (for All ISO 8859-1
Languages)localizationGermanSlaven Rezic eserte@cs.tu-berlin.de wrote a
tutorial how to use umlauts on a FreeBSD machine. The tutorial
is written in German and available at
.Japanese and Korean Language LocalizationlocalizationJapaneselocalizationKoreanFor Japanese, refer to
,
and for Korean, refer to
.Non-English FreeBSD DocumentationSome FreeBSD contributors have translated parts of FreeBSD to
other languages. They are available through links on the main site or in
/usr/share/doc.
diff --git a/pl_PL.ISO8859-2/books/handbook/mail/chapter.xml b/pl_PL.ISO8859-2/books/handbook/mail/chapter.xml
index d678cbeb93..6dddfe3c82 100644
--- a/pl_PL.ISO8859-2/books/handbook/mail/chapter.xml
+++ b/pl_PL.ISO8859-2/books/handbook/mail/chapter.xml
@@ -1,2308 +1,2307 @@
BillLloydOriginal work by JimMockRewritten by Electronic MailSynopsisemailElectronic Mail, better known as email, is one of the
most widely used forms of communication today. This chapter provides
a basic introduction to running a mail server on &os;, as well as an
introduction to sending and receiving email using &os;; however,
it is not a complete reference and in fact many important
considerations are omitted. For more complete coverage of the
subject, the reader is referred to the many excellent books listed
in .After reading this chapter, you will know:What software components are involved in sending and receiving
electronic mail.Where basic sendmail configuration
files are located in FreeBSD.The difference between remote and
local mailboxes.How to block spammers from illegally using your mail server as a
relay.How to install and configure an alternate Mail Transfer Agent on
your system, replacing sendmail.How to troubleshoot common mail server problems.How to use SMTP with UUCP.How to set up the system to send mail only.How to use mail with a dialup connection.How to configure SMTP Authentication for added security.How to install and use a Mail User Agent, such as
mutt to send and receive email.How to download your mail from a remote POP
or IMAP server.How to automatically apply filters and rules to incoming
email.Before reading this chapter, you should:Properly set up your network connection
().Properly set up the DNS information for your mail host
().Know how to install additional third-party software
().Using Electronic MailPOPIMAPDNSThere are five major parts involved in an email exchange. They
are: the user program, the server daemon, DNS, a
remote or local mailbox, and of course, the
mailhost itself.The User ProgramThis includes command line programs such as
mutt,
pine, elm,
and mail, and GUI programs such as
balsa,
xfmail to name a few, and something
more sophisticated like a WWW browser. These
programs simply pass off the email transactions to the local
mailhost, either
by calling one of the server
daemons available, or delivering it over TCP.Mailhost Server Daemonmail server daemonssendmailmail server daemonspostfixmail server daemonsqmailmail server daemonsexim&os; ships with sendmail by
default, but also support numerous other mail server daemons,
just some of which include:exim;postfix;qmail.The server daemon usually has two functions—it is responsible
for receiving incoming mail as well as delivering outgoing mail. It is
not responsible for the collection of mail using protocols
such as POP or IMAP to
read your email, nor does it allow connecting to local
mbox or Maildir mailboxes. You may require
an additional daemon for
that.Older versions of sendmail
have some serious security issues which may result in an
attacker gaining local and/or remote access to your machine.
Make sure that you are running a current version to avoid
these problems. Optionally, install an alternative
MTA from the &os;
Ports Collection.Email and DNSThe Domain Name System (DNS) and its daemon
named play a large role in the delivery of
email. In order to deliver mail from your site to another, the
server daemon will look up the remote site in the DNS to determine the
host that will receive mail for the destination. This process
also occurs when mail is sent from a remote host to your mail
server.MX recordDNS is responsible for mapping
hostnames to IP addresses, as well as for storing information
specific to mail delivery, known as MX records. The MX (Mail
eXchanger) record specifies which host, or hosts, will receive
mail for a particular domain. If you do not have an MX record
for your hostname or domain, the mail will be delivered
directly to your host provided you have an A record pointing
your hostname to your IP address.You may view the MX records for any domain by using the
&man.host.1; command, as seen in the example below:&prompt.user; host -t mx FreeBSD.org
FreeBSD.org mail is handled (pri=10) by mx1.FreeBSD.orgReceiving MailemailreceivingReceiving mail for your domain is done by the mail host. It
will collect all mail sent to your domain and store it
either in mbox (the default method for storing mail) or Maildir format, depending
on your configuration.
Once mail has been stored, it may either be read locally using
applications such as &man.mail.1; or
mutt, or remotely accessed and
collected using protocols such as
POP or IMAP.
This means that should you only
wish to read mail locally, you are not required to install a
POP or IMAP server.Accessing remote mailboxes using POP and IMAPPOPIMAPIn order to access mailboxes remotely, you are required to
have access to a POP or IMAP
server. These protocols allow users to connect to their mailboxes from
remote locations with ease. Though both
POP and IMAP allow users
to remotely access mailboxes, IMAP offers
many advantages, some of which are:IMAP can store messages on a remote
server as well as fetch them.IMAP supports concurrent updates.IMAP can be extremely useful over
low-speed links as it allows users to fetch the structure
of messages without downloading them; it can also
perform tasks such as searching on the server in
order to minimize data transfer between clients and
servers.In order to install a POP or
IMAP server, the following steps should be
performed:Choose an IMAP or
POP server that best suits your needs.
The following POP and
IMAP servers are well known and serve
as some good examples:qpopper;teapop;imap-uw;courier-imap;Install the POP or
IMAP daemon of your choosing from the
ports
collection.Where required, modify /etc/inetd.conf
to load the POP or
IMAP server.It should be noted that both POP and
IMAP transmit information, including
username and password credentials in clear-text. This means
that if you wish to secure the transmission of information
across these protocols, you should consider tunneling
sessions over &man.ssh.1;. Tunneling sessions is
described in .Accessing local mailboxesMailboxes may be accessed locally by directly utilizing
MUAs on the server on which the mailbox
resides. This can be done using applications such as
mutt or &man.mail.1;.
The Mail Hostmail hostThe mail host is the name given to a server that is
responsible for delivering and receiving mail for your host, and
possibly your network.ChristopherShumwayContributed by sendmail Configurationsendmail&man.sendmail.8; is the default Mail Transfer Agent (MTA) in
FreeBSD. sendmail's job is to accept
mail from Mail User Agents (MUA) and deliver it
to the appropriate mailer as defined by its configuration file.
sendmail can also accept network
connections and deliver mail to local mailboxes or deliver it to
another program.sendmail uses the following
configuration files:/etc/mail/access/etc/mail/aliases/etc/mail/local-host-names/etc/mail/mailer.conf/etc/mail/mailertable/etc/mail/sendmail.cf/etc/mail/virtusertableFilenameFunction/etc/mail/accesssendmail access database
file/etc/mail/aliasesMailbox aliases/etc/mail/local-host-namesLists of hosts sendmail
accepts mail for/etc/mail/mailer.confMailer program configuration/etc/mail/mailertableMailer delivery table/etc/mail/sendmail.cfsendmail master
configuration file/etc/mail/virtusertableVirtual users and domain tables/etc/mail/accessThe access database defines what host(s) or IP addresses
have access to the local mail server and what kind of access
they have. Hosts can be listed as ,
, or simply passed
to sendmail's error handling routine with a given mailer error.
Hosts that are listed as , which is the
default, are allowed to send mail to this host as long as the
mail's final destination is the local machine. Hosts that are
listed as are rejected for all mail
connections. Hosts that have the option
for their hostname are allowed to send mail for any destination
through this mail server.Configuring the sendmail
Access Databasecyberspammer.com 550 We do not accept mail from spammers
FREE.STEALTH.MAILER@ 550 We do not accept mail from spammers
another.source.of.spam REJECT
okay.cyberspammer.com OK
128.32 RELAYIn this example we have five entries. Mail senders that
match the left hand side of the table are affected by the action
on the right side of the table. The first two examples give an
error code to sendmail's error
handling routine. The message is printed to the remote host when
a mail matches the left hand side of the table. The next entry
rejects mail from a specific host on the Internet,
another.source.of.spam. The next entry accepts
mail connections from a host
okay.cyberspammer.com, which is more exact than
the cyberspammer.com line above. More specific
matches override less exact matches. The last entry allows
relaying of electronic mail from hosts with an IP address that
begins with 128.32. These hosts would be able
to send mail through this mail server that are destined for other
mail servers.When this file is updated, you need to run
make in /etc/mail/ to
update the database./etc/mail/aliasesThe aliases database contains a list of virtual mailboxes
that are expanded to other user(s), files, programs or other
aliases. Here are a few examples that can be used in
/etc/mail/aliases:Mail Aliasesroot: localuser
ftp-bugs: joe,eric,paul
bit.bucket: /dev/null
procmail: "|/usr/local/bin/procmail"The file format is simple; the mailbox name on the left
side of the colon is expanded to the target(s) on the right.
The
first example simply expands the mailbox root
to the mailbox localuser, which is then
looked up again in the aliases database. If no match is found,
then the message is delivered to the local user
localuser. The next example shows a mail
list. Mail to the mailbox ftp-bugs is
expanded to the three local mailboxes joe,
eric, and paul. Note
that a remote mailbox could be specified as user@example.com. The
next example shows writing mail to a file, in this case
/dev/null. The last example shows sending
mail to a program, in this case the mail message is written to the
standard input of /usr/local/bin/procmail
through a &unix; pipe.When this file is updated, you need to run
make in /etc/mail/ to
update the database./etc/mail/local-host-namesThis is a list of hostnames &man.sendmail.8; is to accept as
the local host name. Place any domains or hosts that
sendmail is to be receiving mail for.
For example, if this mail server was to accept mail for the
domain example.com and the host
mail.example.com, its
local-host-names might look something like
this:example.com
mail.example.comWhen this file is updated, &man.sendmail.8; needs to be
restarted to read the changes./etc/mail/sendmail.cfsendmail's master configuration
file, sendmail.cf controls the overall
behavior of sendmail, including everything
from rewriting e-mail addresses to printing rejection messages to
remote mail servers. Naturally, with such a diverse role, this
configuration file is quite complex and its details are a bit
out of the scope of this section. Fortunately, this file rarely
needs to be changed for standard mail servers.The master sendmail configuration
file can be built from &man.m4.1; macros that define the features
and behavior of sendmail. Please see
/usr/src/contrib/sendmail/cf/README for
some of the details.When changes to this file are made,
sendmail needs to be restarted for
the changes to take effect./etc/mail/virtusertableThe virtusertable maps mail addresses for
virtual domains and
mailboxes to real mailboxes. These mailboxes can be local,
remote, aliases defined in
/etc/mail/aliases or files.Example Virtual Domain Mail Maproot@example.com root
postmaster@example.com postmaster@noc.example.net
@example.com joeIn the above example, we have a mapping for a domain
example.com. This file is processed in a
first match order down the file. The first item maps
root@example.com to the local mailbox root. The next entry maps
postmaster@example.com to the mailbox postmaster on the host
noc.example.net. Finally, if nothing from example.com has
matched so far, it will match the last mapping, which matches
every other mail message addressed to someone at
example.com.
This will be mapped to the local mailbox joe.AndrewBoothmanWritten by GregoryNeil ShapiroInformation taken from e-mails written by Changing Your Mail Transfer Agentemailchange mtaAs already mentioned, FreeBSD comes with
sendmail already installed as your
MTA (Mail Transfer Agent). Therefore by default it is
in charge of your outgoing and incoming mail.However, for a variety of reasons, some system
administrators want to change their system's MTA. These
reasons range from simply wanting to try out another MTA to
needing a specific feature or package which relies on another
mailer. Fortunately, whatever the reason, FreeBSD makes it
easy to make the change.Install a New MTAYou have a wide choice of MTAs available. A good
starting point is the
FreeBSD Ports Collection where
you will be able to find many. Of course you are free to use
any MTA you want from any location, as long as you can make
it run under FreeBSD.Start by installing your new MTA. Once it is installed
it gives you a chance to decide if it really fulfills your
needs, and also gives you the opportunity to configure your
new software before getting it to take over from
sendmail. When doing this, you
should be sure that installing the new software will not attempt
to overwrite system binaries such as
/usr/bin/sendmail. Otherwise, your new
mail software has essentially been put into service before
you have configured it.Please refer to your chosen MTA's documentation for
information on how to configure the software you have
chosen.Disable sendmailThe procedure used to start
sendmail changed significantly
between 4.5-RELEASE, 4.6-RELEASE, and later releases.
Therefore, the procedure used to disable it is subtly
different.If you disable sendmail's
outgoing mail service, it is important that you replace it
with an alternative mail delivery system. If
you choose not to, system functions such as &man.periodic.8;
will be unable to deliver their results by e-mail as they
would normally expect to. Many parts of your system may
expect to have a functional
sendmail-compatible system. If
applications continue to use
sendmail's binaries to try to send
e-mail after you have disabled them, mail could go into an
inactive sendmail queue, and
never be delivered.FreeBSD 4.5-STABLE before 2002/4/4 and Earlier
(Including 4.5-RELEASE and Earlier)Enter:sendmail_enable="NO"into /etc/rc.conf. This will disable
sendmail's incoming mail service,
but if /etc/mail/mailer.conf (see below)
is not changed, sendmail will
still be used to send e-mail.FreeBSD 4.5-STABLE after 2002/4/4
(Including 4.6-RELEASE and Later)In order to completely disable
sendmail, including the outgoing
mail service, you must usesendmail_enable="NONE"in /etc/rc.conf.If you only want to disable
sendmail's incoming mail service,
you should setsendmail_enable="NO"in /etc/rc.conf. However, if
incoming mail is disabled, local delivery will still
function. More information on
sendmail's startup options is
available from the &man.rc.sendmail.8; manual page.FreeBSD 5.0-STABLE and LaterIn order to completely disable
sendmail, including the outgoing
mail service, you must usesendmail_enable="NO"
sendmail_submit_enable="NO"
sendmail_outbound_enable="NO"
sendmail_msp_queue_enable="NO"in /etc/rc.conf.If you only want to disable
sendmail's incoming mail service,
you should setsendmail_enable="NO"in /etc/rc.conf. More information on
sendmail's startup options is
available from the &man.rc.sendmail.8; manual page.Running Your New MTA on BootYou may have a choice of two methods for running your
new MTA on boot, again depending on what version of FreeBSD
you are running.FreeBSD 4.5-STABLE before 2002/4/11
(Including 4.5-RELEASE and Earlier)Add a script to
/usr/local/etc/rc.d/ that
ends in .sh and is executable by
root. The script should accept start and
stop parameters. At startup time the
system scripts will execute the command/usr/local/etc/rc.d/supermailer.sh startwhich you can also use to manually start the server. At
shutdown time, the system scripts will use the
stop option, running the command/usr/local/etc/rc.d/supermailer.sh stopwhich you can also use to manually stop the server
while the system is running.FreeBSD 4.5-STABLE after 2002/4/11
(Including 4.6-RELEASE and Later)With later versions of FreeBSD, you can use the
above method or you can setmta_start_script="filename"in /etc/rc.conf, where
filename is the name of some
script that you want executed at boot to start your
MTA.Replacing sendmail as
the System's Default MailerThe program sendmail is so ubiquitous
as standard software on &unix; systems that some software
just assumes it is already installed and configured.
For this reason, many alternative MTA's provide their own compatible
implementations of the sendmail
command-line interface; this facilitates using them as
drop-in replacements for sendmail.Therefore, if you are using an alternative mailer,
you will need to make sure that software trying to execute
standard sendmail binaries such as
/usr/bin/sendmail actually executes
your chosen mailer instead. Fortunately, FreeBSD provides
a system called &man.mailwrapper.8; that does this job for
you.When sendmail is operating as installed, you will
find something like the following
in /etc/mail/mailer.conf:sendmail /usr/libexec/sendmail/sendmail
send-mail /usr/libexec/sendmail/sendmail
mailq /usr/libexec/sendmail/sendmail
newaliases /usr/libexec/sendmail/sendmail
hoststat /usr/libexec/sendmail/sendmail
purgestat /usr/libexec/sendmail/sendmailThis means that when any of these common commands
(such as sendmail itself) are run,
the system actually invokes a copy of mailwrapper named sendmail, which
checks mailer.conf and
executes /usr/libexec/sendmail/sendmail
instead. This system makes it easy to change what binaries
are actually executed when these default sendmail functions
are invoked.Therefore if you wanted
/usr/local/supermailer/bin/sendmail-compat
to be run instead of sendmail, you could change
/etc/mail/mailer.conf to read:sendmail /usr/local/supermailer/bin/sendmail-compat
send-mail /usr/local/supermailer/bin/sendmail-compat
mailq /usr/local/supermailer/bin/mailq-compat
newaliases /usr/local/supermailer/bin/newaliases-compat
hoststat /usr/local/supermailer/bin/hoststat-compat
purgestat /usr/local/supermailer/bin/purgestat-compatFinishingOnce you have everything configured the way you want it, you should
either kill the sendmail processes that
you no longer need and start the processes belonging to your new
software, or simply reboot. Rebooting will also
give you the opportunity to ensure that you have correctly
configured your system to start your new MTA automatically on boot.TroubleshootingemailtroubleshootingWhy do I have to use the FQDN for hosts on my site?You will probably find that the host is actually in a
different domain; for example, if you are in
foo.bar.edu and you wish to reach
a host called mumble in the bar.edu domain, you will have to
refer to it by the fully-qualified domain name, mumble.bar.edu, instead of just
mumble.Traditionally, this was allowed by BSD BINDBIND resolvers.
However the current version of BIND
that ships with FreeBSD no longer provides default abbreviations
for non-fully qualified domain names other than the domain you
are in. So an unqualified host mumble must
either be found as mumble.foo.bar.edu, or it will be searched
for in the root domain.This is different from the previous behavior, where the
search continued across mumble.bar.edu, and mumble.edu. Have a look at RFC 1535
for why this was considered bad practice, or even a security
hole.As a good workaround, you can place the line:search foo.bar.edu bar.eduinstead of the previous:domain foo.bar.eduinto your /etc/resolv.conf. However, make
sure that the search order does not go beyond the
boundary between local and public administration,
as RFC 1535 calls it.sendmail says mail
loops back to myselfThis is answered in the
sendmail FAQ as follows:I'm getting these error messages:
553 MX list for domain.net points back to relay.domain.net
554 <user@domain.net>... Local configuration error
How can I solve this problem?
You have asked mail to the domain (e.g., domain.net) to be
forwarded to a specific host (in this case, relay.domain.net)
by using an MXMX record
record, but the relay machine does not recognize
itself as domain.net. Add domain.net to /etc/mail/local-host-names
[known as /etc/sendmail.cw prior to version 8.10]
(if you are using FEATURE(use_cw_file)) or add Cw domain.net
to /etc/mail/sendmail.cf.The sendmail FAQ can be found at
and is
recommended reading if you want to do any
tweaking of your mail setup.How can I run a mail server on a dial-up PPPPPP host?You want to connect a FreeBSD box on a LAN to the
Internet. The FreeBSD box will be a mail gateway for the LAN.
The PPP connection is non-dedicated.There are at least two ways to do this. One way is to use
UUCPUUCP.Another way is to get a full-time Internet server to provide secondary
MXMX record
services for your domain. For example, if your company's domain is
example.com and your Internet service provider has
set example.net up to provide secondary MX services
to your domain:example.com. MX 10 example.com.
MX 20 example.net.Only one host should be specified as the final recipient
(add Cw example.com in
/etc/mail/sendmail.cf on example.com).When the sending sendmail is trying to
deliver the mail it will try to connect to you (example.com) over the modem
link. It will most likely time out because you are not online.
The program sendmail will automatically deliver it to the
secondary MX site, i.e. your Internet provider (example.net). The secondary MX
site will then periodically try to connect to
your host and deliver the mail to the primary MX host (example.com).You might want to use something like this as a login
script:#!/bin/sh
# Put me in /usr/local/bin/pppmyisp
( sleep 60 ; /usr/sbin/sendmail -q ) &
/usr/sbin/ppp -direct pppmyispIf you are going to create a separate login script for a
user you could use sendmail -qRexample.com
instead in the script above. This will force all mail in your
queue for example.com to be processed immediately.A further refinement of the situation is as follows:Message stolen from the &a.isp;.> we provide the secondary MX for a customer. The customer connects to
> our services several times a day automatically to get the mails to
> his primary MX (We do not call his site when a mail for his domains
> arrived). Our sendmail sends the mailqueue every 30 minutes. At the
> moment he has to stay 30 minutes online to be sure that all mail is
> gone to the primary MX.
>
> Is there a command that would initiate sendmail to send all the mails
> now? The user has not root-privileges on our machine of course.
In the privacy flags section of sendmail.cf, there is a
definition Opgoaway,restrictqrun
Remove restrictqrun to allow non-root users to start the queue processing.
You might also like to rearrange the MXs. We are the 1st MX for our
customers like this, and we have defined:
# If we are the best MX for a host, try directly instead of generating
# local config error.
OwTrue
That way a remote site will deliver straight to you, without trying
the customer connection. You then send to your customer. Only works for
hosts, so you need to get your customer to name their mail
machine customer.com as well as
hostname.customer.com in the DNS. Just put an A record in
the DNS for customer.com.Why do I keep getting Relaying
Denied errors when sending mail from other
hosts?In default FreeBSD installations,
sendmail is configured to only
send mail from the host it is running on. For example, if
a POP server is available, then users
will be able to check mail from school, work, or other
remote locations but they still will not be able to send
outgoing emails from outside locations. Typically, a few
moments after the attempt, an email will be sent from
MAILER-DAEMON with a
5.7 Relaying Denied error
message.There are several ways to get around this. The most
straightforward solution is to put your ISP's address in
a relay-domains file at
/etc/mail/relay-domains. A quick way
to do this would be:&prompt.root; echo "your.isp.example.com" > /etc/mail/relay-domainsAfter creating or editing this file you must restart
sendmail. This works great if
you are a server administrator and do not wish to send mail
locally, or would like to use a point and click
client/system on another machine or even another ISP. It
is also very useful if you only have one or two email
accounts set up. If there is a large number of addresses
to add, you can simply open this file in your favorite
text editor and then add the domains, one per line:your.isp.example.com
other.isp.example.net
users-isp.example.org
www.example.orgNow any mail sent through your system, by any host in
this list (provided the user has an account on your
system), will succeed. This is a very nice way to allow
users to send mail from your system remotely without
allowing people to send SPAM through your system.Advanced TopicsThe following section covers more involved topics such as mail
configuration and setting up mail for your entire domain.Basic ConfigurationemailconfigurationOut of the box, you should be able to send email to external
hosts as long as you have set up
/etc/resolv.conf or are running your own
name server. If you would like to have mail for your host
delivered to the MTA (e.g., sendmail) on your own FreeBSD host, there are two methods:Run your own name server and have your own domain. For
example, FreeBSD.orgGet mail delivered directly to your host. This is done by
delivering mail directly to the current DNS name for your
machine. For example, example.FreeBSD.org.SMTPRegardless of which of the above you choose, in order to have
mail delivered directly to your host, it must have a permanent
static IP address (not a dynamic address, as with most PPP dial-up configurations). If you are behind a
firewall, it must pass SMTP traffic on to you. If you want to
receive mail directly at your host, you need to be sure of either of two
things:
- MX record
- Make sure that the (lowest-numbered) MX record in your DNS points to your
+ Make sure that the (lowest-numbered) MX recordMX record in your DNS points to your
host's IP address.Make sure there is no MX entry in your DNS for your
host.Either of the above will allow you to receive mail directly at
your host.Try this:&prompt.root; hostname
example.FreeBSD.org
&prompt.root; host example.FreeBSD.org
example.FreeBSD.org has address 204.216.27.XXIf that is what you see, mail directly to
yourlogin@example.FreeBSD.org should work without
problems (assuming sendmail is
running correctly on example.FreeBSD.org).If instead you see something like this:&prompt.root; host example.FreeBSD.org
example.FreeBSD.org has address 204.216.27.XX
example.FreeBSD.org mail is handled (pri=10) by hub.FreeBSD.orgAll mail sent to your host (example.FreeBSD.org) will end up being
collected on hub under the same username instead
of being sent directly to your host.The above information is handled by your DNS server. The DNS
record that carries mail routing information is the
Mail eXchange entry. If
no MX record exists, mail will be delivered directly to the host by
way of its IP address.The MX entry for freefall.FreeBSD.org at one time looked like
this:freefall MX 30 mail.crl.net
freefall MX 40 agora.rdrop.com
freefall MX 10 freefall.FreeBSD.org
freefall MX 20 who.cdrom.comAs you can see, freefall had many MX entries.
The lowest MX number is the host that receives mail directly if
available; if it is not accessible for some reason, the others
(sometimes called backup MXes) accept messages
temporarily, and pass it along when a lower-numbered host becomes
available, eventually to the lowest-numbered host.Alternate MX sites should have separate Internet connections
from your own in order to be most useful. Your ISP or another
friendly site should have no problem providing this service for
you.Mail for Your DomainIn order to set up a mailhost (a.k.a. mail
server) you need to have any mail sent to various workstations
directed to it. Basically, you want to claim any
mail for any hostname in your domain (in this case *.FreeBSD.org) and divert it to your mail
server so your users can receive their mail on
the master mail server.DNSTo make life easiest, a user account with the same
username should exist on both machines. Use
&man.adduser.8; to do this.The mailhost you will be using must be the designated mail
exchanger for each workstation on the network. This is done in
your DNS configuration like so:example.FreeBSD.org A 204.216.27.XX ; Workstation
MX 10 hub.FreeBSD.org ; MailhostThis will redirect mail for the workstation to the mailhost no
matter where the A record points. The mail is sent to the MX
host.You cannot do this yourself unless you are running a DNS
server. If you are not, or cannot run your own DNS server, talk
to your ISP or whoever provides your DNS.If you are doing virtual email hosting, the following
information will come in handy. For this example, we
will assume you have a customer with his own domain, in this
case customer1.org, and you want
all the mail for customer1.org
sent to your mailhost, mail.myhost.com. The entry in your DNS
should look like this:customer1.org MX 10 mail.myhost.comYou do not need an A record for customer1.org if you only
want to handle email for that domain.Be aware that pinging customer1.org will not work unless
an A record exists for it.The last thing that you must do is tell
sendmail on your mailhost what domains
and/or hostnames it should be accepting mail for. There are a few
different ways this can be done. Either of the following will
work:Add the hosts to your
/etc/mail/local-host-names file if you are using the
FEATURE(use_cw_file). If you are using
a version of sendmail earlier than 8.10, the file is
/etc/sendmail.cw.Add a Cwyour.host.com line to your
/etc/sendmail.cf or
/etc/mail/sendmail.cf if you are using
sendmail 8.10 or higher.SMTP with UUCPThe sendmail configuration that ships with FreeBSD is
designed for sites that connect directly to the Internet. Sites
that wish to exchange their mail via UUCP must install another
sendmail configuration file.Tweaking /etc/mail/sendmail.cf manually
is an advanced topic. sendmail version 8 generates config files
via &man.m4.1; preprocessing, where the actual configuration
occurs on a higher abstraction level. The &man.m4.1;
configuration files can be found under
/usr/src/usr.sbin/sendmail/cf.If you did not install your system with full sources, the
sendmail configuration set has been broken out into a separate source
distribution tarball. Assuming you have your FreeBSD source code
CDROM mounted, do:&prompt.root; cd /cdrom/src
&prompt.root; cat scontrib.?? | tar xzf - -C /usr/src/contrib/sendmailThis extracts to only a few hundred kilobytes. The file
README in the cf
directory can serve as a basic introduction to &man.m4.1;
configuration.The best way to support UUCP delivery is to use the
mailertable feature. This creates a database
that sendmail can use to make routing decisions.First, you have to create your .mc
file. The directory
/usr/src/usr.sbin/sendmail/cf/cf contains a
few examples. Assuming you have named your file
foo.mc, all you need to do in order to
convert it into a valid sendmail.cf
is:&prompt.root; cd /usr/src/usr.sbin/sendmail/cf/cf
&prompt.root; make foo.cf
&prompt.root; cp foo.cf /etc/mail/sendmail.cfA typical .mc file might look
like:VERSIONID(`Your version number') OSTYPE(bsd4.4)
FEATURE(accept_unresolvable_domains)
FEATURE(nocanonify)
FEATURE(mailertable, `hash -o /etc/mail/mailertable')
define(`UUCP_RELAY', your.uucp.relay)
define(`UUCP_MAX_SIZE', 200000)
define(`confDONT_PROBE_INTERFACES')
MAILER(local)
MAILER(smtp)
MAILER(uucp)
Cw your.alias.host.name
Cw youruucpnodename.UUCPThe lines containing
accept_unresolvable_domains,
nocanonify, and
confDONT_PROBE_INTERFACES features will
prevent any usage of the DNS during mail delivery. The
UUCP_RELAY clause is needed to support UUCP
delivery. Simply put an Internet hostname there that is able to
handle .UUCP pseudo-domain addresses; most likely, you will
enter the mail relay of your ISP there.Once you have this, you need an
/etc/mail/mailertable file. If you have
only one link to the outside that is used for all your mails,
the following file will suffice:#
# makemap hash /etc/mail/mailertable.db < /etc/mail/mailertable
. uucp-dom:your.uucp.relayA more complex example might look like this:#
# makemap hash /etc/mail/mailertable.db < /etc/mail/mailertable
#
horus.interface-business.de uucp-dom:horus
.interface-business.de uucp-dom:if-bus
interface-business.de uucp-dom:if-bus
.heep.sax.de smtp8:%1
horus.UUCP uucp-dom:horus
if-bus.UUCP uucp-dom:if-bus
. uucp-dom:The first three lines handle special cases where
domain-addressed mail should not be sent out to the default
route, but instead to some UUCP neighbor in order to
shortcut the delivery path. The next line handles
mail to the local Ethernet domain that can be delivered using
SMTP. Finally, the UUCP neighbors are mentioned in the .UUCP
pseudo-domain notation, to allow for a
uucp-neighbor
!recipient
override of the default rules. The last line is always a single
dot, matching everything else, with UUCP delivery to a UUCP
neighbor that serves as your universal mail gateway to the
world. All of the node names behind the
uucp-dom: keyword must be valid UUCP
neighbors, as you can verify using the command
uuname.As a reminder that this file needs to be converted into a
DBM database file before use. The command line to accomplish
this is best placed as a comment at the top of the mailertable file.
You always have to execute this command each time you change
your mailertable file.Final hint: if you are uncertain whether some particular
mail routing would work, remember the
option to sendmail. It starts sendmail in address test
mode; simply enter 3,0, followed
by the address you wish to test for the mail routing. The last
line tells you the used internal mail agent, the destination
host this agent will be called with, and the (possibly
translated) address. Leave this mode by typing CtrlD.&prompt.user; sendmail -bt
ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)
Enter <ruleset> <address>
>3,0 foo@example.com
canonify input: foo @ example . com
...
parse returns: $# uucp-dom $@ your.uucp.relay $: foo < @ example . com . >
>^DBillMoranContributed by Setting Up to Send OnlyThere are many instances where you may only want to send
mail through a relay. Some examples are:Your computer is a desktop machine, but you want
to use programs such as &man.send-pr.1;. To do so, you should use
your ISP's mail relay.The computer is a server that does not handle mail
locally, but needs to pass off all mail to a relay for
processing.Just about any MTA is capable of filling
this particular niche. Unfortunately, it can be very difficult
to properly configure a full-featured MTA
just to handle offloading mail. Programs such as
sendmail and
postfix are largely overkill for
this use.Additionally, if you are using a typical Internet access
service, your agreement may forbid you from running a
mail server.The easiest way to fulfill those needs is to install the
mail/ssmtp port. Execute
the following commands as root:&prompt.root; cd /usr/ports/mail/ssmtp
&prompt.root; make install replace cleanOnce installed,
mail/ssmtp can be configured
with a four-line file located at
/usr/local/etc/ssmtp/ssmtp.conf:root=yourrealemail@example.com
mailhub=mail.example.com
rewriteDomain=example.com
hostname=_HOSTNAME_Make sure you use your real email address for
root. Enter your ISP's outgoing mail relay
in place of mail.example.com (some ISPs call
this the outgoing mail server or
SMTP server).Make sure you disable sendmail,
including the outgoing mail service. See
for details.mail/ssmtp has some
other options available. See the example configuration file in
/usr/local/etc/ssmtp or the manual page of
ssmtp for some examples and more
information.Setting up ssmtp in this manner
will allow any software on your computer that needs to send
mail to function properly, while not violating your ISP's usage
policy or allowing your computer to be hijacked for spamming.Using Mail with a Dialup ConnectionIf you have a static IP address, you should not need to
adjust anything from the defaults. Set your host name to your
assigned Internet name and sendmail will do the rest.If you have a dynamically assigned IP number and use a
dialup PPP connection to the Internet, you will probably have a
mailbox on your ISPs mail server. Let's assume your ISP's domain
is example.net, and that your
user name is user, you have called your
machine bsd.home, and your ISP has
told you that you may use relay.example.net as a mail relay.In order to retrieve mail from your mailbox, you must
install a retrieval agent. The
fetchmail utility is a good choice as
it supports many different protocols. This program is available
as a package or from the Ports Collection (mail/fetchmail). Usually, your ISP will
provide POP. If you are using user PPP, you can
automatically fetch your mail when an Internet connection is
established with the following entry in
/etc/ppp/ppp.linkup:MYADDR:
!bg su user -c fetchmailIf you are using sendmail (as
shown below) to deliver mail to non-local accounts, you probably
want to have sendmail process your
mailqueue as soon as your Internet connection is established.
To do this, put this command after the
fetchmail command in
/etc/ppp/ppp.linkup: !bg su user -c "sendmail -q"Assume that you have an account for
user on bsd.home. In the home directory of
user on bsd.home, create a
.fetchmailrc file:poll example.net protocol pop3 fetchall pass MySecretThis file should not be readable by anyone except
user as it contains the password
MySecret.In order to send mail with the correct
from: header, you must tell
sendmail to use
user@example.net rather than
user@bsd.home. You may also wish to tell
sendmail to send all mail via relay.example.net, allowing quicker mail
transmission.The following .mc file should
suffice:VERSIONID(`bsd.home.mc version 1.0')
OSTYPE(bsd4.4)dnl
FEATURE(nouucp)dnl
MAILER(local)dnl
MAILER(smtp)dnl
Cwlocalhost
Cwbsd.home
MASQUERADE_AS(`example.net')dnl
FEATURE(allmasquerade)dnl
FEATURE(masquerade_envelope)dnl
FEATURE(nocanonify)dnl
FEATURE(nodns)dnl
define(`SMART_HOST', `relay.example.net')
Dmbsd.home
define(`confDOMAIN_NAME',`bsd.home')dnl
define(`confDELIVERY_MODE',`deferred')dnlRefer to the previous section for details of how to turn
this .mc file into a
sendmail.cf file. Also, do not forget to
restart sendmail after updating
sendmail.cf.JamesGorhamWritten by SMTP AuthenticationHaving SMTP Authentication in place on
your mail server has a number of benefits.
SMTP Authentication can add another layer
of security to sendmail, and has the benefit of giving mobile
users who switch hosts the ability to use the same mail server
without the need to reconfigure their mail client settings
each time.Install security/cyrus-sasl
from the ports. You can find this port in
security/cyrus-sasl.
security/cyrus-sasl has
a number of compile time options to choose from and, for
the method we will be using here, make sure to select the
option.After installing security/cyrus-sasl,
edit /usr/local/lib/sasl/Sendmail.conf
(or create it if it does not exist) and add the following
line:pwcheck_method: passwdThis method will enable sendmail
to authenticate against your FreeBSD passwd
database. This saves the trouble of creating a new set of usernames
and passwords for each user that needs to use
SMTP authentication, and keeps the login
and mail password the same.Now edit /etc/make.conf and add the
following lines:SENDMAIL_CFLAGS=-I/usr/local/include/sasl1 -DSASL
SENDMAIL_LDFLAGS=-L/usr/local/lib
SENDMAIL_LDADD=-lsaslThese lines will give sendmail
the proper configuration options for linking
to cyrus-sasl at compile time.
Make sure that cyrus-sasl
has been installed before recompiling
sendmail.Recompile sendmail by executing the following commands:&prompt.root; cd /usr/src/usr.sbin/sendmail
&prompt.root; make cleandir
&prompt.root; make obj
&prompt.root; make
&prompt.root; make installThe compile of sendmail should not have any problems
if /usr/src has not been changed extensively
and the shared libraries it needs are available.After sendmail has been compiled
and reinstalled, edit your /etc/mail/freebsd.mc
file (or whichever file you use as your .mc file. Many administrators
choose to use the output from &man.hostname.1; as the .mc file for
uniqueness). Add these lines to it:dnl set SASL options
TRUST_AUTH_MECH(`GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl
define(`confAUTH_MECHANISMS', `GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl
define(`confDEF_AUTH_INFO', `/etc/mail/auth-info')dnlThese options configure the different methods available to
sendmail for authenticating users.
If you would like to use a method other than
pwcheck, please see the
included documentation.Finally, run &man.make.1; while in /etc/mail.
That will run your new .mc file and create a .cf file named
freebsd.cf (or whatever name you have used
for your .mc file). Then use the
command make install restart, which will
copy the file to sendmail.cf, and will
properly restart sendmail.
For more information about this process, you should refer
to /etc/mail/Makefile.If all has gone correctly, you should be able to enter your login
information into the mail client and send a test message.
For further investigation, set the of
sendmail to 13 and watch
/var/log/maillog for any errors.You may wish to add the following line to /etc/rc.conf
so this service will be available after every system boot:cyrus_pwcheck_enable="YES"This will ensure the initialization of SMTP_AUTH upon system
boot.For more information, please see the sendmail
page regarding
SMTP authentication.MarcSilverContributed by Mail User AgentsMail User AgentsA Mail User Agent (MUA) is an application
that is used to send and receive email. Furthermore, as email
evolves and becomes more complex,
MUA's are becoming increasingly powerful in the
way they interact with email; this gives users increased
functionality and flexibility. &os; contains support for
numerous mail user agents, all of which can be easily installed
using the FreeBSD Ports Collection.
Users may choose between graphical email clients such as
evolution or
balsa, console based clients such as
mutt, pine
or mail, or the web interfaces used by some
large organizations.mail&man.mail.1; is the default Mail User Agent
(MUA) in &os;. It is a
console based MUA that offers all the basic
functionality required to send and receive text-based email,
though it is limited in interaction abilities with attachments
and can only support local mailboxes.Although mail does not natively support
interaction with POP or
IMAP servers, these mailboxes may be
downloaded to a local mbox file using an
application such as fetchmail, which
will be discussed later in this chapter ().In order to send and receive email, simply invoke the
mail command as per the following
example:&prompt.user; mailThe contents of the user mailbox in
/var/mail are
automatically read by the mail utility.
Should the mailbox be empty, the utility exits with a
message indicating that no mails could be found. Once the
mailbox has been read, the application interface is started, and
a list of messages will be displayed. Messages are automatically
numbered, as can be seen in the following example:Mail version 8.1 6/6/93. Type ? for help.
"/var/mail/marcs": 3 messages 3 new
>N 1 root@localhost Mon Mar 8 14:05 14/510 "test"
N 2 root@localhost Mon Mar 8 14:05 14/509 "user account"
N 3 root@localhost Mon Mar 8 14:05 14/509 "sample"Messages can now be read by using the tmail command, suffixed by the message number
that should be displayed. In this example, we will read the
first email:& t 1
Message 1:
From root@localhost Mon Mar 8 14:05:52 2004
X-Original-To: marcs@localhost
Delivered-To: marcs@localhost
To: marcs@localhost
Subject: test
Date: Mon, 8 Mar 2004 14:05:52 +0200 (SAST)
From: root@localhost (Charlie Root)
This is a test message, please reply if you receive it.As can be seen in the example above, the t
key will cause the message to be displayed with full headers.
To display the list of messages again, the h
key should be used.If the email requires a response, you may use
mail to reply, by using either the
R or rmail
keys. The R key instructs
mail to reply only to the sender of the
email, while r replies not only to the sender,
but also to other recipients of the message. You may also
suffix these commands with the mail number which you would like
make a reply to. Once this has been done, the response should
be entered, and the end of the message should be marked by a
single . on a new line. An example can be seen
below:& R 1
To: root@localhost
Subject: Re: test
Thank you, I did get your email.
.
EOTIn order to send new email, the m
key should be used, followed by the
recipient email address. Multiple recipients may also be
specified by separating each address with the ,
delimiter. The subject of the message may then be entered,
followed by the message contents. The end of the message should
be specified by putting a single . on a new
line.& mail root@localhost
Subject: I mastered mail
Now I can send and receive email using mail ... :)
.
EOTWhile inside the mail utility, the
? command may be used to display help at any
time, the &man.mail.1; manual page should also be consulted for
more help with mail.As previously mentioned, the &man.mail.1; command was not
originally designed to handle attachments, and thus deals with
them very poorly. Newer MUAs such as
mutt handle attachments in a much
more intelligent way. But should you still wish to use the
mail command, the converters/mpack port may be of
considerable use.muttmutt is a small yet very
powerful Mail User Agent, with excellent features,
just some of which include:The ability to thread messages;PGP support for digital signing and encryption of
email;MIME Support;Maildir Support;Highly customizable.All of these features help to make
mutt one of the most advanced mail
user agents available. See for more
information on mutt.The stable version of mutt may be
installed using the mail/mutt port, while the current
development version may be installed via the mail/mutt-devel port. After the port
has been installed, mutt can be
started by issuing the following command:&prompt.user; muttmutt will automatically read the
contents of the user mailbox in /var/mail and display the contents
if applicable. If no mails are found in the user mailbox, then
mutt will wait for commands from the
user. The example below shows mutt
displaying a list of messages:In order to read an email, simply select it using the cursor
keys, and press the Enter key. An example of
mutt displaying email can be seen
below:As with the &man.mail.1; command,
mutt allows users to reply only to
the sender of the message as well as to all recipients. To
reply only to the sender of the email, use the
r keyboard shortcut. To send a group reply,
which will be sent to the original sender as well as all the
message recipients, use the g shortcut.mutt makes use of the
&man.vi.1; command as an editor for creating and replying to
emails. This may be customized by the user by creating or
editing their own .muttrc file in their home directory and setting the
editor variable.In order to compose a new mail message, press
m. After a valid subject has been given,
mutt will start &man.vi.1; and the
mail can be written. Once the contents of the mail are
complete, save and quit from vi and
mutt will resume, displaying a
summary screen of the mail that is to be delivered. In order to
send the mail, press y. An example of the
summary screen can be seen below:mutt also contains extensive
help, which can be accessed from most of the menus by pressing
the ? key. The top line also displays the
keyboard shortcuts where appropriate.pinepine is aimed at a beginner
user, but also includes some advanced features.The pine software has had several remote vulnerabilities
discovered in the past, which allowed remote attackers to
execute arbitrary code as users on the local system, by the
action of sending a specially-prepared email. All such
known problems have been fixed, but the
pine code is written in a very insecure style and the &os;
Security Officer believes there are likely to be other
undiscovered vulnerabilities. You install
pine at your own risk.The current version of pine may
be installed using the mail/pine4 port. Once the port has
installed, pine can be started by
issuing the following command:&prompt.user; pineThe first time that pine is run
it displays a greeting page with a brief introduction, as well
as a request from the pine
development team to send an anonymous email message allowing
them to judge how many users are using their client. To send
this anonymous message, press Enter, or
alternatively press E to exit the greeting
without sending an anonymous message. An example of the
greeting page can be seen below:Users are then presented with the main menu, which can be
easily navigated using the cursor keys. This main menu provides
shortcuts for the composing new mails, browsing of mail directories,
and even the administration of address book entries. Below the
main menu, relevant keyboard shortcuts to perform functions
specific to the task at hand are shown.The default directory opened by pine
is the inbox. To view the message index, press
I, or select the MESSAGE INDEX
option as seen below:The message index shows messages in the current directory,
and can be navigated by using the cursor keys. Highlighted
messages can be read by pressing the
Enter key.In the screenshot below, a sample message is displayed by
pine. Keyboard shortcuts are
displayed as a reference at the bottom of the screen. An
example of one of these shortcuts is the r key,
which tells the MUA to reply to the current
message being displayed.Replying to an email in pine is
done using the pico editor, which is
installed by default with pine.
The pico utility makes it easy to
navigate around the message and is slightly more forgiving on
novice users than &man.vi.1; or &man.mail.1;. Once the reply
is complete, the message can be sent by pressing
CtrlX. The pine application
will ask for confirmation.The pine application can be
customized using the SETUP option from the main
menu. Consult
for more information.MarcSilverContributed by Using fetchmailfetchmailfetchmail is a full-featured
IMAP and POP client which
allows users to automatically download mail from remote
IMAP and POP servers and
save it into local mailboxes; there it can be accessed more easily.
fetchmail can be installed using the
mail/fetchmail port, and
offers various features, some of which include:Support of POP3,
APOP, KPOP,
IMAP, ETRN and
ODMR protocols.Ability to forward mail using SMTP, which
allows filtering, forwarding, and aliasing to function
normally.May be run in daemon mode to check periodically for new
messages.Can retrieve multiple mailboxes and forward them based
on configuration, to different local users.While it is outside the scope of this document to explain
all of fetchmail's features, some
basic features will be explained. The
fetchmail utility requires a
configuration file known as .fetchmailrc,
in order to run correctly. This file includes server information
as well as login credentials. Due to the sensitive nature of the
contents of this file, it is advisable to make it readable only by the owner,
with the following command:&prompt.user; chmod 600 .fetchmailrcThe following .fetchmailrc serves as an
example for downloading a single user mailbox using
POP. It tells
fetchmail to connect to example.com using a username of
joesoap and a password of
XXX. This example assumes that the user
joesoap is also a user on the local
system.poll example.com protocol pop3 username "joesoap" password "XXX"The next example connects to multiple POP
and IMAP servers and redirects to different
local usernames where applicable:poll example.com proto pop3:
user "joesoap", with password "XXX", is "jsoap" here;
user "andrea", with password "XXXX";
poll example2.net proto imap:
user "john", with password "XXXXX", is "myth" here;The fetchmail utility can be run in daemon
mode by running it with the flag, followed
by the interval (in seconds) that
fetchmail should poll servers listed
in the .fetchmailrc file. The following
example would cause fetchmail to poll
every 600 seconds:&prompt.user; fetchmail -d 600More information on fetchmail can
be found at .MarcSilverContributed by Using procmailprocmailThe procmail utility is an
incredibly powerful application used to filter incoming mail.
It allows users to define rules which can be
matched to incoming mails to perform specific functions or to
reroute mail to alternative mailboxes and/or email addresses.
procmail can be installed using the
mail/procmail port. Once
installed, it can be directly integrated into most
MTAs; consult your MTA
documentation for more information. Alternatively,
procmail can be integrated by adding
the following line to a .forward in the home
directory of the user utilizing
procmail features:"|exec /usr/local/bin/procmail || exit 75"The following section will display some basic
procmail rules, as well as brief
descriptions on what they do. These rules, and others must be
inserted into a .procmailrc file, which
must reside in the user's home directory.The majority of these rules can also be found in the
&man.procmailex.5; manual page.Forward all mail from user@example.com to an
external address of goodmail@example2.com::0
* ^From.*user@example.com
! goodmail@example2.comForward all mails shorter than 1000 bytes to an external
address of goodmail@example2.com::0
* < 1000
! goodmail@example2.comSend all mail sent to alternate@example.com
into a mailbox called alternate::0
* ^TOalternate@example.com
alternateSend all mail with a subject of Spam to
/dev/null::0
^Subject:.*Spam
/dev/nullA useful recipe that parses incoming &os;.org mailing lists
and places each list in its own mailbox::0
* ^Sender:.owner-freebsd-\/[^@]+@FreeBSD.ORG
{
LISTNAME=${MATCH}
:0
* LISTNAME??^\/[^@]+
FreeBSD-${MATCH}
}
diff --git a/pl_PL.ISO8859-2/books/handbook/network-servers/chapter.xml b/pl_PL.ISO8859-2/books/handbook/network-servers/chapter.xml
index af7d1a0fa7..acfaed70fa 100644
--- a/pl_PL.ISO8859-2/books/handbook/network-servers/chapter.xml
+++ b/pl_PL.ISO8859-2/books/handbook/network-servers/chapter.xml
@@ -1,4758 +1,4738 @@
MurrayStokelyReorganized by Network ServersSynopsisThis chapter will cover some of the more frequently used
network services on &unix; systems. We will cover how to
install, configure, test, and maintain many different types of
network services. Example configuration files are included
throughout this chapter for you to benefit from.After reading this chapter, you will know:How to manage the inetd
daemon.How to set up a network file system.How to set up a network information server for sharing
user accounts.How to set up automatic network settings using DHCP.How to set up a domain name server.How to set up the Apache HTTP Server.How to set up a File Transfer Protocol (FTP) Server.How to set up a file and print server for &windows;
clients using Samba.How to synchronize the time and date, and set up a
time server, with the NTP protocol.Before reading this chapter, you should:Understand the basics of the
/etc/rc scripts.Be familiar with basic network terminology.Know how to install additional third-party
software ().ChernLeeContributed by Updated for &os; 6.1-RELEASE by The &os; Documentation ProjectThe inetdSuper-ServerOverview&man.inetd.8; is sometimes referred to as the Internet
Super-Server because it manages connections for
several services. When a
connection is received by inetd, it
determines which program the connection is destined for, spawns
the particular process and delegates the socket to it (the program
is invoked with the service socket as its standard input, output
and error descriptors). Running
inetd for servers that are not heavily used can reduce the
overall system load, when compared to running each daemon
individually in stand-alone mode.Primarily, inetd is used to
spawn other daemons, but several trivial protocols are handled
directly, such as chargen,
auth, and
daytime.This section will cover the basics in configuring
inetd through its command-line
options and its configuration file,
/etc/inetd.conf.Settingsinetd is initialized through
the &man.rc.8; system. The
inetd_enable option is set to
NO by default, but may be turned on
by sysinstall during installation,
depending on the configuration chosen by the user.
Placing:
inetd_enable="YES" or
inetd_enable="NO" into
/etc/rc.conf will enable or disable
inetd starting at boot time.
The command:
/etc/rc.d/inetd rcvar
can be run to display the current effective setting.Additionally, different command-line options can be passed
to inetd via the
inetd_flags option.Command-Line OptionsLike most server daemons, inetd
has a number of options that it can be passed in order to
modify its behaviour. The full list of options reads:inetdOptions can be passed to inetd using the
inetd_flags option in
/etc/rc.conf. By default,
inetd_flags is set to
-wW -C 60, which turns on TCP wrapping for
inetd's services, and prevents any
single IP address from requesting any service more than 60 times
in any given minute.Novice users may be pleased to note that
these parameters usually do not need to be modified,
although we mention the rate-limiting options below as
they be useful should you find that you are receiving an
excessive amount of connections. A full list of options
can be found in the &man.inetd.8; manual.-c maximumSpecify the default maximum number of simultaneous
invocations of each service; the default is unlimited.
May be overridden on a per-service basis with the
parameter.-C rateSpecify the default maximum number of times a
service can be invoked from a single IP address in one
minute; the default is unlimited. May be overridden on a
per-service basis with the
parameter.-R rateSpecify the maximum number of times a service can be
invoked in one minute; the default is 256. A rate of 0
allows an unlimited number of invocations.-s maximumSpecify the maximum number of times a service can be
invoked from a single IP address at any one time; the
default is unlimited. May be overridden on a per-service
basis with the
parameter.inetd.confConfiguration of inetd is
done via the file /etc/inetd.conf.When a modification is made to
/etc/inetd.conf,
inetd can be forced to re-read its
configuration file by running the command:Reloading the inetd
configuration file&prompt.root; /etc/rc.d/inetd reloadEach line of the configuration file specifies an
individual daemon. Comments in the file are preceded by a
#. The format of each entry in
/etc/inetd.conf is as follows:service-name
socket-type
protocol
{wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]
user[:group][/login-class]
server-program
server-program-argumentsAn example entry for the &man.ftpd.8; daemon
using IPv4 might read:ftp stream tcp nowait root /usr/libexec/ftpd ftpd -lservice-nameThis is the service name of the particular daemon.
It must correspond to a service listed in
/etc/services. This determines
which port inetd must listen
to. If a new service is being created, it must be
placed in /etc/services
first.socket-typeEither stream,
dgram, raw, or
seqpacket. stream
must be used for connection-based, TCP daemons, while
dgram is used for daemons utilizing
the UDP transport protocol.protocolOne of the following:ProtocolExplanationtcp, tcp4TCP IPv4udp, udp4UDP IPv4tcp6TCP IPv6udp6UDP IPv6tcp46Both TCP IPv4 and v6udp46Both UDP IPv4 and v6{wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] indicates whether the
daemon invoked from inetd is
able to handle its own socket or not.
socket types must use the
option, while stream socket
daemons, which are usually multi-threaded, should use
. usually
hands off multiple sockets to a single daemon, while
spawns a child daemon for each
new socket.The maximum number of child daemons
inetd may spawn can be set
using the option. If a limit
of ten instances of a particular daemon is needed, a
/10 would be placed after
. Specifying /0
allows an unlimited number of childrenIn addition to , two other
options which limit the maximum connections from a single
place to a particular daemon can be enabled.
limits
the number of connections from any particular IP address
per minutes, e.g. a value of ten would limit any particular
IP address connecting to a particular service to ten
attempts per minute.
limits the number of children that can be started on
behalf on any single IP address at any moment. These
options are useful to prevent intentional or unintentional
excessive resource consumption and Denial of Service (DoS)
attacks to a machine.In this field, either of or
is mandatory.
,
and
are
optional.A stream-type multi-threaded daemon without any
,
or
limits
would simply be: nowait.The same daemon with a maximum limit of ten daemons
would read: nowait/10.The same setup with a limit of twenty
connections per IP address per minute and a maximum
total limit of ten child daemons would read:
nowait/10/20.These options are utilized by the default
settings of the &man.fingerd.8; daemon,
as seen here:finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -sFinally, an example of this field with a maximum of
100 children in total, with a maximum of 5 for any one
IP address would read:
nowait/100/0/5.userThis is the username that the particular daemon
should run as. Most commonly, daemons run as the
root user. For security purposes, it is
common to find some servers running as the
daemon user, or the least privileged
nobody user.server-programThe full path of the daemon to be executed when a
connection is received. If the daemon is a service
provided by inetd internally,
then should be
used.server-program-argumentsThis works in conjunction with
by specifying the
arguments, starting with argv[0],
passed to the daemon on invocation. If
mydaemon -d is the command line,
mydaemon -d would be the value of
. Again, if
the daemon is an internal service, use
here.SecurityDepending on the choices made at install time, many
of inetd's services may be enabled
by default. If there is no apparent need for a particular
daemon, consider disabling it. Place a # in front of the
daemon in question in /etc/inetd.conf,
and then reload the
inetd configuration. Some daemons, such as
fingerd, may not be desired at all
because they provide
information that may be useful to an attacker.Some daemons are not security-conscious and have long, or
non-existent, timeouts for connection attempts. This allows an
attacker to slowly send connections to a particular daemon,
thus saturating available resources. It may be a good idea to
place ,
or limitations on certain
daemons if you find that you have too many connections.By default, TCP wrapping is turned on. Consult the
&man.hosts.access.5; manual page for more information on placing
TCP restrictions on various inetd
invoked daemons.Miscellaneousdaytime,
time,
echo,
discard,
chargen, and
auth are all internally provided
services of inetd.The auth service provides
identity
network services, and is
configurable to a certain degree, whilst the others are simply on or off.Consult the &man.inetd.8; manual page for more in-depth
information.TomRhodesReorganized and enhanced by BillSwingleWritten by Network File System (NFS)NFSAmong the many different file systems that FreeBSD supports
is the Network File System, also known as NFS. NFS allows a system to share directories and
files with others over a network. By using NFS, users and programs can
access files on remote systems almost as if they were local
files.Some of the most notable benefits that
NFS can provide are:Local workstations use less disk space because commonly
used data can be stored on a single machine and still remain
accessible to others over the network.There is no need for users to have separate home
directories on every network machine. Home directories
could be set up on the NFS server and
made available throughout the network.Storage devices such as floppy disks, CDROM drives, and
&iomegazip; drives can be used by other machines on the network.
This may reduce the number of removable media drives
throughout the network.How NFS WorksNFS consists of at least two main
parts: a server and one or more clients. The client remotely
accesses the data that is stored on the server machine. In
order for this to function properly a few processes have to be
configured and running.The server has to be running the following daemons:NFSserverfile serverUNIX clientsrpcbindmountdnfsdDaemonDescriptionnfsdThe NFS daemon which services
requests from the NFS
clients.mountdThe NFS mount daemon which carries out
the requests that &man.nfsd.8; passes on to it.rpcbind This daemon allows
NFS clients to discover which port
the NFS server is using.The client can also run a daemon, known as
nfsiod. The
nfsiod daemon services the requests
from the NFS server. This is optional, and
improves performance, but is not required for normal and
correct operation. See the &man.nfsiod.8; manual page for
more information.
Configuring NFSNFSconfigurationNFS configuration is a relatively
straightforward process. The processes that need to be
running can all start at boot time with a few modifications to
your /etc/rc.conf file.On the NFS server, make sure that the
following options are configured in the
/etc/rc.conf file:rpcbind_enable="YES"
nfs_server_enable="YES"
mountd_flags="-r"mountd runs automatically
whenever the NFS server is enabled.On the client, make sure this option is present in
/etc/rc.conf:nfs_client_enable="YES"The /etc/exports file specifies which
file systems NFS should export (sometimes
referred to as share). Each line in
/etc/exports specifies a file system to be
exported and which machines have access to that file system.
Along with what machines have access to that file system,
access options may also be specified. There are many such
options that can be used in this file but only a few will be
mentioned here. You can easily discover other options by
reading over the &man.exports.5; manual page.Here are a few example /etc/exports
entries:NFSexport examplesThe following examples give an idea of how to export
file systems, although the settings may be different depending
on your environment and network configuration. For instance,
to export the /cdrom directory to three
example machines that have the same domain name as the server
(hence the lack of a domain name for each) or have entries in
your /etc/hosts file. The
flag makes the exported file system
read-only. With this flag, the remote system will not be able
to write any changes to the exported file system./cdrom -ro host1 host2 host3The following line exports /home to
three hosts by IP address. This is a useful setup if you have
a private network without a DNS server
configured. Optionally the /etc/hosts
file could be configured for internal hostnames; please review
&man.hosts.5; for more information. The
flag allows the subdirectories to be
mount points. In other words, it will not mount the
subdirectories but permit the client to mount only the
directories that are required or needed./home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4The following line exports /a so that
two clients from different domains may access the file system.
The flag allows the
root user on the remote system to write
data on the exported file system as root.
If the -maproot=root flag is not specified,
then even if a user has root access on
the remote system, he will not be able to modify files on
the exported file system./a -maproot=root host.example.com box.example.orgIn order for a client to access an exported file system,
the client must have permission to do so. Make sure the
client is listed in your /etc/exports
file.In /etc/exports, each line represents
the export information for one file system to one host. A
remote host can only be specified once per file system, and may
only have one default entry. For example, assume that
/usr is a single file system. The
following /etc/exports would be
invalid:# Invalid when /usr is one file system
/usr/src client
/usr/ports clientOne file system, /usr, has two lines
specifying exports to the same host, client.
The correct format for this situation is:/usr/src /usr/ports clientThe properties of one file system exported to a given host
must all occur on one line. Lines without a client specified
are treated as a single host. This limits how you can export
file systems, but for most people this is not an issue.The following is an example of a valid export list, where
/usr and /exports
are local file systems:# Export src and ports to client01 and client02, but only
# client01 has root privileges on it
/usr/src /usr/ports -maproot=root client01
/usr/src /usr/ports client02
# The client machines have root and can mount anywhere
# on /exports. Anyone in the world can mount /exports/obj read-only
/exports -alldirs -maproot=root client01 client02
/exports/obj -roThe mountd daemon must be forced to
recheck the /etc/exports file whenever it has
been modified, so the changes can take effect. This can be
accomplished either by sending a HUP signal to the running daemon:&prompt.root; kill -HUP `cat /var/run/mountd.pid`or by invoking the mountd &man.rc.8; script
with the appropriate parameter:&prompt.root; /etc/rc.d/mountd reloadPlease refer to for more
information about using rc scripts.Alternatively, a reboot will make FreeBSD set everything
up properly. A reboot is not necessary though.
Executing the following commands as root
should start everything up.On the NFS server:&prompt.root; rpcbind
&prompt.root; nfsd -u -t -n 4
&prompt.root; mountd -rOn the NFS client:&prompt.root; nfsiod -n 4Now everything should be ready to actually mount a remote file
system. In these examples the
server's name will be server and the client's
name will be client. If you only want to
temporarily mount a remote file system or would rather test the
configuration, just execute a command like this as root on the
client:NFSmounting&prompt.root; mount server:/home /mntThis will mount the /home directory
on the server at /mnt on the client. If
everything is set up correctly you should be able to enter
/mnt on the client and see all the files
that are on the server.If you want to automatically mount a remote file system
each time the computer boots, add the file system to the
/etc/fstab file. Here is an example:server:/home /mnt nfs rw 0 0The &man.fstab.5; manual page lists all the available
options.Practical UsesNFS has many practical uses. Some of
the more common ones are listed below:NFSusesSet several machines to share a CDROM or other media
among them. This is cheaper and often a more convenient
method to install software on multiple machines.On large networks, it might be more convenient to
configure a central NFS server in which
to store all the user home directories. These home
directories can then be exported to the network so that
users would always have the same home directory,
regardless of which workstation they log in to.Several machines could have a common
/usr/ports/distfiles directory. That
way, when you need to install a port on several machines,
you can quickly access the source without downloading it
on each machine.WylieStilwellContributed by ChernLeeRewritten by Automatic Mounts with amdamdautomatic mounter daemon&man.amd.8; (the automatic mounter daemon)
automatically mounts a
remote file system whenever a file or directory within that
file system is accessed. Filesystems that are inactive for a
period of time will also be automatically unmounted by
amd. Using
amd provides a simple alternative
to permanent mounts, as permanent mounts are usually listed in
/etc/fstab.amd operates by attaching
itself as an NFS server to the /host and
/net directories. When a file is accessed
within one of these directories, amd
looks up the corresponding remote mount and automatically mounts
it. /net is used to mount an exported
file system from an IP address, while /host
is used to mount an export from a remote hostname.An access to a file within
/host/foobar/usr would tell
amd to attempt to mount the
/usr export on the host
foobar.Mounting an Export with amdYou can view the available mounts of a remote host with
the showmount command. For example, to
view the mounts of a host named foobar, you
can use:&prompt.user; showmount -e foobar
Exports list on foobar:
/usr 10.10.10.0
/a 10.10.10.0
&prompt.user; cd /host/foobar/usrAs seen in the example, the showmount shows
/usr as an export. When changing directories to
/host/foobar/usr, amd
attempts to resolve the hostname foobar and
automatically mount the desired export.amd can be started by the
startup scripts by placing the following lines in
/etc/rc.conf:amd_enable="YES"Additionally, custom flags can be passed to
amd from the
amd_flags option. By default,
amd_flags is set to:amd_flags="-a /.amd_mnt -l syslog /host /etc/amd.map /net /etc/amd.map"The /etc/amd.map file defines the
default options that exports are mounted with. The
/etc/amd.conf file defines some of the more
advanced features of amd.Consult the &man.amd.8; and &man.amd.conf.5; manual pages for more
information.JohnLindContributed by Problems Integrating with Other SystemsCertain Ethernet adapters for ISA PC systems have limitations
which can lead to serious network problems, particularly with NFS.
This difficulty is not specific to FreeBSD, but FreeBSD systems
are affected by it.The problem nearly always occurs when (FreeBSD) PC systems are
networked with high-performance workstations, such as those made
by Silicon Graphics, Inc., and Sun Microsystems, Inc. The NFS
mount will work fine, and some operations may succeed, but
suddenly the server will seem to become unresponsive to the
client, even though requests to and from other systems continue to
be processed. This happens to the client system, whether the
client is the FreeBSD system or the workstation. On many systems,
there is no way to shut down the client gracefully once this
problem has manifested itself. The only solution is often to
reset the client, because the NFS situation cannot be
resolved.Though the correct solution is to get a
higher performance and capacity Ethernet adapter for the
FreeBSD system, there is a simple workaround that will allow
satisfactory operation. If the FreeBSD system is the
server, include the option
on the mount from the client. If the
FreeBSD system is the client, then mount
the NFS file system with the option .
These options may be specified using the fourth field of the
fstab entry on the client for automatic
mounts, or by using the parameter of the
&man.mount.8; command for manual mounts.It should be noted that there is a different problem,
sometimes mistaken for this one, when the NFS servers and
clients are on different networks. If that is the case, make
certain that your routers are routing the
necessary UDP information, or you will not get anywhere, no
matter what else you are doing.In the following examples, fastws is the host
(interface) name of a high-performance workstation, and
freebox is the host (interface) name of a FreeBSD
system with a lower-performance Ethernet adapter. Also,
/sharedfs will be the exported NFS
file system (see &man.exports.5;), and
/project will be the mount point on the
client for the exported file system. In all cases, note that
additional options, such as or
and may be desirable in
your application.Examples for the FreeBSD system (freebox)
as the client in /etc/fstab on
freebox:fastws:/sharedfs /project nfs rw,-r=1024 0 0As a manual mount command on freebox:&prompt.root; mount -t nfs -o -r=1024 fastws:/sharedfs /projectExamples for the FreeBSD system as the server in
/etc/fstab on
fastws:freebox:/sharedfs /project nfs rw,-w=1024 0 0As a manual mount command on fastws:&prompt.root; mount -t nfs -o -w=1024 freebox:/sharedfs /projectNearly any 16-bit Ethernet adapter will allow operation
without the above restrictions on the read or write size.For anyone who cares, here is what happens when the
failure occurs, which also explains why it is unrecoverable.
NFS typically works with a block size of
8 K (though it may do fragments of smaller sizes). Since
the maximum Ethernet packet is around 1500 bytes, the NFS
block gets split into multiple Ethernet
packets, even though it is still a single unit to the
upper-level code, and must be received, assembled, and
acknowledged as a unit. The
high-performance workstations can pump out the packets which
comprise the NFS unit one right after the other, just as close
together as the standard allows. On the smaller, lower
capacity cards, the later packets overrun the earlier packets
of the same unit before they can be transferred to the host
and the unit as a whole cannot be reconstructed or
acknowledged. As a result, the workstation will time out and
try again, but it will try again with the entire 8 K
unit, and the process will be repeated, ad infinitum.By keeping the unit size below the Ethernet packet size
limitation, we ensure that any complete Ethernet packet
received can be acknowledged individually, avoiding the
deadlock situation.Overruns may still occur when a high-performance
workstations is slamming data out to a PC system, but with the
better cards, such overruns are not guaranteed on NFS
units. When an overrun occurs, the units
affected will be retransmitted, and there will be a fair
chance that they will be received, assembled, and
acknowledged.BillSwingleWritten by EricOgrenEnhanced by UdoErdelhoffNetwork Information System (NIS/YP)What Is It?NISSolarisHP-UXAIXLinuxNetBSDOpenBSDNIS,
which stands for Network Information Services, was developed
by Sun Microsystems to centralize administration of &unix;
(originally &sunos;) systems. It has now essentially become
an industry standard; all major &unix; like systems
(&solaris;, HP-UX, &aix;, Linux, NetBSD, OpenBSD, FreeBSD,
etc) support NIS.yellow pagesNISNIS
was formerly known as Yellow Pages, but because of trademark
issues, Sun changed the name. The old term (and yp) is still
often seen and used.NISdomainsIt is a RPC-based client/server system that allows a group
of machines within an NIS domain to share a common set of
configuration files. This permits a system administrator to
set up NIS client systems with only minimal configuration data
and add, remove or modify configuration data from a single
location.Windows NTIt is similar to the &windowsnt; domain system; although
the internal implementation of the two are not at all similar,
the basic functionality can be compared.Terms/Processes You Should KnowThere are several terms and several important user
processes that you will come across when attempting to
implement NIS on FreeBSD, whether you are trying to create an
NIS server or act as an NIS client:rpcbindportmapTermDescriptionNIS domainnameAn NIS master server and all of its clients
(including its slave servers) have a NIS domainname.
Similar to an &windowsnt; domain name, the NIS
domainname does not have anything to do with
DNS.rpcbindMust be running in order to enable
RPC (Remote Procedure Call, a
network protocol used by NIS). If
rpcbind is not running, it
will be impossible to run an NIS server, or to act as
an NIS client.ypbindBinds an NIS client to its NIS
server. It will take the NIS domainname from the
system, and using RPC, connect to
the server. ypbind is the
core of client-server communication in an NIS
environment; if ypbind dies
on a client machine, it will not be able to access the
NIS server.ypservShould only be running on NIS servers; this is
the NIS server process itself. If &man.ypserv.8;
dies, then the server will no longer be able to
respond to NIS requests (hopefully, there is a slave
server to take over for it). There are some
implementations of NIS (but not the FreeBSD one), that
do not try to reconnect to another server if the
server it used before dies. Often, the only thing
that helps in this case is to restart the server
process (or even the whole server) or the
ypbind process on the
client.
rpc.yppasswddAnother process that should only be running on
NIS master servers; this is a daemon that will allow NIS
clients to change their NIS passwords. If this daemon
is not running, users will have to login to the NIS
master server and change their passwords there.How Does It Work?There are three types of hosts in an NIS environment:
master servers, slave servers, and clients. Servers act as a
central repository for host configuration information. Master
servers hold the authoritative copy of this information, while
slave servers mirror this information for redundancy. Clients
rely on the servers to provide this information to
them.Information in many files can be shared in this manner.
The master.passwd,
group, and hosts
files are commonly shared via NIS. Whenever a process on a
client needs information that would normally be found in these
files locally, it makes a query to the NIS server that it is
bound to instead.Machine Types
-
- NIS
- master server
-
- A NIS master server. This
+ A NIS master serverNISmaster server. This
server, analogous to a &windowsnt; primary domain
controller, maintains the files used by all of the NIS
clients. The passwd,
group, and other various files used
by the NIS clients live on the master server.It is possible for one machine to be an NIS
master server for more than one NIS domain. However,
this will not be covered in this introduction, which
assumes a relatively small-scale NIS
environment.
-
- NIS
- slave server
-
-
- NIS slave servers. Similar to
+ NIS slave serversNISslave server. Similar to
the &windowsnt; backup domain controllers, NIS slave
servers maintain copies of the NIS master's data files.
NIS slave servers provide the redundancy, which is
needed in important environments. They also help to
balance the load of the master server: NIS Clients
always attach to the NIS server whose response they get
first, and this includes slave-server-replies.
-
- NIS
- client
-
-
- NIS clients. NIS clients, like
+ NIS clientsNISclient. NIS clients, like
most &windowsnt; workstations, authenticate against the
NIS server (or the &windowsnt; domain controller in the
&windowsnt; workstations case) to log on.Using NIS/YPThis section will deal with setting up a sample NIS
environment.This section assumes that you are running
FreeBSD 3.3 or later. The instructions given here will
probably work for any version of FreeBSD
greater than 3.0, but there are no guarantees that this is
true.PlanningLet us assume that you are the administrator of a small
university lab. This lab, which consists of 15 FreeBSD
machines, currently has no centralized point of
administration; each machine has its own
/etc/passwd and
/etc/master.passwd. These files are
kept in sync with each other only through manual
intervention; currently, when you add a user to the lab, you
must run adduser on all 15 machines.
Clearly, this has to change, so you have decided to convert
the lab to use NIS, using two of the machines as
servers.Therefore, the configuration of the lab now looks something
like:Machine nameIP addressMachine roleellington10.0.0.2NIS mastercoltrane10.0.0.3NIS slavebasie10.0.0.4Faculty workstationbird10.0.0.5Client machinecli[1-11]10.0.0.[6-17]Other client machinesIf you are setting up a NIS scheme for the first time, it
is a good idea to think through how you want to go about it. No
matter what the size of your network, there are a few decisions
that need to be made.Choosing a NIS Domain NameNISdomainnameThis might not be the domainname that
you are used to. It is more accurately called the
NIS domainname. When a client broadcasts
its requests for info, it includes the name of the NIS
domain that it is part of. This is how multiple servers
on one network can tell which server should answer which
request. Think of the NIS domainname as the name for a
group of hosts that are related in some way.Some organizations choose to use their Internet
domainname for their NIS domainname. This is not
recommended as it can cause confusion when trying to debug
network problems. The NIS domainname should be unique
within your network and it is helpful if it describes the
group of machines it represents. For example, the Art
department at Acme Inc. might be in the
acme-art NIS domain. For this example,
assume you have chosen the name
test-domain.SunOSHowever, some operating systems (notably &sunos;) use
their NIS domain name as their Internet domain name. If one
or more machines on your network have this restriction, you
must use the Internet domain name as
your NIS domain name.Physical Server RequirementsThere are several things to keep in mind when choosing
a machine to use as a NIS server. One of the unfortunate
things about NIS is the level of dependency the clients
have on the server. If a client cannot contact the server
for its NIS domain, very often the machine becomes
unusable. The lack of user and group information causes
most systems to temporarily freeze up. With this in mind
you should make sure to choose a machine that will not be
prone to being rebooted regularly, or one that might be
used for development. The NIS server should ideally be a
stand alone machine whose sole purpose in life is to be an
NIS server. If you have a network that is not very
heavily used, it is acceptable to put the NIS server on a
machine running other services, just keep in mind that if
the NIS server becomes unavailable, it will affect
all of your NIS clients
adversely.NIS Servers The canonical copies of all NIS information are stored
on a single machine called the NIS master server. The
databases used to store the information are called NIS maps.
In FreeBSD, these maps are stored in
/var/yp/[domainname] where
[domainname] is the name of the NIS
domain being served. A single NIS server can support
several domains at once, therefore it is possible to have
several such directories, one for each supported domain.
Each domain will have its own independent set of
maps.NIS master and slave servers handle all NIS requests
with the ypserv daemon.
ypserv is responsible for receiving
incoming requests from NIS clients, translating the
requested domain and map name to a path to the corresponding
database file and transmitting data from the database back
to the client.Setting Up a NIS Master ServerNISserver configurationSetting up a master NIS server can be relatively
straight forward, depending on your needs. FreeBSD comes
with support for NIS out-of-the-box. All you need is to
add the following lines to
/etc/rc.conf, and FreeBSD will do the
rest for you.nisdomainname="test-domain"
This line will set the NIS domainname to
test-domain
upon network setup (e.g. after reboot).nis_server_enable="YES"
This will tell FreeBSD to start up the NIS server processes
when the networking is next brought up.nis_yppasswdd_enable="YES"
This will enable the rpc.yppasswdd
daemon which, as mentioned above, will allow users to
change their NIS password from a client machine.Depending on your NIS setup, you may need to add
further entries. See the section about NIS
servers that are also NIS clients, below, for
details.Now, all you have to do is to run the command
/etc/netstart as superuser. It will
set up everything for you, using the values you defined in
/etc/rc.conf.Initializing the NIS MapsNISmapsThe NIS maps are database files,
that are kept in the /var/yp
directory. They are generated from configuration files in
the /etc directory of the NIS master,
with one exception: the
/etc/master.passwd file. This is for
a good reason, you do not want to propagate passwords to
your root and other administrative
accounts to all the servers in the NIS domain. Therefore,
before we initialize the NIS maps, you should:&prompt.root; cp /etc/master.passwd /var/yp/master.passwd
&prompt.root; cd /var/yp
&prompt.root; vi master.passwdYou should remove all entries regarding system
accounts (bin,
tty, kmem,
games, etc), as well as any accounts
that you do not want to be propagated to the NIS clients
(for example root and any other UID 0
(superuser) accounts).Make sure the
/var/yp/master.passwd is neither group
nor world readable (mode 600)! Use the
chmod command, if appropriate.Tru64 UNIXWhen you have finished, it is time to initialize the
NIS maps! FreeBSD includes a script named
ypinit to do this for you (see its
manual page for more information). Note that this script
is available on most &unix; Operating Systems, but not on
all. On Digital UNIX/Compaq Tru64 UNIX it is called
ypsetup. Because we are generating
maps for an NIS master, we are going to pass the
option to ypinit.
To generate the NIS maps, assuming you already performed
the steps above, run:ellington&prompt.root; ypinit -m test-domain
Server Type: MASTER Domain: test-domain
Creating an YP server will require that you answer a few questions.
Questions will all be asked at the beginning of the procedure.
Do you want this procedure to quit on non-fatal errors? [y/n: n] n
Ok, please remember to go back and redo manually whatever fails.
If you don't, something might not work.
At this point, we have to construct a list of this domains YP servers.
rod.darktech.org is already known as master server.
Please continue to add any slave servers, one per line. When you are
done with the list, type a <control D>.
master server : ellington
next host to add: coltrane
next host to add: ^D
The current list of NIS servers looks like this:
ellington
coltrane
Is this correct? [y/n: y] y
[..output from map generation..]
NIS Map update completed.
ellington has been setup as an YP master server without any errors.ypinit should have created
/var/yp/Makefile from
/var/yp/Makefile.dist.
When created, this file assumes that you are operating
in a single server NIS environment with only FreeBSD
machines. Since test-domain has
a slave server as well, you must edit
/var/yp/Makefile:ellington&prompt.root; vi /var/yp/MakefileYou should comment out the line that saysNOPUSH = "True"(if it is not commented out already).Setting up a NIS Slave ServerNISslave serverSetting up an NIS slave server is even more simple than
setting up the master. Log on to the slave server and edit the
file /etc/rc.conf as you did before.
The only difference is that we now must use the
option when running ypinit.
The option requires the name of the NIS
master be passed to it as well, so our command line looks
like:coltrane&prompt.root; ypinit -s ellington test-domain
Server Type: SLAVE Domain: test-domain Master: ellington
Creating an YP server will require that you answer a few questions.
Questions will all be asked at the beginning of the procedure.
Do you want this procedure to quit on non-fatal errors? [y/n: n] n
Ok, please remember to go back and redo manually whatever fails.
If you don't, something might not work.
There will be no further questions. The remainder of the procedure
should take a few minutes, to copy the databases from ellington.
Transferring netgroup...
ypxfr: Exiting: Map successfully transferred
Transferring netgroup.byuser...
ypxfr: Exiting: Map successfully transferred
Transferring netgroup.byhost...
ypxfr: Exiting: Map successfully transferred
Transferring master.passwd.byuid...
ypxfr: Exiting: Map successfully transferred
Transferring passwd.byuid...
ypxfr: Exiting: Map successfully transferred
Transferring passwd.byname...
ypxfr: Exiting: Map successfully transferred
Transferring group.bygid...
ypxfr: Exiting: Map successfully transferred
Transferring group.byname...
ypxfr: Exiting: Map successfully transferred
Transferring services.byname...
ypxfr: Exiting: Map successfully transferred
Transferring rpc.bynumber...
ypxfr: Exiting: Map successfully transferred
Transferring rpc.byname...
ypxfr: Exiting: Map successfully transferred
Transferring protocols.byname...
ypxfr: Exiting: Map successfully transferred
Transferring master.passwd.byname...
ypxfr: Exiting: Map successfully transferred
Transferring networks.byname...
ypxfr: Exiting: Map successfully transferred
Transferring networks.byaddr...
ypxfr: Exiting: Map successfully transferred
Transferring netid.byname...
ypxfr: Exiting: Map successfully transferred
Transferring hosts.byaddr...
ypxfr: Exiting: Map successfully transferred
Transferring protocols.bynumber...
ypxfr: Exiting: Map successfully transferred
Transferring ypservers...
ypxfr: Exiting: Map successfully transferred
Transferring hosts.byname...
ypxfr: Exiting: Map successfully transferred
coltrane has been setup as an YP slave server without any errors.
Don't forget to update map ypservers on ellington.You should now have a directory called
/var/yp/test-domain. Copies of the NIS
master server's maps should be in this directory. You will
need to make sure that these stay updated. The following
/etc/crontab entries on your slave
servers should do the job:20 * * * * root /usr/libexec/ypxfr passwd.byname
21 * * * * root /usr/libexec/ypxfr passwd.byuidThese two lines force the slave to sync its maps with
the maps on the master server. Although these entries are
not mandatory, since the master server attempts to ensure
any changes to its NIS maps are communicated to its slaves
and because password information is vital to systems
depending on the server, it is a good idea to force the
updates. This is more important on busy networks where map
updates might not always complete.Now, run the command /etc/netstart on the
slave server as well, which again starts the NIS server.NIS Clients An NIS client establishes what is called a binding to a
particular NIS server using the
ypbind daemon.
ypbind checks the system's default
domain (as set by the domainname command),
and begins broadcasting RPC requests on the local network.
These requests specify the name of the domain for which
ypbind is attempting to establish a binding.
If a server that has been configured to serve the requested
domain receives one of the broadcasts, it will respond to
ypbind, which will record the server's
address. If there are several servers available (a master and
several slaves, for example), ypbind will
use the address of the first one to respond. From that point
on, the client system will direct all of its NIS requests to
that server. ypbind will
occasionally ping the server to make sure it is
still up and running. If it fails to receive a reply to one of
its pings within a reasonable amount of time,
ypbind will mark the domain as unbound and
begin broadcasting again in the hopes of locating another
server.Setting Up a NIS ClientNISclient configurationSetting up a FreeBSD machine to be a NIS client is fairly
straightforward.Edit the file /etc/rc.conf and
add the following lines in order to set the NIS domainname
and start ypbind upon network
startup:nisdomainname="test-domain"
nis_client_enable="YES"To import all possible password entries from the NIS
server, remove all user accounts from your
/etc/master.passwd file and use
vipw to add the following line to
the end of the file:+:::::::::This line will afford anyone with a valid account in
the NIS server's password maps an account. There are
many ways to configure your NIS client by changing this
line. See the netgroups
section below for more information.
For more detailed reading see O'Reilly's book on
Managing NFS and NIS.You should keep at least one local account (i.e.
not imported via NIS) in your
/etc/master.passwd and this
account should also be a member of the group
wheel. If there is something
wrong with NIS, this account can be used to log in
remotely, become root, and fix things.To import all possible group entries from the NIS
server, add this line to your
/etc/group file:+:*::After completing these steps, you should be able to run
ypcat passwd and see the NIS server's
passwd map.NIS SecurityIn general, any remote user can issue an RPC to
&man.ypserv.8; and retrieve the contents of your NIS maps,
provided the remote user knows your domainname. To prevent
such unauthorized transactions, &man.ypserv.8; supports a
feature called securenets which can be used to
restrict access to a given set of hosts. At startup,
&man.ypserv.8; will attempt to load the securenets information
from a file called
/var/yp/securenets.This path varies depending on the path specified with the
option. This file contains entries that
consist of a network specification and a network mask separated
by white space. Lines starting with # are
considered to be comments. A sample securenets file might look
like this:# allow connections from local host -- mandatory
127.0.0.1 255.255.255.255
# allow connections from any host
# on the 192.168.128.0 network
192.168.128.0 255.255.255.0
# allow connections from any host
# between 10.0.0.0 to 10.0.15.255
# this includes the machines in the testlab
10.0.0.0 255.255.240.0If &man.ypserv.8; receives a request from an address that
matches one of these rules, it will process the request
normally. If the address fails to match a rule, the request
will be ignored and a warning message will be logged. If the
/var/yp/securenets file does not exist,
ypserv will allow connections from any
host.The ypserv program also has support for
Wietse Venema's TCP Wrapper package.
This allows the administrator to use the
TCP Wrapper configuration files for
access control instead of
/var/yp/securenets.While both of these access control mechanisms provide some
security, they, like the privileged port test, are
vulnerable to IP spoofing attacks. All
NIS-related traffic should be blocked at your firewall.Servers using /var/yp/securenets
may fail to serve legitimate NIS clients with archaic TCP/IP
implementations. Some of these implementations set all
host bits to zero when doing broadcasts and/or fail to
observe the subnet mask when calculating the broadcast
address. While some of these problems can be fixed by
changing the client configuration, other problems may force
the retirement of the client systems in question or the
abandonment of /var/yp/securenets.Using /var/yp/securenets on a
server with such an archaic implementation of TCP/IP is a
really bad idea and will lead to loss of NIS functionality
for large parts of your network.TCP WrappersThe use of the TCP Wrapper
package increases the latency of your NIS server. The
additional delay may be long enough to cause timeouts in
client programs, especially in busy networks or with slow
NIS servers. If one or more of your client systems
suffers from these symptoms, you should convert the client
systems in question into NIS slave servers and force them
to bind to themselves.Barring Some Users from Logging OnIn our lab, there is a machine basie that
is supposed to be a faculty only workstation. We do not want
to take this machine out of the NIS domain, yet the
passwd file on the master NIS server
contains accounts for both faculty and students. What can we
do?There is a way to bar specific users from logging on to a
machine, even if they are present in the NIS database. To do
this, all you must do is add
-username to the
end of the /etc/master.passwd file on the
client machine, where username is
the username of the user you wish to bar from logging in.
This should preferably be done using vipw,
since vipw will sanity check your changes
to /etc/master.passwd, as well as
automatically rebuild the password database when you finish
editing. For example, if we wanted to bar user
bill from logging on to
basie we would:basie&prompt.root; vipw[add -bill to the end, exit]
vipw: rebuilding the database...
vipw: done
basie&prompt.root; cat /etc/master.passwd
root:[password]:0:0::0:0:The super-user:/root:/bin/csh
toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh
daemon:*:1:1::0:0:Owner of many system processes:/root:/sbin/nologin
operator:*:2:5::0:0:System &:/:/sbin/nologin
bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/sbin/nologin
tty:*:4:65533::0:0:Tty Sandbox:/:/sbin/nologin
kmem:*:5:65533::0:0:KMem Sandbox:/:/sbin/nologin
games:*:7:13::0:0:Games pseudo-user:/usr/games:/sbin/nologin
news:*:8:8::0:0:News Subsystem:/:/sbin/nologin
man:*:9:9::0:0:Mister Man Pages:/usr/share/man:/sbin/nologin
bind:*:53:53::0:0:Bind Sandbox:/:/sbin/nologin
uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico
xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/sbin/nologin
pop:*:68:6::0:0:Post Office Owner:/nonexistent:/sbin/nologin
nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/sbin/nologin
+:::::::::
-bill
basie&prompt.root;UdoErdelhoffContributed by Using NetgroupsnetgroupsThe method shown in the previous section works reasonably
well if you need special rules for a very small number of
users and/or machines. On larger networks, you
will forget to bar some users from logging
onto sensitive machines, or you may even have to modify each
machine separately, thus losing the main benefit of NIS:
centralized administration.The NIS developers' solution for this problem is called
netgroups. Their purpose and semantics
can be compared to the normal groups used by &unix; file
systems. The main differences are the lack of a numeric ID
and the ability to define a netgroup by including both user
accounts and other netgroups.Netgroups were developed to handle large, complex networks
with hundreds of users and machines. On one hand, this is
a Good Thing if you are forced to deal with such a situation.
On the other hand, this complexity makes it almost impossible to
explain netgroups with really simple examples. The example
used in the remainder of this section demonstrates this
problem.Let us assume that your successful introduction of NIS in
your laboratory caught your superiors' interest. Your next
job is to extend your NIS domain to cover some of the other
machines on campus. The two tables contain the names of the
new users and new machines as well as brief descriptions of
them.User Name(s)Descriptionalpha, betaNormal employees of the IT departmentcharlie, deltaThe new apprentices of the IT departmentecho, foxtrott, golf, ...Ordinary employeesable, baker, ...The current internsMachine Name(s)Descriptionwar, death,
famine,
pollutionYour most important servers. Only the IT
employees are allowed to log onto these
machines.pride, greed,
envy, wrath,
lust, slothLess important servers. All members of the IT
department are allowed to login onto these
machines.one, two,
three, four,
...Ordinary workstations. Only the
real employees are allowed to use
these machines.trashcanA very old machine without any critical data.
Even the intern is allowed to use this box.If you tried to implement these restrictions by separately
blocking each user, you would have to add one
-user line to
each system's passwd for each user who is
not allowed to login onto that system. If you forget just one
entry, you could be in trouble. It may be feasible to do this
correctly during the initial setup, however you
will eventually forget to add the lines
for new users during day-to-day operations. After all, Murphy
was an optimist.Handling this situation with netgroups offers several
advantages. Each user need not be handled separately; you
assign a user to one or more netgroups and allow or forbid
logins for all members of the netgroup. If you add a new
machine, you will only have to define login restrictions for
netgroups. If a new user is added, you will only have to add
the user to one or more netgroups. Those changes are
independent of each other: no more for each combination
of user and machine do... If your NIS setup is planned
carefully, you will only have to modify exactly one central
configuration file to grant or deny access to machines.The first step is the initialization of the NIS map
netgroup. FreeBSD's &man.ypinit.8; does not create this map by
default, but its NIS implementation will support it once it has
been created. To create an empty map, simply typeellington&prompt.root; vi /var/yp/netgroupand start adding content. For our example, we need at
least four netgroups: IT employees, IT apprentices, normal
employees and interns.IT_EMP (,alpha,test-domain) (,beta,test-domain)
IT_APP (,charlie,test-domain) (,delta,test-domain)
USERS (,echo,test-domain) (,foxtrott,test-domain) \
(,golf,test-domain)
INTERNS (,able,test-domain) (,baker,test-domain)IT_EMP, IT_APP etc.
are the names of the netgroups. Each bracketed group adds
one or more user accounts to it. The three fields inside a
group are:The name of the host(s) where the following items are
valid. If you do not specify a hostname, the entry is
valid on all hosts. If you do specify a hostname, you
will enter a realm of darkness, horror and utter confusion.The name of the account that belongs to this
netgroup.The NIS domain for the account. You can import
accounts from other NIS domains into your netgroup if you
are one of the unlucky fellows with more than one NIS
domain.Each of these fields can contain wildcards. See
&man.netgroup.5; for details.netgroupsNetgroup names longer than 8 characters should not be
used, especially if you have machines running other
operating systems within your NIS domain. The names are
case sensitive; using capital letters for your netgroup
names is an easy way to distinguish between user, machine
and netgroup names.Some NIS clients (other than FreeBSD) cannot handle
netgroups with a large number of entries. For example, some
older versions of &sunos; start to cause trouble if a netgroup
contains more than 15 entries. You can
circumvent this limit by creating several sub-netgroups with
15 users or less and a real netgroup that consists of the
sub-netgroups:BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...]
BIGGRP2 (,joe16,domain) (,joe17,domain) [...]
BIGGRP3 (,joe31,domain) (,joe32,domain)
BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3You can repeat this process if you need more than 225
users within a single netgroup.Activating and distributing your new NIS map is
easy:ellington&prompt.root; cd /var/yp
ellington&prompt.root; makeThis will generate the three NIS maps
netgroup,
netgroup.byhost and
netgroup.byuser. Use &man.ypcat.1; to
check if your new NIS maps are available:ellington&prompt.user; ypcat -k netgroup
ellington&prompt.user; ypcat -k netgroup.byhost
ellington&prompt.user; ypcat -k netgroup.byuserThe output of the first command should resemble the
contents of /var/yp/netgroup. The second
command will not produce output if you have not specified
host-specific netgroups. The third command can be used to
get the list of netgroups for a user.The client setup is quite simple. To configure the server
war, you only have to start
&man.vipw.8; and replace the line+:::::::::with+@IT_EMP:::::::::Now, only the data for the users defined in the netgroup
IT_EMP is imported into
war's password database and only
these users are allowed to login.Unfortunately, this limitation also applies to the
~ function of the shell and all routines
converting between user names and numerical user IDs. In
other words, cd
~user will not work,
ls -l will show the numerical ID instead of
the username and find . -user joe -print
will fail with No such user. To fix
this, you will have to import all user entries
without allowing them to login onto your
servers.This can be achieved by adding another line to
/etc/master.passwd. This line should
contain:+:::::::::/sbin/nologin, meaning
Import all entries but replace the shell with
/sbin/nologin in the imported
entries. You can replace any field in the
passwd entry by placing a default value in
your /etc/master.passwd.Make sure that the line
+:::::::::/sbin/nologin is placed after
+@IT_EMP:::::::::. Otherwise, all user
accounts imported from NIS will have /sbin/nologin as their
login shell.After this change, you will only have to change one NIS
map if a new employee joins the IT department. You could use
a similar approach for the less important servers by replacing
the old +::::::::: in their local version
of /etc/master.passwd with something like
this:+@IT_EMP:::::::::
+@IT_APP:::::::::
+:::::::::/sbin/nologinThe corresponding lines for the normal workstations
could be:+@IT_EMP:::::::::
+@USERS:::::::::
+:::::::::/sbin/nologinAnd everything would be fine until there is a policy
change a few weeks later: The IT department starts hiring
interns. The IT interns are allowed to use the normal
workstations and the less important servers; and the IT
apprentices are allowed to login onto the main servers. You
add a new netgroup IT_INTERN, add the new
IT interns to this netgroup and start to change the
configuration on each and every machine... As the old saying
goes: Errors in centralized planning lead to global
mess.NIS' ability to create netgroups from other netgroups can
be used to prevent situations like these. One possibility
is the creation of role-based netgroups. For example, you
could create a netgroup called
BIGSRV to define the login
restrictions for the important servers, another netgroup
called SMALLSRV for the less
important servers and a third netgroup called
USERBOX for the normal
workstations. Each of these netgroups contains the netgroups
that are allowed to login onto these machines. The new
entries for your NIS map netgroup should look like this:BIGSRV IT_EMP IT_APP
SMALLSRV IT_EMP IT_APP ITINTERN
USERBOX IT_EMP ITINTERN USERSThis method of defining login restrictions works
reasonably well if you can define groups of machines with
identical restrictions. Unfortunately, this is the exception
and not the rule. Most of the time, you will need the ability
to define login restrictions on a per-machine basis.Machine-specific netgroup definitions are the other
possibility to deal with the policy change outlined above. In
this scenario, the /etc/master.passwd of
each box contains two lines starting with +.
The first of them adds a netgroup with the accounts allowed to
login onto this machine, the second one adds all other
accounts with /sbin/nologin as shell. It
is a good idea to use the ALL-CAPS version of
the machine name as the name of the netgroup. In other words,
the lines should look like this:+@BOXNAME:::::::::
+:::::::::/sbin/nologinOnce you have completed this task for all your machines,
you will not have to modify the local versions of
/etc/master.passwd ever again. All
further changes can be handled by modifying the NIS map. Here
is an example of a possible netgroup map for this
scenario with some additional goodies:# Define groups of users first
IT_EMP (,alpha,test-domain) (,beta,test-domain)
IT_APP (,charlie,test-domain) (,delta,test-domain)
DEPT1 (,echo,test-domain) (,foxtrott,test-domain)
DEPT2 (,golf,test-domain) (,hotel,test-domain)
DEPT3 (,india,test-domain) (,juliet,test-domain)
ITINTERN (,kilo,test-domain) (,lima,test-domain)
D_INTERNS (,able,test-domain) (,baker,test-domain)
#
# Now, define some groups based on roles
USERS DEPT1 DEPT2 DEPT3
BIGSRV IT_EMP IT_APP
SMALLSRV IT_EMP IT_APP ITINTERN
USERBOX IT_EMP ITINTERN USERS
#
# And a groups for a special tasks
# Allow echo and golf to access our anti-virus-machine
SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain)
#
# machine-based netgroups
# Our main servers
WAR BIGSRV
FAMINE BIGSRV
# User india needs access to this server
POLLUTION BIGSRV (,india,test-domain)
#
# This one is really important and needs more access restrictions
DEATH IT_EMP
#
# The anti-virus-machine mentioned above
ONE SECURITY
#
# Restrict a machine to a single user
TWO (,hotel,test-domain)
# [...more groups to follow]If you are using some kind of database to manage your user
accounts, you should be able to create the first part of the
map with your database's report tools. This way, new users
will automatically have access to the boxes.One last word of caution: It may not always be advisable
to use machine-based netgroups. If you are deploying a couple of
dozen or even hundreds of identical machines for student labs,
you should use role-based netgroups instead of machine-based
netgroups to keep the size of the NIS map within reasonable
limits.Important Things to RememberThere are still a couple of things that you will need to do
differently now that you are in an NIS environment.Every time you wish to add a user to the lab, you
must add it to the master NIS server only,
and you must remember to rebuild the NIS
maps. If you forget to do this, the new user will
not be able to login anywhere except on the NIS master.
For example, if we needed to add a new user
jsmith to the lab, we would:&prompt.root; pw useradd jsmith
&prompt.root; cd /var/yp
&prompt.root; make test-domainYou could also run adduser jsmith instead
of pw useradd jsmith.Keep the administration accounts out of the
NIS maps. You do not want to be propagating
administrative accounts and passwords to machines that
will have users that should not have access to those
accounts.Keep the NIS master and slave secure, and
minimize their downtime. If somebody either
hacks or simply turns off these machines, they have
effectively rendered many people without the ability to
login to the lab.This is the chief weakness of any centralized administration
system. If you do
not protect your NIS servers, you will have a lot of angry
users!NIS v1 Compatibility FreeBSD's ypserv has some
support for serving NIS v1 clients. FreeBSD's NIS
implementation only uses the NIS v2 protocol, however other
implementations include support for the v1 protocol for
backwards compatibility with older systems. The
ypbind daemons supplied with these
systems will try to establish a binding to an NIS v1 server
even though they may never actually need it (and they may
persist in broadcasting in search of one even after they
receive a response from a v2 server). Note that while support
for normal client calls is provided, this version of
ypserv does not handle v1 map
transfer requests; consequently, it cannot be used as a master
or slave in conjunction with older NIS servers that only
support the v1 protocol. Fortunately, there probably are not
any such servers still in use today.NIS Servers That Are Also NIS Clients Care must be taken when running
ypserv in a multi-server domain
where the server machines are also NIS clients. It is
generally a good idea to force the servers to bind to
themselves rather than allowing them to broadcast bind
requests and possibly become bound to each other. Strange
failure modes can result if one server goes down and others
are dependent upon it. Eventually all the clients will time
out and attempt to bind to other servers, but the delay
involved can be considerable and the failure mode is still
present since the servers might bind to each other all over
again.You can force a host to bind to a particular server by running
ypbind with the
flag. If you do not want to do this manually each time you
reboot your NIS server, you can add the following lines to
your /etc/rc.conf:nis_client_enable="YES" # run client stuff as well
nis_client_flags="-S NIS domain,server"See &man.ypbind.8; for further information.Password FormatsNISpassword formatsOne of the most common issues that people run into when trying
to implement NIS is password format compatibility. If your NIS
server is using DES encrypted passwords, it will only support
clients that are also using DES. For example, if you have
&solaris; NIS clients in your network, then you will almost certainly
need to use DES encrypted passwords.To check which format your servers
and clients are using, look at /etc/login.conf.
If the host is configured to use DES encrypted passwords, then the
default class will contain an entry like this:default:\
:passwd_format=des:\
:copyright=/etc/COPYRIGHT:\
[Further entries elided]Other possible values for the passwd_format
capability include blf and md5
(for Blowfish and MD5 encrypted passwords, respectively).If you have made changes to
/etc/login.conf, you will also need to
rebuild the login capability database, which is achieved by
running the following command as
root:&prompt.root; cap_mkdb /etc/login.confThe format of passwords already in
/etc/master.passwd will not be updated
until a user changes his password for the first time
after the login capability database is
rebuilt.Next, in order to ensure that passwords are encrypted with
the format that you have chosen, you should also check that
the crypt_default in
/etc/auth.conf gives precedence to your
chosen password format. To do this, place the format that you
have chosen first in the list. For example, when using DES
encrypted passwords, the entry would be:crypt_default = des blf md5Having followed the above steps on each of the &os; based
NIS servers and clients, you can be sure that they all agree
on which password format is used within your network. If you
have trouble authenticating on an NIS client, this is a pretty
good place to start looking for possible problems. Remember:
if you want to deploy an NIS server for a heterogenous
network, you will probably have to use DES on all systems
because it is the lowest common standard.GregSutterWritten by Automatic Network Configuration (DHCP)What Is DHCP?Dynamic Host Configuration ProtocolDHCPInternet Software Consortium (ISC)DHCP, the Dynamic Host Configuration Protocol, describes
the means by which a system can connect to a network and obtain the
necessary information for communication upon that network. FreeBSD
versions prior to 6.0 use the ISC (Internet Software
Consortium) DHCP client (&man.dhclient.8;) implementation.
Later versions use the OpenBSD dhclient
taken from OpenBSD 3.7. All
information here regarding dhclient is for
use with either of the ISC or OpenBSD DHCP clients. The DHCP
server is the one included in the ISC distribution.What This Section CoversThis section describes both the client-side components of the ISC and OpenBSD DHCP client and
server-side components of the ISC DHCP system. The
client-side program, dhclient, comes
integrated within FreeBSD, and the server-side portion is
available from the net/isc-dhcp3-server port. The
&man.dhclient.8;, &man.dhcp-options.5;, and
&man.dhclient.conf.5; manual pages, in addition to the
references below, are useful resources.How It WorksUDPWhen dhclient, the DHCP client, is
executed on the client machine, it begins broadcasting
requests for configuration information. By default, these
requests are on UDP port 68. The server replies on UDP 67,
giving the client an IP address and other relevant network
information such as netmask, router, and DNS servers. All of
this information comes in the form of a DHCP
lease and is only valid for a certain time
(configured by the DHCP server maintainer). In this manner,
stale IP addresses for clients no longer connected to the
network can be automatically reclaimed.DHCP clients can obtain a great deal of information from
the server. An exhaustive list may be found in
&man.dhcp-options.5;.FreeBSD Integration&os; fully integrates the ISC or OpenBSD DHCP client,
dhclient (according to the &os; version you run). DHCP client support is provided
within both the installer and the base system, obviating the need
for detailed knowledge of network configurations on any network
that runs a DHCP server. dhclient has been
included in all FreeBSD distributions since 3.2.sysinstallDHCP is supported by
sysinstall. When configuring a
network interface within
sysinstall, the second question
asked is: Do you want to try DHCP configuration of
the interface?. Answering affirmatively will
execute dhclient, and if successful, will
fill in the network configuration information
automatically.There are two things you must do to have your system use
DHCP upon startup:DHCPrequirementsMake sure that the bpf
device is compiled into your kernel. To do this, add
device bpf to your kernel
configuration file, and rebuild the kernel. For more
information about building kernels, see .The
bpf device is already part of
the GENERIC kernel that is supplied
with FreeBSD, so if you do not have a custom kernel, you
should not need to create one in order to get DHCP
working.For those who are particularly security conscious,
you should be warned that bpf
is also the device that allows packet sniffers to work
correctly (although they still have to be run as
root). bpfis required to use DHCP, but if
you are very sensitive about security, you probably
should not add bpf to your
kernel in the expectation that at some point in the
future you will be using DHCP.Edit your /etc/rc.conf to
include the following:ifconfig_fxp0="DHCP"Be sure to replace fxp0 with the
designation for the interface that you wish to dynamically
configure, as described in
.If you are using a different location for
dhclient, or if you wish to pass additional
flags to dhclient, also include the
following (editing as necessary):dhcp_program="/sbin/dhclient"
dhcp_flags=""DHCPserverThe DHCP server, dhcpd, is included
as part of the net/isc-dhcp3-server port in the ports
collection. This port contains the ISC DHCP server and
documentation.FilesDHCPconfiguration files/etc/dhclient.confdhclient requires a configuration file,
/etc/dhclient.conf. Typically the file
contains only comments, the defaults being reasonably sane. This
configuration file is described by the &man.dhclient.conf.5;
manual page./sbin/dhclientdhclient is statically linked and
resides in /sbin. The &man.dhclient.8;
manual page gives more information about
dhclient./sbin/dhclient-scriptdhclient-script is the FreeBSD-specific
DHCP client configuration script. It is described in
&man.dhclient-script.8;, but should not need any user
modification to function properly./var/db/dhclient.leasesThe DHCP client keeps a database of valid leases in this
file, which is written as a log. &man.dhclient.leases.5;
gives a slightly longer description.Further ReadingThe DHCP protocol is fully described in
RFC 2131.
An informational resource has also been set up at
.Installing and Configuring a DHCP ServerWhat This Section CoversThis section provides information on how to configure
a FreeBSD system to act as a DHCP server using the ISC
(Internet Software Consortium) implementation of the DHCP
server.The server is not provided as part of
FreeBSD, and so you will need to install the
net/isc-dhcp3-server
port to provide this service. See for
more information on using the Ports Collection.DHCP Server InstallationDHCPinstallationIn order to configure your FreeBSD system as a DHCP
server, you will need to ensure that the &man.bpf.4;
device is compiled into your kernel. To do this, add
device bpf to your kernel
configuration file, and rebuild the kernel. For more
information about building kernels, see .The bpf device is already
part of the GENERIC kernel that is
supplied with FreeBSD, so you do not need to create a custom
kernel in order to get DHCP working.Those who are particularly security conscious
should note that bpf
is also the device that allows packet sniffers to work
correctly (although such programs still need privileged
access). bpfis required to use DHCP, but if
you are very sensitive about security, you probably
should not include bpf in your
kernel purely because you expect to use DHCP at some
point in the future.The next thing that you will need to do is edit the sample
dhcpd.conf which was installed by the
net/isc-dhcp3-server port.
By default, this will be
/usr/local/etc/dhcpd.conf.sample, and you
should copy this to
/usr/local/etc/dhcpd.conf before proceeding
to make changes.Configuring the DHCP ServerDHCPdhcpd.confdhcpd.conf is
comprised of declarations regarding subnets and hosts, and is
perhaps most easily explained using an example :option domain-name "example.com";
option domain-name-servers 192.168.4.100;
option subnet-mask 255.255.255.0;
default-lease-time 3600;
max-lease-time 86400;
ddns-update-style none;
subnet 192.168.4.0 netmask 255.255.255.0 {
range 192.168.4.129 192.168.4.254;
option routers 192.168.4.1;
}
host mailhost {
hardware ethernet 02:03:04:05:06:07;
fixed-address mailhost.example.com;
}This option specifies the domain that will be provided
to clients as the default search domain. See
&man.resolv.conf.5; for more information on what this
means.This option specifies a comma separated list of DNS
servers that the client should use.The netmask that will be provided to clients.A client may request a specific length of time that a
lease will be valid. Otherwise the server will assign
a lease with this expiry value (in seconds).This is the maximum length of time that the server will
lease for. Should a client request a longer lease, a lease
will be issued, although it will only be valid for
max-lease-time seconds.This option specifies whether the DHCP server should
attempt to update DNS when a lease is accepted or released.
In the ISC implementation, this option is
required.This denotes which IP addresses should be used in
the pool reserved for allocating to clients. IP
addresses between, and including, the ones stated are
handed out to clients.Declares the default gateway that will be provided to
clients.The hardware MAC address of a host (so that the DHCP server
can recognize a host when it makes a request).Specifies that the host should always be given the
same IP address. Note that using a hostname is
correct here, since the DHCP server will resolve the
hostname itself before returning the lease
information.Once you have finished writing your
dhcpd.conf,
you should enable the DHCP server in
/etc/rc.conf, i.e. by adding:dhcpd_enable="YES"
dhcpd_ifaces="dc0"Replace the dc0 interface name with the
interface (or interfaces, separated by whitespace) that your DHCP
server should listen on for DHCP client requests.Then, you can proceed to start the server by issuing the
following command:&prompt.root; /usr/local/etc/rc.d/isc-dhcpd.sh startShould you need to make changes to the configuration of your
server in the future, it is important to note that sending a
SIGHUP signal to
dhcpd does not
result in the configuration being reloaded, as it does with most
daemons. You will need to send a SIGTERM
signal to stop the process, and then restart it using the command
above.FilesDHCPconfiguration files/usr/local/sbin/dhcpddhcpd is statically linked and
resides in /usr/local/sbin. The
&man.dhcpd.8; manual page installed with the
port gives more information about
dhcpd./usr/local/etc/dhcpd.confdhcpd requires a configuration
file, /usr/local/etc/dhcpd.conf before it
will start providing service to clients. This file needs to
contain all the information that should be provided to clients
that are being serviced, along with information regarding the
operation of the server. This configuration file is described
by the &man.dhcpd.conf.5; manual page installed
by the port./var/db/dhcpd.leasesThe DHCP server keeps a database of leases it has issued
in this file, which is written as a log. The manual page
&man.dhcpd.leases.5;, installed by the port
gives a slightly longer description./usr/local/sbin/dhcrelaydhcrelay is used in advanced
environments where one DHCP server forwards a request from a
client to another DHCP server on a separate network. If you
require this functionality, then install the net/isc-dhcp3-relay port. The
&man.dhcrelay.8; manual page provided with the
port contains more detail.ChernLeeContributed by TomRhodesDanielGerzoDomain Name System (DNS)OverviewBIND&os; utilizes, by default, a version of BIND (Berkeley
Internet Name Domain), which is the most common implementation
of the DNS protocol. DNS
is the protocol through which names are mapped to
IP addresses, and vice versa. For example, a
query for www.FreeBSD.org will
receive a reply with the IP address of The
&os; Project's web server, whereas, a query for ftp.FreeBSD.org will return the
IP address of the corresponding
FTP machine. Likewise, the opposite can
happen. A query for an IP address can
resolve its hostname. It is not necessary to run a name server
to perform DNS lookups on a system.&os; currently comes with BIND9
DNS server software by default. Our
installation provides enhanced security features, a new file
system layout and automated &man.chroot.8; configuration.DNSDNS is coordinated across the Internet
through a somewhat complex system of authoritative root, Top
Level Domain (TLD), and other smaller-scale
name servers which host and cache individual domain
information.Currently, BIND is maintained by the
Internet Software Consortium
.TerminologyTo understand this document, some terms related to
DNS must be understood.resolverreverse DNSroot zoneTermDefinitionForward DNSMapping of hostnames to IP addresses.OriginRefers to the domain covered in a particular zone
file.named, BIND, name serverCommon names for the BIND name server package within
&os;.ResolverA system process through which a
machine queries a name server for zone information.Reverse DNSThe opposite of forward DNS;
mapping of IP addresses to
hostnames.Root zoneThe beginning of the Internet zone hierarchy.
All zones fall under the root zone, similar to how
all files in a file system fall under the root
directory.ZoneAn individual domain, subdomain, or portion of the
DNS administered by the same
authority.zonesexamplesExamples of zones:. is the root zone.org. is a Top Level Domain
(TLD) under the root zone.example.org. is a
zone under the org.
TLD.1.168.192.in-addr.arpa is a zone
referencing all IP addresses which fall
under the 192.168.1.*
IP space.As one can see, the more specific part of a hostname appears
to its left. For example, example.org. is more specific than
org., as org. is more specific
than the root zone. The layout of each part of a hostname is
much like a file system: the
/dev directory falls
within the root, and so on.Reasons to Run a Name ServerName servers usually come in two forms: an authoritative
name server, and a caching name server.An authoritative name server is needed when:One wants to serve DNS information to
the world, replying authoritatively to queries.A domain, such as example.org, is registered and
IP addresses need to be assigned to
hostnames under it.An IP address block requires reverse
DNS entries (IP to
hostname).A backup or second name server, called a slave, will
reply to queries.A caching name server is needed when:A local DNS server may cache and
respond more quickly than querying an outside name
server.When one queries for www.FreeBSD.org, the resolver usually
queries the uplink ISP's name server, and
retrieves the reply. With a local, caching
DNS server, the query only has to be made
once to the outside world by the caching DNS
server. Every additional query will not have to look to the
outside of the local network, since the information is cached
locally.How It WorksIn &os;, the BIND daemon is called
named for obvious reasons.FileDescription&man.named.8;The BIND daemon.&man.rndc.8;Name server control utility./etc/namedbDirectory where BIND zone information resides./etc/namedb/named.confConfiguration file of the daemon.Depending on how a given zone is configured on the server,
the files related to that zone can be found in the master, slave, or dynamic subdirectories of the
/etc/namedb directory.
These files contain the DNS information that
will be given out by the name server in response to queries.Starting BINDBINDstartingSince BIND is installed by default, configuring it all is
relatively simple.The default named configuration
is that of a basic resolving name server, ran in a
&man.chroot.8; environment. To start the server one time with
this configuration, use the following command:&prompt.root; /etc/rc.d/named forcestartTo ensure the named daemon is
started at boot each time, put the following line into the
/etc/rc.conf:named_enable="YES"There are obviously many configuration options for
/etc/namedb/named.conf that are beyond the
scope of this document. However, if you are interested in the
startup options for named on &os;,
take a look at the
named_* flags in
/etc/defaults/rc.conf and consult the
&man.rc.conf.5; manual page. The
section is also a good read.Configuration FilesBINDconfiguration filesConfiguration files for named
currently reside in
/etc/namedb directory and
will need modification before use, unless all that is needed is
a simple resolver. This is where most of the configuration will
be performed.Using make-localhostTo configure a master zone for the localhost visit the
/etc/namedb directory
and run the following command:&prompt.root; sh make-localhostIf all went well, a new file should exist in the
master subdirectory.
The filenames should be localhost.rev for
the local domain name and localhost-v6.rev
for IPv6 configurations. As the default
configuration file, required information will
be present in the named.conf file./etc/namedb/named.conf// $FreeBSD$
//
// Refer to the named.conf(5) and named(8) man pages, and the documentation
// in /usr/share/doc/bind9 for more details.
//
// If you are going to set up an authoritative server, make sure you
// understand the hairy details of how DNS works. Even with
// simple mistakes, you can break connectivity for affected parties,
// or cause huge amounts of useless Internet traffic.
options {
directory "/etc/namedb";
pid-file "/var/run/named/pid";
dump-file "/var/dump/named_dump.db";
statistics-file "/var/stats/named.stats";
// If named is being used only as a local resolver, this is a safe default.
// For named to be accessible to the network, comment this option, specify
// the proper IP address, or delete this option.
listen-on { 127.0.0.1; };
// If you have IPv6 enabled on this system, uncomment this option for
// use as a local resolver. To give access to the network, specify
// an IPv6 address, or the keyword "any".
// listen-on-v6 { ::1; };
// In addition to the "forwarders" clause, you can force your name
// server to never initiate queries of its own, but always ask its
// forwarders only, by enabling the following line:
//
// forward only;
// If you've got a DNS server around at your upstream provider, enter
// its IP address here, and enable the line below. This will make you
// benefit from its cache, thus reduce overall DNS traffic in the Internet.
/*
forwarders {
127.0.0.1;
};
*/Just as the comment says, to benefit from an uplink's
cache, forwarders can be enabled here.
Under normal circumstances, a name server will recursively
query the Internet looking at certain name servers until it
finds the answer it is looking for. Having this enabled will
have it query the uplink's name server (or name server
provided) first, taking advantage of its cache. If the uplink
name server in question is a heavily trafficked, fast name
server, enabling this may be worthwhile.127.0.0.1 will
not work here. Change this
IP address to a name server at your
uplink. /*
* If there is a firewall between you and nameservers you want
* to talk to, you might need to uncomment the query-source
* directive below. Previous versions of BIND always asked
* questions using port 53, but BIND versions 8 and later
* use a pseudo-random unprivileged UDP port by default.
*/
// query-source address * port 53;
};
// If you enable a local name server, don't forget to enter 127.0.0.1
// first in your /etc/resolv.conf so this server will be queried.
// Also, make sure to enable it in /etc/rc.conf.
zone "." {
type hint;
file "named.root";
};
zone "0.0.127.IN-ADDR.ARPA" {
type master;
file "master/localhost.rev";
};
// RFC 3152
zone "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA" {
type master;
file "master/localhost-v6.rev";
};
// NB: Do not use the IP addresses below, they are faked, and only
// serve demonstration/documentation purposes!
//
// Example slave zone config entries. It can be convenient to become
// a slave at least for the zone your own domain is in. Ask
// your network administrator for the IP address of the responsible
// primary.
//
// Never forget to include the reverse lookup (IN-ADDR.ARPA) zone!
// (This is named after the first bytes of the IP address, in reverse
// order, with ".IN-ADDR.ARPA" appended.)
//
// Before starting to set up a primary zone, make sure you fully
// understand how DNS and BIND works. There are sometimes
// non-obvious pitfalls. Setting up a slave zone is simpler.
//
// NB: Don't blindly enable the examples below. :-) Use actual names
// and addresses instead.
/* An example master zone
zone "example.net" {
type master;
file "master/example.net";
};
*/
/* An example dynamic zone
key "exampleorgkey" {
algorithm hmac-md5;
secret "sf87HJqjkqh8ac87a02lla==";
};
zone "example.org" {
type master;
allow-update {
key "exampleorgkey";
};
file "dynamic/example.org";
};
*/
/* Examples of forward and reverse slave zones
zone "example.com" {
type slave;
file "slave/example.com";
masters {
192.168.1.1;
};
};
zone "1.168.192.in-addr.arpa" {
type slave;
file "slave/1.168.192.in-addr.arpa";
masters {
192.168.1.1;
};
};
*/In named.conf, these are examples of
slave entries for a forward and reverse zone.For each new zone served, a new zone entry must be added
to named.conf.For example, the simplest zone entry for
example.org can look
like:zone "example.org" {
type master;
file "master/example.org";
};The zone is a master, as indicated by the
statement, holding its zone information
in /etc/namedb/master/example.org
indicated by the statement.zone "example.org" {
type slave;
file "slave/example.org";
};In the slave case, the zone information is transferred
from the master name server for the particular zone, and saved
in the file specified. If and when the master server dies or
is unreachable, the slave name server will have the
transferred zone information and will be able to serve
it.Zone FilesBINDzone filesAn example master zone file for example.org (existing within
/etc/namedb/master/example.org) is as
follows:$TTL 3600 ; 1 hour
example.org. IN SOA ns1.example.org. admin.example.org. (
2006051501 ; Serial
10800 ; Refresh
3600 ; Retry
604800 ; Expire
86400 ; Minimum TTL
)
; DNS Servers
IN NS ns1.example.org.
IN NS ns2.example.org.
; MX Records
IN MX 10 mx.example.org.
IN MX 20 mail.example.org.
IN A 192.168.1.1
; Machine Names
localhost IN A 127.0.0.1
ns1 IN A 192.168.1.2
ns2 IN A 192.168.1.3
mx IN A 192.168.1.4
mail IN A 192.168.1.5
; Aliases
www IN CNAME @
Note that every hostname ending in a . is an
exact hostname, whereas everything without a trailing
. is referenced to the origin. For example,
www is translated into
www.origin.
In our fictitious zone file, our origin is
example.org., so www
would translate to www.example.org.
The format of a zone file follows:
recordname IN recordtype valueDNSrecords
The most commonly used DNS records:
SOAstart of zone authorityNSan authoritative name serverAa host addressCNAMEthe canonical name for an aliasMXmail exchangerPTRa domain name pointer (used in reverse DNS)
example.org. IN SOA ns1.example.org. admin.example.org. (
2006051501 ; Serial
10800 ; Refresh after 3 hours
3600 ; Retry after 1 hour
604800 ; Expire after 1 week
86400 ) ; Minimum TTL of 1 dayexample.org.the domain name, also the origin for this
zone file.ns1.example.org.the primary/authoritative name server for this
zone.admin.example.org.the responsible person for this zone,
email address with @
replaced. (admin@example.org becomes
admin.example.org)2006051501the serial number of the file. This
must be incremented each time the zone file is
modified. Nowadays, many admins prefer a
yyyymmddrr format for the serial
number. 2006051501 would mean
last modified 05/15/2006, the latter
01 being the first time the zone
file has been modified this day. The serial number
is important as it alerts slave name servers for a
zone when it is updated.
IN NS ns1.example.org.
This is an NS entry. Every name server that is going to reply
authoritatively for the zone must have one of these entries.
localhost IN A 127.0.0.1
ns1 IN A 192.168.1.2
ns2 IN A 192.168.1.3
mx IN A 192.168.1.4
mail IN A 192.168.1.5
The A record indicates machine names. As seen above,
ns1.example.org would resolve
to 192.168.1.2.
IN A 192.168.1.1This line assigns IP address
192.168.1.1 to the current origin,
in this case example.org.
www IN CNAME @
The canonical name record is usually used for giving aliases
to a machine. In the example, www is
aliased to the master machine which name equals
to domain name example.org
(192.168.1.1).
CNAMEs can be used to provide alias
hostnames, or round robin one hostname among multiple
machines.
MX record
IN MX 10 mail.example.org.
The MX record indicates which mail
servers are responsible for handling incoming mail for the
zone. mail.example.org is the
hostname of the mail server, and 10 being the priority of
that mail server.
One can have several mail servers, with priorities of 10,
20 and so on. A mail server attempting to deliver to example.org would first try the
highest priority MX (the record with the lowest priority
number), then the second highest, etc, until the mail can be
properly delivered.
For in-addr.arpa zone files (reverse DNS), the same format is
used, except with PTR entries instead of
A or CNAME.
$TTL 3600
1.168.192.in-addr.arpa. IN SOA ns1.example.org. admin.example.org. (
2006051501 ; Serial
10800 ; Refresh
3600 ; Retry
604800 ; Expire
3600 ) ; Minimum
IN NS ns1.example.org.
IN NS ns2.example.org.
1 IN PTR example.org.
2 IN PTR ns1.example.org.
3 IN PTR ns2.example.org.
4 IN PTR mx.example.org.
5 IN PTR mail.example.org.This file gives the proper IP address to hostname
mappings of our above fictitious domain.Caching Name ServerBINDcaching name serverA caching name server is a name server that is not
authoritative for any zones. It simply asks queries of its
own, and remembers them for later use. To set one up, just
configure the name server as usual, omitting any inclusions of
zones.SecurityAlthough BIND is the most common implementation of DNS,
there is always the issue of security. Possible and
exploitable security holes are sometimes found.
While &os; automatically drops
named into a &man.chroot.8;
environment; there are several other security mechanisms in
place which could help to lure off possible
DNS service attacks.It is always good idea to read CERT's security advisories
and to subscribe to the &a.security-notifications; to stay up to
date with the current Internet and &os; security issues.If a problem arises, keeping sources up to date and
having a fresh build of named would
not hurt.Further ReadingBIND/named manual pages:
&man.rndc.8; &man.named.8; &man.named.conf.5;Official ISC BIND
PageOfficial ISC BIND
Forum
BIND FAQO'Reilly
DNS and BIND 5th EditionRFC1034
- Domain Names - Concepts and FacilitiesRFC1035
- Domain Names - Implementation and SpecificationMurrayStokelyContributed by Apache HTTP Serverweb serverssetting upApacheOverview&os; is used to run some of the busiest web sites in the
world. The majority of web servers on the Internet are using
the Apache HTTP Server.
Apache software packages should be
included on your FreeBSD installation media. If you did not
install Apache when you first
installed FreeBSD, then you can install it from the www/apache13 or www/apache20 port.Once Apache has been installed
successfully, it must be configured.This section covers version 1.3.X of the
Apache HTTP Server as that is the
most widely used version for &os;. Apache 2.X introduces many
new technologies but they are not discussed here. For more
information about Apache 2.X, please see .ConfigurationApacheconfiguration fileThe main Apache HTTP Server configuration file is
installed as
/usr/local/etc/apache/httpd.conf on &os;.
This file is a typical &unix; text configuration file with
comment lines beginning with the #
character. A comprehensive description of all possible
configuration options is outside the scope of this book, so
only the most frequently modified directives will be described
here.ServerRoot "/usr/local"This specifies the default directory hierarchy for
the Apache installation. Binaries are stored in the
bin and
sbin subdirectories
of the server root, and configuration files are stored in
etc/apache.ServerAdmin you@your.addressThe address to which problems with the server should
be emailed. This address appears on some
server-generated pages, such as error documents.ServerName www.example.comServerName allows you to set a host name which is
sent back to clients for your server if it is different
to the one that the host is configured with (i.e., use www
instead of the host's real name).DocumentRoot "/usr/local/www/data"DocumentRoot: The directory out of which you will
serve your documents. By default, all requests are taken
from this directory, but symbolic links and aliases may
be used to point to other locations.It is always a good idea to make backup copies of your
Apache configuration file before making changes. Once you are
satisfied with your initial configuration you are ready to
start running Apache.Running ApacheApachestarting or stoppingApache does not run from the
inetd super server as many other
network servers do. It is configured to run standalone for
better performance for incoming HTTP requests from client web
browsers. A shell script wrapper is included to make
starting, stopping, and restarting the server as simple as
possible. To start up Apache for
the first time, just run:&prompt.root; /usr/local/sbin/apachectl startYou can stop the server at any time by typing:&prompt.root; /usr/local/sbin/apachectl stopAfter making changes to the configuration file for any
reason, you will need to restart the server:&prompt.root; /usr/local/sbin/apachectl restartTo restart Apache without
aborting current connections, run:&prompt.root; /usr/local/sbin/apachectl gracefulAdditional information available at
&man.apachectl.8; manual page.To launch Apache at system
startup, add the following line to
/etc/rc.conf:apache_enable="YES"If you would like to supply additional command line
options for the Apachehttpd program started at system boot, you
may specify them with an additional line in
rc.conf:apache_flags=""Now that the web server is running, you can view your web
site by pointing a web browser to
http://localhost/. The default web page
that is displayed is
/usr/local/www/data/index.html.Virtual HostingApache supports two different
types of Virtual Hosting. The first method is Name-based
Virtual Hosting. Name-based virtual hosting uses the clients
HTTP/1.1 headers to figure out the hostname. This allows many
different domains to share the same IP address.To setup Apache to use
Name-based Virtual Hosting add an entry like the following to
your httpd.conf:NameVirtualHost *If your webserver was named www.domain.tld and
you wanted to setup a virtual domain for
www.someotherdomain.tld then you would add
the following entries to
httpd.conf:<VirtualHost *>
ServerName www.domain.tld
DocumentRoot /www/domain.tld
</VirtualHost>
<VirtualHost *>
ServerName www.someotherdomain.tld
DocumentRoot /www/someotherdomain.tld
</VirtualHost>Replace the addresses with the addresses you want to use
and the path to the documents with what you are using.For more information about setting up virtual hosts,
please consult the official Apache
documentation at: .Apache ModulesApachemodulesThere are many different Apache modules available to add
functionality to the basic server. The FreeBSD Ports
Collection provides an easy way to install
Apache together with some of the
more popular add-on modules.mod_sslweb serverssecureSSLcryptographyThe mod_ssl module uses the OpenSSL library to provide
strong cryptography via the Secure Sockets Layer (SSL v2/v3)
and Transport Layer Security (TLS v1) protocols. This
module provides everything necessary to request a signed
certificate from a trusted certificate signing authority so
that you can run a secure web server on &os;.If you have not yet installed
Apache, then a version of Apache
1.3.X that includes mod_ssl may be installed with the www/apache13-modssl port. SSL
support is also available for Apache 2.X in the
www/apache20 port,
where it is enabled by default.Dynamic Websites with Perl & PHPIn the past few years, more businesses have turned to the
Internet in order to enhance their revenue and increase
exposure. This has also increased the need for interactive
web content. While some companies, such as µsoft;, have
introduced solutions into their proprietary products, the
open source community answered the call. Two options for
dynamic web content include
mod_perl &
mod_php.mod_perlmod_perlPerlThe Apache/Perl integration project brings together the
full power of the Perl programming language and the Apache
HTTP Server. With the mod_perl module it is possible to
write Apache modules entirely in Perl. In addition, the
persistent interpreter embedded in the server avoids the
overhead of starting an external interpreter and the penalty
of Perl start-up time.mod_perl is available a few
different ways. To use mod_perl
remember that mod_perl 1.0 only
works with Apache 1.3 and
mod_perl 2.0 only works with
Apache 2.
mod_perl 1.0 is available in
www/mod_perl and a
statically compiled version is available in
www/apache13-modperl.
mod_perl 2.0 is avaliable in
www/mod_perl2.TomRhodesWritten by mod_phpmod_phpPHPPHP, also known as PHP:
Hypertext Preprocessor is a general-purpose scripting
language that is especially suited for Web development.
Capable of being embedded into HTML its
syntax draws upon C, &java;, and Perl with the intention of
allowing web developers to write dynamically generated
webpages quickly.To gain support for PHP5 for the
Apache web server, begin by
installing the
www/mod_php5
port.This will install and configure the modules required
to support dynamic PHP applications. Check
to ensure the following sections have been added to
/usr/local/etc/apache/httpd.conf:LoadModule php5_module libexec/apache/libphp5.soAddModule mod_php5.c
<IfModule mod_php5.c>
DirectoryIndex index.php index.html
</IfModule>
<IfModule mod_php5.c>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
</IfModule>Once completed, a simple call to the
apachectl command for a graceful
restart is needed to load the PHP
module:&prompt.root; apachectl gracefulThe PHP support in &os; is extremely
modular so the base install is very limited. It is very easy
to add support using the
lang/php5-extensions port.
This port provides a menu driven interface to
PHP extension installation.
Alternatively, individual extensions can be installed using
the appropriate port.For instance, to add support for the
MySQL database server to
PHP5, simply install the
databases/php5-mysql
port.After installing an extension, the
Apache server must be reloaded to
pick up the new configuration changes:&prompt.root; apachectl gracefulMurrayStokelyContributed by File Transfer Protocol (FTP)FTP serversOverviewThe File Transfer Protocol (FTP) provides users with a
simple way to transfer files to and from an FTP server. &os;
includes FTP
server software, ftpd, in the base
system. This makes setting up and administering an FTP server on FreeBSD
very straightforward.ConfigurationThe most important configuration step is deciding which
accounts will be allowed access to the FTP server. A normal
FreeBSD system has a number of system accounts used for
various daemons, but unknown users should not be allowed to
log in with these accounts. The
/etc/ftpusers file is a list of users
disallowed any FTP access. By default, it includes the
aforementioned system accounts, but it is possible to add
specific users here that should not be allowed access to
FTP.You may want to restrict the access of some users without
preventing them completely from using FTP. This can be
accomplished with the /etc/ftpchroot
file. This file lists users and groups subject to FTP access
restrictions. The &man.ftpchroot.5; manual page has all of
the details so it will not be described in detail here.FTPanonymousIf you would like to enable anonymous FTP access to your
server, then you must create a user named
ftp on your &os; system. Users will then
be able to log on to your FTP server with a username of
ftp or anonymous and
with any password (by convention an email address for the user
should be used as the password). The FTP server will call
&man.chroot.2; when an anonymous user logs in, to restrict
access to only the home directory of the
ftp user.There are two text files that specify welcome messages to
be displayed to FTP clients. The contents of the file
/etc/ftpwelcome will be displayed to
users before they reach the login prompt. After a successful
login, the contents of the file
/etc/ftpmotd will be displayed. Note
that the path to this file is relative to the login environment, so the
file ~ftp/etc/ftpmotd would be displayed
for anonymous users.Once the FTP server has been configured properly, it must
be enabled in /etc/inetd.conf. All that
is required here is to remove the comment symbol
# from in front of the existing
ftpd line :ftp stream tcp nowait root /usr/libexec/ftpd ftpd -lAs explained in ,
the inetd configuration must be reloaded
after this configuration file is changed.You can now log on to your FTP server by typing:&prompt.user; ftp localhostMaintainingsysloglog filesFTPThe ftpd daemon uses
&man.syslog.3; to log messages. By default, the system log
daemon will put messages related to FTP in the
/var/log/xferlog file. The location of
the FTP log can be modified by changing the following line in
/etc/syslog.conf:ftp.info /var/log/xferlogFTPanonymousBe aware of the potential problems involved with running
an anonymous FTP server. In particular, you should think
twice about allowing anonymous users to upload files. You may
find that your FTP site becomes a forum for the trade of
unlicensed commercial software or worse. If you do need to
allow anonymous FTP uploads, then you should set up the
permissions so that these files can not be read by other
anonymous users until they have been reviewed.MurrayStokelyContributed by File and Print Services for µsoft.windows; clients (Samba)Samba serverMicrosoft Windowsfile serverWindows clientsprint serverWindows clientsOverviewSamba is a popular open source
software package that provides file and print services for
µsoft.windows; clients. Such clients can connect to and
use FreeBSD filespace as if it was a local disk drive, or
FreeBSD printers as if they were local printers.Samba software packages should
be included on your FreeBSD installation media. If you did
not install Samba when you first
installed FreeBSD, then you can install it from the net/samba3 port or package.ConfigurationA default Samba configuration
file is installed as
/usr/local/etc/smb.conf.default. This
file must be copied to
/usr/local/etc/smb.conf and customized
before Samba can be used.The smb.conf file contains runtime
configuration information for
Samba, such as definitions of the
printers and file system shares that you would
like to share with &windows; clients. The
Samba package includes a web based
tool called swat which provides a
simple way of configuring the smb.conf
file.Using the Samba Web Administration Tool (SWAT)The Samba Web Administration Tool (SWAT) runs as a
daemon from inetd. Therefore, the
following line in /etc/inetd.conf
should be uncommented before swat can be
used to configure Samba:swat stream tcp nowait/400 root /usr/local/sbin/swatAs explained in ,
the inetd must be reloaded after this configuration
file is changed.Once swat has been enabled in
inetd.conf, you can use a browser to
connect to . You will
first have to log on with the system root account.Once you have successfully logged on to the main
Samba configuration page, you can
browse the system documentation, or begin by clicking on the
Globals tab. The Globals section corresponds to the
variables that are set in the [global]
section of
/usr/local/etc/smb.conf.Global SettingsWhether you are using swat or
editing /usr/local/etc/smb.conf
directly, the first directives you are likely to encounter
when configuring Samba
are:workgroupNT Domain-Name or Workgroup-Name for the computers
that will be accessing this server.netbios name
- NetBIOS
-
- This sets the NetBIOS name by which a Samba server
+ This sets the NetBIOSNetBIOS name by which a Samba server
is known. By default it is the same as the first
component of the host's DNS name.server stringThis sets the string that will be displayed with
the net view command and some other
networking tools that seek to display descriptive text
about the server.Security SettingsTwo of the most important settings in
/usr/local/etc/smb.conf are the
security model chosen, and the backend password format for
client users. The following directives control these
options:securityThe two most common options here are
security = share and security
= user. If your clients use usernames that
are the same as their usernames on your &os; machine
then you will want to use user level security. This
is the default security policy and it requires clients
to first log on before they can access shared
resources.In share level security, client do not need to log
onto the server with a valid username and password
before attempting to connect to a shared resource.
This was the default security model for older versions
of Samba.passdb backend
- NIS+
- LDAP
- SQL database
-
Samba has several
different backend authentication models. You can
- authenticate clients with LDAP, NIS+, a SQL database,
+ authenticate clients with LDAPLDAP, NIS+NIS+, a SQL databaseSQL database,
or a modified password file. The default
authentication method is smbpasswd,
and that is all that will be covered here.Assuming that the default smbpasswd
backend is used, the
/usr/local/private/smbpasswd file must
be created to allow Samba to
authenticate clients. If you would like to give all of
your &unix; user accounts access from &windows; clients, use the
following command:&prompt.root; grep -v "^#" /etc/passwd | make_smbpasswd > /usr/local/private/smbpasswd
&prompt.root; chmod 600 /usr/local/private/smbpasswdPlease see the Samba
documentation for additional information about configuration
options. With the basics outlined here, you should have
everything you need to start running
Samba.Starting SambaTo enable Samba when your
system boots, add the following line to
/etc/rc.conf:samba_enable="YES"You can then start Samba at any
time by typing:&prompt.root; /usr/local/etc/rc.d/samba.sh start
Starting SAMBA: removing stale tdbs :
Starting nmbd.
Starting smbd.Samba actually consists of
three separate daemons. You should see that both the
nmbd and smbd daemons
are started by the samba.sh script. If
you enabled winbind name resolution services in
smb.conf, then you will also see that
the winbindd daemon is started.You can stop Samba at any time
by typing :&prompt.root; /usr/local/etc/rc.d/samba.sh stopSamba is a complex software
suite with functionality that allows broad integration with
µsoft.windows; networks. For more information about
functionality beyond the basic installation described here,
please see .TomHukinsContributed by Clock Synchronization with NTPNTPOverviewOver time, a computer's clock is prone to drift. The
Network Time Protocol (NTP) is one way to ensure your clock stays
accurate.Many Internet services rely on, or greatly benefit from,
computers' clocks being accurate. For example, a web server
may receive requests to send a file if it has been modified since a
certain time. In a local area network environment, it is
essential that computers sharing files from the same file
server have synchronized clocks so that file timestamps stay
consistent. Services such as &man.cron.8; also rely on
an accurate system clock to run commands at the specified
times.NTPntpdFreeBSD ships with the &man.ntpd.8; NTP server which can be used to query
other NTP
servers to set the clock on your machine or provide time
services to others.Choosing Appropriate NTP ServersNTPchoosing serversIn order to synchronize your clock, you will need to find
one or more NTP servers to use. Your network
administrator or ISP may have set up an NTP server for this
purpose—check their documentation to see if this is the
case. There is an online
list of publicly accessible NTP servers which you can
use to find an NTP server near to you. Make sure you are
aware of the policy for any servers you choose, and ask for
permission if required.Choosing several unconnected NTP servers is a good idea in
case one of the servers you are using becomes unreachable or
its clock is unreliable. &man.ntpd.8; uses the responses it
receives from other servers intelligently—it will favor
unreliable servers less than reliable ones.Configuring Your MachineNTPconfigurationBasic ConfigurationntpdateIf you only wish to synchronize your clock when the
machine boots up, you can use &man.ntpdate.8;. This may be
appropriate for some desktop machines which are frequently
rebooted and only require infrequent synchronization, but
most machines should run &man.ntpd.8;.Using &man.ntpdate.8; at boot time is also a good idea
for machines that run &man.ntpd.8;. The &man.ntpd.8;
program changes the clock gradually, whereas &man.ntpdate.8;
sets the clock, no matter how great the difference between a
machine's current clock setting and the correct time.To enable &man.ntpdate.8; at boot time, add
ntpdate_enable="YES" to
/etc/rc.conf. You will also need to
specify all servers you wish to synchronize with and any
flags to be passed to &man.ntpdate.8; in
ntpdate_flags.General ConfigurationNTPntp.confNTP is configured by the
/etc/ntp.conf file in the format
described in &man.ntp.conf.5;. Here is a simple
example:server ntplocal.example.com prefer
server timeserver.example.org
server ntp2a.example.net
driftfile /var/db/ntp.driftThe server option specifies which
servers are to be used, with one server listed on each line.
If a server is specified with the prefer
argument, as with ntplocal.example.com, that server is
preferred over other servers. A response from a preferred
server will be discarded if it differs significantly from
other servers' responses, otherwise it will be used without
any consideration to other responses. The
prefer argument is normally used for NTP
servers that are known to be highly accurate, such as those
with special time monitoring hardware.The driftfile option specifies which
file is used to store the system clock's frequency offset.
The &man.ntpd.8; program uses this to automatically
compensate for the clock's natural drift, allowing it to
maintain a reasonably correct setting even if it is cut off
from all external time sources for a period of time.The driftfile option specifies which
file is used to store information about previous responses
from the NTP servers you are using. This file contains
internal information for NTP. It should not be modified by
any other process.Controlling Access to Your ServerBy default, your NTP server will be accessible to all
hosts on the Internet. The restrict
option in /etc/ntp.conf allows you to
control which machines can access your server.If you want to deny all machines from accessing your NTP
server, add the following line to
/etc/ntp.conf:restrict default ignoreIf you only want to allow machines within your own
network to synchronize their clocks with your server, but
ensure they are not allowed to configure the server or used
as peers to synchronize against, addrestrict 192.168.1.0 mask 255.255.255.0 nomodify notrapinstead, where 192.168.1.0 is
an IP address on your network and 255.255.255.0 is your network's
netmask./etc/ntp.conf can contain multiple
restrict options. For more details, see
the Access Control Support subsection of
&man.ntp.conf.5;.Running the NTP ServerTo ensure the NTP server is started at boot time, add the
line ntpd_enable="YES" to
/etc/rc.conf. If you wish to pass
additional flags to &man.ntpd.8;, edit the
ntpd_flags parameter in
/etc/rc.conf.To start the server without rebooting your machine, run
ntpd being sure to specify any additional
parameters from ntpd_flags in
/etc/rc.conf. For example:&prompt.root; ntpd -p /var/run/ntpd.pidUsing ntpd with a Temporary Internet
ConnectionThe &man.ntpd.8; program does not need a permanent
connection to the Internet to function properly. However, if
you have a temporary connection that is configured to dial out
on demand, it is a good idea to prevent NTP traffic from
triggering a dial out or keeping the connection alive. If you
are using user PPP, you can use filter
directives in /etc/ppp/ppp.conf. For
example: set filter dial 0 deny udp src eq 123
# Prevent NTP traffic from initiating dial out
set filter dial 1 permit 0 0
set filter alive 0 deny udp src eq 123
# Prevent incoming NTP traffic from keeping the connection open
set filter alive 1 deny udp dst eq 123
# Prevent outgoing NTP traffic from keeping the connection open
set filter alive 2 permit 0/0 0/0For more details see the PACKET
FILTERING section in &man.ppp.8; and the examples in
/usr/share/examples/ppp/.Some Internet access providers block low-numbered ports,
preventing NTP from functioning since replies never
reach your machine.Further InformationDocumentation for the NTP server can be found in
/usr/share/doc/ntp/ in HTML
format.
diff --git a/pl_PL.ISO8859-2/books/handbook/ppp-and-slip/chapter.xml b/pl_PL.ISO8859-2/books/handbook/ppp-and-slip/chapter.xml
index fe62c1eda2..8855b4ca39 100644
--- a/pl_PL.ISO8859-2/books/handbook/ppp-and-slip/chapter.xml
+++ b/pl_PL.ISO8859-2/books/handbook/ppp-and-slip/chapter.xml
@@ -1,3171 +1,3127 @@
JimMockRestructured, reorganized, and updated by PPP and SLIPSynopsisPPPSLIPFreeBSD has a number of ways to link one computer to
another. To establish a network or Internet connection through a
dial-up modem, or to allow others to do so through you, requires
the use of PPP or SLIP. This chapter describes setting up
these modem-based communication services in detail.After reading this chapter, you will know:How to set up user PPP.How to set up kernel PPP.How to set up PPPoE (PPP over
Ethernet).How to set up PPPoA (PPP over
ATM).How to configure and set up a SLIP client and
server.PPPuser PPPPPPkernel PPPPPPover EthernetBefore reading this chapter, you should:Be familiar with basic network terminology.Understand the basics and purpose of a dialup connection
and PPP and/or SLIP.You may be wondering what the main difference is between user
PPP and kernel PPP. The answer is simple: user PPP processes the
inbound and outbound data in userland rather than in the kernel.
This is expensive in terms of copying the data between the kernel
and userland, but allows a far more feature-rich PPP implementation.
User PPP uses the tun device to communicate
with the outside world whereas kernel PPP uses the
ppp device.Throughout in this chapter, user PPP will simply be
referred to as ppp unless a distinction needs to be made between it
and any other PPP software such as pppd.
Unless otherwise stated, all of the commands explained in this
chapter should be executed as root.TomRhodesUpdated and enhanced by BrianSomersOriginally contributed by NikClaytonWith input from DirkFrömbergPeterChildsUsing User PPPUser PPPAssumptionsThis document assumes you have the following:
-
- ISP
-
-
- PPP
-
- An account with an Internet Service Provider (ISP) which
- you connect to using PPP.
+ An account with an Internet Service Provider (ISP)ISP which
+ you connect to using PPPPPP.You have a modem or
other device connected to your system and configured
correctly which allows you to connect to your ISP.The dial-up number(s) of your ISP.
-
- PAP
-
-
- CHAP
-
-
- UNIX
-
-
- login name
-
-
- password
-
- Your login name and password. (Either a
- regular &unix; style login and password pair, or a PAP or CHAP
+ Your login namelogin name and passwordpassword. (Either a
+ regular &unix;UNIX style login and password pair, or a
+ PAPPAP or CHAPCHAP
login and password pair.)
-
- nameserver
-
-
- The IP address of one or more name servers.
+ The IP address of one or more name serversnameserver.
Normally, you will be given two IP addresses by your ISP to
use for this. If they have not given you at least one, then
you can use the enable dns command in
ppp.conf and
ppp will set the name servers for
you. This feature depends on your ISPs PPP implementation
supporting DNS negotiation.The following information may be supplied by your ISP, but
is not completely necessary:The IP address of your ISP's gateway. The gateway is
the machine to which you will connect and will be set up as
your default route. If you do not have
this information, we can make one up and your ISP's PPP
server will tell us the correct value when we connect.This IP number is referred to as
HISADDR by
ppp.The netmask you should use. If your ISP has not
provided you with one, you can safely use 255.255.255.255.
-
- static IP address
-
-
- If your ISP provides you with a static IP address and
+ If your ISP provides you with a static IP addressstatic IP address and
hostname, you can enter it. Otherwise, we simply let the
peer assign whatever IP address it sees fit.If you do not have any of the required information, contact
your ISP.Throughout this section, many of the examples showing
the contents of configuration files are numbered by line.
These numbers serve to aid in the presentation and
discussion only and are not meant to be placed in the actual
file. Proper indentation with tab and space characters is
also important.Automatic PPP ConfigurationPPPconfigurationBoth ppp and pppd
(the kernel level implementation of PPP) use the configuration
files located in the /etc/ppp directory.
Examples for user ppp can be found in
/usr/share/examples/ppp/.Configuring ppp requires that you edit a
number of files, depending on your requirements. What you put
in them depends to some extent on whether your ISP allocates IP
addresses statically (i.e., you get given one IP address, and
always use that one) or dynamically (i.e., your IP address
changes each time you connect to your ISP).PPP and Static IP AddressesPPPwith static IP addressesYou will need to edit the
/etc/ppp/ppp.conf configuration file. It
should look similar to the example below.Lines that end in a : start in
the first column (beginning of the line)— all other
lines should be indented as shown using spaces or
tabs.1 default:
2 set log Phase Chat LCP IPCP CCP tun command
3 ident user-ppp VERSION (built COMPILATIONDATE)
4 set device /dev/cuaa0
5 set speed 115200
6 set dial "ABORT BUSY ABORT NO\\sCARRIER TIMEOUT 5 \
7 \"\" AT OK-AT-OK ATE1Q0 OK \\dATDT\\T TIMEOUT 40 CONNECT"
8 set timeout 180
9 enable dns
10
11 provider:
12 set phone "(123) 456 7890"
13 set authname foo
14 set authkey bar
15 set login "TIMEOUT 10 \"\" \"\" gin:--gin: \\U word: \\P col: ppp"
16 set timeout 300
17 set ifaddr x.x.x.xy.y.y.y 255.255.255.255 0.0.0.0
18 add default HISADDRLine 1:Identifies the default entry. Commands in this
entry are executed automatically when ppp is run.Line 2:Enables logging parameters. When the configuration
is working satisfactorily, this line should be reduced
to saying
set log phase tun
in order to avoid excessive log file sizes.Line 3:Tells PPP how to identify itself to the peer.
PPP identifies itself to the peer if it has any trouble
negotiating and setting up the link, providing information
that the peers administrator may find useful when
investigating such problems.Line 4:Identifies the device to which the modem is
connected. COM1 is
/dev/cuaa0 and
COM2 is
/dev/cuaa1.Line 5:Sets the speed you want to connect at. If 115200
does not work (it should with any reasonably new modem),
try 38400 instead.Line 6 & 7:
- PPPuser PPP
-
- The dial string. User PPP uses an expect-send
+ The dial string. User PPPPPPuser PPP uses an expect-send
syntax similar to the &man.chat.8; program. Refer to
the manual page for information on the features of this
language.Note that this command continues onto the next line
for readability. Any command in
ppp.conf may do this if the last
character on the line is a ``\'' character.Line 8:Sets the idle timeout for the link. 180 seconds
is the default, so this line is purely cosmetic.Line 9:Tells PPP to ask the peer to confirm the local
resolver settings. If you run a local name server, this
line should be commented out or removed.Line 10:A blank line for readability. Blank lines are ignored
by PPP.Line 11:Identifies an entry for a provider called
provider. This could be changed
to the name of your ISP so
that later you can use the
to start the connection.Line 12:Sets the phone number for this provider. Multiple
phone numbers may be specified using the colon
(:) or pipe character
(|)as a separator. The difference
between the two separators is described in &man.ppp.8;.
To summarize, if you want to rotate through the numbers,
use a colon. If you want to always attempt to dial the
first number first and only use the other numbers if the
first number fails, use the pipe character. Always
quote the entire set of phone numbers as shown.You must enclose the phone number in quotation marks
(") if there is any intention on using
spaces in the phone number. This can cause a simple, yet
subtle error.Line 13 & 14:Identifies the user name and password. When
connecting using a &unix; style login prompt, these
values are referred to by the set
login command using the \U and \P
variables. When connecting using PAP or CHAP, these
values are used at authentication time.Line 15:
- PAP
- CHAPIf you are using PAP or CHAP, there will be no login
at this point, and this line should be commented out or
- removed. See PAP and CHAP
+ removed. See PAPPAP and CHAPCHAP
authentication for further details.The login string is of the same chat-like syntax as
the dial string. In this example, the string works for
a service whose login session looks like this:J. Random Provider
login: foo
password: bar
protocol: pppYou will need to alter this script to suit your
own needs. When you write this script for the first
time, you should ensure that you have enabled
chat logging so you can determine if
the conversation is going as expected.Line 16:
- timeout
-
- Sets the default idle timeout (in seconds) for the
+ Sets the default idle timeouttimeout (in seconds) for the
connection. Here, the connection will be closed
automatically after 300 seconds of inactivity. If you
never want to timeout, set this value to zero or use
the command line switch.Line 17:
- ISP
-
Sets the interface addresses. The string
x.x.x.x should be
replaced by the IP address that your provider has
allocated to you. The string
y.y.y.y should be
- replaced by the IP address that your ISP indicated
+ replaced by the IP address that your ISPISP indicated
for their gateway (the machine to which you
connect). If your ISP has not given you a gateway
address, use 10.0.0.2/0. If you need to
use a guessed address, make sure that
you create an entry in
/etc/ppp/ppp.linkup as per the
instructions for PPP and Dynamic IP
addresses. If this line is omitted,
ppp cannot run in
mode.Line 18:Adds a default route to your ISP's gateway. The
special word HISADDR is replaced with
the gateway address specified on line 17. It is
important that this line appears after line 17,
otherwise HISADDR will not yet be
initialized.If you do not wish to run ppp in ,
this line should be moved to the
ppp.linkup file.It is not necessary to add an entry to
ppp.linkup when you have a static IP
address and are running ppp in mode as your
routing table entries are already correct before you connect.
You may however wish to create an entry to invoke programs after
connection. This is explained later with the sendmail
example.Example configuration files can be found in the
/usr/share/examples/ppp/ directory.PPP and Dynamic IP AddressesPPPwith dynamic IP addressesIPCPIf your service provider does not assign static IP
addresses, ppp can be configured to
negotiate the local and remote addresses. This is done by
guessing an IP address and allowing
ppp to set it up correctly using the IP
Configuration Protocol (IPCP) after connecting. The
ppp.conf configuration is the same as
PPP and Static IP
Addresses, with the following change:17 set ifaddr 10.0.0.1/0 10.0.0.2/0 255.255.255.255Again, do not include the line number, it is just for
reference. Indentation of at least one space is
required.Line 17:The number after the / character
is the number of bits of the address that ppp will
insist on. You may wish to use IP numbers more
appropriate to your circumstances, but the above example
will always work.The last argument (0.0.0.0) tells
PPP to start negotiations using address 0.0.0.0 rather than 10.0.0.1 and is necessary for some
ISPs. Do not use 0.0.0.0 as the first
argument to set ifaddr as it prevents
PPP from setting up an initial route in
mode.If you are not running in mode, you
will need to create an entry in
/etc/ppp/ppp.linkup.
ppp.linkup is used after a connection has
been established. At this point, ppp will
have assigned the interface addresses and it will now be
possible to add the routing table entries:1 provider:
2 add default HISADDRLine 1:On establishing a connection,
ppp will look for an entry in
ppp.linkup according to the
following rules: First, try to match the same label
as we used in ppp.conf. If
that fails, look for an entry for the IP address of
our gateway. This entry is a four-octet IP style
label. If we still have not found an entry, look
for the MYADDR entry.Line 2:This line tells ppp to add a
default route that points to
HISADDR.
HISADDR will be replaced with the
IP number of the gateway as negotiated by the
IPCP.See the pmdemand entry in the files
/usr/share/examples/ppp/ppp.conf.sample
and
/usr/share/examples/ppp/ppp.linkup.sample
for a detailed example.Receiving Incoming CallsPPPreceiving
incoming callsWhen you configure ppp to
receive incoming calls on a machine connected to a LAN, you
must decide if you wish to forward packets to the LAN. If you
do, you should allocate the peer an IP number from your LAN's
subnet, and use the command enable proxy in
your /etc/ppp/ppp.conf file. You should
also confirm that the /etc/rc.conf file
contains the following:gateway_enable="YES"Which getty?Configuring FreeBSD for Dial-up
Services provides a good description on enabling
dial-up services using &man.getty.8;.An alternative to getty is mgetty,
a smarter version of getty designed
with dial-up lines in mind.The advantages of using mgetty is
that it actively talks to modems,
meaning if port is turned off in
/etc/ttys then your modem will not answer
the phone.Later versions of mgetty (from
0.99beta onwards) also support the automatic detection of
PPP streams, allowing your clients script-less access to
your server.Refer to Mgetty and
AutoPPP for more information on
mgetty.PPP PermissionsThe ppp command must normally be
run as the root user. If however,
you wish to allow ppp to run in
server mode as a normal user by executing
ppp as described below, that user
must be given permission to run ppp
by adding them to the network group
in /etc/group.You will also need to give them access to one or more
sections of the configuration file using the
allow command:allow users fred maryIf this command is used in the default
section, it gives the specified users access to
everything.PPP Shells for Dynamic-IP UsersPPP shellsCreate a file called
/etc/ppp/ppp-shell containing the
following:#!/bin/sh
IDENT=`echo $0 | sed -e 's/^.*-\(.*\)$/\1/'`
CALLEDAS="$IDENT"
TTY=`tty`
if [ x$IDENT = xdialup ]; then
IDENT=`basename $TTY`
fi
echo "PPP for $CALLEDAS on $TTY"
echo "Starting PPP for $IDENT"
exec /usr/sbin/ppp -direct $IDENTThis script should be executable. Now make a symbolic
link called ppp-dialup to this script
using the following commands:&prompt.root; ln -s ppp-shell /etc/ppp/ppp-dialupYou should use this script as the
shell for all of your dialup users.
This is an example from /etc/passwd
for a dialup PPP user with username
pchilds (remember do not directly edit
the password file, use &man.vipw.8;).pchilds:*:1011:300:Peter Childs PPP:/home/ppp:/etc/ppp/ppp-dialupCreate a /home/ppp directory that
is world readable containing the following 0 byte
files:-r--r--r-- 1 root wheel 0 May 27 02:23 .hushlogin
-r--r--r-- 1 root wheel 0 May 27 02:22 .rhostswhich prevents /etc/motd from being
displayed.PPP Shells for Static-IP UsersPPP shellsCreate the ppp-shell file as above,
and for each account with statically assigned IPs create a
symbolic link to ppp-shell.For example, if you have three dialup customers,
fred, sam, and
mary, that you route class C networks
for, you would type the following:&prompt.root; ln -s /etc/ppp/ppp-shell /etc/ppp/ppp-fred
&prompt.root; ln -s /etc/ppp/ppp-shell /etc/ppp/ppp-sam
&prompt.root; ln -s /etc/ppp/ppp-shell /etc/ppp/ppp-maryEach of these users dialup accounts should have their
shell set to the symbolic link created above (for example,
mary's shell should be
/etc/ppp/ppp-mary).Setting Up ppp.conf for Dynamic-IP UsersThe /etc/ppp/ppp.conf file should
contain something along the lines of:default:
set debug phase lcp chat
set timeout 0
ttyd0:
set ifaddr 203.14.100.1 203.14.100.20 255.255.255.255
enable proxy
ttyd1:
set ifaddr 203.14.100.1 203.14.100.21 255.255.255.255
enable proxyThe indenting is important.The default: section is loaded for
each session. For each dialup line enabled in
/etc/ttys create an entry similar to
the one for ttyd0: above. Each line
should get a unique IP address from your pool of IP
addresses for dynamic users.Setting Up ppp.conf for Static-IP
UsersAlong with the contents of the sample
/usr/share/examples/ppp/ppp.conf
above you should add a section for each of the
statically assigned dialup users. We will continue with
our fred, sam,
and mary example.fred:
set ifaddr 203.14.100.1 203.14.101.1 255.255.255.255
sam:
set ifaddr 203.14.100.1 203.14.102.1 255.255.255.255
mary:
set ifaddr 203.14.100.1 203.14.103.1 255.255.255.255The file /etc/ppp/ppp.linkup
should also contain routing information for each static
IP user if required. The line below would add a route
for the 203.14.101.0
class C via the client's ppp link.fred:
add 203.14.101.0 netmask 255.255.255.0 HISADDR
sam:
add 203.14.102.0 netmask 255.255.255.0 HISADDR
mary:
add 203.14.103.0 netmask 255.255.255.0 HISADDRmgetty and AutoPPPmgettyAutoPPPLCPConfiguring and compiling mgetty
with the AUTO_PPP option enabled
allows mgetty to detect the LCP phase
of PPP connections and automatically spawn off a ppp
shell. However, since the default login/password
sequence does not occur it is necessary to authenticate
users using either PAP or CHAP.This section assumes the user has successfully
configured, compiled, and installed a version of
mgetty with the
AUTO_PPP option (v0.99beta or
later).Make sure your
/usr/local/etc/mgetty+sendfax/login.config
file has the following in it:/AutoPPP/ - - /etc/ppp/ppp-pap-dialupThis will tell mgetty to run the
ppp-pap-dialup script for detected
PPP connections.Create a file called
/etc/ppp/ppp-pap-dialup containing the
following (the file should be executable):#!/bin/sh
exec /usr/sbin/ppp -direct pap$IDENTFor each dialup line enabled in
/etc/ttys, create a corresponding entry
in /etc/ppp/ppp.conf. This will
happily co-exist with the definitions we created
above.pap:
enable pap
set ifaddr 203.14.100.1 203.14.100.20-203.14.100.40
enable proxyEach user logging in with this method will need to have
a username/password in
/etc/ppp/ppp.secret file, or
alternatively add the following option to authenticate users
via PAP from the /etc/passwd file.enable passwdauthIf you wish to assign some users a static IP number,
you can specify the number as the third argument in
/etc/ppp/ppp.secret. See
/usr/share/examples/ppp/ppp.secret.sample
for examples.MS ExtensionsDNSNetBIOSPPPMicrosoft extensionsIt is possible to configure PPP to supply DNS and
NetBIOS nameserver addresses on demand.To enable these extensions with PPP version 1.x, the
following lines might be added to the relevant section of
/etc/ppp/ppp.conf.enable msext
set ns 203.14.100.1 203.14.100.2
set nbns 203.14.100.5And for PPP version 2 and above:accept dns
set dns 203.14.100.1 203.14.100.2
set nbns 203.14.100.5This will tell the clients the primary and secondary
name server addresses, and a NetBIOS nameserver host.In version 2 and above, if the
set dns line is omitted, PPP will use the
values found in /etc/resolv.conf.PAP and CHAP AuthenticationPAPCHAPSome ISPs set their system up so that the authentication
part of your connection is done using either of the PAP or
CHAP authentication mechanisms. If this is the case, your ISP
will not give a login: prompt when you
connect, but will start talking PPP immediately.PAP is less secure than CHAP, but security is not normally
an issue here as passwords, although being sent as plain text
with PAP, are being transmitted down a serial line only.
There is not much room for crackers to
eavesdrop.Referring back to the PPP
and Static IP addresses or PPP and Dynamic IP addresses
sections, the following alterations must be made:13 set authname MyUserName
14 set authkey MyPassword
15 set loginLine 13:This line specifies your PAP/CHAP user name. You
will need to insert the correct value for
MyUserName.Line 14:
- password
-
- This line specifies your PAP/CHAP password. You
+ This line specifies your PAP/CHAP passwordpassword. You
will need to insert the correct value for
MyPassword. You may want to
add an additional line, such as:16 accept PAPor16 accept CHAPto make it obvious that this is the intention, but
PAP and CHAP are both accepted by default.Line 15:Your ISP will not normally require that you log into
the server if you are using PAP or CHAP. You must
therefore disable your set login
string.Changing Your ppp Configuration on the
FlyIt is possible to talk to the ppp
program while it is running in the background, but only if a
suitable diagnostic port has been set up. To do this, add the
following line to your configuration:set server /var/run/ppp-tun%d DiagnosticPassword 0177This will tell PPP to listen to the specified
&unix; domain socket, asking clients for the specified
password before allowing access. The
%d in the name is replaced with the
tun device number that is in
use.Once a socket has been set up, the &man.pppctl.8;
program may be used in scripts that wish to manipulate the
running program.Using PPP Network Address Translation CapabilityPPPNATPPP has ability to use internal NAT without kernel diverting
capabilities. This functionality may be enabled by the following
line in /etc/ppp/ppp.conf:nat enable yesAlternatively, PPP NAT may be enabled by command-line
option -nat. There is also
/etc/rc.conf knob named
ppp_nat, which is enabled by default.If you use this feature, you may also find useful
the following /etc/ppp/ppp.conf options
to enable incoming connections forwarding:nat port tcp 10.0.0.2:ftp ftp
nat port tcp 10.0.0.2:http httpor do not trust the outside at allnat deny_incoming yesFinal System ConfigurationPPPconfigurationYou now have ppp configured, but there
are a few more things to do before it is ready to work. They
all involve editing the /etc/rc.conf
file.Working from the top down in this file, make sure the
hostname= line is set, e.g.:hostname="foo.example.com"If your ISP has supplied you with a static IP address and
name, it is probably best that you use this name as your host
name.Look for the network_interfaces variable.
If you want to configure your system to dial your ISP on demand,
make sure the tun0 device is added to
the list, otherwise remove it.network_interfaces="lo0 tun0"
ifconfig_tun0=The ifconfig_tun0 variable should be
empty, and a file called
/etc/start_if.tun0 should be created.
This file should contain the line:ppp -auto mysystemThis script is executed at network configuration time,
starting your ppp daemon in automatic mode. If you have a LAN
for which this machine is a gateway, you may also wish to use
the switch. Refer to the manual page
for further details.Make sure that the router program is set to NO with
the following line in your
/etc/rc.conf:router_enable="NO"routedIt is important that the routed daemon is
not started, as
routed tends to delete the default routing
table entries created by ppp.It is probably worth your while ensuring that the
sendmail_flags line does not include the
option, otherwise
sendmail will attempt to do a network lookup
every now and then, possibly causing your machine to dial out.
You may try:sendmail_flags="-bd"sendmailThe downside of this is that you must force
sendmail to re-examine the mail queue
whenever the ppp link is up by typing:&prompt.root; /usr/sbin/sendmail -qYou may wish to use the !bg command in
ppp.linkup to do this automatically:1 provider:
2 delete ALL
3 add 0 0 HISADDR
4 !bg sendmail -bd -q30mSMTPIf you do not like this, it is possible to set up a
dfilter to block SMTP traffic. Refer to the
sample files for further details.All that is left is to reboot the machine. After rebooting,
you can now either type:&prompt.root; pppand then dial provider to start the PPP
session, or, if you want ppp to establish
sessions automatically when there is outbound traffic (and
you have not created the start_if.tun0
script), type:&prompt.root; ppp -auto providerSummaryTo recap, the following steps are necessary when setting up
ppp for the first time:Client side:Ensure that the tun device is
built into your kernel.Ensure that the
tunN device
file is available in the /dev
directory.Create an entry in
/etc/ppp/ppp.conf. The
pmdemand example should suffice for
most ISPs.If you have a dynamic IP address, create an entry in
/etc/ppp/ppp.linkup.Update your /etc/rc.conf
file.Create a start_if.tun0 script if
you require demand dialing.Server side:Ensure that the tun device is
built into your kernel.Ensure that the
tunN device
file is available in the /dev
directory.Create an entry in /etc/passwd
(using the &man.vipw.8; program).Create a profile in this users home directory that runs
ppp -direct direct-server or
similar.Create an entry in
/etc/ppp/ppp.conf. The
direct-server example should
suffice.Create an entry in
/etc/ppp/ppp.linkup.Update your /etc/rc.conf
file.Gennady B.SorokopudParts originally contributed by RobertHuffUsing Kernel PPPSetting Up Kernel PPPPPPkernel PPPBefore you start setting up PPP on your machine, make sure
that pppd is located in
/usr/sbin and the directory
/etc/ppp exists.pppd can work in two modes:As a client — you want to connect your
machine to the outside world via a PPP serial connection or
modem line.
- PPPserver
-
As a server — your machine is located on
the network, and is used to connect other computers using
- PPP.
+ PPPPPPserver.
In both cases you will need to set up an options file
(/etc/ppp/options or
~/.ppprc if you have more than one user on
your machine that uses PPP).You will also need some modem/serial software (preferably
comms/kermit), so you can dial and
establish a connection with the remote host.TrevRoydhouseBased on information provided by Using pppd as a ClientPPPclientCiscoThe following /etc/ppp/options might be
used to connect to a Cisco terminal server PPP line.crtscts # enable hardware flow control
modem # modem control line
noipdefault # remote PPP server must supply your IP address
# if the remote host does not send your IP during IPCP
# negotiation, remove this option
passive # wait for LCP packets
domain ppp.foo.com # put your domain name here
:<remote_ip> # put the IP of remote PPP host here
# it will be used to route packets via PPP link
# if you didn't specified the noipdefault option
# change this line to <local_ip>:<remote_ip>
defaultroute # put this if you want that PPP server will be your
# default routerTo connect:KermitmodemDial to the remote host using Kermit (or some other modem
program), and enter your user name and password (or whatever
is needed to enable PPP on the remote host).Exit Kermit (without
hanging up the line).Enter the following:&prompt.root; /usr/src/usr.sbin/pppd.new/pppd /dev/tty0119200Be sure to use the appropriate speed and device name.Now your computer is connected with PPP. If the connection
fails, you can add the option to the
/etc/ppp/options file, and check console messages
to track the problem.Following /etc/ppp/pppup script will make
all 3 stages automatic:#!/bin/sh
ps ax |grep pppd |grep -v grep
pid=`ps ax |grep pppd |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing pppd, PID=' ${pid}
kill ${pid}
fi
ps ax |grep kermit |grep -v grep
pid=`ps ax |grep kermit |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing kermit, PID=' ${pid}
kill -9 ${pid}
fi
ifconfig ppp0 down
ifconfig ppp0 delete
kermit -y /etc/ppp/kermit.dial
pppd /dev/tty01 19200Kermit/etc/ppp/kermit.dial is a Kermit
script that dials and makes all necessary authorization on the
remote host (an example of such a script is attached to the end
of this document).Use the following /etc/ppp/pppdown script
to disconnect the PPP line:#!/bin/sh
pid=`ps ax |grep pppd |grep -v grep|awk '{print $1;}'`
if [ X${pid} != "X" ] ; then
echo 'killing pppd, PID=' ${pid}
kill -TERM ${pid}
fi
ps ax |grep kermit |grep -v grep
pid=`ps ax |grep kermit |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing kermit, PID=' ${pid}
kill -9 ${pid}
fi
/sbin/ifconfig ppp0 down
/sbin/ifconfig ppp0 delete
kermit -y /etc/ppp/kermit.hup
/etc/ppp/ppptestCheck to see if pppd is still running by executing
/usr/etc/ppp/ppptest, which should look like
this:#!/bin/sh
pid=`ps ax| grep pppd |grep -v grep|awk '{print $1;}'`
if [ X${pid} != "X" ] ; then
echo 'pppd running: PID=' ${pid-NONE}
else
echo 'No pppd running.'
fi
set -x
netstat -n -I ppp0
ifconfig ppp0To hang up the modem, execute
/etc/ppp/kermit.hup, which should
contain:set line /dev/tty01 ; put your modem device here
set speed 19200
set file type binary
set file names literal
set win 8
set rec pack 1024
set send pack 1024
set block 3
set term bytesize 8
set command bytesize 8
set flow none
pau 1
out +++
inp 5 OK
out ATH0\13
echo \13
exitHere is an alternate method using chat
instead of kermit:The following two files are sufficient to accomplish a
pppd connection./etc/ppp/options:/dev/cuaa1 115200
crtscts # enable hardware flow control
modem # modem control line
connect "/usr/bin/chat -f /etc/ppp/login.chat.script"
noipdefault # remote PPP serve must supply your IP address
# if the remote host doesn't send your IP during
# IPCP negotiation, remove this option
passive # wait for LCP packets
domain <your.domain> # put your domain name here
: # put the IP of remote PPP host here
# it will be used to route packets via PPP link
# if you didn't specified the noipdefault option
# change this line to <local_ip>:<remote_ip>
defaultroute # put this if you want that PPP server will be
# your default router/etc/ppp/login.chat.script:The following should go on a single line.ABORT BUSY ABORT 'NO CARRIER' "" AT OK ATDT<phone.number>
CONNECT "" TIMEOUT 10 ogin:-\\r-ogin: <login-id>
TIMEOUT 5 sword: <password>Once these are installed and modified correctly, all you need
to do is run pppd, like so:&prompt.root; pppdUsing pppd as a Server/etc/ppp/options should contain something
similar to the following:crtscts # Hardware flow control
netmask 255.255.255.0 # netmask (not required)
192.114.208.20:192.114.208.165 # IP's of local and remote hosts
# local ip must be different from one
# you assigned to the Ethernet (or other)
# interface on your machine.
# remote IP is IP address that will be
# assigned to the remote machine
domain ppp.foo.com # your domain
passive # wait for LCP
modem # modem lineThe following /etc/ppp/pppserv script
will tell pppd to behave as a
server:#!/bin/sh
ps ax |grep pppd |grep -v grep
pid=`ps ax |grep pppd |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing pppd, PID=' ${pid}
kill ${pid}
fi
ps ax |grep kermit |grep -v grep
pid=`ps ax |grep kermit |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing kermit, PID=' ${pid}
kill -9 ${pid}
fi
# reset ppp interface
ifconfig ppp0 down
ifconfig ppp0 delete
# enable autoanswer mode
kermit -y /etc/ppp/kermit.ans
# run ppp
pppd /dev/tty01 19200Use this /etc/ppp/pppservdown script to
stop the server:#!/bin/sh
ps ax |grep pppd |grep -v grep
pid=`ps ax |grep pppd |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing pppd, PID=' ${pid}
kill ${pid}
fi
ps ax |grep kermit |grep -v grep
pid=`ps ax |grep kermit |grep -v grep|awk '{print $1;}'`
if [ "X${pid}" != "X" ] ; then
echo 'killing kermit, PID=' ${pid}
kill -9 ${pid}
fi
ifconfig ppp0 down
ifconfig ppp0 delete
kermit -y /etc/ppp/kermit.noansThe following Kermit script
(/etc/ppp/kermit.ans) will enable/disable
autoanswer mode on your modem. It should look like this:set line /dev/tty01
set speed 19200
set file type binary
set file names literal
set win 8
set rec pack 1024
set send pack 1024
set block 3
set term bytesize 8
set command bytesize 8
set flow none
pau 1
out +++
inp 5 OK
out ATH0\13
inp 5 OK
echo \13
out ATS0=1\13 ; change this to out ATS0=0\13 if you want to disable
; autoanswer mode
inp 5 OK
echo \13
exitA script named /etc/ppp/kermit.dial is
used for dialing and authenticating on the remote host. You will
need to customize it for your needs. Put your login and password
in this script; you will also need to change the input statement
depending on responses from your modem and remote host.;
; put the com line attached to the modem here:
;
set line /dev/tty01
;
; put the modem speed here:
;
set speed 19200
set file type binary ; full 8 bit file xfer
set file names literal
set win 8
set rec pack 1024
set send pack 1024
set block 3
set term bytesize 8
set command bytesize 8
set flow none
set modem hayes
set dial hangup off
set carrier auto ; Then SET CARRIER if necessary,
set dial display on ; Then SET DIAL if necessary,
set input echo on
set input timeout proceed
set input case ignore
def \%x 0 ; login prompt counter
goto slhup
:slcmd ; put the modem in command mode
echo Put the modem in command mode.
clear ; Clear unread characters from input buffer
pause 1
output +++ ; hayes escape sequence
input 1 OK\13\10 ; wait for OK
if success goto slhup
output \13
pause 1
output at\13
input 1 OK\13\10
if fail goto slcmd ; if modem doesn't answer OK, try again
:slhup ; hang up the phone
clear ; Clear unread characters from input buffer
pause 1
echo Hanging up the phone.
output ath0\13 ; hayes command for on hook
input 2 OK\13\10
if fail goto slcmd ; if no OK answer, put modem in command mode
:sldial ; dial the number
pause 1
echo Dialing.
output atdt9,550311\13\10 ; put phone number here
assign \%x 0 ; zero the time counter
:look
clear ; Clear unread characters from input buffer
increment \%x ; Count the seconds
input 1 {CONNECT }
if success goto sllogin
reinput 1 {NO CARRIER\13\10}
if success goto sldial
reinput 1 {NO DIALTONE\13\10}
if success goto slnodial
reinput 1 {\255}
if success goto slhup
reinput 1 {\127}
if success goto slhup
if < \%x 60 goto look
else goto slhup
:sllogin ; login
assign \%x 0 ; zero the time counter
pause 1
echo Looking for login prompt.
:slloop
increment \%x ; Count the seconds
clear ; Clear unread characters from input buffer
output \13
;
; put your expected login prompt here:
;
input 1 {Username: }
if success goto sluid
reinput 1 {\255}
if success goto slhup
reinput 1 {\127}
if success goto slhup
if < \%x 10 goto slloop ; try 10 times to get a login prompt
else goto slhup ; hang up and start again if 10 failures
:sluid
;
; put your userid here:
;
output ppp-login\13
input 1 {Password: }
;
; put your password here:
;
output ppp-password\13
input 1 {Entering SLIP mode.}
echo
quit
:slnodial
echo \7No dialtone. Check the telephone line!\7
exit 1
; local variables:
; mode: csh
; comment-start: "; "
; comment-start-skip: "; "
; end:TomRhodesContributed by Troubleshooting PPP ConnectionsPPPtroubleshootingThis section covers a few issues which may arise when
using PPP over a modem connection. For instance, perhaps you
need to know exactly what prompts the system you are dialing
into will present. Some ISPs present the
ssword prompt, and others will present
password; if the ppp
script is not written accordingly, the login attempt will
fail. The most common way to debug ppp
connections is by connecting manually. The following
information will walk you through a manual connection step by
step.Check the Device NodesIf you reconfigured your kernel then you recall the
sio device. If you did not
configure your kernel, there is no reason to worry. Just
check the dmesg output for the modem
device with:&prompt.root; dmesg | grep sioYou should get some pertinent output about the
sio devices. These are the COM
ports we need. If your modem acts like a standard serial
port then you should see it listed on
sio1, or COM2. If so, you are not
required to rebuild the kernel.
When matching up sio modem is on sio1 or
COM2 if you are in DOS, then your
modem device would be /dev/cuaa1.Connecting ManuallyConnecting to the Internet by manually controlling
ppp is quick, easy, and a great way to
debug a connection or just get information on how your
ISP treats ppp client
connections. Lets start PPP from
the command line. Note that in all of our examples we will
use example as the hostname of the
machine running PPP. You start
ppp by just typing
ppp:&prompt.root; pppWe have now started ppp.ppp ON example> set device /dev/cuaa1We set our modem device, in this case it is
cuaa1.ppp ON example> set speed 115200Set the connection speed, in this case we
are using 115,200 kbps.ppp ON example> enable dnsTell ppp to configure our
resolver and add the nameserver lines to
/etc/resolv.conf. If ppp
cannot determine our hostname, we can set one manually later.ppp ON example> termSwitch to terminal mode so that we can manually
control the modem.deflink: Entering terminal mode on /dev/cuaa1
type '~h' for helpat
OK
atdt123456789Use at to initialize the modem,
then use atdt and the number for your
ISP to begin the dial in process.CONNECTConfirmation of the connection, if we are going to have
any connection problems, unrelated to hardware, here is where
we will attempt to resolve them.ISP Login:myusernameHere you are prompted for a username, return the
prompt with the username that was provided by the
ISP.ISP Pass:mypasswordThis time we are prompted for a password, just
reply with the password that was provided by the
ISP. Just like logging into
&os;, the password will not echo.Shell or PPP:pppDepending on your ISP this prompt
may never appear. Here we are being asked if we wish to
use a shell on the provider, or to start
ppp. In this example, we have chosen
to use ppp as we want an Internet
connection.Ppp ON example>Notice that in this example the first
has been capitalized. This shows that we have successfully
connected to the ISP.PPp ON example>We have successfully authenticated with our
ISP and are waiting for the
assigned IP address.PPP ON example>We have made an agreement on an IP
address and successfully completed our connection.PPP ON example>add default HISADDRHere we add our default route, we need to do this before
we can talk to the outside world as currently the only
established connection is with the peer. If this fails due to
existing routes you can put a bang character
! in front of the .
Alternatively, you can set this before making the actual
connection and it will negotiate a new route
accordingly.If everything went good we should now have an active
connection to the Internet, which could be thrown into the
background using CTRLz If you notice the
PPP return to ppp then
we have lost our connection. This is good to know because it
shows our connection status. Capital P's show that we have a
connection to the ISP and lowercase p's
show that the connection has been lost for whatever reason.
ppp only has these 2 states.DebuggingIf you have a direct line and cannot seem to make a
connection, then turn hardware flow
CTS/RTS to off with the . This is mainly the case if you are
connected to some PPP capable
terminal servers, where PPP hangs
when it tries to write data to your communication link, so
it would be waiting for a CTS, or Clear
To Send signal which may never come. If you use this option
however, you should also use the
option, which may be required to defeat hardware dependent
on passing certain characters from end to end, most of the
time XON/XOFF. See the &man.ppp.8; manual page for more
information on this option, and how it is used.If you have an older modem, you may need to use the
. Parity is set at none
be default, but is used for error checking (with a large
increase in traffic) on older modems and some
ISPs. You may need this option for
the Compuserve ISP.PPP may not return to the
command mode, which is usually a negotiation error where
the ISP is waiting for your side to start
negotiating. At this point, using the ~p
command will force ppp to start sending the configuration
information.If you never obtain a login prompt, then most likely you
need to use PAP or
CHAP authentication instead of the
&unix; style in the example above. To use
PAP or CHAP just add
the following options to PPP
before going into terminal mode:ppp ON example> set authname myusernameWhere myusername should be
replaced with the username that was assigned by the
ISP.ppp ON example> set authkey mypasswordWhere mypassword should be
replaced with the password that was assigned by the
ISP.If you connect fine, but cannot seem to find any domain
name, try to use &man.ping.8; with an IP
address and see if you can get any return information. If
you experience 100 percent (100%) packet loss, then it is most
likely that you were not assigned a default route. Double
check that the option
was set during the connection. If you can connect to a
remote IP address then it is possible
that a resolver address has not been added to the
/etc/resolv.conf. This file should
look like:domain example.com
nameserver x.x.x.x
nameserver y.y.y.yWhere x.x.x.x and
y.y.y.y should be replaced with
the IP address of your
ISP's DNS servers. This information may
or may not have been provided when you signed up, but a
quick call to your ISP should remedy
that.You could also have &man.syslog.3; provide a logging
function for your PPP connection.
Just add:!ppp
*.* /var/log/ppp.logto /etc/syslog.conf. In most cases, this
functionality already exists.JimMockContributed (from http://node.to/freebsd/how-tos/how-to-freebsd-pppoe.html) by Using PPP over Ethernet (PPPoE)PPPover EthernetPPPoEPPP, over EthernetThis section describes how to set up PPP over Ethernet
(PPPoE).Configuring the KernelNo kernel configuration is necessary for PPPoE any longer. If
the necessary netgraph support is not built into the kernel, it will
be dynamically loaded by ppp.Setting Up ppp.confHere is an example of a working
ppp.conf:default:
set log Phase tun command # you can add more detailed logging if you wish
set ifaddr 10.0.0.1/0 10.0.0.2/0
name_of_service_provider:
set device PPPoE:xl1 # replace xl1 with your Ethernet device
set authname YOURLOGINNAME
set authkey YOURPASSWORD
set dial
set login
add default HISADDRRunning pppAs root, you can run:&prompt.root; ppp -ddial name_of_service_providerStarting ppp at BootAdd the following to your /etc/rc.conf
file:ppp_enable="YES"
ppp_mode="ddial"
ppp_nat="YES" # if you want to enable nat for your local network, otherwise NO
ppp_profile="name_of_service_provider"Using a PPPoE Service TagSometimes it will be necessary to use a service tag to establish
your connection. Service tags are used to distinguish between
different PPPoE servers attached to a given network.You should have been given any required service tag information
in the documentation provided by your ISP. If you cannot locate
it there, ask your ISP's tech support personnel.As a last resort, you could try the method suggested by the
Roaring Penguin
PPPoE program which can be found in the Ports Collection. Bear in mind however,
this may de-program your modem and render it useless, so
think twice before doing it. Simply install the program shipped
with the modem by your provider. Then, access the
System menu from the program. The name of your
profile should be listed there. It is usually
ISP.The profile name (service tag) will be used in the PPPoE
configuration entry in ppp.conf as the provider
part of the set device command (see the &man.ppp.8;
manual page for full details). It should look like this:set device PPPoE:xl1:ISPDo not forget to change xl1
to the proper device for your Ethernet card.Do not forget to change ISP
to the profile you have just found above.For additional information, see:Cheaper
Broadband with FreeBSD on DSL by Renaud
Waldura.
Nutzung von T-DSL und T-Online mit FreeBSD
by Udo Erdelhoff (in German).PPPoE with a &tm.3com; HomeConnect ADSL Modem Dual LinkThis modem does not follow RFC 2516
(A Method for transmitting PPP over Ethernet
(PPPoE), written by L. Mamakos, K. Lidl, J. Evarts,
D. Carrel, D. Simone, and R. Wheeler). Instead, different packet
type codes have been used for the Ethernet frames. Please complain
to 3Com if you think it
should comply with the PPPoE specification.In order to make FreeBSD capable of communicating with this
device, a sysctl must be set. This can be done automatically at
boot time by updating /etc/sysctl.conf:net.graph.nonstandard_pppoe=1or can be done immediately with the command:&prompt.root; sysctl net.graph.nonstandard_pppoe=1Unfortunately, because this is a system-wide setting, it is
not possible to talk to a normal PPPoE client or server and a
&tm.3com; HomeConnect ADSL Modem at the same time.Using PPP over ATM (PPPoA)PPPover ATMPPPoAPPP, over ATMThe following describes how to set up PPP over ATM (PPPoA).
PPPoA is a popular choice among European DSL providers.Using PPPoA with the Alcatel &speedtouch; USBPPPoA support for this device is supplied as a port in
FreeBSD because the firmware is distributed under Alcatel's
license agreement and can not be redistributed freely
with the base system of FreeBSD.To install the software, simply use the Ports Collection. Install the
net/pppoa port and follow the
instructions provided with it.Like many USB devices, the Alcatel &speedtouch; USB needs to
download firmware from the host computer to operate properly.
It is possible to automate this process in &os; so that this
transfer takes place whenever the device is plugged into a USB
port. The following information can be added to the
/etc/usbd.conf file to enable this
automatic firmware transfer. This file must be edited as the
root user.device "Alcatel SpeedTouch USB"
devname "ugen[0-9]+"
vendor 0x06b9
product 0x4061
attach "/usr/local/sbin/modem_run -f /usr/local/libdata/mgmt.o"To enable the USB daemon, usbd,
put the following the line into
/etc/rc.conf:usbd_enable="YES"It is also possible to set up
ppp to dial up at startup. To do
this add the following lines to
/etc/rc.conf. Again, for this procedure
you will need to be logged in as the root
user.ppp_enable="YES"
ppp_mode="ddial"
ppp_profile="adsl"For this to work correctly you will need to have used the
sample ppp.conf which is supplied with the
net/pppoa port.Using mpdYou can use mpd to connect to a
variety of services, in particular PPTP services. You can find
mpd in the Ports Collection,
net/mpd. Many ADSL modems
require that a PPTP tunnel is created between the modem and
computer, one such modem is the Alcatel &speedtouch;
Home.First you must install the port, and then you can
configure mpd to suit your
requirements and provider settings. The port places a set of
sample configuration files which are well documented in
PREFIX/etc/mpd/.
Note here that PREFIX means the directory
into which your ports are installed, this defaults to
/usr/local/. A complete guide to
configure mpd is available in
HTML format once the port has been installed. It is placed in
PREFIX/share/doc/mpd/.
Here is a sample configuration for connecting to an ADSL
service with mpd. The configuration
is spread over two files, first the
mpd.conf:default:
load adsl
adsl:
new -i ng0 adsl adsl
set bundle authname username
set bundle password password
set bundle disable multilink
set link no pap acfcomp protocomp
set link disable chap
set link accept chap
set link keep-alive 30 10
set ipcp no vjcomp
set ipcp ranges 0.0.0.0/0 0.0.0.0/0
set iface route default
set iface disable on-demand
set iface enable proxy-arp
set iface idle 0
openThe username used to authenticate with your ISP.The password used to authenticate with your ISP.The mpd.links file contains information about
the link, or links, you wish to establish. An example
mpd.links to accompany the above example is given
beneath:adsl:
set link type pptp
set pptp mode active
set pptp enable originate outcall
set pptp self 10.0.0.1
set pptp peer 10.0.0.138The IP address of your &os; computer which you will be
using mpd from.The IP address of your ADSL modem. For the Alcatel
&speedtouch; Home this address defaults to 10.0.0.138.It is possible to initialize the connection easily by issuing the
following command as root:&prompt.root; mpd -b adslYou can see the status of the connection with the following
command:&prompt.user; ifconfig ng0
ng0: flags=88d1<UP,POINTOPOINT,RUNNING,NOARP,SIMPLEX,MULTICAST> mtu 1500
inet 216.136.204.117 --> 204.152.186.171 netmask 0xffffffffUsing mpd is the recommended way to
connect to an ADSL service with &os;.Using pptpclientIt is also possible to use FreeBSD to connect to other PPPoA
services using
net/pptpclient.To use net/pptpclient to
connect to a DSL service, install the port or package and edit your
/etc/ppp/ppp.conf. You will need to be
root to perform both of these operations. An
example section of ppp.conf is given
below. For further information on ppp.conf
options consult the ppp manual page,
&man.ppp.8;.adsl:
set log phase chat lcp ipcp ccp tun command
set timeout 0
enable dns
set authname username
set authkey password
set ifaddr 0 0
add default HISADDRThe username of your account with the DSL provider.The password for your account.Because you must put your account's password in the
ppp.conf file in plain text form you should
make sure than nobody can read the contents of this file. The
following series of commands will make sure the file is only
readable by the root account. Refer to the
manual pages for &man.chmod.1; and &man.chown.8; for further
information.&prompt.root; chown root:wheel /etc/ppp/ppp.conf
&prompt.root; chmod 600 /etc/ppp/ppp.confThis will open a tunnel for a PPP session to your DSL router.
Ethernet DSL modems have a preconfigured LAN IP address which you
connect to. In the case of the Alcatel &speedtouch; Home this address is
10.0.0.138. Your router documentation
should tell you which address your device uses. To open the tunnel and
start a PPP session execute the following
command:&prompt.root; pptp addressadslYou may wish to add an ampersand (&) to the
end of the previous command because pptp
will not return your prompt to you otherwise.A tun virtual tunnel device will be
created for interaction between the pptp
and ppp processes. Once you have been
returned to your prompt, or the pptp
process has confirmed a connection you can examine the tunnel like
so:&prompt.user; ifconfig tun0
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
inet 216.136.204.21 --> 204.152.186.171 netmask 0xffffff00
Opened by PID 918If you are unable to connect, check the configuration of
your router, which is usually accessible via
telnet or with a web browser. If you still
cannot connect you should examine the output of the
pptp command and the contents of the
ppp log file,
/var/log/ppp.log for clues.SatoshiAsamiOriginally contributed by GuyHelmerWith input from PieroSeriniUsing SLIPSLIPSetting Up a SLIP ClientSLIPclientThe following is one way to set up a FreeBSD machine for SLIP
on a static host network. For dynamic hostname assignments (your
address changes each time you dial up), you probably need to
have a more complex setup.First, determine which serial port your modem is connected to.
Many people set up a symbolic link, such as
/dev/modem, to point to the real device name,
/dev/cuaaN (or /dev/cuadN under &os; 6.X). This allows you to
abstract the actual device name should you ever need to move
the modem to a different port. It can become quite cumbersome when you
need to fix a bunch of files in /etc and
.kermrc files all over the system!/dev/cuaa0 (or /dev/cuad0 under &os; 6.X) is
COM1, cuaa1 (or /dev/cuad1) is
COM2, etc.Make sure you have the following in your kernel configuration
file:device slIt is included in the GENERIC kernel, so
this should not be a problem unless you have deleted it.Things You Have to Do Only OnceAdd your home machine, the gateway and nameservers to
your /etc/hosts file. Ours looks like
this:127.0.0.1 localhost loghost
136.152.64.181 water.CS.Example.EDU water.CS water
136.152.64.1 inr-3.CS.Example.EDU inr-3 slip-gateway
128.32.136.9 ns1.Example.EDU ns1
128.32.136.12 ns2.Example.EDU ns2Make sure you have hosts before
bind in your
/etc/host.conf on FreeBSD versions
prior to 5.0. Since FreeBSD 5.0, the system uses
the file /etc/nsswitch.conf instead,
make sure you have files before
dns in the line
of this file. Without these parameters funny
things may happen.Edit the /etc/rc.conf file.Set your hostname by editing the line that
says:hostname="myname.my.domain"Your machine's full Internet hostname should be
placed here.
- default route
-
- Designate the default router by changing the
+ Designate the default routerdefault route by changing the
line:defaultrouter="NO"to:defaultrouter="slip-gateway"Make a file /etc/resolv.conf which
contains:domain CS.Example.EDU
nameserver 128.32.136.9
nameserver 128.32.136.12
- nameserver
- domain name
- As you can see, these set up the nameserver hosts. Of
- course, the actual domain names and addresses depend on your
+ As you can see, these set up the nameservernameserver hosts. Of
+ course, the actual domain namesdomain name and addresses depend on your
environment.Set the password for root and
toor (and any other
accounts that do not have a password).Reboot your machine and make sure it comes up with the
correct hostname.Making a SLIP ConnectionSLIPconnecting withDial up, type slip at the prompt,
enter your machine name and password. What is required to
be entered depends on your environment. If you use
Kermit, you can try a script like this:# kermit setup
set modem hayes
set line /dev/modem
set speed 115200
set parity none
set flow rts/cts
set terminal bytesize 8
set file type binary
# The next macro will dial up and login
define slip dial 643-9600, input 10 =>, if failure stop, -
output slip\x0d, input 10 Username:, if failure stop, -
output silvia\x0d, input 10 Password:, if failure stop, -
output ***\x0d, echo \x0aCONNECTED\x0aOf course, you have to change the username and password
to fit yours. After doing so, you can just type
slip from the Kermit prompt to
connect.Leaving your password in plain text anywhere in the
filesystem is generally a bad idea.
Do it at your own risk.Leave the Kermit there (you can suspend it by
Ctrlz) and as root, type:&prompt.root; slattach -h -c -s 115200 /dev/modemIf you are able to ping hosts on the
other side of the router, you are connected! If it does not
work, you might want to try instead of
as an argument to
slattach.How to Shutdown the ConnectionDo the following:&prompt.root; kill -INT `cat /var/run/slattach.modem.pid`to kill slattach. Keep in mind you must be
root to do the above. Then go back to
kermit (by running fg if you suspended it) and
exit from
it (q).The &man.slattach.8; manual page says you have
to use ifconfig sl0 down
to mark the interface down, but this does not
seem to make any difference.
(ifconfig sl0 reports the same thing.)Some times, your modem might refuse to drop the carrier.
In that case, simply start kermit and quit
it again. It usually goes out on the second try.TroubleshootingIf it does not work, feel free to ask on &a.net.name; mailing list. The things that
people tripped over so far:Not using or in
slattach (This should not be fatal,
but some users have reported that this solves their
problems.)Using instead of
(might be hard to see the difference on
some fonts).Try ifconfig sl0 to see your
interface status. For example, you might get:&prompt.root; ifconfig sl0
sl0: flags=10<POINTOPOINT>
inet 136.152.64.181 --> 136.152.64.1 netmask ffffff00If you get no route to host
messages from &man.ping.8;, there may be a problem with your
routing table. You can use the netstat -r
command to display the current routes :&prompt.root; netstat -r
Routing tables
Destination Gateway Flags Refs Use IfaceMTU Rtt Netmasks:
(root node)
(root node)
Route Tree for Protocol Family inet:
(root node) =>
default inr-3.Example.EDU UG 8 224515 sl0 - -
localhost.Exampl localhost.Example. UH 5 42127 lo0 - 0.438
inr-3.Example.ED water.CS.Example.E UH 1 0 sl0 - -
water.CS.Example localhost.Example. UGH 34 47641234 lo0 - 0.438
(root node)The preceding examples are from a relatively busy system.
The numbers on your system will vary depending on
network activity.Setting Up a SLIP ServerSLIPserverThis document provides suggestions for setting up SLIP Server
services on a FreeBSD system, which typically means configuring
your system to automatically start up connections upon login for
remote SLIP clients.PrerequisitesTCP/IP networkingThis section is very technical in nature, so background
knowledge is required. It is assumed that you are familiar with
the TCP/IP network protocol, and in particular, network and node
addressing, network address masks, subnetting, routing, and
routing protocols, such as RIP. Configuring SLIP services on a
dial-up server requires a knowledge of these concepts, and if
you are not familiar with them, please read a copy of either
Craig Hunt's TCP/IP Network Administration
published by O'Reilly & Associates, Inc. (ISBN Number
0-937175-82-X), or Douglas Comer's books on the TCP/IP
protocol.modemIt is further assumed that you have already set up your
modem(s) and configured the appropriate system files to allow
logins through your modems. If you have not prepared your
system for this yet, please see for details on dialup services
configuration.
You may also want to check the manual pages for &man.sio.4; for
information on the serial port device driver and &man.ttys.5;,
&man.gettytab.5;, &man.getty.8;, & &man.init.8; for
information relevant to configuring the system to accept logins
on modems, and perhaps &man.stty.1; for information on setting
serial port parameters (such as clocal for
directly-connected serial interfaces).Quick OverviewIn its typical configuration, using FreeBSD as a SLIP server
works as follows: a SLIP user dials up your FreeBSD SLIP Server
system and logs in with a special SLIP login ID that uses
/usr/sbin/sliplogin as the special user's
shell. The sliplogin program browses the
file /etc/sliphome/slip.hosts to find a
matching line for the special user, and if it finds a match,
connects the serial line to an available SLIP interface and then
runs the shell script
/etc/sliphome/slip.login to configure the
SLIP interface.An Example of a SLIP Server LoginFor example, if a SLIP user ID were
Shelmerg, Shelmerg's
entry in /etc/master.passwd would look
something like this:Shelmerg:password:1964:89::0:0:Guy Helmer - SLIP:/usr/users/Shelmerg:/usr/sbin/sliploginWhen Shelmerg logs in,
sliplogin will search
/etc/sliphome/slip.hosts for a line that
had a matching user ID; for example, there may be a line in
/etc/sliphome/slip.hosts that
reads:Shelmerg dc-slip sl-helmer 0xfffffc00 autocompsliplogin will find that matching line,
hook the serial line into the next available SLIP interface,
and then execute /etc/sliphome/slip.login
like this:/etc/sliphome/slip.login 0 19200 Shelmerg dc-slip sl-helmer 0xfffffc00 autocompIf all goes well,
/etc/sliphome/slip.login will issue an
ifconfig for the SLIP interface to which
sliplogin attached itself (SLIP interface
0, in the above example, which was the first parameter in the
list given to slip.login) to set the
local IP address (dc-slip), remote IP address
(sl-helmer), network mask for the SLIP
interface (0xfffffc00), and
any additional flags (autocomp). If
something goes wrong, sliplogin usually
logs good informational messages via the
syslogd daemon facility, which usually logs
to /var/log/messages (see the manual
pages for &man.syslogd.8; and &man.syslog.conf.5; and perhaps
check /etc/syslog.conf to see to what
syslogd is logging and where it is
logging to).Kernel ConfigurationkernelconfigurationSLIP&os;'s default kernel (GENERIC)
comes with SLIP (&man.sl.4;) support; in case of a custom
kernel, you have to add the following line to your kernel
configuration file:device slBy default, your &os; machine will not forward packets.
If you want your FreeBSD SLIP Server to act as a router, you
will have to edit the /etc/rc.conf file and
change the setting of the gateway_enable variable to
.You will then need to reboot for the new settings to take
effect.Please refer to on
Configuring the FreeBSD Kernel for help in
reconfiguring your kernel.Sliplogin ConfigurationAs mentioned earlier, there are three files in the
/etc/sliphome directory that are part of
the configuration for /usr/sbin/sliplogin
(see &man.sliplogin.8; for the actual manual page for
sliplogin): slip.hosts,
which defines the SLIP users and their associated IP
addresses; slip.login, which usually just
configures the SLIP interface; and (optionally)
slip.logout, which undoes
slip.login's effects when the serial
connection is terminated.slip.hosts Configuration/etc/sliphome/slip.hosts contains
lines which have at least four items separated by
whitespace:SLIP user's login IDLocal address (local to the SLIP server) of the SLIP
linkRemote address of the SLIP linkNetwork maskThe local and remote addresses may be host names
(resolved to IP addresses by
/etc/hosts or by the domain name
service, depending on your specifications in the file
/etc/nsswitch.conf), and the network mask may be
a name that can be resolved by a lookup into
/etc/networks. On a sample system,
/etc/sliphome/slip.hosts looks like
this:#
# login local-addr remote-addr mask opt1 opt2
# (normal,compress,noicmp)
#
Shelmerg dc-slip sl-helmerg 0xfffffc00 autocompAt the end of the line is one or more of the
options: — no header
compression — compress
headers — compress headers if
the remote end allows it — disable ICMP packets
(so any ping packets will be dropped instead
of using up your bandwidth)SLIPTCP/IP networkingYour choice of local and remote addresses for your SLIP
links depends on whether you are going to dedicate a TCP/IP
subnet or if you are going to use proxy ARP on
your SLIP server (it is not true proxy ARP, but
that is the terminology used in this section to describe it).
If you are not sure which method to select or how to assign IP
addresses, please refer to the TCP/IP books referenced in
the SLIP Prerequisites ()
and/or consult your IP network manager.If you are going to use a separate subnet for your SLIP
clients, you will need to allocate the subnet number out of
your assigned IP network number and assign each of your SLIP
client's IP numbers out of that subnet. Then, you will
probably need to configure a static route to the SLIP
subnet via your SLIP server on your nearest IP router.EthernetOtherwise, if you will use the proxy ARP
method, you will need to assign your SLIP client's IP
addresses out of your SLIP server's Ethernet subnet, and you
will also need to adjust your
/etc/sliphome/slip.login and
/etc/sliphome/slip.logout scripts to use
&man.arp.8; to manage the proxy-ARP entries in the SLIP
server's ARP table.slip.login ConfigurationThe typical /etc/sliphome/slip.login
file looks like this:#!/bin/sh -
#
# @(#)slip.login 5.1 (Berkeley) 7/1/90
#
# generic login file for a slip line. sliplogin invokes this with
# the parameters:
# 1 2 3 4 5 6 7-n
# slipunit ttyspeed loginname local-addr remote-addr mask opt-args
#
/sbin/ifconfig sl$1 inet $4 $5 netmask $6This slip.login file merely runs
ifconfig for the appropriate SLIP interface
with the local and remote addresses and network mask of the
SLIP interface.If you have decided to use the proxy ARP
method (instead of using a separate subnet for your SLIP
clients), your /etc/sliphome/slip.login
file will need to look something like this:#!/bin/sh -
#
# @(#)slip.login 5.1 (Berkeley) 7/1/90
#
# generic login file for a slip line. sliplogin invokes this with
# the parameters:
# 1 2 3 4 5 6 7-n
# slipunit ttyspeed loginname local-addr remote-addr mask opt-args
#
/sbin/ifconfig sl$1 inet $4 $5 netmask $6
# Answer ARP requests for the SLIP client with our Ethernet addr
/usr/sbin/arp -s $5 00:11:22:33:44:55 pubThe additional line in this
slip.login, arp -s
$5 00:11:22:33:44:55 pub, creates an ARP entry
in the SLIP server's ARP table. This ARP entry causes the
SLIP server to respond with the SLIP server's Ethernet MAC
address whenever another IP node on the Ethernet asks to
speak to the SLIP client's IP address.EthernetMAC addressWhen using the example above, be sure to replace the
Ethernet MAC address (00:11:22:33:44:55) with the MAC address of
your system's Ethernet card, or your proxy ARP
will definitely not work! You can discover your SLIP server's
Ethernet MAC address by looking at the results of running
netstat -i; the second line of the output
should look something like:ed0 1500 <Link>0.2.c1.28.5f.4a 191923 0 129457 0 116This indicates that this particular system's Ethernet MAC
address is 00:02:c1:28:5f:4a
— the periods in the Ethernet MAC address given by
netstat -i must be changed to colons and
leading zeros should be added to each single-digit hexadecimal
number to convert the address into the form that &man.arp.8;
desires; see the manual page on &man.arp.8; for complete
information on usage.When you create
/etc/sliphome/slip.login and
/etc/sliphome/slip.logout, the
execute bit (i.e., chmod 755
/etc/sliphome/slip.login /etc/sliphome/slip.logout)
must be set, or sliplogin will be unable
to execute it.slip.logout Configuration/etc/sliphome/slip.logout is not
strictly needed (unless you are implementing proxy
ARP), but if you decide to create it, this is an
example of a basic
slip.logout script:#!/bin/sh -
#
# slip.logout
#
# logout file for a slip line. sliplogin invokes this with
# the parameters:
# 1 2 3 4 5 6 7-n
# slipunit ttyspeed loginname local-addr remote-addr mask opt-args
#
/sbin/ifconfig sl$1 downIf you are using proxy ARP, you will want to
have /etc/sliphome/slip.logout remove the
ARP entry for the SLIP client:#!/bin/sh -
#
# @(#)slip.logout
#
# logout file for a slip line. sliplogin invokes this with
# the parameters:
# 1 2 3 4 5 6 7-n
# slipunit ttyspeed loginname local-addr remote-addr mask opt-args
#
/sbin/ifconfig sl$1 down
# Quit answering ARP requests for the SLIP client
/usr/sbin/arp -d $5The arp -d $5 removes the ARP entry
that the proxy ARPslip.login added when the SLIP client
logged in.It bears repeating: make sure
/etc/sliphome/slip.logout has the execute
bit set after you create it (i.e., chmod 755
/etc/sliphome/slip.logout).Routing ConsiderationsSLIProutingIf you are not using the proxy ARP method for
routing packets between your SLIP clients and the rest of your
network (and perhaps the Internet), you will probably
have to add static routes to your closest default router(s) to
route your SLIP clients subnet via your SLIP server.Static Routesstatic routesAdding static routes to your nearest default routers
can be troublesome (or impossible if you do not have
authority to do so...). If you have a multiple-router
network in your organization, some routers, such as those
made by Cisco and Proteon, may not only need to be
configured with the static route to the SLIP subnet, but
also need to be told which static routes to tell other
routers about, so some expertise and
troubleshooting/tweaking may be necessary to get
static-route-based routing to work.Running &gated;&gated;&gated; is proprietary software now and
will not be available as source code to the public anymore
(more info on the &gated; website). This
section only exists to ensure backwards compatibility for
those that are still using an older version.An alternative to the headaches of static routes is to
install &gated; on your FreeBSD SLIP server
and configure it to use the appropriate routing protocols
(RIP/OSPF/BGP/EGP) to tell other routers about your SLIP
subnet.
You will need to write a /etc/gated.conf
file to configure your &gated;; here is a sample, similar to
what the author used on a FreeBSD SLIP server:#
# gated configuration file for dc.dsu.edu; for gated version 3.5alpha5
# Only broadcast RIP information for xxx.xxx.yy out the ed Ethernet interface
#
#
# tracing options
#
traceoptions "/var/tmp/gated.output" replace size 100k files 2 general ;
rip yes {
interface sl noripout noripin ;
interface ed ripin ripout version 1 ;
traceoptions route ;
} ;
#
# Turn on a bunch of tracing info for the interface to the kernel:
kernel {
traceoptions remnants request routes info interface ;
} ;
#
# Propagate the route to xxx.xxx.yy out the Ethernet interface via RIP
#
export proto rip interface ed {
proto direct {
xxx.xxx.yy mask 255.255.252.0 metric 1; # SLIP connections
} ;
} ;
#
# Accept routes from RIP via ed Ethernet interfaces
import proto rip interface ed {
all ;
} ;RIPThe above sample gated.conf file
broadcasts routing information regarding the SLIP subnet
xxx.xxx.yy via RIP onto the
Ethernet; if you are using a different Ethernet driver than
the ed driver, you will need to
change the references to the ed
interface appropriately. This sample file also sets up
tracing to /var/tmp/gated.output for
debugging &gated;'s activity; you can
certainly turn off the tracing options if
&gated; works correctly for you. You will need to
change the xxx.xxx.yy's into the
network address of your own SLIP subnet (be sure to change the
net mask in the proto direct clause as
well).Once you have installed and configured
&gated; on your system, you will need to
tell the FreeBSD startup scripts to run
&gated; in place of
routed. The easiest way to accomplish
this is to set the router and
router_flags variables in
/etc/rc.conf. Please see the manual
page for &gated; for information on
command-line parameters.
diff --git a/ru_RU.KOI8-R/books/handbook/boot/chapter.xml b/ru_RU.KOI8-R/books/handbook/boot/chapter.xml
index 8346cc6885..4cf430362d 100644
--- a/ru_RU.KOI8-R/books/handbook/boot/chapter.xml
+++ b/ru_RU.KOI8-R/books/handbook/boot/chapter.xml
@@ -1,1039 +1,1035 @@
АндрейЗахватовПеревод на русский язык: Процесс загрузки FreeBSDОписаниезагрузканачальная загрузкаПроцесс включения компьютера и загрузки операционной системы
называется процессом первоначальной загрузки, или просто
загрузкой. Процесс загрузки FreeBSD предоставляет большие
возможности по гибкой настройке того, что происходит при запуске системы,
позволяя вам выбирать из различных операционных систем, установленных на
одном и том же компьютере, или даже из различных версий той же самой
операционной системы или установленного ядра.Эта глава подробно описывает параметры, которые вы можете изменить
для настройки процесса загрузки FreeBSD. Под этим подразумевается все,
что происходит до начала работы ядра FreeBSD, обнаружения устройств и
запуска &man.init.8;. Если вы не совсем уверены, то это происходит,
когда выводимый текст меняет цвет с ярко-белого на серый.После чтения этой главы вы будете знать:Из каких частей состоит система начальной загрузки FreeBSD, и
как эти части взаимодействуют.Параметры, которые вы можете передать компонентам начальной
загрузки FreeBSD для управления этим процессом.Основы работы &man.device.hints.5;Только для x86Эта глава описывает процесс загрузки FreeBSD только для систем
на основе архитектуры Intel x86.Проблема загрузкиВключение компьютера и запуск операционной системы приводят к
интересной дилемме. По определению до запуска операционной системы
компьютер не умеет ничего. В том числе и не знает, как запускать программы
с диска. Так что компьютер не может запустить программу с диска без
операционной системы, но программы операционной системы находятся на
диске, но как запустить операционную систему?Эта проблема имеет параллели с одной проблемой из книги
Приключения барона Мюнхгаузена. Герой провалился в
болото, и вытащил сам себя, ухватив за волосы и потянув. В эпоху начала
компьютеризации термин начальная загрузка
применялся к механизму, используемому для загрузки операционной системы,
и затем был сокращен до просто загрузки.BIOSBasic Input/Output SystemBIOSНа оборудовании архитектуры x86 за загрузку операционной системы
отвечает BIOS (Basic Input/Output System). Для этого BIOS ищет на
жестком диске MBR (Master Boot Record), которая должна располагаться в
определенном месте на диске. BIOS может загрузить и запустить MBR, и
предполагается, что MBR может взять на себя остальную работу, связанную с
загрузкой операционной системы.Master Boot Record (MBR)Boot LoaderВыполняемую часть MBR обычно называют менеджером
загрузки (boot manager), в особенности если она
взаимодействует с пользователем. В этом случае менеджер загрузки,
как правило, занимает большее пространство на первом
треке диска или внутри файловой системы ОС.
(Менеджер загрузки иногда называют загрузчиком (boot
loader), но во &os; этот термин используется для
описания более поздней фазы загрузки). Среди популярных менеджеров
загрузки стоит отметить boot0 (он же
Boot Easy, стандартный менеджер загрузки
&os;), Grub, GAG
и LILO. Из перечисленных менеджеров
загрузки в MBR помещается только
boot0.Если на вашем диске установлена только одна операционная система, то
стандартной MBR будет достаточно. Такая MBR выполняет поиск на диске
первого загрузочного (активного) слайса, после чего запускает с этого слайса код
загрузки оставшейся части операционной системы. Утилита &man.fdisk.8;
по умолчанию устанавливает именно такую MBR, на основе файла
/boot/mbr.Если на ваших дисках установлено несколько операционных систем, то
вы можете установить другой менеджер загрузки, который может выдать список различных
операционных систем и позволит вам выбрать одну из них для загрузки.
Два варианта менеджеров загрузки будут описаны чуть ниже.Оставшаяся часть системы начальной загрузки FreeBSD разделяется на
три этапа. Первый этап запускается из MBR, и он знает достаточно для
перевода компьютера в особое состояние и загрузки второго этапа. Второй
этап может делать несколько больше до запуска третьего этапа. Третий
этап заканчивает работу по загрузке операционной системы. Работа
разделена на эти три этапа, потому что стандарты ПК ограничивают размеры
программ, которые могут быть запущены на первом и втором этапах.
Последовательное выполнение работ позволяет FreeBSD получить более гибкий
загрузчик.ядроinitЗатем стартует ядро, которое начинает опознавать устройства и
выполняет их инициализацию. После завершения процесса своей загрузки,
ядро передает управление пользовательскому процессу с именем
&man.init.8;, который выполняет проверку дисков на возможность
использования. Затем &man.init.8; запускает пользовательский процесс
настройки ресурсов, который монтирует файловые системы, выполняет
настройку сетевых адаптеров для работы в сети и вообще осуществляет
запуск всех процессов, обычно выполняемых в системе FreeBSD при
загрузке.Менеджер загрузки и этапы загрузкиBoot ManagerМенеджер загрузкиMaster Boot Record (MBR)Код MBR или менеджера загрузки время от времени называют
нулевой стадией процесса загрузки. В этом
разделе мы обсудим два из упомянутых ранее менеджеров загрузки:
boot0 и
LILO.MBR для FreeBSD находится в /boot/boot0. Это
копия MBR, так как настоящая MBR должна
располагаться в специальном месте диска, вне области FreeBSD.boot0 очень прост, так как программа
в MBR может иметь размер, не превышающий 512
байт. Если вы установили MBR FreeBSD и несколько операционных
систем на ваш жесткий диск, то во время загрузки вы увидите нечто
похожее на следующее:Менеджер загрузки boot0:MBR, устанавливаемый программой установки &os; или утилитой
&man.boot0cfg.8;, основан на /boot/boot0.
(boot0 очень прост, так как программа
в MBR может иметь размер, не превышающий 446
байт, так как часть первого сектора диска занята таблицей слайсов
и сигнатурой 0x55AA).
Если вы установили boot0 и несколько операционных
систем на ваш жесткий диск, то во время загрузки вы увидите нечто
похожее на следующее:Образец экрана boot0F1 DOS
F2 FreeBSD
F3 Linux
F4 ??
F5 Drive 1
Default: F2Известно, что другие операционные системы, в частности,
&windows; 95, записывают поверх существующей MBR свою собственную.
Если так случилось в вашем случае, или же вы хотите заменить
существующую MBR на MBR от FreeBSD, то воспользуйтесь следующей
командой:&prompt.root; fdisk -B -b /boot/boot0 deviceЗдесь device является устройством, с
которого вы загружаетесь, таким, как ad0 в
случае первого диска IDE, ad2 в случае первого
диска IDE на втором контроллере IDE, da0 для
первого диска SCSI и так далее. Если вы используете MBR
нестандартного вида, воспользуйтесь &man.boot0cfg.8;.Менеджер загрузки LILO:Для того, чтобы этот менеджер загрузки мог загружать &os;,
загрузите Linux и добавьте к существующему файлу конфигурации
/etc/lilo.conf такие строки:other=/dev/hdXY
table=/dev/hdb
loader=/boot/chain.b
label=FreeBSDУкажите диск с основным разделом &os; в терминах Linux,
заменив X буквой диска, используемой в
Linux, а Y — номером основного
раздела. Если вы используете диски SCSI,
замените /dev/hd на
/dev/sd. Строка
может быть опущена, если
обе операционные системы находятся на одном диске. Теперь
запустите /sbin/lilo -v для того, чтобы ваши
изменения были восприняты системой, что должно быть подтверждено
сообщениями на экране.Этап первый, /boot/boot1, и этап второй,
/boot/boot2Концептуально первый и второй этапы загрузки являются частями одной
и той же программы, в одной области диска. Из-за ограничений на
объем дискового пространства они были разделены на две, но вы всегда
должны устанавливать их вместе. Они копируются инсталлятором или
утилитой bsdlabel (см. ниже) из общего
файла /boot/boot.Они располагаются вне файловых систем, на первом треке загрузочного слайса,
то есть там, где boot0 или
любой другой менеджер загрузки ожидает найти
программу, которую следует запустить для продолжение процесса загрузки.
Количество используемых секторов легко может быть вычислено из
размера файла /boot/boot.boot1 очень прост, так как он не может иметь
размер, превышающий 512 байт, и знает лишь о метке
диска FreeBSD, хранящей информацию о слайсе, для того,
чтобы найти и запустить boot2.boot2 устроен несколько более сложно, и умеет
работать с файловой системой FreeBSD в объёме, достаточном для
нахождения в ней файлов, и может предоставлять простой интерфейс для
выбора и передачи управления ядру или загрузчику.Так как загрузчик устроен
гораздо более сложно, и дает удобный и простой способ настройки
процесса загрузки, boot2 обычно запускает его,
однако раньше его задачей был запуск непосредственно самого
ядра.Образец экрана boot2
>> FreeBSD/i386 BOOT
Default: 0:ad(0,a)/boot/loader
boot:
Если вам когда-либо понадобится заменить установленные
boot1 и boot2, то используйте
утилиту &man.bsdlabel.8;:&prompt.root; bsdlabel -B disksliceЗдесь diskslice являются диском и
слайсом, с которых вы загружаетесь, например,
ad0s1 в случае первого слайса на первом диске
IDE.Режим Dangerously DedicatedЕсли вы используете только имя диска, к примеру,
ad0, в команде &man.bsdlabel.8; вы
создадите диск в режиме эксклюзивного использования, без слайсов.
Это, скорее всего, вовсе не то, что вы хотите сделать, так что дважды
проверьте параметры команды &man.bsdlabel.8;, прежде, чем нажать
Return.Третий этап, /boot/loaderзагрузчикПередача управления загрузчику является последним, третьим этапом в
процессе начальной загрузки, а сам загрузчик находится в файловой
системе, обычно как /boot/loader.Загрузчик являет собой удобный в использовании инструмент для
настройки при помощи простого набора команд, управляемого более мощным
интерпретатором с более сложным набором команд.Процесс работы загрузчикаВо время инициализации загрузчик пытается произвести поиск
консоли, дисков и определить, с какого диска он был запущен.
Соответствующим образом он задаёт значения переменных и запускает
интерпретатор, которому могут передаваться пользовательские команды
как из скрипта, так и в интерактивном режиме.загрузчикконфигурация загрузчикаЗатем загрузчик читает файл
/boot/loader.rc, который по умолчанию использует
файл /boot/defaults/loader.conf, устанавливающий
подходящие значения по умолчанию для переменных и читает файл
/boot/loader.conf для изменения в этих
переменных. Затем с этими переменными работает
loader.rc, загружающий выбранные модули и
ядро.И наконец, по умолчанию загрузчик выдерживает 10-секундную паузу,
ожидая нажатия клавиши, и загружает ядро, если этого не произошло.
Если ожидание было прервано, пользователю выдается
приглашение, которое воспринимает простой набор команд, с помощью
которых пользователь может изменить значения переменных, выгрузить
все модули, загрузить модули и окончательно продолжить процесс
загрузки или перезагрузить машину.Встроенные команды загрузчикаДалее следуют наиболее часто используемые команды загрузчика.
Полное описание всех имеющихся команд можно найти на странице
справки о команде &man.loader.8;.autoboot секундыПродолжает загрузку ядра, если не будет прерван в течение
указанного в секундах промежутка времени. Он выводит счетчик,
и по умолчанию выдерживается интервал в 10 секунд.boot
-параметрыимя ядраПродолжить процесс загрузки указанного ядра, если оно было
указано, и с указанными параметрами, если они были
указаны. Загрузка и использование указанного ядра
возможны лишь после выгрузки текущего ядра, а выгрузка текущего
ядра производится командой unload.boot-confПовторно провести тот же самый процесс автоматической
настройки модулей на основе переменных, что был произведен при
загрузке. Это имеет смысл, если до этого вы выполнили команду
unload, изменили некоторые переменные,
например, наиболее часто меняемую kernel.help
темаВывод сообщений подсказки из файла
/boot/loader.help. Если в качестве темы
указано слово index, то выводится список
имеющихся тем.include имя файла
…Выполнить файл с указанным именем. Файл считывается и
его содержимое интерпретируется строчка за строчкой. Ошибка
приводит к немедленному прекращению выполнения команды
include.load типимя файлаЗагружает ядро, модуль ядра или файл указанного типа с
указанным именем. Все аргументы после имени файла передаются в
файл.ls маршрутВыводит список файлов по указанному маршруту или в корневом
каталоге, если маршрут не был указан. Если указан параметр
, будут выводиться и размеры файлов.lsdev Выводится список всех устройств, с которых могут быть
загружены модули. Если указан параметр ,
выводится дополнительная информация.lsmod Выводит список загруженных модулей. Если указан параметр
, то выводится дополнительная
информация.more имя файлаВывод указанного файла с паузой при выводе каждой строки
LINES.rebootВыполнить немедленную перезагрузку машины.set переменнаяset
переменная=значениеЗадает значения переменных окружения загрузчика.unloadУдаление из памяти всех загруженных модулей.Примеры использования загрузчикаВот несколько примеров практического использования
загрузчика:
- однопользовательский режимЧтобы просто загрузить ваше ядро обычным образом, но в
- однопользовательском режиме:
+ однопользовательском режиме:однопользовательский режимboot -sДля выгрузки обычных ядра и модулей, а потом просто загрузить
ваше старое (или другое) ядро:
-
- kernel.old
- unloadload kernel.oldВы можете использовать kernel.GENERIC
для обозначения стандартного ядра, поставляемого на установочном
- диске, или kernel.old для обращения к ранее
+ диске, или kernel.oldkernel.old для обращения к ранее
установленному ядру (после того, как, например, вы обновили или
отконфигурировали новое ядро).Для загрузки ваших обычных модулей с другим ядром
используйте такие команды:unloadset kernel="kernel.old"boot-confДля загрузки скрипта конфигурации ядра (автоматизированный
скрипт, который выполняет то, что вы обычно делаете в
конфигураторе ядра во время загрузки):load -t userconfig_script /boot/kernel.confJoseph J.BarbishПредоставил Загрузочные экранные заставкиЗаставка создает более привлекательный вид процесса
загрузки по сравнению с традиционными сообщениями загрузки.
Изображение заставки будет отображаться до тех пор, пока
не придет очередь приглашения ввода логина на консоли или в
менеджере дисплеев.Есть два базовых окружения во &os;. Первое — это
окружение командной строки текстовой виртуальной консоли.
По завершении загрузки системы вам предоставляется консольное
приглашение ввода логина. Второе окружение — это
графическое окружение рабочего стола X11. После установки X11 и одной из графических оболочек,
таких как GNOME,
KDE или XFce,
становится возможным запуск рабочего стола Х11 командой
startx.Некоторые пользователи предпочитают графический интерфейс
входа традиционному текстовому приглашению ввода логина.
Менеджеры экранов, наподобие
XDM для &xorg;,
gdm для GNOME,
kdm для KDE
(а также другие, доступные из коллекции портов), изначально
предоставляют графический интерфейс входа. После успешного входа
в систему они запускают соответствующий оконный менеджер.В текстовом окружении экранная заставка скрывает все подробности
процесса загрузки и сообщения стартовых скриптов до момента выдачи
приглашения ввода логина. Если используется экранная заставка
перед входом в графическое окружение, то пользователи получают
визуально более чистый старт системы, чем-то напоминающий опыт
работы с µsoft; &windows; или с иной не unix-подобной
системой.Экранная заставка в действииВ качестве заставки можно использовать лишь содержащие
256 цветов изображения формата BMP
(.bmp) или изображения формата
PCX (.pcx) от ZSoft.
К тому же, для вывода на стандартный VGA адаптер, файл
изображения заставки должен иметь разрешение не более
320 на 200 пикселей.Чтобы можно было использовать изображения большего размера,
вплоть до максимального 1024 на 768, активируйте поддержку
VESA. Активация может быть осуществлена либо
подключением модуля VESA во время загрузки
системы, либо сборкой специализированного ядра с добавленной
опцией VESA (смотрите ). Поддержка режима VESA
дает пользователям возможность отображать заставку, перекрывающую
всю видимую область экрана.Отображаемая во время загрузки заставка может
быть убрана нажатием любой клавиши на клавиатуре.С настройками по умолчанию заставка также становится
хранителем экрана в консольном окружении. После некоторого
бездействия экран сменится заставкой, яркость которой
будет периодически изменяться от её максимального значения
к минимальному и обратно. Подобное поведение заставки может
быть переопределено добавлением строки saver=
в /etc/rc.conf. В качестве значения опции
saver= можно выбрать одно из встроенных
имен хранителей экранов, а с полным перечнем можно ознакомиться
на странице справочника &man.splash.4;. Хранитель экрана,
используемый по умолчанию, называется warp.
Заметьте, что установка опции saver= в
/etc/rc.conf воздействует исключительно
на текстовые виртуальные консоли. Она не влияет на менеджеры
экранов X11.Несколько сообщений загрузчика, включая меню загрузки
и счетчик, отображаются во время загрузки, даже если экран-заставка
активирован.Файлы-примеры с изображениями для заставок могут быть
скачаны из галереи по адресу http://artwork.freebsdgr.org.
Установив порт sysutils/bsd-splash-changer, между
загрузками вы получите автоматическую смену случайно выбираемых
изображений заставок.Активация экранной заставкиФайл изображения для заставки (.bmp
или .pcx) следует разместить в корневой
файловой системе, например в каталоге /boot.Для работы заставки с разрешением, доступным при загрузке
(256 цветов и не более 320х200 точек), отредактируйте
/boot/loader.conf, добавив в него
следующие строки:splash_bmp_load="YES"
bitmap_load="YES"
bitmap_name="/boot/splash.bmp"Для получения больших разрешений видео режима (вплоть до
максимального 1024x768), внесите в
/boot/loader.conf следующие записи:vesa_load="YES"
splash_bmp_load="YES"
bitmap_load="YES"
bitmap_name="/boot/splash.bmp"Вышеприведённый пример подразумевает, что файл
/boot/splash.bmp
содержит изображение заставки. Если же требуется выводить файл
формата PCX, то используйте следующие строки
(в зависимости от необходимого разрешения может также
потребоваться строка vesa_load="YES"):splash_pcx_load="YES"
bitmap_load="YES"
bitmap_name="/boot/splash.pcx"Возможное имя файла не ограничено одним лишь словом
splash. Оно может выбираться произвольно, например:
splash_640x400.bmp
или blue_wave.pcx.
Важен лишь тип файла: он должен быть либо BMP,
либо PCX.Далее приведены еще две полезные опции
loader.conf:beastie_disable="YES"Эта опция отключит меню загрузчика, но приглашение с
обратным отсчетом останется. Даже при не отображаемом меню
во время отсчета возможен выбор номера варианта
загрузки.loader_logo="beastie"Эта установка заменит слова &os;,
которые отображаются справа от меню загрузчика, цветным
логотипом демона, который занимал это место в предыдущих
релизах &os;.За более детальной информацией обратитесь к следующим
страницам справочника: &man.splash.4;, &man.loader.conf.5; и
&man.vga.4;.Взаимодействие с ядром во время загрузкиядровзаимодействия во время загрузкиКак только ядро окажется загруженным при помощи загрузчика (обычный способ) или boot2 (минуя загрузчик), оно проверяет
флаги загрузки, если они есть, и действует соответствующим
образом.Флаги загрузки ядраядрофлаги загрузкиВот наиболее часто используемые флаги загрузки:во время инициализации ядра запрашивать устройство для
его монтирования в качестве корневой файловой системы.загрузка с компакт-диска.запустить UserConfig для конфигурации ядра во время
загрузкипосле загрузки перейти в однопользовательский режимво время запуска ядра выводить более подробную
информациюЕсть и другие флаги загрузки, обратитесь к странице
справочника по &man.boot.8; для выяснения подробной информации по
ним.TomRhodesТекст предоставил Хинты устройствdevice.hintsВо время начального запуска системы загрузчик &man.loader.8;
производит чтение файла &man.device.hints.5;. В этом файле
хранится необходимая для загрузки ядра информация, задаваемая в виде
переменных, которую иногда называют хинтами для устройств (device
hints). Эти хинты устройств используются
драйверами устройств для их конфигурации.Хинты для устройств могут быть также заданы в приглашении начального загрузчика Стадии 3. Переменные
могут быть добавлены при помощи команды set, удалены
посредством unset и просмотрены командой
show. В этот момент могут быть также переопределены
переменные, заданные в файле /boot/device.hints.
Хинты для устройств, введённые в начальном загрузчике, не сохраняются, и
при следующей перезагрузке будут утеряны.После загрузки системы для выдачи значений всех переменных можно
воспользоваться командой &man.kenv.1;.Синтаксически в файле /boot/device.hints в
каждой строке определяется по
одной переменной, в качестве метки начала комментария используется
стандартный символ #. Строки строятся следующим
образом:hint.driver.unit.keyword="value"Синтаксис для начального загрузчика Стадии 3 таков:set hint.driver.unit.keyword=valuedriver определяет имя драйвера устройства,
unit соответствует порядковому номеру модуля
устройства, а keyword является ключевым словом хинта.
В качестве ключевых слов могут применяться следующие опции:at: задаёт шину, к которой подключено
устройство.port: задаёт начальный адрес используемого
диапазона ввода/вывода (I/O).irq: задаёт используемый номер запроса на
прерывание.drq: задаёт номер канала DMA.maddr: задаёт физический адрес памяти,
занимаемый устройством.flags: устанавливает различные битовые флаги
для устройства.disabled: если установлено в значение
1, то устройство не используется.Драйверы устройств могут поддерживать (и даже требовать) другие
хинты, здесь не перечисленные, поэтому рекомендуется просматривать
справочные страницы по этим драйверам. Для получения дополнительной
информации обратитесь к страницам справки по
&man.device.hints.5;, &man.kenv.1;, &man.loader.conf.5; и
&man.loader.8;.Init: инициализация управления процессамиinitПосле того, как ядро завершит загрузку, оно передает управление
пользовательскому процессу &man.init.8;, который расположен
в файле /sbin/init или в файле, маршрут к которому
указан в переменной init_pathзагрузчика.Процесс автоматической перезагрузкиПроцесс автоматической перезагрузки проверяет целостность
имеющихся файловых систем. Если это не так, и утилита
&man.fsck.8; не может исправить положение, то
&man.init.8; переводит систему в однопользовательский режим для того,
чтобы системный администратор сам разобрался с возникающими
проблемами.Однопользовательский режимоднопользовательский режимконсольВ этот режим можно перейти во время процесса автоматической перезагрузки,
при ручной загрузке с параметром
или заданием переменной boot_single для программы
loader.Этот режим может быть также вызван запуском программы
&man.shutdown.8; без параметров перезагрузки
() или останова () из
многопользовательского
режима.Если режим доступа к системной консоли console
установлен в файле /etc/ttys в
insecure, то система выведет запрос на ввод пароля
пользователя root перед переходом в
однопользовательский режим.Незащищённая консоль в /etc/ttys# name getty type status comments
#
# Если консоль помечена как "insecure", то init будет запрашивать пароль
# пользователя root при переходе в однопользовательский режим.
console none unknown off insecureОбозначение консоли как insecure означает,
что вы считаете физический доступ к консоли незащищённым, и хотите,
чтобы только тот, кто знает пароль пользователя
root, мог воспользоваться однопользовательским
режимом, но это не значит, что вы хотите работать с консолью
небезопасным способом. Таким образом, если вы хотите добиться
защищённости, указывайте insecure, а
не secure.Многопользовательский режиммногопользовательский режимЕсли &man.init.8; определит, что ваши файловые системы
находятся в полном порядке, или после того, как пользователь выйдет
из однопользовательского
режима, система перейдет в многопользовательский режим, работа
в котором начинается с настройки ресурсов системы.Настройка ресурсов (rc)файлы rcСистема настройки ресурсов считывает настройки, применяемые по
умолчанию, из файла /etc/defaults/rc.conf, а
настройки, специфичные для конкретной системы, из
/etc/rc.conf, после чего осуществляется
монтирование файловых систем, перечисленных в файле
/etc/fstab, запуск сетевых служб, различных
системных даемонов и, наконец, выполнение скриптов запуска
дополнительно установленных пакетов.Страница справочника по &man.rc.8; является хорошим источником
информации о системе настройки ресурсов, так же, как и
самостоятельное изучение скриптов.Процесс остановки системыshutdownВо время контролируемого процесса остановки системы через утилиту
&man.shutdown.8; программа &man.init.8; будет
пытаться запустить скрипт /etc/rc.shutdown, после
чего будет посылать всем процессам сигнал TERM, а
затем и KILL тем процессам, которые ещё не завершили
свою работу.Для выключения машины с FreeBSD на аппаратных платформах и системах,
которые поддерживают управление электропитанием, просто воспользуйтесь
командой shutdown -p now для немедленного отключения
электропитания. Чтобы просто перезагрузить систему FreeBSD,
воспользуйтесь командой shutdown -r now. Для запуска
команды &man.shutdown.8; вам необходимо быть пользователем
root или членом группы
operator. Кроме того, можно также
воспользоваться командами &man.halt.8; и &man.reboot.8;, пожалуйста,
обратитесь к соответствующим страницам справки и справочной странице по
команде &man.shutdown.8; для получения дополнительной информации.Для управления электропитанием требуется наличие поддержки
&man.acpi.4; в ядре или в виде загруженного модуля.
diff --git a/ru_RU.KOI8-R/books/handbook/cutting-edge/chapter.xml b/ru_RU.KOI8-R/books/handbook/cutting-edge/chapter.xml
index 563a7601c0..81ac2cffbf 100644
--- a/ru_RU.KOI8-R/books/handbook/cutting-edge/chapter.xml
+++ b/ru_RU.KOI8-R/books/handbook/cutting-edge/chapter.xml
@@ -1,2366 +1,2309 @@
JimMockРеструктурирование, реорганизацию и частичное обновление
выполнил JordanHubbardОригинальный текст написали Poul-HenningKampJohnPolstraNikClaytonАндрейЗахватовПеревод на русский язык: Обновление системы и смена версииКраткий обзорМежду релизами над &os; ведется постоянная работа. Некоторые
отдают предпочтение официально выпущенным версиям, в то время как
остальные предпочитают использовать последние разработки. Тем не
менее, даже для официальных версий часто выходят обновления,
связанные с безопасностью и другими критическими исправлениями.
Независимо от используемой версии &os; предоставляет все необходимые
инструменты для поддержания системы в актуальном состоянии, а также
позволяет легко перейти на другую версию. Эта глава поможет
вам решить, хотите ли вы отслеживать систему в процессе работы над ней
или останетесь верным одному из выпущенных релизов. Также имеются
простейшие инструменты для поддержания вашей системы в актуальном
состоянии.После чтения этой главы вы будете знать:Какие программы можно использовать для обновления системы и
Коллекции Портов.Как поддерживать вашу систему в актуальном состоянии при
помощи freebsd-update,
CVSup, CVS
или CTM.Как узнать состояние установленной системы по отношению к
известной нетронутой копии.Разницу между двумя ветвями разработки: &os.stable; и
&os.current;.Как перестраивать и переустанавливать базовую систему полностью
при помощи make buildworld (и других).Перед чтением этой главы вы должны:Полностью настроить своё подключение к сети ().Знать, как устанавливать дополнительное программное обеспечение
других разработчиков ().В этой главе для получения и обновления исходных текстов &os;
используется команда cvsup. Для этого вам
нужно установить порт или пакет net/cvsup-without-gui. Начиная с версии
&os; 6.2-RELEASE для этих целей можно воспользоваться командой
&man.csup.1;, которая входит в состав системы.TomRhodesОригинальный текст написал ColinPercivalНа основе заметок, которые предоставил Обновление FreeBSDобновление и смена версииfreebsd-updateобновление и смена версииПрименение обновлений безопасности — важный момент в
сопровождении программного обеспечения, особенно такого как
операционная система. Для &os; этот процесс не был простым в
течение долгого времени. На исходный код нужно было накладывать
патчи, перестраивать код в двоичные файлы, а затем эти двоичные файлы
требовалось переустановить. Теперь это давно не так, и &os; включает программу с простым
названием freebsd-update. Эта программа
предоставляет две различные функции. Во-первых, она позволяет
применить к базовой системе &os; обновления безопасности и критические
исправления в двоичном виде, без необходимости сборки и установки.
Во-вторых, программа поддерживает обновление системы со сменой
старшего или младшего номера версии.Двоичные обновления доступны для всех архитектур и версий,
поддерживаемых группой безопасности; тем не менее, для работы
некоторых из возможностей, таких как смена версии операционной
системы &os;, требуется последняя версия &man.freebsd-update.8;
и по крайней мере &os; 6.3. Перед обновлением до новой версии
следует ознакомиться с объявлением о выпуске текущей версии, так
как там может содержаться важная информация, применимая к версии,
на которую намечен переход. С соответствующими объявлениями можно
ознакомиться, перейдя по следующей ссылке: .Если имеется задание crontab, запускающее
freebsd-update, то перед началом выполнения
следующих действий его обязательно нужно выключить.Конфигурационный файлНекоторые пользователи могут пожелать изменить
конфигурационный файл для лучшего контроля над процессом
обновления. Все параметры подробно задокументированы, но
для некоторых из них может понадобиться дополнительное
разъяснение:# Components of the base system which should be kept updated.
Components src world kernelДанный параметр определяет, какие части &os; будут обновлены.
По умолчанию обновляется исходный код (src), вся базовая система
(world) и ядро (kernel). Компоненты те же самые, что и во время
установки; в частности, добавление "world/games" позволяет
обновить игры. Использование "src/bin" позволяет обновить
исходный код в src/bin.Лучшим вариантом будет оставить всё как есть, поскольку
изменение этого перечня с целью добавления особых пунктов
потребует от пользователя указания подряд всех пунктов, которые
пользователь захочет обновить. Это может привести к негативным
последствиям из-за возможной рассинхронизации между исходными
текстами и двоичными файлами.# Paths which start with anything matching an entry in an IgnorePaths
# statement will be ignored.
IgnorePathsДобавьте сюда пути к каталогам (например, /bin или /sbin), которые вы хотели бы
оставить нетронутыми в процессе обновления. Этот параметр можно
использовать для предотвращения перезаписывания локальных
изменений программой freebsd-update.# Paths which start with anything matching an entry in an UpdateIfUnmodified
# statement will only be updated if the contents of the file have not been
# modified by the user (unless changes are merged; see below).
UpdateIfUnmodified /etc/ /var/ /root/ /.cshrc /.profileОбновлять конфигурационные файлы в указанных каталогах, только
если они не содержат изменений. При наличии каких-либо изменений
со стороны пользователя автоматическое обновление таких файлов
отменяется. Есть другой параметр
KeepModifiedMetadata, который предписывает
команде freebsd-update сохранять изменения во
время процесса слияния.# When upgrading to a new &os; release, files which match MergeChanges
# will have any local changes merged into the version from the new release.
MergeChanges /etc/ /var/named/etc/Список каталогов с конфигурационными файлами, для которых
freebsd-update попытается выполнить слияние.
Процесс слияния файла представляет собой набор изменений
в формате &man.diff.1;, похож на &man.mergemaster.8;, но с
меньшим количеством параметров: результат слияния принимается,
открывается редактор или freebsd-update
прекращает свою работу. В случае сомнений сделайте резервную
копию /etc и просто
согласитесь со всеми изменениями. Для получения подробной
информации по команде mergemaster смотрите
.# Directory in which to store downloaded updates and temporary
# files used by &os; Update.
# WorkDir /var/db/freebsd-updateЭтот каталог предназначен для размещения патчей и временных
файлов. В случае, когда пользователь выполняет обновление со сменой
версии, в этом месте должен иметь по крайней мере гигабайт дискового
пространства.# When upgrading between releases, should the list of Components be
# read strictly (StrictComponents yes) or merely as a list of components
# which *might* be installed of which &os; Update should figure out
# which actually are installed and upgrade those (StrictComponents no)?
# StrictComponents noЕсли выставлено значение yes, то
freebsd-update будет исходить из того, что
список Components является полным, и не будет
пытаться выполнить изменения за пределами этого списка.
В действительности freebsd-update попытается
обновить все файлы, которые принадлежат списку
Components.Обновления безопасностиОбновления безопасности хранятся на удалённой машине и могут
быть загружены и установлены с использованием следующей
команды:&prompt.root; freebsd-update fetch
&prompt.root; freebsd-update installЕсли были установлены обновления ядра, то после этого
нужно перезагрузить систему. Если все пошло хорошо, система
должна быть с установленными исправлениями, и
freebsd-update можно запускать в качестве ночного
задания &man.cron.8;. Для этого достаточно добавить следующую
запись в /etc/crontab:@daily root freebsd-update cronЭта запись означает, что freebsd-update будет
запускаться ежедневно. В данном случае, в соответствии с аргументом
freebsd-update ограничится
проверкой доступных обновлений. В случае наличия обновлений они
будут автоматически загружены и сохранены на локальном диске.
Пользователю root будет отправлено
соответствующее письмо, так что эти обновления можно будет
установить самостоятельно.На случай, если что-то пошло не так, в
freebsd-update предусмотрен механизм возврата
последнего набора изменений с использованием следующей команды:&prompt.root; freebsd-update rollbackЕсли после завершения всех действий было изменено ядро или
какой-либо из его модулей, система должна быть перезагружена.
Это позволит &os; загрузить новые двоичные файлы в память.Команда freebsd-update работает только
с ядром GENERIC. Если в
GENERIC присутствуют изменения или
используется собственная конфигурация ядра,
freebsd-update завершится неудачно.Обновления со сменой старшей и младшей версийЭтот процесс удаляет старые объектные файлы и библиотеки, что
может нарушить работу большинства сторонних приложений. Все
установленные порты рекомендуется либо удалить и переустановить
заново, либо обновить с использованием программы ports-mgmt/portupgrade. Большинство
пользователей предпочтут выполнить тестовое построение, запустив для
этого следующую команду:&prompt.root; portupgrade -afЭто позволит убедиться в том, что всё будет переустановлено
правильно. Обратите внимание, что если переменной окружения
BATCH присвоить значение yes,
то на все вопросы в течение этого процесса будет возвращаться
ответ yes, что позволит исключить необходимость
ручного вмешательства в процесс построения.Обновления со сменой старшей и младшей версий можно выполнить,
указав значение версии, на которую будет произведен переход, в
качестве аргумента команды freebsd-update.
Так, например, можно выполнить обновление до версии
&os; 6.3:&prompt.root; freebsd-update -r 6.3-RELEASE upgradeПосле своего запуска freebsd-update
анализирует содержимое конфигурационного файла и собирает
необходимую для проведения обновления информацию о текущей
установленной системе. На экран будет выдан перечень компонентов,
которые удалось и не удалось обнаружить установленными.
Например:Looking up update.FreeBSD.org mirrors... 1 mirrors found.
Fetching metadata signature for 6.3-BETA1 from update1.FreeBSD.org... done.
Fetching metadata index... done.
Inspecting system... done.
The following components of FreeBSD seem to be installed:
kernel/smp src/base src/bin src/contrib src/crypto src/etc src/games
src/gnu src/include src/krb5 src/lib src/libexec src/release src/rescue
src/sbin src/secure src/share src/sys src/tools src/ubin src/usbin
world/base world/info world/lib32 world/manpages
The following components of FreeBSD do not seem to be installed:
kernel/generic world/catpages world/dict world/doc world/games
world/proflibs
Does this look reasonable (y/n)? yСледующим шагом freebsd-update попытается
загрузить по сети файлы, необходимые для выполнения обновления.
В некоторых случаях может потребоваться ответить на вопросы
относительно того, что и как устанавливать.После того, как все изменения были загружены, они будут
применены. Этот процесс может занять определённое время, в
зависимости от производительности и текущей загруженности
компьютера. Затем будет выполнено слияние конфигурационных файлов
— эта часть процесса требует от пользователя определённого
вмешательства, так как для файла можно выполнить слияние
автоматически, а можно открыть текстовый редактор для слияния
вручную. Результат успешного слияния будет показан на экране.
Неудачное или пропущенное слияние вызовет преждевременное завершение
программы. Можно подготовить резервную копию каталога /etc для таких важных файлов как
master.passwd и group и
выполнить их слияние вручную позднее.На данном этапе система еще не модифицирована, и все изменения
и слияния происходят в отдельном каталоге. Теперь, когда все
изменения успешно применены, все конфигурационные файлы слиты и
кажется, что процесс должен пройти плавно, пользователь должен
установить изменения.После завершения этого процесса, изменения могут быть
установлены на диск с помощью следующей команды.&prompt.root; freebsd-update installВ первую очередь изменения будут применены к ядру и его модулям.
После этого компьютер должен быть перезагружен. Следующая команда
выполнит перезагрузку компьютера, после чего будет загружено новое
ядро:&prompt.root; shutdown -r nowПосле перезагрузки нужно повторно запустить команду
freebsd-update. Команда прочитает, на каком
этапе она находится, и перейдёт к удалению старых объектных файлов
и совместно используемых библиотек. Чтобы перейти к этому этапу,
выполните следующую команду:&prompt.root; freebsd-update installКоличество этапов установки обновлений может быть два вместо
трёх и зависит от того, были ли изменены номера версий каких-либо
совместно используемых библиотек.Теперь понадобится пересобрать и переустановить всё стороннее
программное обеспечение. Это необходимая операция, так как
установленное программное обеспечение может зависеть от библиотек,
которые были удалены в процессе смены версии операционной системы.
Для автоматизации этого процесса можно воспользоваться командой
ports-mgmt/portupgrade.
Начать можно со следующих команд:&prompt.root; portupgrade -f ruby
&prompt.root; rm /var/db/pkg/pkgdb.db
&prompt.root; portupgrade -f ruby18-bdb
&prompt.root; rm /var/db/pkg/pkgdb.db /usr/ports/INDEX-*.db
&prompt.root; portupgrade -afПосле этого завершите процесс обновления последним запуском
freebsd-update. Выполните следующую команду,
чтобы убедиться, что ничего не забыто в процессе обновления:&prompt.root; freebsd-update installПерезагрузите компьютер с новой версией &os;. На этом процесс
завершён.Сравнение состояния системыУтилита freebsd-update может быть
использована для проверки состояния установленной версии &os;
относительно известной хорошей копии. Оценивается текущая версия
системных утилит, библиотек и конфигурационных файлов. Для того,
чтобы начать сравнение, выполните следующую команду:&prompt.root; freebsd-update IDS >> outfile.idsНе смотря на то, что команда называется
IDS, это ни в коей мере не должно являться
заменой системе обнаружения вторжений, такой как security/snort. Поскольку
freebsd-update сохраняет свои данные на
диске, возможность подмены становится очевидной. И хотя эта
возможность может быть уменьшена при использовании настройки
kern.securelevel, а также используя для
записи данных freebsd-update файловую
систему, которая в остальное время смонтирована только на
чтение, лучшим решением будет сравнить систему относительно
эталона на физически защищенном носителе, таком как
DVD или внешний USB диск
с включённой защитой от записи.Теперь запустится проверка системы, в результате которой будет
выведен список файлов с их контрольными суммами в &man.sha256.1; с
известным значением для файла из релиза и значением для текущего
в системе. Результат выводится слишком быстро для наглядного
сравнения и вскоре заполняет консольный буфер. По этой причине в
данном примере вывод перенаправлен в файл
outfile.ids.Эти строки также очень длинные, но зато такой формат вывода
удобен для разбора. Так, для получения списка всех отличающихся
от релиза файлов достаточно выполнить такую команду:&prompt.root; cat outfile.ids | awk '{ print $1 }' | more
/etc/master.passwd
/etc/motd
/etc/passwd
/etc/pf.confВывод специально обрезан, на самом деле файлов намного больше.
Некоторые из них изменены в ходе нормальной работы: так, файл
/etc/passwd был изменён после заведения
пользователей в системе. В некоторых случаях могут быть и другие
файлы, такие как модули ядра, которые могли измениться вследствие
обновления через freebsd-update. Для
исключения из проверки конкретных файлов и каталогов укажите их
в качестве значения параметра IDSIgnorePaths
в /etc/freebsd-update.conf.Эта система может использоваться как часть более сложной
процедуры обновления, в отличие от описанного выше способа.TomRhodesПредоставил ColinPercivalНа основе заметок, которые предоставил Portsnap: средство обновления Коллекции Портовобновление и смена версииPortsnapобновление и смена версииДля обновления Коллекции Портов в базовую поставку &os;
включена утилита &man.portsnap.8;. Во время её выполнения
устанавливается соединение с удалённым сервером, проверяется
правильность ключа и загружается новая копия Коллекции Портов.
Ключ используется для проверки целостности загруженных файлов
для исключения возможности подмены на этапе передачи файлов.
Для получения последней версии файлов Коллекции Портов выполните
следующую команду:&prompt.root; portsnap fetch
Looking up portsnap.FreeBSD.org mirrors... 3 mirrors found.
Fetching snapshot tag from portsnap1.FreeBSD.org... done.
Fetching snapshot metadata... done.
Updating from Wed Aug 6 18:00:22 EDT 2008 to Sat Aug 30 20:24:11 EDT 2008.
Fetching 3 metadata patches.. done.
Applying metadata patches... done.
Fetching 3 metadata files... done.
Fetching 90 patches.....10....20....30....40....50....60....70....80....90. done.
Applying patches... done.
Fetching 133 new ports or files... done.В данном примере показано, что &man.portsnap.8; обнаружила
и верифицировала несколько патчей относительно текущего содержимого
портов. Здесь также видно, что утилита уже запускалась ранее,
иначе при первом запуске была бы загружена вся коллекция.После того как &man.portsnap.8; успешно завершила операцию
fetch, Коллекция Портов и сопутствующие патчи
находятся на локальной системе и прошли проверку целостности.
Обновлённые файлы можно установить командой:&prompt.root; portsnap extract
/usr/ports/.cvsignore
/usr/ports/CHANGES
/usr/ports/COPYRIGHT
/usr/ports/GIDs
/usr/ports/KNOBS
/usr/ports/LEGAL
/usr/ports/MOVED
/usr/ports/Makefile
/usr/ports/Mk/bsd.apache.mk
/usr/ports/Mk/bsd.autotools.mk
/usr/ports/Mk/bsd.cmake.mk
...На этом процесс завершён, и теперь приложения можно
установить или обновить с использованием Коллекции Портов.Для последовательного запуска обоих процессов выполните
следующую команду:&prompt.root; portsnap fetch updateИспользование ветви разработки-CURRENT-STABLEВо FreeBSD имеется две ветки разработки: &os.current; и &os.stable;.
Этот раздел описывает каждую из них и объясняет, как синхронизировать
вашу систему с любой из веток. Сначала будет обсуждаться ветка
&os.current;, затем &os.stable;.Как следовать текущим разработкам во &os;Пока вы читаете этот текст, помните, что &os.current; является
передовым краем работ над &os;. Предполагается, что
пользователи &os.current; технически более грамотны и могут решать
проблемы с системой самостоятельно. Если вы являетесь во &os;
новичком, вам лучше сначала дважды подумать, прежде чем
её устанавливать.Что такое &os.current;?snapshot&os.current; является последними рабочими версиями исходных
текстов &os;. Сюда включаются неоконченные работы, экспериментальные
изменения и промежуточные механизмы, которые могут присутствовать, а
могут и отсутствовать в следующем официальном релизе программного
обеспечения. Хотя многие из разработчиков &os; выполняют компиляцию
из исходных текстов &os.current; ежедневно, случаются периоды, когда
исходные тексты заведомо не могут быть откомпилированы. Такие
проблемы обычно решаются так быстро, как это возможно, но всё-таки
момент, когда вы загрузили исходные тексты &os.current;, может
повлиять на то, содержат они мину замедленного действия или очень
нужную функциональность!Кому нужна &os.current;?&os.current; предназначается трём основным заинтересованным
группам:Участники проекта &os;, активно работающие над
некоторой частью дерева исходных текстов и для кого работа в
current является абсолютной
необходимостью.Участники проект &os;, которые являются
активными тестерами. Они тратят свое время на
исправление проблем для того, чтобы &os.current; оставалась,
насколько это возможно, нормально работающей системой. Есть
также люди, которые вносят важные предложения по изменениям и
общему направлению развития &os; и присылают свои патчи,
реализующие эти изменения.Те, кто просто хотят быть в курсе всех изменений или
используют текущие исходные тексты для ознакомительных целей (к
примеру, для чтения, но не для
использования). Такие люди также иногда высказывают замечания
или предоставляют код.Чем &os.current; не является?Быстрым способом получить предварительную версию, в
случае, если вы услышали, что здесь появилась некая крутая
возможность, и вы хотите быть первым в вашем микрорайоне, у
кого она есть. Здесь быть первым из тех, кто имеет это
программное обеспечение означает также быть первым из тех, кто
столкнулся с ошибками в нём.Быстрым способом получения исправлений. Любая версия
&os.current; является в равной мере как источником исправлений
существующих ошибок, так и источником появления новых.Официально поддерживаемой каким бы то ни было
способом. Мы прилагаем все усилия, чтобы помочь тем, кто
изначально принадлежит одной из трех признанных
групп пользователей &os.current;, но у нас просто нет
времени на техническую поддержку. Это не потому, что
мы гадкие и злые люди, которые ни за что не будут помогать другим
(если бы это было так, мы бы не создали &os;). Мы просто не в
силах отвечать на сотни сообщений в день и
работать над FreeBSD! Если бы стоял выбор между тем, отвечать ли
на множество вопросов об экспериментально коде или продолжать
работу над совершенствованием &os;, большинство разработчиков
проголосовало бы за последнее.Использование &os.current;
-
- -CURRENT
-
- использование
-
-
- Подпишитесь на списки рассылки &a.current.name; и
+ Подпишитесь на списки рассылки &a.current.name;-CURRENTиспользование и
&a.svn-src-head.name;. Это не просто хорошая идея, это
необходимость. Если вы не являетесь
участником списка рассылки &a.current.name;,
то вы не увидите замечаний,
высказываемых о текущем состоянии системы и в итоге можете
столкнуться со множеством проблем, которые уже были найдены и
решены другими. Ещё хуже, если вы пропустите важные сообщения,
касающиеся жизнеспособности вашей системы.Список рассылки &a.svn-src-head.name; позволит вам для каждого
изменения увидеть соответствующую запись в журнале коммитов,
а они порой содержат относящуюся к делу
информацию о возможных побочных эффектах.Чтобы подписаться на эти и другие доступные списки
рассылки, перейдите по ссылке &a.mailman.lists.link; и щёлкните
на списке, к которому вы хотите подключиться. Инструкции по
дальнейшим действиям размещены там же. Если вы заинтересованы
в отслеживании изменений всего дерева исходных текстов, то мы
рекомендуем вам подписаться на &a.svn-src-all.name;.Загрузите исходные тексты с зеркального сайта &os;. Вы можете
сделать это одним из следующих двух способов:
-
- cvsup
-
-
-
- cron
-
-
-
- -CURRENT
-
- Синхронизация при помощи CVSup
-
-
-
- При помощи программы cvsup
+ При помощи программы cvsupcvsup
с sup-файлом
standard-supfile, который можно найти в
каталоге /usr/share/examples/cvsup. Это
наиболее
рекомендуемый метод, так как он позволяет вам загрузить набор
исходных текстов один раз полностью, а затем загружать только
произошедшие изменения. Многие запускают
cvsup при помощи программы
- cron и получают самые свежие исходные
+ croncron и получают самые свежие исходные
тексты автоматически. Измените примерный файл
supfile выше и отконфигурируйте cvsup для вашего окружения.
+ linkend="cvsup">cvsup-CURRENTСинхронизация при помощи CVSup для вашего окружения.Примерный файл standard-supfile
предназначен для отслеживания специальной ветки
безопасности &os;, а не &os.current;. Вам нужно
открыть этот файл на редактирование и заменить в нём
строку:*default release=cvs tag=RELENG_X_Yна следующую:*default release=cvs tag=.Для получения подробной информации по использованию
тегов обратитесь к разделу Руководства Теги CVS.-CURRENTСинхронизация при помощи CTMПри помощи CTM. Если у вас очень
плохое подключение (дорогое или предоставляющее доступ только
к электронной почте), то CTM
можно рассматривать как вариант. Однако в нем много
"подводных камней", и его использование может
привести к появлению неправильных файлов. Это привело к
тому, что этот способ используется редко, что, в свою
очередь, увеличивает шанс появления периодов его
неработы. Мы рекомендуем использовать CVSup всем, чья скорость
подключения равна 9600 bps и выше.Если вам нужны исходные тексты для компиляции и запуска, а
не просто для ознакомления, то загружайте исходные тексты
ветки &os.current; полностью, а не отдельные
ее части. Причиной является то, что многие части исходных
текстов зависят от других обновлений где-то еще, и попытка
компиляции лишь некоторой части программ в этом случае
гарантированно вызовет проблемы.
-
- -CURRENT
-
- компиляция
-
-
- Перед тем, как компилировать &os.current;, внимательно
+ Перед тем, как компилировать &os.current;-CURRENTкомпиляция, внимательно
прочтите файл Makefile в каталоге
/usr/src. В процессе обновления вы
по крайней мере раз должны пройти через установку нового ядра и перестроение всех
компонентов системы. Чтение списка рассылки &a.current.name; и
/usr/src/UPDATING позволит вам быть в курсе
всех процедур, которые иногда бывают необходимы в процессе
работы над следующим релизом.Будьте активным подписчиком! Если вы работаете с
&os.current;, мы хотим знать, что вы думаете о ней, особенно
если у вас есть соображения по ее улучшению или исправлению
ошибок. Пожелания, к которым прилагается код, всегда
принимаются с большим энтузиазмом!Работа с веткой stable во &os;Что такое &os.stable;?-STABLE&os.stable; является нашей веткой разработки, из которой делаются
основные релизы. Изменения в этой ветке происходят с разной
скоростью, и при этом предполагается, что сначала они были выполнены
для &os.current; в целях тестирования. Однако эта ветка
остаётся веткой для разработки, а это значит,
что в любой момент времени исходные тексты &os.stable; могут
оказаться неприменимы для некоторой задачи. Это просто ещё одна
ветка при разработке, а не ресурс для конечных пользователей.Кому нужна &os.stable;?Если вы заинтересованы в отслеживании процесса разработки FreeBSD
или хотите принять в нём участие, особенно в той мере, насколько это
касается выпуска следующего релиза FreeBSD с точкой, то
вам необходимо отслеживать &os.stable;.Хотя правда то, что исправления, касающиеся безопасности, также
делаются и в ветке &os.stable;, вам не нужно
для этого отслеживать &os.stable;. Каждый бюллетень по безопасности
FreeBSD описывает, как решить проблему для тех релизов, которых он
касается
Это не совсем так. Мы не можем поддерживать старые релизы
FreeBSD бесконечно долго, хотя мы поддерживаем их многие годы.
Полное описание текущей политики безопасности относительно
старых релизов FreeBSD можно найти по адресу
http://www.FreeBSD.org/ru/security/.
, а отслеживание ветки разработки в полном объёме только ради
исправлений пробелов в безопасности приводит к появлению большого
количества дополнительных ненужных изменений.Хотя мы прилагаем все усилия, чтобы ветка &os.stable; всегда
компилировалась и работала, этого нельзя гарантировать. Кроме того,
несмотря на то, что перед включением в &os.stable;, код
разрабатывается в &os.current;, гораздо большее количество людей
работают с &os.stable;, чем с &os.current;. Поэтому неудивительно,
что в &os.stable; иногда
обнаруживаются ошибки и всплывают непредвиденные ситуации, которые не
проявляли себя в &os.current;.По этим причинам мы не рекомендуем слепо
отслеживать &os.stable;, и, что особенно важно, вы не должны
обновлять какие-либо сервера, находящиеся в активной эксплуатации, до
&os.stable; без предварительного тщательного тестирования кода в
вашей среде разработки.Если у вас нет возможности сделать это, то мы рекомендуем
работать с самой последним релизом &os; и использовать механизм
обновления бинарных файлов для перехода от релиза к релизу.Использование &os.stable;
-
- -STABLE
- использование
-
- Подпишитесь на список рассылки &a.stable.name;. Это позволит
+ Подпишитесь на список рассылки &a.stable.name;-STABLEиспользование. Это позволит
вам узнавать о зависимостях процесса компиляции,
которые могут появиться в ветке &os.stable; или
любых других проблемах, требующих особого внимания. В этом
списке рассылки разработчики также делают объявления о
спорных исправлениях или добавлениях,
давая пользователям возможность высказать свое мнение о
возможных тонких моментах.Присоединяйтесь к соответствующему списку рассылки
SVN для той ветви, которую вы
используете. Например, если вы используете ветвь 7-STABLE, то
присоединяйтесь к списку &a.svn-src-stable-7.name;. Это
позволит вам просматривать записи в журнале коммитов для
каждого изменения, а они порой содержат относящуюся к делу
информацию о возможных побочных эффектах.Чтобы подключиться к этим и другим доступным спискам
рассылки, перейдите по ссылке &a.mailman.lists.link; и щёлкните
на списке, к которому вы хотите подключиться. Инструкции по
дальнейшим действиям размещены там же. Если вы заинтересованы
в отслеживании изменений всего дерева исходных текстов, то мы
рекомендуем вам подписаться на &a.svn-src-all.name;.Если вы собираетесь установить новую систему, и хотите,
чтобы она соответствовала ежемесячным стандартным сборкам
ветви &os.stable;, обратитесь к
странице снэпшотов
. Либо вы
можете установить самый последний релиз &os.stable;, загрузив его
с зеркалирующих сайтов, а затем
следовать инструкциям ниже по обновлению исходных текстов вашей
системы до самой последней версии &os.stable;.Если вы уже работаете с предыдущим релизом &os; и хотите
обновить его из исходных текстов, то вы можете легко это
сделать с зеркального сайта &os;.
Это можно сделать одним из двух способов:
-
- cvsup
-
-
-
- cron
-
-
-
- -STABLE
-
-
- Синхронизация при помощи CVSup
-
-
-
- При помощи программы cvsup
+ При помощи программы cvsupcvsup
с sup-файлом
stable-supfile из каталога
/usr/share/examples/cvsup.
Это наиболее рекомендуемый
метод, так как он позволяет вам загрузить набор исходных
текстов один раз полностью, а затем загружать только
произошедшие изменения. Многие запускают
cvsup при помощи программы
- cron и получают самые свежие исходные
+ croncron и получают самые свежие исходные
тексты автоматически. Измените примерный файл
supfile выше и отконфигурируйте cvsup для вашего окружения.
+ linkend="cvsup">cvsup-STABLEСинхронизация при помощи CVSup для вашего окружения.
-
- -STABLE
- синхронизация при помощи CTM
-
-
При помощи CTM. Если у вас нет
+ linkend="ctm">CTM-STABLEсинхронизация при помощи CTM. Если у вас нет
быстрого и недорогого подключения к Интернет, то это как раз
тот метод, которым вы должны воспользоваться.Итак, если вам нужен быстрый доступ к
исходным текстам и нагрузка на каналы связи для вас не
проблема, то используйте cvsup
или ftp. В противном случае воспользуйтесь
CTM.
-
- -STABLE
- компиляция
-
-
- Перед тем, как компилировать &os.stable;, внимательно
+ Перед тем, как компилировать &os.stable;-STABLEкомпиляция, внимательно
прочтите файл Makefile в каталоге
/usr/src. В процессе обновления вы
по крайней мере раз должны пройти через установку нового ядра и перестроение всех
компонентов системы. Чтение списка рассылки &a.stable.name; и
/usr/src/UPDATING
позволит вам быть в курсе всех процедур,
которые иногда бывают необходимы при переходе к следующему
релизу.Синхронизация ваших исходных текстовИмеются различные способы использования Интернет (или почтового)
подключения для того, чтобы иметь самые последние версии исходных
текстов любого проекта &os;, в зависимости от
того, чем вы интересуетесь. Основной сервис, который мы предлагаем,
это Анонимный CVS, CVSup и CTM.Хотя имеется возможностью обновлять только часть дерева исходных
текстов, процедурой, которую мы настоятельно советуем, является обновление всего
дерева и перекомпиляция пользовательских программ (то есть тех,
которые работают в пространстве имен пользователя, например те, что
находятся в каталогах /bin и
/sbin) и ядра. Обновление только части дерева
исходных текстов, только текстов ядра или только текстов
пользовательских программ часто приводит к возникновению проблем. Эти
проблемы могут варьироваться от ошибок компиляции до аварийных
остановов системы или порчи данных.CVSанонимныйАнонимный CVS и
CVSup используют модель
pull обновления исходных текстов. В случае
CVSup пользователь (или скрипт программы
cron) вызывают cvsup, а она
работает с каким-либо сервером cvsupd, чтобы
выполнить обновление ваших
файлов. Обновления, которые вы получаете, актуальны с точностью до
минуты, и вы получаете их тогда и только тогда, когда сами захотите.
Вы можете с легкостью ограничить обновления конкретными файлами
или каталогами, которые представляют для вас интерес. Обновления
создаются на лету сервером согласно тому, что у вас есть и что вы
хотите иметь. Анонимный CVS гораздо проще,
чем CVSup в том смысле, что он представляет
собой всего лишь расширение
CVS, позволяющее загрузить изменения
непосредственно с удаленного хранилища CVS.
CVSup может делать это гораздо более
эффективно, однако анонимным CVS легче
пользоваться.CTMCTM, с другой стороны, не сравнивает
последовательно исходные тексты, имеющиеся у вас, с теми, что
находятся в главном архиве и вообще ни коим образом не касается наших
серверов. Вместо этого несколько раз в день на главной машине CTM
запускается скрипт, находящий изменения в файлах с момента
своего предыдущего запуска; все замеченные изменения сжимаются,
помечаются последовательным номером и кодируются для передачи по
электронной почте (в форме печатаемых символов ASCII).
После получения эти дельта-файлы CTM могут быть
переданы утилите &man.ctm.rmail.1;, которая осуществит автоматическое
декодирование, проверку и применение изменений к пользовательской
копии исходных текстов. Этот процесс гораздо более эффективен, чем
CVSup, и требует меньше ресурсов нашего
сервера, так как он сделан по модели push, а не
pull.Несомненно, есть и минусы. Если вы случайно уничтожили
часть вашего архива, то CVSup обнаружит
и загрузит поврежденную часть. CTM этого
делать не будет, и если вы уничтожили какую-то часть вашего дерева
исходных текстов (и у вас нет архивной копии), то вам нужно будет
начать с самого начала (с последнего базового
дельта-файла), перестроив всё с помощью
CTM, или, используя анонимный
CVS, просто удалить повреждённую часть и
пересинхронизироваться.Пересборка worldПересборка worldПосле того, как вы синхронизировали ваше локальное дерево
исходных текстов с некоторой версией &os;
(&os.stable;, &os.current; и так далее),
то можете использовать эти исходные тексты для перестроения
системы.Создайте резервную копиюНевозможно переоценить важность создания резервной
копии вашей системы до того, как вы будете
это делать. Хотя перестроение системы (пока вы следуете этим
инструкциям) является простой задачей, вы всегда можете допустить
ошибку, или ошибка может оказаться в исходных текстах, что может
привести к тому, что система перестанет загружаться.Обязательно сделайте резервную копию. И держите под рукой
аварийную (fixit) дискету или загрузочный компакт диск. Может быть,
вам никогда не приходилось ими
пользоваться, но, постучав по дереву, всегда лучше подготовиться, чем
потом сожалеть.Подпишитесь на соответствующий список рассылкисписок рассылкиВетки &os.stable; и &os.current; кода по природе своей являются
изменяющимися. В разработке &os; участвуют
люди, и время от времени случаются ошибки.Иногда эти ошибки достаточно безобидны и приводят к выводу
нового диагностического сообщения. Бывает, что изменение оказывается
катастрофическим, и система не может загрузиться или разрушаются
файловые системы (или что-нибудь ещё хуже).Если возникают подобные проблемы, в соответствующем списке
рассылки публикуется сообщение heads up, в котором
описывается природа проблемы и затрагиваемые системы. Когда проблема
решается, публикуется сообщение all clear.Если вы пытаетесь отслеживать &os.stable; или &os.current; и не
читаете &a.stable; или &a.current; соответственно, то
вы напрашиваетесь на неприятности.Не используйте make worldМножество старой документации рекомендует использование
make world. При этом пропускаются многие
важные шаги, и использование этой команды возможно лишь в том
случае, если вы точно знаете, что делаете. Почти во всех
обстоятельствах make world это неправильный
способ, вместо него необходимо использовать описанную здесь
процедуру.Канонический способ обновления вашей системыДля обновления вашей системы вы должны прочесть
/usr/src/UPDATING для выяснения шагов, которые
нужно предпринять перед построением системы из вашей версии исходных
текстов, а затем выполнить следующую последовательность
действий:&prompt.root; cd /usr/src
&prompt.root; make buildworld
&prompt.root; make buildkernel
&prompt.root; make installkernel
&prompt.root; shutdown -r nowЕсть несколько редких случаев, когда перед выполнением
buildworld необходимо дополнительно
запустить mergemaster -p. Они описаны в файле
UPDATING. В общем случае вы можете без ущерба
пропустить этот шаг, если не выполняете обновление с одной большой
версии &os; на другую.После успешного выполнения installkernel
вам необходимо загрузить систему в однопользовательском режиме (то
есть посредством команды boot -s, заданной в
приглашении загрузчика). После этого выполните:&prompt.root; mount -a -t ufs
&prompt.root; mergemaster -p
&prompt.root; cd /usr/src
&prompt.root; make installworld
&prompt.root; mergemaster
&prompt.root; rebootПрочтите более полное описаниеОписанная выше последовательность является только краткой
выжимкой для того, чтобы помочь вам начать. Вы должны всё же
прочесть последующие разделы для полного понимания каждого шага,
особенно если собираетесь использовать собственную конфигурацию
ядра.Прочтите /usr/src/UPDATINGПеред тем, как делать что-либо, прочтите
/usr/src/UPDATING (или соответствующий файл
в вашей копии исходных текстов). В этом файле
содержится важная информация о проблемах, с которыми вы можете
столкнуться, или указан порядок, в котором вы должны запускать
определенные команды. Если в файле UPDATING
написано нечто, противоречащее тому, что вы здесь читаете, то
нужно следовать указаниям в UPDATING.Чтение UPDATING не заменит подписки на
соответствующий список рассылки, как это и описано выше. Эти два
условия являются дополняющими, а не взаимоисключающими друг
друга.Проверьте содержимое /etc/make.confmake.confПросмотрите файлы /usr/share/examples/etc/make.conf
и /etc/make.conf. Первый содержит некоторые
предопределенные по умолчанию значения – большинство из них
закомментировано. Чтобы воспользоваться ими при перестроении системы
из исходных текстов, добавьте их в файл
/etc/make.conf. Имейте в виду, что все,
добавляемое вами в /etc/make.conf, используется
также каждый раз при запуске команды make, так что
полезно задать здесь значения, подходящие вашей системе.Вероятно стоит скопировать строки
CFLAGS и NO_PROFILE,
расположенные в
/usr/share/examples/etc/make.conf, в файл
/etc/make.conf и раскомментировать их.Посмотрите на другие определения (COPTFLAGS,
NOPORTDOCS и так далее) и решите, нужны ли они
вам.Обновите файлы в каталоге /etcКаталог /etc содержит значительную часть
информации о конфигурации вашей системы, а также скрипты, работающие
в начале работы системы. Некоторые из этих скриптов меняются от
версии к версии &os;.Некоторые конфигурационные файлы также используются в ежедневной
работе системы. В частности, файл
/etc/group.Случалось, что установочная часть make installworld
ожидала существования определённых имен пользователей или групп. При
обновлении существует вероятность, что эти пользователи или группы не
существуют. Это вызывает проблемы при обновлении. В некоторых
случаях make buildworld проверяет наличие этих
пользователей или групп.Примером этого является добавление пользователя
smmsp. Пользователи столкнулись с прерыванием
процесса установки, когда &man.mtree.8; пыталась
создать /var/spool/clientmqueue.Выходом является запуск утилиты &man.mergemaster.8; в
режиме, предваряющем построение системы, задаваемым опцией
. Она будет сравнивать только те файлы, которые
необходимы для успешного выполнения целей
buildworld или
installworld. Если ваша старая версия
утилиты mergemaster не поддерживает опцию
, воспользуйтесь новой версией из дерева исходных
текстов при первом запуске:&prompt.root; cd /usr/src/usr.sbin/mergemaster
&prompt.root; ./mergemaster.sh -pЕсли вы параноик, можете поискать файлы, владельцем которых
является та группа, которую вы переименовываете или удаляете:&prompt.root; find / -group GID -printвыдаст список всех файлов, владельцем которых является группа
GID (задаваемая именем или
численным значением ID).Перейдите в однопользовательский режимоднопользовательский режимВам может понадобиться откомпилировать систему в
однопользовательском режиме. Кроме обычного выигрыша в
скорости процесса, переустановка системы затрагивает много важных
системных файлов, все стандартные выполнимые файлы системы,
библиотеки, include-файлы и так далее. Изменение их на работающей
системе (в частности, в которой активно работают пользователи) может
привести к неприятностям.многопользовательский режимДругим способом является компиляция системы в многопользовательском
режиме с последующим переходом в однопользовательский режим для
выполнения установки. Если вы хотите поступить именно так, просто
следуйте инструкциям до момента окончания построения. Вы можете
отложить переход в однопользовательский режим до завершения целей
installkernel или
installworld.Как администратор, вы можете выполнить:&prompt.root; shutdown nowна работающей системе, что переведет ее в однопользовательский
режим.Либо вы можете выполнить перезагрузку и в приглашении загрузчика
выбрать пункт single user. После этого система загрузится в
однопользовательском режиме. В приглашении командного процессора вы
должны запустить:&prompt.root; fsck -p
&prompt.root; mount -u /
&prompt.root; mount -a -t ufs
&prompt.root; swapon -aЭти команды выполняют проверку файловых систем, повторно монтируют
/ в режиме чтения/записи, монтируют все
остальные файловые системы UFS, перечисленные в файле
/etc/fstab и включат подкачку.Если часы в вашей CMOS настроены на местное время, а не на GMT
(это имеет место, если команда &man.date.1; выдаёт
неправильные время и зону), то вам может понадобиться запустить
следующую команду:&prompt.root; adjkerntz -iЭто обеспечит корректную настройку местного часового пояса
— без этого впоследствии вы можете столкнуться с некоторыми
проблемами.Удалите /usr/objПри перестроении частей системы они помещаются в каталоги,
которые (по умолчанию) находятся в /usr/obj.
Структура повторяет структуру /usr/src.Вы можете ускорить выполнение процесса make buildworld
и, возможно, избавить себя от некоторой головной боли, связанной с
зависимостями, удалив этот каталог.На некоторых файлах из /usr/obj могут быть
установлены специальные флаги (обратитесь к &man.chflags.1; за
дополнительной информацией), которые сначала должны быть
сняты.
&prompt.root; cd /usr/obj
&prompt.root; chflags -R noschg *
&prompt.root; rm -rf *Перекомпилируйте исходные тексты базовой системыСохраните выводНеплохо сохранить вывод, получаемый при работе программы
&man.make.1;, в файл. Если что-то вдруг пойдет не так, вы будете
иметь копию сообщения об ошибке и полную картину того, где она
произошла. Хотя это может и не помочь в определении причин
происходящего, это может помочь другим, если вы опишите вашу
проблему в одном из списков рассылки &os;.Проще всего это сделать при помощи команды &man.script.1; с
параметром, в котором указано имя файла, в который нужно сохранить
вывод. Вы должны сделать это непосредственно перед тем, как
перестроить систему, а по окончании процесса набрать
exit.
&prompt.root; script /var/tmp/mw.out
Script started, output file is /var/tmp/mw.out
&prompt.root; make world… compile, compile, compile …
&prompt.root; exit
Script done, …
Если вы делаете это, не сохраняйте
вывод в /tmp. Этот каталог может быть
очищен при следующей перезагрузке. Лучше сохранить его в
/var/tmp (как в предыдущем примере) или в
домашнем каталоге пользователя root.Компиляция базовых компонентов системыВы должны находиться в каталоге
/usr/src:&prompt.root; cd /usr/src(если, конечно, ваш исходный код не находится в другом месте, в
случае чего вам нужно перейти в соответствующий каталог).makeДля полного перестроения системы используется
команда &man.make.1;. Эта команда читает инструкции из файла
Makefile, описывающего, как должны быть
перестроены программы, которые составляют систему &os;, в каком
порядке они должны быть построены и так далее.Общий формат командной строки, которую вы будет набирать,
таков:&prompt.root; make -x -DVARIABLEtargetВ этом примере
является параметром, который вы передаете в &man.make.1;.
Обратитесь к справочной странице программы &man.make.1;, которая
содержит список возможных параметров.
передает переменную в Makefile. Поведение
Makefile определяется этими переменными. Это
те же самые переменные, которые задаются в
/etc/make.conf, и это — еще один способ
их задания.&prompt.root; make -DNO_PROFILE=true targetявляется другим способом указания того, что библиотеки для
профилирования строить не нужно, и соответствует строкеNO_PROFILE= true # Обход построения библиотек для профилированияв файле /etc/make.conf.target указывает программе
&man.make.1; на то, что вы хотите сделать. Каждый файл
Makefile определяет некоторое количество
различных целей, и ваш выбор цели определяет то, что
будет делаться.Некоторые цели, перечисленные в файле
Makefile, не предназначены для вызова. Просто
они используются в процессе построения для разбиения его на этапы.В большинстве случаев вам не нужно передавать никаких
параметров в &man.make.1;, так что ваша команда будет выглядеть
примерно так:
&prompt.root; make targetЗамените target на одну или более из
опций сборки. Первой из них всегда должна быть опция
buildworld.Как указывают на это названия,
buildworld строит полностью новое дерево
в каталоге /usr/obj, а
installworld устанавливает это дерево на
используемой машине.Разделение этих опций весьма полезно по двум причинам. Во-первых, это позволяет
вам безопасно строить систему, зная, что компоненты вашей рабочей
системы затронуты не будут. Построение
самодостаточно. По этой причине вы можете спокойно
запустить buildworld на машине, работающей в
многопользовательском режиме без опаски получить какие-либо проблемы.
Но всё же рекомендуется запускать цель
installworld в однопользовательском
режиме.Во-вторых, это позволяет вам использовать монтирование по NFS для
обновления многих машин в сети. Если у вас есть три машины,
A, B и C, которые
вы хотите обновить, запустите make buildworld и
make installworld на машине A.
Хосты B и C должны будут
затем смонтировать по NFS каталоги /usr/src
и /usr/obj с машины A, и вы
сможете запустить make installworld для установки
результатов построения на машинах B и
C.Хотя цель world всё ещё имеется в
наличии, вам настоятельно рекомендуется не пользоваться ею.Выполните&prompt.root; make buildworldИмеется возможность задавать команде
make параметр , который
приводит к запуску нескольких одновременно работающих процессов.
Наиболее полезно использовать это на многопроцессорных машинах.
Однако, так как процесс компиляции больше всего требователен к
подсистеме ввода/вывода, а не к производительности процессора, это
можно использовать и на машинах с одним процессором.На типичной машине с одним CPU вы должны запускать:
&prompt.root; make -j4 buildworld&man.make.1; будет иметь до 4 одновременно работающих
процессов. Эмпирические замеры, опубликованные как-то в списке рассылки,
показывают, что в среднем это дает наибольшее увеличение
производительности.Если у вас многопроцессорная машина и вы используете ядро с
настройками для SMP, попробуйте использовать значения между 6 и
10 и посмотрите, как это отразится на скорости работы.Время на построениеперестроение worldзатраченное времяНа время компиляции влияет множество факторов, но на данный
момент современные машины
справляются с построением дерева &os.stable; примерно за 1-2 часа
без дополнительных хитростей и убыстряющих процесс уловок. Дерево
&os.current; строится несколько дольше.Откомпилируйте и установите новое ядроядрокомпиляцияЧтобы получить полную отдачу от вашей новой системы, вы должны
перекомпилировать ядро. Это практически необходимость, так как
отдельные структуры в памяти могут меняться, и программы типа
&man.ps.1; и &man.top.1; не будут работать, пока версии ядра и
исходных текстов системы не будут совпадать.Самым простым и надежным способом сделать это является компиляция и
установка ядра на основе GENERIC. Хотя в
GENERIC могут оказаться не все необходимые для
работы вашей системы устройства, в нем имеется все необходимое
для перезагрузки вашей системы обратно в однопользовательский режим.
Это является хорошей проверкой на правильность работы новой системы.
После загрузки с ядром GENERIC и проверки
работоспособности системы вы можете построить новое ядро на основе
вашего обычного конфигурационного файла ядра.В &os; важно выполнить buildworld перед сборкой
нового ядра.Если вы хотите построить собственное ядро и уже подготовили файл
конфигурации, просто используйте
KERNCONF=MYKERNEL
следующим образом:&prompt.root; cd /usr/src
&prompt.root; make buildkernel KERNCONF=MYKERNEL
&prompt.root; make installkernel KERNCONF=MYKERNELЗаметьте, что, если вы установили
kern.securelevel в значение, превышающее 1,
и установили флаг noschg или
подобный на бинарный файл ядра, то вы будете вынуждены перейти в
однопользовательский режим для того, чтобы воспользоваться
installkernel. В противном случае вы
должны выполнять эти команды без проблем. Обратитесь к справочным
страницам об &man.init.8; для получения подробной информации о
kern.securelevel и &man.chflags.1; для получения
информации о различных флагах файлов.Перезагрузитесь в однопользовательский режимоднопользовательский режимДля проверки работоспособности ядра вы должны перезагрузить систему
и перейти в однопользовательский режим. Сделайте это, следуя указаниям
в .Установите новые версии системных программЕсли вы компилировали достаточно свежую версию &os;, в которой
имеется команда make buildworld, то для установки
новых версий программ вы должны теперь выполнить команду
installworld.Запустите&prompt.root; cd /usr/src
&prompt.root; make installworldЕсли при выполнении команды make buildworld вы
задавали значения каких-либо переменных, то при выполнении
make installworld вы должны задать те же самые
переменные. Это не всегда так для остальных параметров; например,
при выполнении installworld никогда не
должен использоваться параметр .Например, если вы выполняли команду:&prompt.root; make -DNO_PROFILE buildworldто результат её выполнения должен устанавливаться командой&prompt.root; make -DNO_PROFILE installworldВ противном случае будет делаться попытка установить библиотеки
для профилирования, которые не компилировались на этапе выполнения
команды make buildworld.Обновите файлы, не обновленные по команде
make installworldПри перестроении системы не будут обновляться некоторые каталоги
(в частности, /etc, /var и
/usr) с конфигурационными
файлами.Самым простым способом обновить такие файлы является запуск
утилиты &man.mergemaster.8;, хотя можно сделать это и вручную, если вам
так больше нравится. Вне зависимости от выбранного вами способа
обязательно сделайте резервную копию каталога /etc
на случай, если произойдёт что-то непредвиденное.TomRhodesТекст предоставил mergemastermergemasterУтилита &man.mergemaster.8; является скриптом для оболочки Боурна,
которая поможет вам в определении разницы между вашими
конфигурационными файлами в каталоге /etc и
конфигурационными файлами из дерева исходных текстов
/usr/src/etc. Это является рекомендуемым
способом синхронизации системных конфигурационных файлов с теми, что
размещены в дереве исходных текстов.Для начала просто наберите mergemaster в
приглашении командной строки и посмотрите, что происходит.
mergemaster построит временное окружение для
пользователя root, начиная от /, а затем
заполнит его различными системными конфигурационными файлами. Эти
файлы затем будут сравниваться с теми, что установлены в вашей
системе. В этот момент файлы, которые имеют отличия, будут выданы в
формате &man.diff.1;, где знак будет означать
добавленные или изменённые строки, а знак будет
означать строки, которые были либо полностью удалены, либо заменены
на новые. Обратитесь к страницам справочной системы по команде
&man.diff.1; для получения более полной информации о синтаксисе
команды &man.diff.1; и формате выдачи отличий в файлах.Затем &man.mergemaster.8; выдаст вам каждый файл, в котором есть
изменения, и в этот момент у вас есть возможность либо удалить новый
файл (который будем считать временным), установить временный файл в
его неизменённом виде, объединить временный файл с установленным на
данный момент, либо просмотреть выдачу &man.diff.1; ещё раз.Выбор удаления временного файла укажет &man.mergemaster.8; на то,
что мы хотим оставить наш текущий файл без изменений и удалить его
новую версию. Делать это не рекомендуется, если только
у вас нет причин вносить изменения в текущий файл. Вы можете
получить помощь в любое время, набрав ? в
приглашении &man.mergemaster.8;. Если пользователь выбирает пропуск
файла, запрос появится снова после того, как будут обработаны все
остальные файлы.Выбор установки немодифицированного временного файла приведёт к
замене текущего файла новым. Для большинства немодифицированных
файлов это является подходящим вариантом.Выбор варианта с объединением файла приведёт к вызову текстового
редактора, содержащего текст обоих файлов. Теперь вы можете
объединить их, просматривая оба файла на экране, и выбирая те части
из обоих, что подходят для окончательного варианта. Когда файлы
сравниваются на экране, то нажатие l выбирает
содержимое слева, а нажатие r выбирает содержимое
справа. В окончательном варианте будет файл, состоящий из обеих
частей, который и будет установлен. Этот вариант используется для
файлов, настройки в которых изменялись пользователем.Выбор повторного просмотра &man.diff.1;-разниц выдаст вам разницы
между файлами, как это делала утилита &man.mergemaster.8; до того,
как запросила вас о выборе.После того, как утилита &man.mergemaster.8; закончит работу с
системными файлами, она выдаст запрос относительно других параметров.
&man.mergemaster.8; может запросить вас относительно перестроения
файла паролей и завершит запросом на удаление оставшихся
временных файлов.Обновление в ручном режимеОднако если вы хотите произвести обновление вручную, то вы не
можете просто скопировать файлы из /usr/src/etc в
/etc и получить работающую систему. Некоторые
из этих файлов сначала нужно установить. Это нужно
потому, что каталог /usr/src/etcне является копией того, что должен содержать
ваш каталог /etc. Кроме того, есть файлы,
которые должны присутствовать в /etc, но которых
нет в /usr/src/etc.Если вы используете &man.mergemaster.8; (как это рекомендуется),
то вы можете перейти сразу к следующему
разделу.Вручную проще всего сделать это, установив файлы в новый каталог,
а затем пройтись по ним, отмечая разницу.Сделайте резервную копию вашего каталога
/etcХотя, в теории, никаких автоматических действий с этим
каталогом не производится,
всегда лучше чувствовать себя уверенным. Так что скопируйте
имеющийся каталог /etc в какое-нибудь
безопасное место. Запустите что-то вроде:&prompt.root; cp -Rp /etc /etc.old задает выполнение рекурсивного копирования,
а сохраняет даты, владельца файлов и тому
подобное.Вам нужно создать шаблонную структуру каталогов для установки
нового содержимого /etc и других файлов.
Подходящим местом является /var/tmp/root, и в нём
потребуется разместить некоторое количество подкаталогов.&prompt.root; mkdir /var/tmp/root
&prompt.root; cd /usr/src/etc
&prompt.root; make DESTDIR=/var/tmp/root distrib-dirs distributionЭти команды приведут к созданию нужной структуры каталогов и
установке файлов. Множество каталогов, созданных в
/var/tmp/root, будут пустыми и должны быть удалены.
Проще всего сделать это так:&prompt.root; cd /var/tmp/root
&prompt.root; find -d . -type d | xargs rmdir 2>/dev/nullЭти команды удалят все пустые каталоги. (Стандартный поток
диагностических сообщений перенаправляется в
/dev/null для исключения предупреждений о
непустых каталогах.)Теперь /var/tmp/root содержит все файлы,
которые должны быть помещены в соответствующие места в
/. Теперь пройдитесь по каждому их этих файлов
и определите, чем они отличаются от имеющихся у вас файлов.Заметьте, что некоторые из файлов, которые были установлены в
каталог /var/tmp/root, имеют первым символом
.. На момент написания единственными такими файлами
являлись файлы начальных скриптов командных процессоров в
/var/tmp/root/ и
/var/tmp/root/root/, хотя могут быть и другие
(зависит от того, когда вы это читаете). Обязательно пользуйтесь
командой ls -a, чтобы выявить их.Проще всего сделать это путём сравнения двух файлов при помощи
команды &man.diff.1;:&prompt.root; diff /etc/shells /var/tmp/root/etc/shellsЭта команда покажет разницу между вашим файлом
/etc/shells и новым файлом
/var/tmp/root/etc/shells. Используйте это для
определения того, переносить ли сделанные вами изменения или
скопировать поверх вашего старого файла.Называйте новый корневой каталог
(/var/tmp/root) по дате, чтобы вы смогли легко
выявить разницу между версиямиЧастое перестроение системы означает также и частое обновление
/etc, которое может быть несколько
обременительным.Вы можете ускорить этот процесс, сохраняя копию последнего
набора измененных файлов, которые вы перенесли в
/etc. Следующая процедура подаст вам одну
идею о том, как это сделать.Выполните перестроение системы обычным образом. Когда вы
вам потребуется обновить /etc и другие
каталоги, дайте целевому каталогу имя на основе текущей даты.
Если вы делаете это 14 февраля 1998 года, то вы можете сделать
следующее:&prompt.root; mkdir /var/tmp/root-19980214
&prompt.root; cd /usr/src/etc
&prompt.root; make DESTDIR=/var/tmp/root-19980214 \
distrib-dirs distributionПеренесите изменение из этого каталога, как это описано
выше.Не удаляйте каталог
/var/tmp/root-19980214 после окончания
этого процесса.Когда вы загрузите самую последнюю версию исходного кода и
перестроите систему, выполните шаг 1. Это даст вам новый
каталог, который может называться
/var/tmp/root-19980221 (если вы ждете
неделю между обновлениями).Теперь вы можете видеть изменения, которые были сделаны
за прошедшую неделю, выполнив при помощи команды &man.diff.1;
рекурсивное сравнение двух каталогов:&prompt.root; cd /var/tmp
&prompt.root; diff -r root-19980214 root-19980221Как правило, здесь содержится гораздо меньше отличий, чем
между каталогами
/var/tmp/root-19980221/etc и
/etc. Так как отличий меньше, то и легче
перенести эти изменения в ваш каталог
/etc.Теперь вы можете удалить более старый из двух каталогов
/var/tmp/root-*:&prompt.root; rm -rf /var/tmp/root-19980214Повторяйте этот процесс всякий раз, когда вам нужно
перенести изменения в каталог /etc.Для автоматической генерации имён каталогов можно
использовать команду &man.date.1;:&prompt.root; mkdir /var/tmp/root-`date "+%Y%m%d"`ПерезагрузкаТеперь вы сделали всё. После того, как вы проверили, что всё
на месте, можете перегрузить систему. Простая команда
&man.shutdown.8; должна это сделать:&prompt.root; shutdown -r nowЗавершениеТеперь у вас имеется успешно обновлённая система &os;.
Поздравляем!Если что-то работает неправильно, можно с лёгкостью перестроить
конкретную часть системы. Например, если вы случайно удалили файл
/etc/magic в процессе обновления или переноса
/etc, то команда &man.file.1; перестанет работать.
В таком случае это можно исправить вот так:&prompt.root; cd /usr/src/usr.bin/file
&prompt.root; make all installВопросы?Нужно ли полностью перестраивать систему при каждом
изменении?Простого ответа на этот вопрос нет, так как это зависит от
характера изменения. Например, если вы только что выполнили
CVSup, и оказалось, что с момента
последнего его запуска были изменены следующие файлы:src/games/cribbage/instr.csrc/games/sail/pl_main.csrc/release/sysinstall/config.csrc/release/sysinstall/media.csrc/share/mk/bsd.port.mkто перестраивать всю систему незачем. Вы можете просто
перейти в соответствующий подкаталог и выдать команду
make all install, этого будет достаточно.
Однако, если меняется что-то важное, например,
src/lib/libc/stdlib, то вы должны
перестроить всю систему или по крайней мере те ее части, которые
скомпонованы статически.В конце концов, выбор за вами. Может быть вам нравится
перестраивать систему, скажем, каждый вечер, а изменения
скачивать ночью. Или вы можете захотеть перестраивать только
те вещи, которые менялись, но быть уверенным, что отслежены все
изменения.И, конечно же, всё это зависит от того, как часто вы хотите
делать обновление, и отслеживаете ли вы &os.stable; или
&os.current;.Компиляция прерывается с большим количеством ошибок по
сигналу 11сигнал 11
(или с другим номером сигнала). Что
случилось?Как правило, это говорит о проблемах с оборудованием.
(Пере)построение системы является эффективным стресс-тестом для
вашего оборудования и частенько выявляет проблемы с памятью.
Обычно это проявляется в виде неожиданных сбоев компилятора
или получения странных программных сигналов.Явным указателем на это является то, что при перезапуске
процедуры построения она прекращается в различные моменты
времени.В этом случае вы мало что можете сделать, разве что
попробовать заменить комплектующие вашей машины для определения
сбоящей компоненты.Могу ли я удалить каталог /usr/obj
после окончания?Если отвечать коротко, то да.Каталог /usr/obj содержит все
объектные файлы, которые создаются во время фазы компиляции.
Обычно одним из первых шагов в процессе make buildworld
является удаление этого каталога. В этом случае сохранение
/usr/obj после окончания имеет мало смысла;
вдобавок, он будет занимать большой объём дискового
пространства (на данный момент около 340 МБ).Однако если вы точно знаете, что делаете, то можете заставить
процедуру make buildworld пропустить этот шаг. Это
позволит последующие построения выполняться гораздо быстрее, так
как большинство исходных текстов не нужно будет
перекомпилировать. Оборотной стороной медали этого подхода
является вероятность появления некоторых проблем с зависимостями,
что может привести к прерыванию построения по странным причинам.
Это частенько вызывает шум в списках рассылки &os;, когда
кто-либо жалуется на прерывание процесса построения, не обращая
внимания на то, что он пытается срезать углы на
повороте.Могут ли быть продолжены прерванные процессы
построения?Это зависит от того, насколько далеко зашел процесс
построения перед тем, как вы обнаружили проблему.В общем случае (и это несложное и
быстрое правило) процесс make buildworld строит
новые копии необходимых инструментальных средств (таких, как
&man.gcc.1; и &man.make.1;) и системные библиотеки. Затем эти
средства и библиотеки устанавливаются. Новые инструментальные
средства и библиотеки затем используются для перестроения
самих себя, и повторно устанавливаются. Система в целом
(теперь включая обычные пользовательские программы, такие,
как &man.ls.1; или &man.grep.1;) теперь перестраивается с
новыми системными файлами.Если вы на последнем шаге, и вы знаете это (потому что
просматривали вывод, который сохраняете), то вы можете
(достаточно безболезненно) выполнить команду:… исправление проблемы …
&prompt.root; cd /usr/src
&prompt.root; make -DNO_CLEAN allПри этом результат предыдущего запуска
make buildworld откатываться не будет.Если вы видите сообщение:--------------------------------------------------------------
Building everything..
--------------------------------------------------------------в выводе команды make buildworld, то делать так
достаточно безопасно.Если этого сообщения не было, или вы в этом не уверены, то
всегда лучше обезопасить себя, и начать построение с самого
начала.Как ускорить процесс построения системы?Работайте в однопользовательском режиме.Разместите каталоги /usr/src и
/usr/obj в отдельных файловых
системах, располагающихся на разных дисках. Если это
возможно, то разместите эти диски на разных дисковых
контроллерах.Ещё лучше разместить эти файловые системы на нескольких
дисках при помощи устройства &man.ccd.4; (драйвер
объединённых дисков).Выключите генерацию профилирующего кода (установив
NO_PROFILE=true в файле
/etc/make.conf). Вам это скорее
всего никогда не понадобится.Также в /etc/make.conf установите
значение CFLAGS во что-то типа . Оптимизация выполняется
гораздо медленнее, а разница между и
обычно несущественна.
позволяет компилятору использовать для
связи вместо временных файлов программные каналы, что
уменьшает обращение к диску (за счет оперативной
памяти).Передайте утилите &man.make.1; параметр
для запуска
параллельно нескольких процессов. Обычно это помогает вне
зависимости от того, сколько процессоров установлено в вашей
машине.Файловая система, на которой располагается каталог
/usr/src, может быть смонтирована (или
перемонтирована) с опцией . При этом
запись на диск информации о времени последнего доступа к
файлам будет отключена. Скорее всего, вам эта информация и
не нужна.&prompt.root; mount -u -o noatime /usr/srcВ примере предполагается, что
/usr/src располагается на
собственной файловой системе. Если это не так (то
есть он является частью, скажем,
/usr), то вам нужно использовать
точку монтирования той файловой системы, а не
/usr/src.Файловая система, на которой располагается
/usr/obj, может быть смонтирована (или
перемонтирована) с параметром . Это
приведёт к тому, что операции записи на диск будут
выполняться асинхронно. Другими словами, запись будет
завершаться немедленно, но данные записываться на диск
несколькими секундами позже. Это позволит объединять
операции записи и приведёт к значительному приросту
производительности.Имейте в виду, что эта опция делает вашу файловую
систему менее устойчивой. С этой опцией имеется больше
шансов, что при перезагрузке машины после неожиданного
сбоя при пропадании напряжения файловая система окажется
в невосстановимом состоянии.Если каталог /usr/obj — это все,
что есть в этой файловой системе, то это не проблема.
Если на той же самой файловой системе имеются какие-то
важные данные, то проверьте давность ваших резервных
копий перед включением этой опции.&prompt.root; mount -u -o async /usr/objКак и раньше, если каталог
/usr/obj располагается не на
собственной файловой системе, то в примере замените его
на имя соответствующей точки монтирования.Что мне делать, если что-то пошло не так?Скрупулезно проверьте, чтобы в вашем окружении не было
мешающих остатков от предыдущих построений. Это достаточно
просто.&prompt.root; chflags -R noschg /usr/obj/usr
&prompt.root; rm -rf /usr/obj/usr
&prompt.root; cd /usr/src
&prompt.root; make cleandir
&prompt.root; make cleandirДа, команду make cleandir действительно
нужно выполнять дважды.После этого повторите весь процесс снова, начиная с
make buildworld.Если у вас все еще есть проблемы, пришлите текст ошибки и
выдачу команды uname -a на адрес списка рассылки
&a.questions.name;. Будьте готовы ответить на другие вопросы о
конфигурации вашей системы!MikeMeyerТекст предоставил Отслеживание исходных текстов для нескольких машинNFSinstalling multiple machinesЕсли у вас множество машин, для которых вы хотите отслеживать одно
и то же дерево исходных текстов, то загрузка кода и перестроение системы
полностью выглядит как ненужная трата ресурсов: дискового пространства,
пропускной способности сети и процессорного времени. Так оно и есть, и
решением является выделение одной машины, которая выполняет основной
объём работы, в то время как остальные используют результаты работы
посредством NFS. В этом разделе описывается именно этот метод.ПодготовкаПервым делом определите набор машин, на которых выполняется один
и тот же набор бинарных программ, и мы будем называть его
набором для построения. Каждая машина может иметь
собственное уникальное ядро, но они будут работать с одними и теми же
программами пользователя. Из этого набора выберите машину, которая
будет являться машиной для построения. Она станет
машиной, на которой будут строиться ядро и всё окружение. В идеальном
случае с достаточно незагруженным CPU для выполнения команд
make buildworld и make
buildkernel. Вам также потребуется выбрать машину,
которая будет тестовой для проверки обновлений
программного обеспечения прежде, чем оно будет запущено в промышленную
эксплуатацию. Это должна быть машина, которая
может быть в нерабочем состоянии достаточно долго. Это может быть
машина для построения, но не обязательно.Все машины в этом наборе для построения должны монтировать каталоги
/usr/obj и
/usr/src с одной и той же машины и в одну и ту же
точку монтирования. В идеальном случае они располагаются на разных
дисках машины построения, но они могут также монтироваться по NFS на
этой машине. Если у вас имеется несколько наборов для построения, то
каталог /usr/src должен быть на машине построения,
а по NFS он должен быть смонтирован на остальных.Наконец, удостоверьтесь в том, что файлы
/etc/make.conf и
/etc/src.conf на всех машинах набора для
построения соответствуют машине построения. Это означает, что машина
построения должна строить все части основного системного набора,
которые будут устанавливаться на каждой машине из набора для
построения. Кроме того, у каждой машины построения должно быть задано
имя ядра посредством переменной KERNCONF в файле
/etc/make.conf, а машина построения должна
перечислить их все в переменной KERNCONF, причём
первым должно быть имя её собственного ядра. Машина построения должна
хранить конфигурационные файлы ядра каждой машины в каталоге
/usr/src/sys/arch/conf,
если на ней будут строиться соответствующие ядра..Основные системные компонентыТеперь, когда всё это сделано, вы готовы к построению. Постройте
ядро и всё окружение так, как это описано в на машине построения, но ничего не
устанавливайте. После того, как процесс построения завершится,
перейдите к тестовой машине и установите только что построенное ядро.
Если эта машина монтирует каталоги /usr/src и
/usr/obj посредством NFS, то при перезагрузке в
однопользовательский режим вам потребуется задействовать сеть и
смонтировать их. Самым простым способом сделать это является переход
во многопользовательский режим и запуск команды shutdown
now для перехода в однопользовательский режим. После этого
вы можете установить новое ядро и всё окружение, а затем выполнить
команду mergemaster обычным образом. После
выполнения этих действий перезагрузитесь для возвращения к обычному
режиму работы во многопользовательском режиме с этой машиной.После того, как вы убедитесь в нормальной работе всего на тестовой
машине, проведите ту же самую процедуру для установки нового
программного обеспечения на каждой из оставшихся машин из набора для
построения.ПортыТе же самые идеи могут использоваться и для дерева портов. Первым
критическим шагом является монтирование /usr/ports
с одной и той же машины на всех компьютерах в наборе для построения.
Затем вы можете корректно настроить /etc/make.conf
для использования общего каталога с дистрибутивными файлами. Вы должны
задать переменную DISTDIR так, чтобы она указывала
на общедоступный каталог, доступный тому пользователю, который
отображается в пользователя root для ваших точек
монтирования NFS. Каждая машина
должна задавать WRKDIRPREFIX так, чтобы она
указывала на локальный каталог построения. Наконец, если вы
собираетесь строить и распространять пакеты, то должны задать
переменную PACKAGES так, чтобы она указывала на
каталог, соответствующий DISTDIR.
diff --git a/ru_RU.KOI8-R/books/handbook/mail/chapter.xml b/ru_RU.KOI8-R/books/handbook/mail/chapter.xml
index b86b09e4a8..27e9c30afe 100644
--- a/ru_RU.KOI8-R/books/handbook/mail/chapter.xml
+++ b/ru_RU.KOI8-R/books/handbook/mail/chapter.xml
@@ -1,2215 +1,2211 @@
BillLloydОригинальную версию предоставил JimMockПереписал АлексейДокучаевПеревод на русский язык: ДенисПеплинЭлектронная почтаКраткий обзорemailЭлектронная почта называемая также email, является
на сегодняшний день одним из самых популярных средств связи. Эта глава
описывает основы работы с почтовым сервером в &os;, а также введение
в процесс отправки и получения почты в &os;; однако, это не полноценный
справочник и фактически в главу не вошло много важной информации.
Более подробно эта тема рассмотрена во множестве прекрасных книг, список
которых приведен в .После прочтения этой главы вы узнаете:Какие программные компоненты задействованы в отправке и
получении электронной почты.Какие основные файлы настройки
sendmail имеются в FreeBSD.Разницу между удаленными и локальными почтовыми
ящиками.Как запретить спамерам использовать ваш почтовый
сервер для пересылки почты.Как установить и настроить альтернативный агент передачи почты
(Mail Transfer Agent, MTA), заменив им
sendmail.Как разрешить наиболее часто встречающиеся проблемы с почтовым
сервером.Как настроить систему только для отправки почты.Как использовать почту с коммутируемым подключением к
сети.Как настроить SMTP аутентификацию для дополнительной
защиты.Как установить и настроить почтовый агент пользователя
(Mail User Agent, MUA), например
mutt, для отправки и получения
почты.Как загрузить почту с удаленного POP или
IMAP сервера.Как автоматически применять фильтры и правила к входящей
почте.Перед прочтением этой главы вам потребуется:Правильно настроить сетевое подключение
().Правильно настроить DNS для почтового сервера
().Знать как устанавливать дополнительное программное обеспечение
сторонних разработчиков ().Использование электронной почтыPOPIMAPDNSВ работе почтовой системы задействованы пять основных частей:
пользовательский почтовый клиент
(Mail User Agent, MUA),
почтовый сервис (даемон)
(Mail Transfer Agent, MTA), сервер DNS, удаленный или локальный почтовый ящик,
и конечно сам почтовый сервер.Пользовательский почтовый клиентОбычно, это программа типа mutt,
alpine, elm,
mail, а также программы с графическим
интерфейсом, такие, как balsa или
xfmail, или интегрированные приложения
(например, какой-либо WWW браузер типа Netscape). Все эти программы
общаются с локальным почтовым
сервером, вызывая какой-либо даемон, или напрямую по протоколу
TCP.Почтовый даемонпочтовые даемоныsendmailпочтовые даемоныpostfixпочтовые даемоныqmailпочтовые даемоныexim&os; по умолчанию поставляется с
sendmail, но помимо того поддерживает
множество других даемонов почтового сервера, вот лишь некоторые
из них:exim;postfix;qmail.Почтовый даемон выполняет только две функции: он отвечает за прием
входящей почты и отправку исходящей. Он не
отвечает за выдачу
почты по протоколам POP или
IMAP, и не обеспечивает подключения к локальным
почтовым ящикам mbox или Maildir. Для этих целей
вам может потребоваться дополнительный
даемон.Старые версии sendmail содержат
некоторые серьезные ошибки безопасности, которые могут
привести к получению атакующим локального и/или удаленного
доступа к вашему компьютеру. Убедитесь, что вы работаете
с современной версией, свободной от таких ошибок.
Или установите альтернативный MTA
из Коллекции Портов &os;.Email и DNSСлужба имен доменов (Domain Name System, DNS) и соответствующий
ей даемон named играют важную роль в доставке
почты. Для доставки почты с вашего сайта другому, даемон почтового
сервера обратится к DNS для определения удаленного хоста, отвечающего
за доставку почты по назначению. Тот же процесс происходит при
доставке почты с удаленного хоста на ваш почтовый сервер.MX recordDNS отвечает за сопоставления имен хостов
IP адресам, как и за хранение информации, предназначенной для
доставки почты, известной как MX записи. Запись MX (Mail
eXchanger) определяет хост или хосты, которые будут получать почту
для определенного домена. Если для вашего имени хоста или домена
нет записи MX, почта будет доставлена непосредственно на ваш хост,
IP адрес которого определен в записи A.Вы можете просмотреть MX записи для любого домена с помощью
команды &man.host.1;, как показано в примере ниже:&prompt.user; host -t mx FreeBSD.org
FreeBSD.org mail is handled (pri=10) by mx1.FreeBSD.orgПолучение почтыemailполучениеПолучение почты для вашего домена выполняет почтовый сервер.
Он сохраняет отправленную в ваш домен почту в формате либо
mbox (это метод по умолчанию),
либо Maildir, в зависимости от настроек.
После сохранения почты ее можно либо прочитать локально, используя
такие приложения как &man.mail.1;, mutt,
или удаленно, по таким протоколам как POP или
IMAP. Это
означает, что для локального чтения почты вам не потребуется
устанавливать сервер POP или
IMAP.Доступ к удаленным почтовым ящикам по протоколам
POP и IMAPPOPIMAPДля удаленного доступа к почтовым ящикам вам потребуется
доступ к POP или IMAP
серверу.
Хотя удаленный доступ обеспечивают оба протокола
POP и IMAP, последний
предоставляет множество дополнительных возможностей, вот некоторые
из них:IMAP может как хранить сообщения на
удаленном сервере, так и забирать их.IMAP поддерживает одновременные
обновления.IMAP может быть очень полезен для
низкоскоростных соединений, поскольку позволяет пользователям
получить структуру сообщений без их загрузки; он также может
использоваться для выполнения таких задач как поиск на сервере,
для минимизации объема передаваемых между клиентом и сервером
данных.Для установки POP или
IMAP сервера необходимо выполнить следующие
действия:Выберите IMAP или
POP сервер, который подходит вам наилучшим
образом. Следующие POP и
IMAP серверы хорошо известны и могут быть
приведены в качестве примера:qpopper;teapop;imap-uw;courier-imap;dovecot;Установите POP или
IMAP даемон, выбранный из Коллекции
Портов.Если потребуется, настройте
/etc/inetd.conf
для запуска POP или
IMAP сервера.Необходимо отметить, что и POP и
IMAP серверы передают информацию, включая
имя пользователя и пароль, в незашифрованном виде. Это означает,
что если вы хотите защитить передачу информации по этим
протоколам, потребуется использовать туннелирование сессий через
&man.ssh.1; или при помощи SSL. Туннелирование соединений описано
в , а SSL —
в .Доступ к локальным почтовым ящикамДоступ к почтовым ящикам может быть осуществлен непосредственно
путем использования MUA на сервере, где
эти ящики расположены. Это можно сделать используя приложения
вроде mutt или
&man.mail.1;.Почтовый хостпочтовый хостПочтовый хост это сервер, который отвечает за отправку и получение
почты для вашего компьютера, и возможно, для всей вашей сети.ChristopherShumwayПредоставил Настройка sendmailsendmailВ FreeBSD по умолчанию программой передачи почты (Mail Transfer
Agent, MTA) является &man.sendmail.8;. Работа
sendmail заключается в приеме почты от
почтовых программ пользователей (Mail User Agents,
MUA) и отправке ее на соответствующий адрес,
в соответствии с имеющимися настройками.
sendmail может также принимать входящие
соединения по сети и доставлять почту в локальные почтовые ящики
или перенаправлять их другой программе.sendmail использует следующие файлы
настройки:/etc/mail/access/etc/mail/aliases/etc/mail/local-host-names/etc/mail/mailer.conf/etc/mail/mailertable/etc/mail/sendmail.cf/etc/mail/virtusertableИмя файлаНазначение/etc/mail/accessФайл базы данных доступа
sendmail/etc/mail/aliasesСинонимы почтовых ящиков/etc/mail/local-host-namesСписок хостов, для которых
sendmail принимает почту/etc/mail/mailer.confНастройки почтовой программы/etc/mail/mailertableТаблица доставки почтовой программы/etc/mail/sendmail.cfОсновной файл настройки
sendmail/etc/mail/virtusertableТаблицы виртуальных пользователей и доменов/etc/mail/accessБаза данных доступа определяет список хостов или IP адресов,
имеющих доступ к локальному почтовому серверу, а также тип
предоставляемого доступа. Хосты могут быть перечислены как
, ,
или просто переданы процедуре обработки ошибок
sendmail с заданным сообщением об ошибке.
Хостам, перечисленным с параметром по умолчанию ,
разрешено отправлять почты на этот хост, если адрес назначения почты
принадлежит локальной машине. Все почтовые соединения от хостов,
перечисленных с параметром , отбрасываются.
Для хостов, перечисленных с параметром ,
разрешена передача через этот сервер почты с любым адресом
назначения.Настройка базы данных доступа
sendmailcyberspammer.com 550 We do not accept mail from spammers
FREE.STEALTH.MAILER@ 550 We do not accept mail from spammers
another.source.of.spam REJECT
okay.cyberspammer.com OK
128.32 RELAYВ этом примере приведены пять записей. К отправителям, чей адрес
соответствует записи в левой части таблицы, применяется правило
записанное в правой части таблицы. В первых двух примерах
код ошибки будет передан процедуре обработке ошибок
sendmail. В этом случае на удаленном хосте
будет получено соответствующее сообщение. В следующем примере почта
отбрасывается почта от определенного хоста,
another.source.of.spam. В четвертом примере
разрешается прием почты от хоста okay.cyberspammer.com, имя которого более точно
совпадает с этой записью, чем с cyberspammer.com в примере выше. При более
точном совпадении правила перезаписываются. В последнем примере
разрешается пересылка почты от хостов с IP адресами, начинающимися
с 128.32. Эти хосты смогут отправлять почту через
этот почтовый сервер для других почтовых серверов.После изменения этого файла для обновления базы данных
вам потребуется запустить make в каталоге
/etc/mail/./etc/mail/aliasesБаза данных синонимов содержит список виртуальных почтовых
ящиков, принадлежащих другим пользователям, файлам, программам, или
другим синонимам. Вот несколько примеров, которые могут быть
использованы для /etc/mail/aliases:Mail Aliasesroot: localuser
ftp-bugs: joe,eric,paul
bit.bucket: /dev/null
procmail: "|/usr/local/bin/procmail"Формат файла прост; имя почтового ящика слева от двоеточия
сопоставляется назначению(ям) справа. В первом примере
производится сопоставление почтового ящика
root почтовому ящику
localuser, для которого затем опять будет
произведен поиск в базе данных синонимов. Если совпадений не
обнаружится, сообщение будет доставлено локальному пользователю
localuser. В следующем примере приведен
список рассылки. Почта на адрес ftp-bugs
рассылается на три локальных почтовых ящика: joe,
eric и paul. Обратите
внимание, что удалённый почтовый ящик может быть задан в виде
user@example.com. В следующем примере
показана запись почты в файл, в данном случае
/dev/null. И в последнем примере показано
отправление почты программе, в данном случае почтовое сообщение
переправляется через канал &unix; на стандартный вход
/usr/local/bin/procmail.После обновления этого файла вам потребуется запустить
make в каталоге /etc/mail/
для обновления базы данных./etc/mail/local-host-namesВ этом файле находится список имен хостов, принимаемых
программой &man.sendmail.8; в качестве локальных. Поместите в
этот файл любые домены или хосты, для которых
sendmail должен принимать почту.
Например, если этот почтовый сервер должен принимать почту для
домена example.com и хоста
mail.example.com, его файл
local-host-names может выглядеть примерно
так:example.com
mail.example.comПосле обновления этого файла необходимо перезапустить
&man.sendmail.8;, чтобы он смог перечитать изменения./etc/mail/sendmail.cfОсновной файл настройки sendmail,
sendmail.cf управляет общим поведением
sendmail, включая все, от перезаписи
почтовых адресов до отправки удаленным серверам сообщений об
отказе от пересылки почты. Конечно, файл настройки с таким
многообразием возможностей очень сложен и подробное его описание
выходит за рамки данного раздела. К счастью, для стандартных
почтовых серверов изменять этот файл придется не часто.Основной файл настройки sendmail
может быть собран из макроса &man.m4.1;, определяющего возможности
и поведение sendmail. Подробнее
этот процесс описан в файле
/usr/src/contrib/sendmail/cf/README.Для применения изменений после правки файла необходимо
перезапустить sendmail./etc/mail/virtusertableФайл virtusertable сопоставляет виртуальные
почтовые домены и почтовые ящики реальным почтовым ящикам. Эти
почтовые ящики могут быть локальными, удаленными, синонимами,
определенными в /etc/mail/aliases, или
файлами.Пример таблицы виртуального доменаroot@example.com root
postmaster@example.com postmaster@noc.example.net
@example.com joeВ примере выше мы видим сопоставление адресов для домена
example.com. Почта
обрабатывается по первому совпадению с записью в этом файле.
Первая запись сопоставляет адрес root@example.com
локальному почтовому ящику root.
Вторая запись сопоставляет postmaster@example.com
локальному почтовому ящику postmaster
на хосте noc.example.net. Наконец,
до этого момента адрес в домене example.com не совпал ни с одним из
предыдущих, будет применено последнее сопоставление, в которому
соответствует всякое другое почтовое сообщение, отправленное на любой
адрес в example.com. Это сообщение
будет доставлено в локальный почтовый ящик
joe.AndrewBoothmanНаписал GregoryNeil ShapiroИнформация получена из писем, написанных Установка другой почтовой программыemailзамена mtaКак уже упоминалось, FreeBSD поставляется с MTA (Mail Transfer Agent)
sendmail. Следовательно, по умолчанию
именно эта программа отвечает за вашу исходящую и входящую
почту.Однако, по различным причинам некоторые системные администраторы
заменяют системный MTA. Эти причины варьируются от простого желания
попробовать другой MTA до потребности в определенных возможностях
пакета, основанного на другой почтовой программе. К счастью, вне
зависимости от причины, в FreeBSD такая замена выполняется
просто.Установка нового MTAВам предоставлен широкий выбор MTA. Начните с поиска в
Коллекции Портов FreeBSD,
где их немало. Конечно, вы можете использовать любой MTA
по желанию, взятый откуда угодно, если только сможете
запустить его под FreeBSD.Начните с установки нового MTA. После установки у вас будет
возможность решить, действительно ли он подходит вашем нуждам,
а также настроить новое программное обеспечение перед тем, как
заменить им sendmail. При установке
новой программы убедитесь, что она не пытается перезаписать
системные файлы, такие как /usr/bin/sendmail.
Иначе ваша новая почтовая программа фактически начнет работать
до того, как вы ее настроите.Обратитесь к документации на выбранный MTA
за информацией по его настройке.Отключение sendmailЕсли вы отключите сервис исходящей почты
sendmail, необходимо
заменить его альтернативной системой
доставки почты. Если вы не сделаете этого, системные программы,
такие как &man.periodic.8;, не смогут отправлять сообщения
по электронной почте как обычно. Многие программы в вашей
системе могут требовать наличия функционирующей
sendmail-совместимой системы.
Если приложения будут продолжать использовать программу
sendmail для отправки почты
после того, как вы её отключили, почта может попасть в
неактивную очередь sendmail и никогда
не будет доставлена.Для полного отключения
sendmail, включая сервис исходящей
почты, используйтеsendmail_enable="NO"
sendmail_submit_enable="NO"
sendmail_outbound_enable="NO"
sendmail_msp_queue_enable="NO"в /etc/rc.conf.Если вы хотите отключить только сервис входящей почты
sendmail, установитеsendmail_enable="NO"в /etc/rc.conf. Дополнительная информация
о параметрах запуска sendmail
доступна на странице справочника &man.rc.sendmail.8;.Запуск нового MTA при загрузкеНовый МТА можно запускать автоматически при загрузке системы
добавив соответствующую строку в /etc/rc.conf.
Ниже приведен пример для postfix:&prompt.root; echo 'postfix_enable=YES' >> /etc/rc.confС этого момента МТА будет запускаться автоматически во время
загрузки системы.Замещение sendmail как
почтовой программы по умолчаниюПрограмма sendmail настолько
распространена в качестве стандартной программы для систем &unix;,
что многие программы считают, что она уже установлена и настроена.
По этой причине многие альтернативные MTA предоставляют собственные
совместимые реализации интерфейса командной строки
sendmail; это облегчает их использование
в качестве прозрачной замены
sendmail.Поэтому если вы используете альтернативную почтовую программу,
потребуется убедиться, что когда программное обеспечение
пытается выполнить стандартные исполняемые файлы
sendmail, такие как
/usr/bin/sendmail, на самом деле выполняются
программы вновь установленной почтовой системы. К счастью,
FreeBSD предоставляет систему, называемую &man.mailwrapper.8;,
которая выполняет эту работу за вас.Когда установлен sendmail,
файл /etc/mail/mailer.conf выглядит
примерно так:sendmail /usr/libexec/sendmail/sendmail
send-mail /usr/libexec/sendmail/sendmail
mailq /usr/libexec/sendmail/sendmail
newaliases /usr/libexec/sendmail/sendmail
hoststat /usr/libexec/sendmail/sendmail
purgestat /usr/libexec/sendmail/sendmailЭто означает, что когда выполняется какая-то из этих стандартных
программ (например сам sendmail), система на
самом деле вызывает копию mailwrapper, называемую
sendmail, которая обращается к
mailer.conf и выполняет вместо этого
/usr/libexec/sendmail/sendmail.
Такая схема делает простой замену программ, которые на самом деле
выполняются, когда вызываются стандартные функции
sendmail.Поэтому если вы хотите выполнять
/usr/local/supermailer/bin/sendmail-compat
вместо sendmail, отредактируйте
/etc/mail/mailer.conf так:sendmail /usr/local/supermailer/bin/sendmail-compat
send-mail /usr/local/supermailer/bin/sendmail-compat
mailq /usr/local/supermailer/bin/mailq-compat
newaliases /usr/local/supermailer/bin/newaliases-compat
hoststat /usr/local/supermailer/bin/hoststat-compat
purgestat /usr/local/supermailer/bin/purgestat-compatЗапуск новой почтовой программыКак только вы все настроили, потребуется или уничтожить
процесс sendmail, который уже не
нужен и запустить новую почтовую программу, или просто перегрузить
систему. Перезагрузка также даст вам возможность проверить,
правильно ли настроена система для автоматического запуска
MTA при загрузке.Поиск и устранение неисправностейemailустранение неисправностейПочему я должен использовать FQDN для хостов вне моей
подсети?Вы, видимо, обнаружили, что хост, к которому вы обратились,
оказался на самом деле в другом домене; например, если вы
находитесь в домене foo.bar.edu и
хотите обратиться к хосту mumble в домене bar.edu, то должны указать его полное
доменное имя, mumble.bar.edu, а не
просто mumble.Традиционно, программа разрешения имен BSD BINDBIND позволяла это
делать. Однако, текущая версия BIND,
поставляемая с FreeBSD, больше не добавляет имена доменов,
отличающихся от того, в котором вы находитесь, для не полностью
указанных имен хостов. То есть, имя mumble будет
опознан как mumble.foo.bar.edu или
будет искаться в корневом домене.Это отличается от предыдущего поведения, при котором поиск
продолжался в доменах mumble.bar.edu и mumble.edu. Если вам интересны причины
объявления такого поведения плохой практикой и даже ошибкой в
безопасности, обратитесь к RFC 1535.Хорошим решением будет поместить строкуsearch foo.bar.edu bar.eduвместо ранее используемой:domain foo.bar.eduв файл /etc/resolv.conf. Однако
удостоверьтесь, что порядок поиска не нарушает границ
полномочий между локальным и внешним администрированием, в
терминологии RFC 1535.sendmail выдает ошибку
mail loops back to myselfВ FAQ по sendmail дан следующий
ответ:Я получаю такие сообщения об ошибке:
553 MX list for domain.net points back to relay.domain.net
554 <user@domain.net>... Local configuration error
Как можно решить эту проблему?
Согласно записям MX, почта для домена domain.net перенаправляется на хост
relay.domain.net, однако последний не распознается как
domain.net. Добавьте domain.net в файл
/etc/mail/local-host-names
[известный как /etc/sendmail.cw до версии 8.10]
(если вы используете
FETURE(use_cw_file)) или добавьте Cw domain.net в файл
/etc/mail/sendmail.cf.FAQ по sendmail можно найти на
и рекомендуется
прочесть его при желании произвести некоторые
усовершенствования настроек почтовой системы.Как организовать работу почтового сервера при коммутируемом
соединении с Интернет?Вы хотите подключить к интернет компьютер с FreeBSD, работающий
в локальной сети. Компьютер с FreeBSD будет почтовым шлюзом
для локальной сети. PPP соединение не выделенное.Существует как минимум два пути, чтобы сделать это. Один
способ это использование UUCPUUCP.Другой способ это использование постоянно работающего интернет
сервера для обеспечения вторичного MXMX record сервиса вашего домена.
Например, домен вашей компании example.com, и провайдер интернет
настроил example.net
для обеспечения вторичного MX сервиса:example.com. MX 10 example.com.
MX 20 example.net.Только один хост должен быть указан в качестве последнего
получателя (добавьте запись Cw example.com в
файл /etc/mail/sendmail.cf на машине
example.com).Когда программа sendmail (со стороны
отправителя) захочет доставить почту, она
попытается соединиться с вашим хостом (example.com) через модемное подключение.
Скорее всего, ей это не удастся (вы,
вероятнее всего, не будете подключены к интернет).
Программа sendmail
автоматически перейдет ко вторичному MX серверу, т.е. вашему
провайдеру (example.net).
Вторичный MX сервер будет периодически пытаться соединиться с
вашим хостом и доставить почту на основной сервер MX
(example.com).Вы можете воспользоваться следующим сценарием, чтобы забирать
почту каждый раз, когда вы входите в систему:#!/bin/sh
# Put me in /usr/local/bin/pppmyisp
( sleep 60 ; /usr/sbin/sendmail -q ) &
/usr/sbin/ppp -direct pppmyispЕсли же вы хотите написать отдельный пользовательский скрипт,
лучше воспользоваться командой
sendmail -qRexample.com вместо вышеприведенного
сценария, так как в этом случае вся почта в очереди для хоста
example.com будет обработана
немедленно.Рассмотрим эту ситуацию подробнее:Вот пример сообщения из &a.isp.name;.> Мы предоставляем вторичный MX для наших клиентов. Вы соединяетесь
> с нашим сервером несколько раз в день, чтобы забрать почту для вашего
> первичного (главного) MX (мы не соединяемся с ним каждый раз, когда
> приходит новая почта для его доменов). Далее, sendmail отправляет
> почту, находящуюся в очереди каждые 30 минут, и клиент должен быть
> подключен к Интернет в течении 30 минут, чтобы удостовериться, что
> вся почта ушла на основной MX-сервер.
>
> Может быть, есть какая-либо команда, которая заставит sendmail
> немедленно отправить все почту, находящуюся в очереди? Естественно,
> пользователи не обладают какими-либо повышенными привилегиями на
> нашем сервере.
В разделе privacy flags файла
sendmail.cf, определяется опция
Уберите restrictqrun, чтобы разрешить рядовым
пользователям инициировать работу с очередью. Вам также может понадобиться
изменить порядок MX-серверов. Так, если вы предоставляете первый (основной)
MX-сервер для ваши пользователей, мы указываем:
# If we are the best MX for a host, try directly instead of generating
# local config error.
OwTrue
Таким образом, удаленный хост будет доставлять почту непосредственно к вам,
не пытаясь установить соединение с клиентом. Затем уже вы, в свою очередь,
отсылаете ее клиенту. Удостоверьтесь, что в DNS есть записи про
customer.com и hostname.customer.com. Просто
добавьте запись A в DNS для customer.com.Почему я продолжаю получать ошибки Relaying
Denied при отправки почты через другие
хосты?В установке FreeBSD по умолчанию,
sendmail настроен для отправки
почты только от хоста, на котором он работает. Например,
если доступен POP сервер, пользователи
смогут проверять почту из школы, с работы или других
удаленных точек, но не смогут отправлять письма. Обычно,
через некоторое время после попытки будет отправлено письмо
от MAILER-DAEMON с сообщением
об ошибке 5.7 Relaying Denied.Есть несколько путей разрешения этой ситуации. Самый прямой
путь это использование адреса вашего провайдера в файле
relay-domains, расположенном в
/etc/mail/relay-domains. Быстрый способ
сделать это:&prompt.root; echo "your.isp.example.com" > /etc/mail/relay-domainsПосле создания или редактирования этого файла вы должны
перезапустить sendmail. Это отлично
работает, если вы администратор сервера и не хотите отправлять
почту локально, или хотите воспользоваться почтовым
клиентом/системой на другом компьютере или даже через другого
провайдера. Это также очень полезно, если у вас настроены одна
или две почтовые записи. Если необходимо добавить несколько
адресов, вы можете просто открыть этот файл в текстовом редакторе и
добавить домены, по одному на строку:your.isp.example.com
other.isp.example.net
users-isp.example.org
www.example.orgТеперь будет отправляться любая почта, посылаемая через вашу
систему любым хостом из этого списка (предоставляемого
пользователем, имеющим учетную запись в вашей системе).
Это отличный способ разрешить пользователям отправлять почту
через вашу систему удаленно, одновременно он блокирует отправку
спама.Расширенное руководствоВ следующем разделе рассматриваются более сложные темы, такие как
настройка почты и включение почтовой системы для всего домена.Базовая конфигурацияemailнастройкаИзначально, вы можете отправлять почту во внешний
мир если правильно составлен файл
/etc/resolv.conf или запущен свой сервер
имен. Если вы хотите, чтобы почта, предназначенная для хоста в
вашем домене, доставлялась MTA (например,
sendmail) на вашем хосте FreeBSD, есть два
пути:Запустите свой собственный сервер DNS, тем самым организовав
собственный домен, например, FreeBSD.orgПолучайте почту для вашего хоста непосредственно. Это
работает при доставке почты непосредственно на DNS имя вашей
машины. Например, example.FreeBSD.org.SMTPНезависимо от выбранного из предложенных выше вариантов, для
доставки почты непосредственно на ваш хост у него должен быть
постоянный IP адрес (а не динамический,
как у большинства PPP соединений). Если вы находитесь за
брандмауэром, то последний должен пропускать SMTP-пакеты. Если
вы хотите, чтобы почта приходила непосредственно на ваш
хост, необходимо убедиться в одном из двух:
-
- MX record
-
-
- Убедитесь, что запись (с наименьшим номером) MX в
+ Убедитесь, что запись (с наименьшим номером) MX вMX record
DNS соответствует IP адресу вашего хоста.Убедитесь, что в DNS для вашего хоста вообще отсутствует
MX-запись.Выполнение любого из перечисленных условий обеспечит доставку
почты для вашего хоста.Попробуйте это:&prompt.root; hostname
example.FreeBSD.org
&prompt.root; host example.FreeBSD.org
example.FreeBSD.org has address 204.216.27.XXЕсли вы это видите, то можно без проблем посылать почту на
yourlogin@example.FreeBSD.org
(предполагается, что sendmail на example.FreeBSD.org работает правильно).Однако, если вы видите это:&prompt.root; host example.FreeBSD.org
example.FreeBSD.org has address 204.216.27.XX
example.FreeBSD.org mail is handled (pri=10) by hub.FreeBSD.orgто вся почта, посланная на example.FreeBSD.org будет собираться на
hub (для того же пользователя), вместо того, чтобы
быть отосланной непосредственно на ваш хост.Эта информация обрабатывается вашим DNS сервером. Соответствующая
запись DNS, указывающая, через какой хост будет проходить ваша
почта, называется MX (Mail
eXchanger). Если для хоста отсутствует такая
запись, почта будет приходить прямо на этот хост.Допустим, что запись MX для хоста freefall.FreeBSD.org в какой-то момент
выглядела так:freefall MX 30 mail.crl.net
freefall MX 40 agora.rdrop.com
freefall MX 10 freefall.FreeBSD.org
freefall MX 20 who.cdrom.comВы видите, что для хоста freefall существуют
несколько MX-записей. Запись с наименьшим номером соответствует
хосту, получающему почту непосредственно, если он доступен; если
он недоступен по каким-то причинам, другие сервера (иногда называемые
(резервными MX) временно получают почту, и хранят ее
пока не станут доступны хосты с меньшими номерами, в конечном итоге
отправляя почту на эти хосты.Чтобы альтернативные MX-хосты использовались наиболее
эффективно, они должны быть независимо подключены к Интернет. Ваш
провайдер (или дружественный сайт) скорее всего без проблем сможет
оказать подобные услуги.Почта для вашего доменаДля настройки почтового хоста (почтовый
сервер) вам потребуется, чтобы почта, направляемая различным рабочим
станциям, пересылалась этому хосту. Обычно вам необходима
доставка всей почты для любого хоста вашего домена (в данном случае
*.FreeBSD.org) на почтовый сервер, чтобы
пользователи могли получать свою почту на с этого сервера.DNSЧтобы облегчить себе (и другим) жизнь, создайте на обеих машинах
учетные записи с одинаковыми именами пользователей, например, с помощью
команды &man.adduser.8;.Сервер, который вы будете использовать в качестве почтового,
должен быть объявлен таковым для каждой машины в домене. Вот
фрагмент примерной конфигурации:example.FreeBSD.org A 204.216.27.XX ; Рабочая станция
MX 10 hub.FreeBSD.org ; Почтовый шлюзТаким образом, вся корреспонденция, адресованная рабочей
станции, будет обрабатываться вашим почтовым сервером, независимо от
того, что указано в A-записи.Все это можно реализовать только в том случае, если вы
используете сервер DNS. Если вы по каким-либо причинам не имеете
возможности установить свой собственный сервер имен, необходимо
договориться с провайдером или теми, кто поддерживает ваш
DNS.Если вы хотите поддерживать несколько виртуальных почтовых
серверов, может пригодиться следующая информация. Допустим, что
ваш клиент зарезервировал домен, например, customer1.org, и вам требуется, чтобы
почта, предназначенная для customer1.org приходила на ваш хост,
например, mail.myhost.com. В таком
случае, DNS должен выглядеть так:customer1.org MX 10 mail.myhost.comЗаметьте, что если вам требуется только получать почту для
домена, соответствующая A-запись не
нужна.Помните, что если вы попытаетесь каким-либо образом обратиться
к хосту customer1.org, у вас
вряд ли что-либо получится, если нет A-записи для этого
хоста.Последнее, что вы должны сделать – это сказать программе
sendmail, для каких доменов и/или хостов
она должна принимать почту. Это можно сделать несколькими
способами:Добавьте названия этих хостов в файл
/etc/mail/local-host-names, если вы используете
FEATURE(use_cw_file). Если у вас
sendmail
версии ниже 8.10, необходимо отредактировать файл
/etc/sendmail.cw.Добавьте строку Cwyour.host.com в файл
/etc/sendmail.cf или
/etc/mail/sendmail.cf (если у вас
sendmail
версии 8.10 или более поздней).BillMoranПредоставил Настройка почты только для отправкиСуществует множество случаев, когда может потребоваться только
отправка почты через почтовый сервер. Вот отдельные примеры:У вас настольный компьютер, но вы хотите использовать такие
программы как &man.send-pr.1;. Для пересылки почты вам потребуется
использовать почтовый сервер провайдера.Ваш компьютер является сервером, где почта не хранится локально,
необходима только переправка всей почты через внешний почтовый
сервер.Практически любой MTA способен работать и в
этих условиях. К сожалению, может быть очень сложно правильно настроить
полноценный MTA для работы только с исходящей
почтой. Такие программы, как sendmail
и postfix слишком избыточны для этих
целей.К тому же, если вы используете обычные средства доступа в
интернет, условий для запуска почтового сервера может
быть недостаточно.Простейшим способом удовлетворить имеющиеся потребности может быть
установка порта mail/ssmtp.
Выполните под root следующие команды:&prompt.root; cd /usr/ports/mail/ssmtp
&prompt.root; make install replace cleanПосле установки потребуется настроить
mail/ssmtp с помощью файла из
четырех строк, расположенного в
/usr/local/etc/ssmtp/ssmtp.conf:root=yourrealemail@example.com
mailhub=mail.example.com
rewriteDomain=example.com
hostname=_HOSTNAME_Убедитесь, что используете существующий почтовый адрес для
root. Введите сервер вашего провайдера для
пересылки исходящей почты вместо mail.example.com (некоторые провайдеры
называют его сервером исходящей почты или
SMTP сервером).Убедитесь, что вы выключили sendmail,
включая сервис исходящей почты. За подробностями обращайтесь к
.У пакета mail/ssmtp имеются
и другие параметры. Обратитесь к файлу с примером настройки
в /usr/local/etc/ssmtp или к странице справочника
ssmtp за примерами и дополнительной
информацией.Установка ssmtp таким способом
позволит правильно работать любым программам на вашем компьютере,
которым требуется отправка почты, но не нарушит политику вашего
провайдера и не позволит вашему компьютеру быть использованным
спамерами.Использование почты с коммутируемым соединениемЕсли у вас есть статический IP, настройки по умолчанию менять
не потребуется. Установите имя хоста в соответствии с присвоенным
именем интернет и sendmail будет делать
свою работу.Если у вас динамический IP адрес и используется коммутируемое
PPP соединение с интернет, у вас возможно уже есть почтовый ящик
на сервере провайдера. Предположим, что домен провайдера называется
example.net, и что ваше
имя пользователя user, ваш компьютер называется
bsd.home, и провайдер сообщил вам, что
возможно использование relay.example.net в качестве сервера для пересылки
почты.Для получения почты из почтового ящика необходима установка
соответствующей программы. Хорошим выбором является
утилита fetchmail, она поддерживает
множество различных протоколов. Эта программа доступна в виде
пакета или из Коллекции Портов (mail/fetchmail). Обычно провайдер
предоставляет доступ по протоколу POP. Если
вы работаете с пользовательским PPP, то можете
автоматически забирать почту после установления соединения с
интернет с помощью следующей записи в
/etc/ppp/ppp.linkup:MYADDR:
!bg su user -c fetchmailЕсли вы используете sendmail (как
показано ниже) для доставки почты к не-локальным учетным записям,
вам возможно потребуется обработка почтовой очереди
sendmail сразу после установки
соединения с интернет. Для выполнения этой работы поместите
в /etc/ppp/ppp.linkup следующую команду
сразу после fetchmail: !bg su user -c "sendmail -q"Предполагается, что учетная запись для
user существует на bsd.home. В домашнем каталоге
user на bsd.home, создайте файл
.fetchmailrc:poll example.net protocol pop3 fetchall pass MySecretЭтот файл не должен быть доступен на чтение никому, кроме
user, поскольку в нем находится пароль
MySecret.Для отправки почты с правильным заголовком
from:, вам потребуется сообщить
sendmail использовать
user@example.net вместо
user@bsd.home. Вы можете также указать
sendmail отправлять почту через relay.example.net, для более быстрой пересылки
почты.Должен подойти следующий файл .mc:VERSIONID(`bsd.home.mc version 1.0')
OSTYPE(bsd4.4)dnl
FEATURE(nouucp)dnl
MAILER(local)dnl
MAILER(smtp)dnl
Cwlocalhost
Cwbsd.home
MASQUERADE_AS(`example.net')dnl
FEATURE(allmasquerade)dnl
FEATURE(masquerade_envelope)dnl
FEATURE(nocanonify)dnl
FEATURE(nodns)dnl
define(`SMART_HOST', `relay.example.net')
Dmbsd.home
define(`confDOMAIN_NAME',`bsd.home')dnl
define(`confDELIVERY_MODE',`deferred')dnlОбратитесь к предыдущему разделу за информацией о том, как
преобразовать этот файл .mc в файл
sendmail.cf. Не забудьте также перезапустить
sendmail после обновления
sendmail.cf.JamesGorhamНаписал SMTP аутентификацияНаличие SMTP аутентификации на почтовом сервере
дает множество преимуществ. SMTP аутентификация
может добавить дополнительный уровень безопасности к
sendmail, и позволяет мобильным пользователям,
подключающимся к разным хостам, возможность использовать тот же
почтовый сервер без необходимости перенастройки почтового клиента
при каждом подключении.Установите
security/cyrus-sasl2
из портов. Вы можете найти этот порт в
security/cyrus-sasl2.
В пакете security/cyrus-sasl2
есть множество параметров компиляции. Для используемого здесь
метода SMTP аутентификации убедитесь, что параметр
не отключен.После установки
security/cyrus-sasl2,
отредактируйте /usr/local/lib/sasl2/Sendmail.conf
(или создайте его если он не существует) и добавьте следующую
строку:pwcheck_method: saslauthdЗатем установите
security/cyrus-sasl2-saslauthd
и добавьте в /etc/rc.conf следующую
строку:saslauthd_enable="YES"а затем запустите saslauthd:&prompt.root; service saslauthd startЭтот даемон является посредником для аутентификации
sendmail через базу данных
passwd FreeBSD. Это позволяет избежать
проблем, связанных с созданием нового набора имен пользователей
и паролей для каждого пользователя, которому необходима
SMTP аутентификация, пароль для входа в систему
и для отправки почты будет одним и тем же.Теперь отредактируйте /etc/make.conf и
добавьте следующие строки:SENDMAIL_CFLAGS=-I/usr/local/include/sasl -DSASL
SENDMAIL_LDFLAGS=-L/usr/local/lib
SENDMAIL_LDADD=-lsasl2Эти параметры необходимы sendmail
для подключения cyrus-sasl2
во время компиляции. Убедитесь, что cyrus-sasl2 был установлен до
перекомпиляции sendmail.Перекомпилируйте sendmail, выполнив
следующие команды:&prompt.root; cd /usr/src/lib/libsmutil
&prompt.root; make cleandir && make obj && make
&prompt.root; cd /usr/src/lib/libsm
&prompt.root; make cleandir && make obj && make
&prompt.root; cd /usr/src/usr.sbin/sendmail
&prompt.root; make cleandir && make obj && make && make installКомпиляция sendmail должна пройти
без проблем, если /usr/src не был сильно
изменен и доступны необходимые разделяемые библиотеки.После компилирования и переустановки
sendmail, отредактируйте файл
/etc/mail/freebsd.mc (или тот файл, который
используется в качестве .mc; многие
администраторы используют в качестве имени этого файла
вывод &man.hostname.1; для обеспечения уникальности).
Добавьте к нему следующие строки:dnl set SASL options
TRUST_AUTH_MECH(`GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl
define(`confAUTH_MECHANISMS', `GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnlЭти параметры настраивают различные методы, доступные
sendmail для аутентификации пользователей.
Если вы хотите использовать вместо
pwcheck другой метод, обратитесь к
прилагаемой документации.Наконец, запустите &man.make.1; в каталоге
/etc/mail. Из файла
.mc будет создан файл
.cf, называющийся
freebsd.cf (или с тем именем, которое было
использовано для файла .mc). Затем
используйте команду make install restart,
которая скопирует файл в sendmail.cf,
и правильно перезапустит sendmail.
Дополнительная информация об этом процессе находится в
/etc/mail/Makefile.Если все шаги пройдены успешно, введите информацию для
аутентификации в настройки почтового клиента и отправьте тестовое
сообщение. Для определения причин возможных ошибок установите
параметр sendmail
в 13 и просмотрите
/var/log/maillog.За дальнейшей информацией обратитесь к странице
sendmail, посвященной
SMTP аутентификации.MarcSilverПредоставил Почтовые программы пользователейпочтовые программы пользователейПочтовая программа пользователя (Mail User Agent,
MUA) это приложение, используемое для отправки
и получения почты. Кроме того, поскольку почта
эволюционирует и становится более сложной,
MUA совершенствуют свои функции по обработке
почты, становятся более удобны в использовании. &os; поддерживает
множество различных пользовательских почтовых программ, каждая
из которых может быть легко установлена из Коллекции Портов FreeBSD. Пользователи могут
выбирать между графическими почтовыми клиентами, такими как
evolution или
balsa, консольными клиентами, такими
как mutt, alpine
или mail, или Web-интерфейсами, используемыми в
некоторых больших организациях.mailВ &os; в качестве MUA по умолчанию используется
&man.mail.1;. Это консольный MUA, предоставляющий
все основные функции, необходимые для отправки и получения текстовых
сообщений, хотя его возможности по работе с вложениями ограничены и
он может работать только с локальными почтовыми ящиками.Хотя mail не поддерживает работу с серверами
POP или IMAP, эти почтовые
ящики могут быть загружены в локальный файл mbox
с помощью fetchmail, который будет
обсуждаться далее в этой главе ().Для отправки и получения почты выполните
mail:&prompt.user; mailСодержимое почтового ящика в каталоге
/var/mail будет автоматически
прочитано утилитой mail. Если почтовый ящик
пуст, утилита завершит работу с сообщением о том, что почта не
была обнаружена. После чтения почтового ящика запустится
интерфейс программы и будет отображен список сообщений. Сообщения
нумеруются автоматически и будут выглядеть как в этом примере:Mail version 8.1 6/6/93. Type ? for help.
"/var/mail/marcs": 3 messages 3 new
>N 1 root@localhost Mon Mar 8 14:05 14/510 "test"
N 2 root@localhost Mon Mar 8 14:05 14/509 "user account"
N 3 root@localhost Mon Mar 8 14:05 14/509 "sample"Теперь сообщения могут быть прочитаны с помощью команды
t, завершаемой номером сообщения, которое должно
быть отображено. В этом примере мы прочтем первое сообщение:& t 1
Message 1:
From root@localhost Mon Mar 8 14:05:52 2004
X-Original-To: marcs@localhost
Delivered-To: marcs@localhost
To: marcs@localhost
Subject: test
Date: Mon, 8 Mar 2004 14:05:52 +0200 (SAST)
From: root@localhost (Charlie Root)
This is a test message, please reply if you receive it.Как видно в примере выше, клавиша t выводит
сообщение со всеми заголовками. Для повторного вывода
списка сообщений необходимо использовать клавишу
h.Если требуется ответить на сообщение, используйте для
ответа mail, нажав клавишу R или
r. Клавиша R используется в
mail для ответа только отправителю,
а r для ответа и отправителю, и другим получателям
сообщения. Вы можете также завершить эти команды номером письма,
на которое хотите составить ответ. После этого необходимо ввести
ответ, конец сообщения должен быть завершен символом
. на новой строке. Пример можно увидеть ниже:& R 1
To: root@localhost
Subject: Re: test
Thank you, I did get your email.
.
EOTДля отправки нового сообщения используйте клавишу
m и введите адрес получателя. Несколько получателей
могут быть указаны через запятую. Введите тему сообщения и
его содержимое. Конец сообщения отмечается помещением
символа . на новой строке.& mail root@localhost
Subject: I mastered mail
Now I can send and receive email using mail ... :)
.
EOTВ утилите mail для вызова справки в любой
момент может быть использована команда ?,
для получения помощи по mail необходимо также
обратиться к странице справочника &man.mail.1;.Как упоминалось выше, команда &man.mail.1; не была первоначально
предназначена для работы с вложениями, и поэтому их поддержка
довольно слабая. Современные MUA,
такие как mutt, работают с вложениями
гораздо более уверенно. Но если вы все же предпочитаете
использовать mail,
установите порт converters/mpack.muttmutt это небольшая но очень
мощная почтовая программа с отличными возможностями, в числе
которых:Возможность сортировки сообщений по дискуссиям;Поддержка PGP для подписи и шифрования сообщений;Поддержка MIME;Поддержка Maildir;Широкие возможности настройки.Все эти возможности делают
mutt одним из самых лучших почтовых
клиентов. Обратитесь к за
дополнительной информацией по mutt.Стабильная версия mutt может быть
установлена из порта mail/mutt.
После установки порта, mutt может
быть запущен следующей командой:&prompt.user; muttmutt автоматически прочтет содержимое
пользовательского почтового ящика в каталоге /var/mail и отобразит почту,
если она имеется в наличии. Если почты в ящике пользователя нет,
mutt будет ожидать команд от пользователя.
В примере ниже показан mutt со
списком сообщений:Для чтения почты выберите сообщение с помощью клавиш
навигации и нажмите Enter. Пример
mutt, отображающего сообщение, показан
ниже:Как и команда &man.mail.1;, mutt
позволяет пользователям отвечать как только отправителю, так и всем
получателям. Для ответа только отправителю почты, используйте
клавишу r. Для группового ответа и отправителю
сообщения и всем получателям используйте клавишу
g.mutt использует &man.vi.1; в качестве
редактора для создания писем и ответа на них. Редактор можно
заменить путем создания или редактирования собственного
.muttrc в своем домашнем каталоге и установки
переменной , или установкой переменной
окружения EDITOR. Обратитесь к
за более подробной
информацией о настройке mutt.Для создания нового почтового сообщения нажмите
m. После введения темы
mutt запустит &man.vi.1; для создания
письма. Как только письмо будет завершено, сохраните его и закройте
vi, mutt продолжит
работу, отобразив окно с сообщением, которое должно быть отправлено.
Для отправки сообщения нажмите y. Пример окна с
сообщением показан ниже:mutt также содержит исчерпывающий
справочник, к которому можно обратиться из большинства меню,
нажав клавишу ?. Верхняя строка также показывает
клавиатурные сокращения, которые могут быть использованы.alpinealpine предназначен для начинающих
пользователей, но включает некоторые дополнительные
возможности.В программе alpine ранее были
обнаружены некоторые уязвимости,
позволяющие удаленному взломщику выполнять произвольный код
с правами пользователя локальной системы путем отправки
специально подготовленного письма. Все эти
известные проблемы были исправлены,
но код alpine написан в очень
небезопасном стиле и офицеры
безопасности &os; считают, что возможно наличие других
не обнаруженных уязвимостей. Имейте это ввиду при установке
alpine.Текущая версия alpine может быть
установлена из порта mail/alpine.
Как только порт установлен, alpine можно
запустить командой:&prompt.user; alpineПри первом запуске alpine отображает
страницу приветствия с кратким введением, а также просьбу
команды разработчиков alpine
отправить анонимное почтовое сообщение, позволяющее им
определить количество пользователей, работающих с их почтовым
клиентом. Для отправки анонимного сообщения нажмите
Enter, или E для выхода
из приветствия без отправки анонимного сообщения. Пример
приветствия показан ниже:Затем отображается главное меню, перемещение по которому
осуществляется с помощью клавиш навигации. В главном меню
находятся ссылки для составления новых писем, просмотра почтовых
каталогов, и даже управления адресной книгой. Ниже главного меню
показаны клавиатурные сокращения, выполняющие
соответствующие задачи.По умолчанию alpine открывает каталог
inbox. Для просмотра списка
сообщений нажмите I, или выберите
MESSAGE INDEX, как показано ниже:В списке показаны сообщения в текущем каталоге, они могут быть
просмотрены с помощью клавиш навигации. Подсвеченные сообщения
можно прочесть нажав Enter.На снимке экрана ниже показан пример письма, отображаемого
alpine. Внизу экрана даны клавиатурные
сокращения. Например, r используется для
указания MUA ответить на отображаемое в
данный момент сообщение.Ответ на письмо в alpine осуществляется
с помощью редактора pico, который
устанавливается по умолчанию вместе с alpine.
pico упрощает навигацию в сообщении
гораздо проще для новых пользователей, чем &man.vi.1; или
&man.mail.1;. Как только ответ будет готов, сообщение можно отправить
нажав CtrlX.
alpine запросит подтверждение.Программа alpine может быть настроена
через пункт SETUP главного меню.
Обратитесь к странице
за дальнейшей информацией.MarcSilverПредоставил Использование fetchmailfetchmailfetchmail это полноценный
IMAP и POP клиент,
позволяющий пользователям автоматически загружать почту с
удаленных серверов IMAP и POP
в локальные почтовые ящики; так доступ к почтовым ящикам упрощается.
fetchmail может быть установлен из
порта mail/fetchmail и
предоставляет различные возможности, в том числе:Поддержка протоколов POP3,
APOP, KPOP,
IMAP, ETRN и
ODMR.Возможность пересылки почты через SMTP,
что позволяет использовать функции фильтрации, перенаправления и
синонимов.Может быт запущен в режиме даемона для периодической проверки
поступающих сообщений.Может забирать почту с нескольких почтовых ящиков и рассылать
ее различным локальным пользователям в зависимости от
настроек.Описание всех возможностей
fetchmail выходит за пределы этой главы,
за дополнительной информацией обратитесь к документации по
fetchmail. Утилита
fetchmail требует наличия
файла настройки .fetchmailrc. Этот файл
включает информацию о сервере, а также информацию для аутентификации.
Поскольку этот файл содержит важную информацию, правильно будет
сделать его доступным для чтения только владельцем с помощью
следующей команды:&prompt.user; chmod 600 .fetchmailrcВ следующем примере файл .fetchmailrc
предназначен для загрузки одного почтового ящика по протоколу
POP. Этот файл указывает
fetchmail соединиться с
example.com с именем пользователя
joesoap и паролем XXX.
В примере подразумевается, что пользователь joesoap
существует также и в локальной системе.poll example.com protocol pop3 username "joesoap" password "XXX"В следующем примере производится подключение к нескольким
POP и IMAP серверам,
при необходимости почта перенаправляется другим локальным
пользователям:poll example.com proto pop3:
user "joesoap", with password "XXX", is "jsoap" here;
user "andrea", with password "XXXX";
poll example2.net proto imap:
user "john", with password "XXXXX", is "myth" here;Утилита fetchmail может работать
в режиме даемона с флагом , заданным с
интервалом (в секундах), через который
fetchmail должен опрашивать
серверы, перечисленные в .fetchmailrc.
В следующем примере fetchmail будет
забирать почту каждые 600 секунд:&prompt.user; fetchmail -d 600Дополнительную информацию о fetchmail
можно найти на сайте .MarcSilverПредоставил Использование procmailprocmailУтилита procmail это невероятно
мощное приложение, используемое для фильтрации входящей почты.
Она позволяет пользователям определять правила,
которые могут быть сопоставлены входящим письмам для выполнения
определенных действий или для перенаправления почты в
альтернативные почтовые ящики и/или на почтовые адреса.
procmail может быть установлен
с помощью порта mail/procmail.
После установки он может быть непосредственно интегрирован в
большинство MTA; сверьтесь с документацией
на ваш MTA. Другой способ интеграции
procmail – добавление в
файл .forward, находящийся в домашнем
каталоге пользователя, следующей строки:"|exec /usr/local/bin/procmail || exit 75"В этом разделе будут показаны основы настройки правил
procmail, а также краткое описание их
действия. Эти и другие правила должны быть помещены в файл
.procmailrc, который должен находиться в домашнем
каталоге пользователя.Большую часть этих правил также можно найти на странице справочника
&man.procmailex.5;.Перенаправление всей почты от user@example.com на
внешний адрес goodmail@example2.com::0
* ^From.*user@example.com
! goodmail@example2.comПеренаправление всей почты объемом меньше 1000 байт на внешний адрес
goodmail@example2.com::0
* < 1000
! goodmail@example2.comПеренаправление всей почты, отправляемой на
alternate@example.com, в почтовый ящик
alternate::0
* ^TOalternate@example.com
alternateПеренаправление всей почты с Spam в
/dev/null::0
^Subject:.*Spam
/dev/nullПолезный пример, обрабатывающий входящую почту со списков
рассылки &os;.org и
помещающий каждый список в отдельный почтовый ящик.:0
* ^Sender:.owner-freebsd-\/[^@]+@FreeBSD.ORG
{
LISTNAME=${MATCH}
:0
* LISTNAME??^\/[^@]+
FreeBSD-${MATCH}
}
diff --git a/ru_RU.KOI8-R/books/handbook/network-servers/chapter.xml b/ru_RU.KOI8-R/books/handbook/network-servers/chapter.xml
index 21375238ea..6d91ff8aea 100644
--- a/ru_RU.KOI8-R/books/handbook/network-servers/chapter.xml
+++ b/ru_RU.KOI8-R/books/handbook/network-servers/chapter.xml
@@ -1,5269 +1,5254 @@
MurrayStokelyРеорганизовал АндрейЗахватовПеревод на русский язык: Сетевые серверыКраткий обзорЭта глава посвящена некоторым наиболее часто используемым сетевым
службам систем &unix;. Мы опишем, как установить, настроить,
протестировать и поддерживать многие различные типы сетевых сервисов.
Для облегчения вашей работы в главу включены
примеры конфигурационных файлов.После чтения этой главы вы будете знать:Как управлять даемоном inetd.Как настроить сетевую файловую систему.Как настроить сетевой сервер информации для совместного
использования учётных записей пользователей.Как настроить автоматическое конфигурирование сетевых параметров
при помощи DHCP.Как настроить сервер имён.Как настроить Apache HTTP
сервер.Как настроить файловый и сервер печати для &windows;
клиентов с использованием Samba.Как синхронизировать дату и время, а также настроить сервер
времени с протоколом NTP.Как настроить стандартный демон протоколирования,
syslogd, принимать сообщения от удалённых
хостов.Перед чтением этой главы вы должны:Понимать основы работы скриптов
/etc/rc.Свободно владеть основными сетевыми терминами.Знать как устанавливать дополнительные программы сторонних
разработчиков ().ChernLeeТекст предоставил Обновлено: Проект документации &os;Супер-серверinetdОбзор&man.inetd.8; иногда называют также супер-сервером
Интернет, потому что он управляет соединениями к многим
сервисам. Когда
inetd принимает соединение, он определяет,
для какой программы предназначено соединение, запускает соответствующий
процесс и предоставляет ему сокет, ссылка на который передается
процессу в качестве стандартных устройств ввода, вывода и сообщения об
ошибках. Для не слишком нагруженных серверов запуск через
inetd может уменьшить общую нагрузку на систему по
сравнению с запуском каждого даемона индивидуально в выделенном
режиме.В первую очередь inetd используется для
вызова других даемонов, но несколько простых протоколов, таких, как
chargen, auth и
daytime, обслуживаются
непосредственно.Этот раздел посвящен основам настройки
inetd посредством его параметров командной
строки и его конфигурационного файла,
/etc/inetd.conf.Настройкиinetd инициализируется посредством
системы &man.rc.8;. Параметр
inetd_enable по умолчанию установлен в
NO, однако может быть включен утилитой
sysinstall в процессе установки.
Указаниеinetd_enable="YES"илиinetd_enable="NO"в файле
/etc/rc.conf разрешит или запретит запуск
inetd во время загрузки.
Команда/etc/rc.d/inetd rcvarпокажет текущие установки переменных, относящихся к
inetd.Кроме того, через inetd_flags даемону
inetd могут быть переданы различные
параметры командной строки.Параметры командной строкиКак и большинство даемонов, для inetd
существует большое количество разнообразных опций, изменяющих
его поведение. Полный из список таков:inetdОпции могут передаваться inetd
при помощи переменной inetd_flags файла
/etc/rc.conf. По умолчанию переменная
inetd_flags установлена в -wW -C
60, то есть включает обработку TCP wrapping и запрещает
обращаться с одного IP-адреса к сервису более чем 60 раз в
минуту.Несмотря на то, что ниже по тексту мы упоминаем опции ограничения
частоты обращения к службам (rate-limiting), в большинстве случаев
начинающим пользователям нет необходимости менять эти параметры. Эти
опции могут стать полезными в том случае, если вы обнаружите, что ваша
система принимает чрезмерное количество соединений. Полный список
опций можно найти на странице справочника &man.inetd.8;.-c maximumОпределение максимального числа одновременных запусков каждой
службы; по умолчание не ограничено. Может быть переопределено
индивидуально для каждой службы при помощи параметра
.-C rateОпределение по умолчанию максимального количества раз,
которое служба может быть вызвана с одного IP-адреса в минуту; по
умолчанию не ограничено. Может быть переопределено для каждой
службы параметром
.-R rateОпределяет максимальное количество раз, которое служба может
быть вызвана в минуту; по умолчанию 256. Частота, равная 0,
не ограничивает число вызовов.-s maximumЗадает максимальное количество процессов, одновременно
обслуживающих один сервис для одного IP-адреса; по умолчанию
не ограничено. Может переопределяться для каждой службы
параметром .inetd.confНастройка inetd производится через файл
/etc/inetd.conf.Если в файле /etc/inetd.conf делались
изменения, то inetd можно заставить считать
его конфигурационный файл повторно посредством командыПерезагрузка конфигурационного файла
inetd&prompt.root; /etc/rc.d/inetd reloadВ каждой строке конфигурационного файла описывается отдельный
даемон. Комментариям в файле предшествует знак #.
Строки в файле
/etc/inetd.conf имеют такой формат:service-name
socket-type
protocol
{wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]
user[:group][/login-class]
server-program
server-program-argumentsПример записи для даемона &man.ftpd.8;,
использующего IPv4:ftp stream tcp nowait root /usr/libexec/ftpd ftpd -lservice-nameЭто имя сервиса, предоставляемого конкретным даемоном. Оно
должно соответствовать сервису, указанному в файле
/etc/services. Здесь определяется, какой
порт должен обслуживать inetd. При
создании нового сервиса он должен помещаться сначала в файл
/etc/services.socket-typestream, dgram,
raw либо seqpacket.
stream должен использоваться для
ориентированных на соединение даемонов TCP, когда как
dgram используется для даемонов, использующих
транспортный протокол UDP.protocolОдно из следующих:ПротоколОписаниеtcp, tcp4TCP IPv4udp, udp4UDP IPv4tcp6TCP IPv6udp6UDP IPv6tcp46TCP как для IPv4, так и для v6udp46UDP как для IPv4, так и для v6{wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] определяет, может ли даемон,
вызванный из inetd, работать с
собственным сокетом, или нет. Сокеты типа
должны использовать параметр , когда как
даемоны с потоковыми
сокетами, которые обычно многопоточны, должны использовать
. обычно передает
много сокетов одному даемону, когда как
порождает даемон для каждого нового сокета.Максимальное число порожденных даемонов, которых может
создать inetd, может быть задано
параметром . Если нужно ограничение в
десять экземпляров некоторого даемона, то после параметра
нужно задать
/10. При задании /0
ограничения на количество экземпляров снимаются.Кроме , могут быть задействованы
два других параметра, ограничивающих максимальное число соединений от
одного источника.
ограничивает
количество соединений от одного IP-адреса в течение минуты, так что
значение, равное десяти, будет ограничивать
любой заданный IP-адрес на выполнение десяти попыток подключения
к некоторому сервису в минуту. Параметр
ограничивает количество
дочерних процессов, которые могут быть одновременно
задействованы на обслуживание одного IP-адреса.
Эти опции полезны для предотвращения
намеренного или ненамеренного расходования ресурсов и атак типа
Denial of Service (DoS) на машину.В этом поле одно из значений
или
обязательны. ,
и
опциональны.Многопоточный даемон типа stream без ограничений
,
или
будет
определен просто как nowait.Тот же самый даемон с ограничением в максимум десять даемонов
будет определен так: nowait/10.Та же конфигурация с ограничением в двадцать
соединений на IP-адрес в минуту и общим ограничением в максимум
десять порожденных даемонов выглядит так:
nowait/10/20.Эти параметры, используемые все со значениями по умолчанию
даемоном &man.fingerd.8;, имеют такой
вид:finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -sНаконец, пример, описывающий ограничение на 100 даемонов
в целом, при этом не более чем по 5 на один IP-адрес,
будет выглядеть так:
nowait/100/0/5.userЭто имя пользователя, под которым должен
работать соответствующий даемон. Чаще всего даемоны работают
как пользователь root. Для обеспечения
безопасности некоторые серверы запускаются как пользователь
daemon или как пользователь с минимальными
правами nobody.server-programПолный маршрут к даемону, который будет выполняться при
установлении соединения. Если даемон является сервисом,
предоставляемым самим inetd, то нужно
задать ключевое слово .server-program-argumentsЭтот параметр работает вместе с параметром
, задавая параметры, начиная с
argv[0], передаваемые даемону при запуске.
Если в командной
строке задано mydaemon -d, то
mydaemon -d будет являться значением для
. И снова, если даемон
является внутренней службой, то здесь нужно использовать
.БезопасностьВ зависимости от выбранных при установке параметров,
многие из служб inetd могут оказаться по
умолчанию включенными. Если нет особой нужды в некотором даемоне,
подумайте, не стоит ли его выключить?
Поместите знак # перед ненужным даемоном
в /etc/inetd.conf
и пошлите сигнал для inetd.
Некоторые даемоны, такие, как fingerd,
вообще нежелательны, потому что они дают информацию, которая
может оказаться полезной атакующему.Некоторые даемоны не заботятся о безопасности и имеют большие
тайм-ауты для соединений или вообще их не имеют. Это позволяет
атакующему неспешно устанавливать соединения к конкретному даемону,
истощая имеющиеся ресурсы. Может оказаться полезным задать для
некоторых даемонов ограничения
,
и ,
особенно если вы обнаружите слишком большое число соединений.По умолчанию механизм TCP wrapping включен. Обратитесь к
справочной странице по &man.hosts.access.5; для получения более
подробной информации о задании ограничений TCP для различных даемонов,
запускаемых посредством inetd.Разноеdaytime,
time,
echo,
discard,
chargen и
auth все являются услугами, предоставляемыми
самим inetd.Сервис auth предоставляет
идентификационные сетевые услуги
и поддается настройке; прочие сервисы ненастраиваемы.Обратитесь к справочной странице по &man.inetd.8; для получения
более подробной информации.TomRhodesРеорганизация и улучшения BillSwingleТекст создал Network File System (NFS)NFSКроме поддержки многих прочих типов файловых систем, во FreeBSD
встроена поддержка сетевой файловой системы (Network File System),
известной как NFS. NFS позволяет
системе использовать каталоги и файлы совместно с другими машинами,
посредством сети. Посредством NFS пользователи и
программы могут получать доступ к файлам на удалённых системах точно так
же, как если бы это были файлы на собственных дисках.Вот некоторые из наиболее заметных преимуществ, которые даёт
использование NFS:Отдельно взятые рабочие станции используют меньше собственного
дискового пространства, так как совместно используемые данные могут
храниться на одной отдельной машине и быть доступными для других
машин в сети.Пользователям не нужно иметь домашние каталоги, отдельные
для каждой машины в вашей сети. Домашние каталоги могут
располагаться на сервере NFS и их можно сделать
доступными отовсюду в сети.Устройства хранения информации, такие, как дискеты, приводы
CD-ROM и устройства &iomegazip;, могут использоваться другими машинами в
сети. Это может привести к уменьшению переносимых устройств хранения
информации в сети.Как работает NFSNFS строится по крайней мере из двух основных
частей: сервера и одного или большего количества клиентов. Клиент
обращается к данным, находящимся на сервере, в режиме удалённого
доступа. Для того, чтобы это нормально функционировало, нужно
настроить и запустить несколько процессов.На сервере работают следующие даемоны:NFSсерверфайл серверUNIX клиентыrpcbindmountdnfsdДаемонОписаниеnfsdДаемон NFS, обслуживающий запросы от
клиентов NFS.mountdДаемон монтирования NFS, который
выполняет запросы, передаваемые ему от &man.nfsd.8;.rpcbindЭтот даемон позволяет клиентам
NFS определить порт, используемый сервером
NFS.Клиент может запустить также даемон, называемый
nfsiod. nfsiod
обслуживает запросы, поступающие от сервера от сервера
NFS. Он необязателен, увеличивает
производительность, однако для нормальной и правильной работы не
требуется. Для получения дополнительной информации обратитесь к
разделу справочной системы о &man.nfsiod.8;.Настройка NFSNFSнастройкаНастройка NFS является достаточно незамысловатым
процессом. Все процессы, которые должны быть запущены, могут быть
запущены во время загрузки посредством нескольких модификаций в
вашем файле /etc/rc.conf.Проверьте, что на NFS-сервере в файле
/etc/rc.conf имеются такие строки:rpcbind_enable="YES"
nfs_server_enable="YES"
nfs_server_flags="-u -t -n 4"
mountd_flags="-r"mountd запускается автоматически, если включена
функция сервера NFS.На клиенте убедитесь, что в файле /etc/rc.conf
присутствует такой параметр:nfs_client_enable="YES"Файл /etc/exports определяет, какие
файловые системы на вашем сервере NFS будут
экспортироваться (иногда их называют совместно
используемыми). Каждая строка в
/etc/exports задаёт файловую систему, которая
будет экспортироваться и какие машины будут иметь к ней доступ. Кроме
машин, имеющих доступ, могут задаваться другие параметры, влияющие на
характеристики доступа. Имеется полный набор параметров,
которые можно использовать, но здесь пойдёт речь лишь о некоторых из
них. Описания остальных параметров можно найти на страницах справочной
системы по &man.exports.5;.Вот несколько примерных строк из файла
/etc/exports:NFSпримеры экспортированияВ следующих примерах даётся общая идея того, как экспортировать
файловые системы, хотя конкретные параметры могут отличаться в
зависимости от ваших условий и конфигурации сети. К примеру, чтобы
экспортировать каталог /cdrom для трёх машин,
находящихся в том же самом домене, что и сервер (поэтому отсутствует
доменное имя для каждой машины) или для которых имеются записи в
файле /etc/hosts. Флаг
указывает на использование экспортируемой файловой
системы в режиме только чтения. С этим флагом удалённая система не
сможет никоим образом изменить экспортируемую файловую систему./cdrom -ro host1 host2 host3В следующей строке экспортируется файловая система
/home, которая становится доступной трем хостам,
указанным по их IP-адресам. Это полезно, если у вас есть собственная
сеть без настроенного сервера DNS. Как вариант,
файл /etc/hosts может содержать внутренние имена
хостов; пожалуйста, обратитесь к справочную систему по &man.hosts.5;
для получения дополнительной информации. Флаг
позволяет рассматривать подкаталоги в
качестве точек монтирования. Другими словами, это не монтирование
подкаталогов, но разрешение клиентам монтировать только каталоги,
которые им требуются или нужны./home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4В строке, приведённой ниже, файловая система
/a экспортируется таким образом, что она доступна
двум клиентам из других доменов. Параметр
позволяет пользователю
root удалённой системы осуществлять запись на
экспортируемую файловую систему как пользователь
root. Если параметр
-maproot=root не задан,
то даже если пользователь имеет права доступа root
на удалённой системе, он не сможет модифицировать
файлы на экспортированной файловой системе./a -maproot=root host.example.com box.example.orgДля того, чтобы клиент смог обратиться к экспортированной файловой
системе, он должен иметь права сделать это. Проверьте, что клиент
указан в вашем файле /etc/exports.В файле /etc/exports каждая строка содержит
информацию об экспортировании для отдельной файловой системы для
отдельно взятого хоста. Удалённый хост может быть задан только
один раз для каждой файловой системы, и может иметь
только одну запись, используемую по умолчанию, для каждой локальной
файловой системы. К примеру, предположим, что
/usr является отдельной файловой системой.
Следующий /etc/exports будет некорректен:# Invalid when /usr is one file system
/usr/src client
/usr/ports clientОдна файловая система, /usr, имеет две
строки, задающие экспортирование для одного и того же хоста,
client. Правильный формат в этом случае таков:/usr/src /usr/ports clientСвойства отдельной файловой системы, экспортируемой некоторому
хосту, должны задаваться в одной строке. Строки без указания клиента
воспринимаются как отдельный хост. Это ограничивает то, как вы можете
экспортировать файловые системы, но для большинства это не
проблема.Ниже приведён пример правильного списка экспортирования, где
/usr и /exports являются
локальными файловыми системами:# Экспортируем src и ports для client01 и client02, но
# только client01 имеет права пользователя root на них
/usr/src /usr/ports -maproot=root client01
/usr/src /usr/ports client02
# Клиентские машины имеют пользователя root и могут монтировать всё в
# каталоге /exports. Кто угодно может монтировать /exports/obj в режиме чтения
/exports -alldirs -maproot=root client01 client02
/exports/obj -roДаемон mountd должен быть
проинформирован об изменении файла /etc/exports,
чтобы изменения вступили в силу. Это может быть достигнуто посылкой
сигнала HUP процессу mountd:&prompt.root; kill -HUP `cat /var/run/mountd.pid`или вызовом скрипта mountd подсистемы &man.rc.8;
с соответствующим параметром:&prompt.root; /etc/rc.d/mountd onereloadЗа подробной информацией о работе скриптов rc.d обращайтесь к
.Как вариант, при перезагрузке FreeBSD всё настроится правильно.
Хотя выполнять перезагрузку вовсе не обязательно. Выполнение следующих
команд пользователем root запустит всё, что
нужно.На сервере NFS:&prompt.root; rpcbind
&prompt.root; nfsd -u -t -n 4
&prompt.root; mountd -rНа клиенте NFS:&prompt.root; nfsiod -n 4Теперь всё должно быть готово к реальному монтированию удалённой
файловой системы. В приводимых примерах сервер будет носить имя
server, а клиент будет носить имя
client. Если вы только хотите
временно смонтировать удалённую файловую систему, или всего лишь
протестировать ваши настройки, то просто запустите команды, подобные
приводимым здесь, работая как пользователь root на
клиентской машине:NFSмонтирование&prompt.root; mount server:/home /mntПо этой команде файловая система /home на
сервере будет смонтирована в каталог /mnt на
клиенте. Если всё настроено правильно, вы сможете войти в каталог
/mnt на клиенте и увидеть файлы, находящиеся на
сервере.Если вы хотите автоматически монтировать удалённую файловую
систему при каждой загрузке компьютера, добавьте файловую систему в
/etc/fstab. Вот пример:server:/home /mnt nfs rw 0 0На страницах справочной системы по &man.fstab.5; перечислены все
доступные параметры.Блокировка файловНекоторым приложениям (например, mutt)
для корректной работы необходима возможность блокировки файлов
(file locking). При работе по NFS блокировка
файлов может осуществляться при помощи демона
rpc.lockd. Чтобы его активировать, добавьте
следующие записи в файл /etc/rc.conf как
на клиенте, так и на сервере NFS (предполагается,
что и клиент, и сервер уже сконфигурированы):rpc_lockd_enable="YES"
rpc_statd_enable="YES"Запустите демоны, выполнив следующие команды:&prompt.root; /etc/rc.d/lockd start
&prompt.root; /etc/rc.d/statd startЕсли нет необходимости в настоящей блокировке файлов между
сервером NFS и клиентами, то клиент
NFS может быть настроен так, чтобы выполнять
блокировки файлов локально, для чего необходимо передать опцию
команде &man.mount.nfs.8;. За подробностями
обратитесь к странице справочника &man.mount.nfs.8;.Практическое использованиеУ NFS есть много вариантов практического
применения. Ниже приводится несколько наиболее широко распространённых
способов её использования:NFSиспользованиеНастройка несколько машин для совместного использования CDROM
или других носителей. Это более дешёвый и зачастую более удобный
способ установки программного обеспечения на несколько машин.В больших сетях может оказаться более удобным настроить
центральный сервер NFS, на котором размещаются
все домашние каталоги пользователей. Эти домашние каталоги могут
затем экспортироваться в сеть так, что пользователи всегда будут
иметь один и тот же домашний каталог вне зависимости от того, на
какой рабочей станции они работают.Несколько машин могут иметь общий каталог
/usr/ports/distfiles. Таким образом, когда
вам нужно будет установить порт на несколько машин, вы сможете быстро
получить доступ к исходным текстам без их загрузки на каждой
машине.WylieStilwellТекст предоставил ChernLeeТекст переписал Автоматическое монтирование с
amdamdдаемон автоматического монтирования&man.amd.8; (даемон автоматического монтирования) автоматически
монтирует удалённую файловую систему,
как только происходит обращение к файлу или каталогу в этой файловой
системе. Кроме того, файловые системы, которые были неактивны
некоторое время, будут автоматически размонтированы даемоном
amd. Использование
amd является простой альтернативой
статическому монтированию, так как в последнем случае обычно всё должно
быть описано в файле /etc/fstab.amd работает, сам выступая как сервер
NFS для каталогов /host и
/net. Когда происходит обращение к файлу в одном
из этих каталогов, amd ищет соответствующий
удаленный ресурс для монтирования и автоматически его монтирует.
/net используется для монтирования экспортируемой
файловой системы по адресу IP, когда как каталог
/host используется для монтирования ресурса по
удаленному имени хоста.Обращение к файлу в каталоге
/host/foobar/usr укажет
amd на выполнение попытки монтирования
ресурса /usr, который находится на хосте
foobar.Монтирование ресурса при помощи
amdВы можете посмотреть доступные для монтирования ресурсы
отдалённого хоста командой showmount. К примеру,
чтобы посмотреть ресурсы хоста с именем foobar, вы
можете использовать:&prompt.user; showmount -e foobar
Exports list on foobar:
/usr 10.10.10.0
/a 10.10.10.0
&prompt.user; cd /host/foobar/usrКак видно из примера, showmount показывает
/usr как экспортируемый ресурс. При переходе в
каталог /host/foobar/usr даемон
amd пытается разрешить имя хоста
foobar и автоматически смонтировать требуемый
ресурс.amd может быть запущен из скриптов
начальной загрузки, если поместить такую строку в файл
/etc/rc.conf:amd_enable="YES"Кроме того, даемону amd могут быть
переданы настроечные флаги через параметр
amd_flags. По умолчанию
amd_flags настроен следующим образом:amd_flags="-a /.amd_mnt -l syslog /host /etc/amd.map /net /etc/amd.map"Файл /etc/amd.map задает опции, используемые
по умолчанию при монтировании экспортируемых ресурсов. В файле
/etc/amd.conf заданы настройки некоторых более
сложных возможностей amd.Обратитесь к справочным страницам по &man.amd.8; и &man.amd.conf.5;
для получения более полной информации.JohnLindТекст предоставил Проблемы взаимодействия с другими системамиНекоторые сетевые адаптеры для систем PC с шиной ISA имеют
ограничения, которые могут привести к серьезным проблемам в сети, в
частности, с NFS. Эти проблемы не специфичны для FreeBSD, однако
эту систему они затрагивают.Проблема, которая возникает практически всегда при работе по сети
систем PC (FreeBSD) с высокопроизводительными рабочими станциями,
выпущенными такими производителями, как Silicon Graphics, Inc. и Sun
Microsystems, Inc. Монтирование по протоколу NFS будет работать
нормально, и некоторые операции также будут выполняться успешно, но
неожиданно сервер окажется недоступным для клиент, хотя запросы к и
от других систем будут продолжаться обрабатываться. Такое встречается
с клиентскими системами, не зависимо от того, является ли клиент
машиной с FreeBSD или рабочей станцией. Во многих системах при
возникновении этой проблемы нет способа корректно завершить работу
клиента. Единственным выходом зачастую является холодная перезагрузка
клиента, потому что ситуация с NFS не может быть разрешена.Хотя правильным решением является установка более
производительного и скоростного сетевого адаптера на систему FreeBSD,
имеется простое решение, приводящее к удовлетворительным результатам.
Если система FreeBSD является сервером, укажите
параметр на клиенте при монтировании. Если
система FreeBSD является клиентом, то смонтируйте
файловую систему NFS с параметром . Эти
параметры могут быть заданы в четвертом поле записи в файле
fstab клиента при автоматическом монтировании,
или при помощи параметра в команде &man.mount.8; при
монтировании вручную.Нужно отметить, что имеется также другая проблема, ошибочно
принимаемая за приведенную выше, когда серверы и клиенты NFS находятся
в разных сетях. Если это тот самый случай,
проверьте, что ваши маршрутизаторы пропускают
нужную информацию UDP, в противном случае вы
ничего не получите, что бы вы ни предпринимали.В следующих примерах fastws является именем хоста
(интерфейса) высокопроизводительной рабочей станции, а
freebox является именем хоста (интерфейса) системы
FreeBSD со слабым сетевым адаптером. Кроме того,
/sharedfs будет являться экспортируемой через NFS
файловой системой (обратитесь к страницам справочной системы по команде
&man.exports.5;), а /project будет точкой
монтирования экспортируемой файловой системы на клиенте. В любом
случае, отметьте, что для вашего приложения могут понадобиться
дополнительные параметры, такие, как ,
или .Пример системы FreeBSD (freebox) как клиента
в файле /etc/fstab на машине
freebox:fastws:/sharedfs /project nfs rw,-r=1024 0 0Команда, выдаваемая вручную на машине
freebox:&prompt.root; mount -t nfs -o -r=1024 fastws:/sharedfs /projectПример системы FreeBSD в качестве сервера в файле
/etc/fstab на машине
fastws:freebox:/sharedfs /project nfs rw,-w=1024 0 0Команда, выдаваемая вручную на машине
fastws:&prompt.root; mount -t nfs -o -w=1024 freebox:/sharedfs /projectПрактически все 16-разрядные сетевые адаптеры позволят работать
без указанных выше ограничений на размер блоков при чтении и
записи.Для тех, кто интересуется, ниже описывается, что же происходит в
при появлении этой ошибки, и объясняется, почему ее невозможно
устранить. Как правило, NFS работает с блоками размером
8 килобайт (хотя отдельные фрагменты могут иметь меньшие
размеры). Так, пакет Ethernet имеет максимальный размер около
1500 байт, то
блок NFS разбивается на несколько пакетов Ethernet, хотя
на более высоком уровне это все тот же единый блок, который должен быть
принят, собран и подтвержден как один блок.
Высокопроизводительные рабочие станции могут посылать пакеты, которые
соответствуют одному блоку NFS, сразу друг за другом, насколько это
позволяет делать стандарт. На слабых, низкопроизводительных адаптерах
пакеты, пришедшие позже, накладываются поверх ранее пришедших пакетов
того же самого блока до того, как они могут быть переданы хосту и
блок как единое целое не может быть собран или подтвержден. В
результате рабочая станция входит в ситуацию тайм-аута и пытается
повторить передачу, но уже с полным блоком в 8 КБ, и процесс будет
повторяться снова, до бесконечности.Задав размер блока меньше размера пакета Ethernet, мы достигаем
того, что любой полностью полученный пакет Ethernet может быть
подтвержден индивидуально, и избежим тупиковую ситуацию.Наложение пакетов может все еще проявляться, когда
высокопроизводительные рабочие станции сбрасывают данные на PC-систему,
однако повторение этой ситуации не обязательно с более скоростными
адаптерами с блоками NFS. Когда происходит наложение,
затронутые блоки будут переданы снова, и скорее всего, они будут
получены, собраны и подтверждены.BillSwingleТекст создал EricOgrenВнёс добавления UdoErdelhoffNetwork Information System (NIS/YP)Что это такое?NISSolarisHP-UXAIXLinuxNetBSDOpenBSDNIS,
что является сокращением от Network Information Services
(Сетевые Информационные Службы), которые были разработаны компанией
Sun Microsystems для централизованного администрирования систем &unix;
(изначально &sunos;). В настоящее время эти службы практически стали
промышленным стандартом; все основные &unix;-подобные системы
(&solaris;, HP-UX, &aix;, Linux, NetBSD, OpenBSD, FreeBSD и так далее)
поддерживают NIS.yellow pagesNISNIS
первоначально назывались Yellow Pages (или yp), но из-за
проблем с торговым знаком Sun изменила это название. Старое название
(и yp) всё ещё часто употребляется.NISдоменыЭто система клиент/сервер на основе вызовов RPC, которая позволяет
группе машин в одном домене NIS совместно использовать общий набор
конфигурационных файлов. Системный администратор может настроить
клиентскую систему NIS только с минимальной настроечной информацией, а
затем добавлять, удалять и модифицировать настроечную информацию из
одного места.Windows NTЭто похоже на систему доменов &windowsnt;; хотя их внутренние
реализации не так уж и похожи, основные функции сравнимы.Термины/программы, о которых вы должны знатьСуществует несколько терминов и некоторое количество
пользовательских программ, которые будут нужны, когда вы будете
пытаться сделать NIS во FreeBSD, и в случае создания сервера, и
в случае работы в качестве клиента NIS:rpcbindportmapТерминОписаниеИмя домена NISГлавный сервер NIS и все его клиенты (включая вторичные
серверы), имеют доменное имя NIS. Как и в случае с именем
домена &windowsnt;, имя домена NIS не имеет ничего общего с
DNS.rpcbindДля обеспечения работы RPC (Remote Procedure Call,
Удалённого Вызова Процедур, сетевого протокола, используемого
NIS), должен быть запущен даемон rpcbind.
Если даемон rpcbind не запущен, невозможно
будет запустить сервер NIS, или работать как
NIS-клиент.ypbindСвязывает
NIS-клиента с его NIS-сервером. Он определяет имя NIS-домена
системы, и при помощи RPC подключается к серверу.
ypbind является основой клиент-серверного
взаимодействия в среде NIS; если на клиентской машине
программа ypbind перестанет работать, то
эта машина не сможет получить доступ к серверу NIS.ypservПрограмма ypserv, которая должна
запускаться только на серверах NIS: это и есть
сервер NIS. Если &man.ypserv.8; перестанет работать, то
сервер не сможет отвечать на запросы NIS (к счастью, на этот
случай предусмотрен вторичный сервер). Есть несколько
реализаций NIS (к FreeBSD это не относится), в которых не
производится попыток подключиться к другому серверу, если ранее
используемый сервер перестал работать. Зачастую единственным
средством, помогающим в этой ситуации, является перезапуск
серверного процесса (или сервера полностью) или процесса
ypbind на клиентской машине.rpc.yppasswddПрограмма rpc.yppasswdd, другой
процесс, который запускается только на главных NIS-серверах:
это даемон, позволяющий клиентам NIS изменять свои
пароли NIS. Если этот даемон не запущен, то пользователи
должны будут входить на основной сервер NIS и там менять свои
пароли.Как это работает?В системе NIS существует три типа хостов: основные (master)
серверы, вторичные (slave) серверы и клиентские машины. Серверы
выполняют роль централизованного хранилища информации о конфигурации
хостов. Основные серверы хранят оригиналы этой информации, когда как
вторичные серверы хранят ее копию для обеспечения избыточности.
Клиенты связываются с серверами, чтобы предоставить им эту
информацию.Информация во многих файлах может совместно использоваться
следующим образом. Файлы master.passwd,
group и hosts используются
совместно через NIS. Когда процессу, работающему на клиентской машине,
требуется информация, как правило, находящаяся в этих файлах локально,
то он делает запрос к серверу NIS, с которым связан.Типы машин
-
- NIS
- главный сервер
-
-
- Основной сервер NIS.
+ Основной сервер NISNISглавный сервер.
Такой сервер, по аналогии с первичным контроллером домена
&windowsnt;, хранит файлы, используемые всеми клиентами NIS. Файлы
passwd, group и
различные другие файлы, используемые клиентами NIS, находятся
на основном сервере.Возможно использование одной машины в качестве сервера для
более чем одного домена NIS. Однако, в этом введении такая
ситуация не рассматривается, и предполагается менее масштабное
использование NIS.
-
- NIS
- вторичный сервер
-
-
- Вторичные серверы NIS. Похожие на
+ Вторичные серверы NISNISвторичный сервер. Похожие на
вторичные контроллеры доменов &windowsnt;, вторичные серверы
NIS содержат копии оригинальных файлов данных NIS. Вторичные
серверы NIS обеспечивают избыточность, что нужно в критичных
приложениях. Они также помогают распределять нагрузку на
основной сервер: клиенты NIS всегда подключаются к тому серверу
NIS, который ответил первым, в том числе и к вторичным
серверам.
-
- NIS
- клиент
-
-
- Клиенты NIS.
+ Клиенты NISNISклиент.
Клиенты NIS, как и большинство рабочих станций &windowsnt;,
аутентифицируются на сервере NIS (или на контроллере домена
&windowsnt; для рабочих станций &windowsnt;) во время
входа в систему.Использование NIS/YPВ этом разделе приводится пример настройки NIS.ПланированиеДавайте предположим, что вы являетесь администратором в маленькой
университетской лаборатории. В настоящий момент в этой лаборатории
с 15 машинами отсутствует единая точка администрирования; на каждой
машине имеются собственные файлы /etc/passwd и
/etc/master.passwd. Эти файлы синхронизируются
друг с другом только вручную; сейчас, когда вы добавляете
пользователя в лаборатории, вы должны выполнить команду
adduser на всех 15 машинах. Понятно, что такое
положение вещей нужно исправлять, так что вы решили перевести
сеть на использование NIS, используя две машины в качестве
серверов.Итак, конфигурация лаборатории сейчас выглядит примерно
так:Имя машиныIP-адресРоль машиныellington10.0.0.2Основной сервер NIScoltrane10.0.0.3Вторичный сервер NISbasie10.0.0.4Факультетская рабочая станцияbird10.0.0.5Клиентская машинаcli[1-11]10.0.0.[6-17]Другие клиентские машиныЕсли вы определяете схему NIS первый раз, ее нужно хорошо
обдумать. Вне зависимости от размеров вашей сети, есть несколько
ключевых моментов, которые требуют принятия решений.Выбор имени домена NISNISимя доменаЭто имя не должно быть именем домена, которое
вы использовали. Более точно это имя называется именем
домена NIS. Когда клиент рассылает запросы на получение
информации, он включает в них имя домена NIS, частью которого
является. Таким способом многие сервера в сети могут указать,
какой сервер на какой запрос должен отвечать. Думайте о домене
NIS как об имени группы хостов, которые каким-то образом
связаны.Некоторые организации в качестве имени домена NIS используют
свой домен Интернет. Это не рекомендуется, так как может вызвать
проблемы в процессе решения сетевых проблем. Имя домена NIS должно
быть уникальным в пределах вашей сети и хорошо, если оно будет
описывать группу машин, которые представляет. Например,
художественный отдел в компании Acme Inc. может находиться в
домене NIS с именем acme-art. В нашем примере
положим, что мы выбрали имя test-domain.SunOSНесмотря на это, некоторые операционные системы (в частности,
&sunos;) используют свое имя домена NIS в качестве имени домена
Интернет. Если одна или более машин в вашей сети имеют такие
ограничения, вы обязаны использовать имя
домена Интернет в качестве имени домена NIS.Требования к серверуЕсть несколько вещей, которые нужно иметь в виду при выборе
машины для использования в качестве сервера NIS. Одной из
обескураживающей вещью, касающейся NIS, является уровень
зависимости клиентов от серверов. Если клиент не может
подключиться к серверу своего домена NIS, зачастую машину просто
становится нельзя использовать. Отсутствие информации о
пользователях и группах приводит к временной остановке работы
большинства систем. Зная это, вы должны выбрать машину, которая
не должна подвергаться частым перезагрузкам и не используется
для разработки. Сервер NIS в идеале должен быть отдельно стоящей
машиной, единственным целью в жизни которой является быть сервером
NIS. Если вы работаете в сети, которая не так уж сильно загружена,
то можно поместить сервер NIS на машине, на которой запущены и
другие сервисы, просто имейте в виду, что если сервер NIS
становится недоступным, то это негативно отражается на
всех клиентах NIS.Серверы NISОригинальные копии всей информации NIS хранится на единственной
машине, которая называется главным сервером NIS. Базы данных,
которые используются для хранения информации, называются картами NIS.
Во FreeBSD эти карты хранятся в
/var/yp/[domainname], где
[domainname] является именем обслуживаемого
домена NIS. Один сервер NIS может поддерживать одновременно
несколько доменов, так что есть возможность иметь несколько таких
каталогов, по одному на каждый обслуживаемый домен. Каждый домен
будет иметь свой собственный независимый от других набор карт.Основной и вторичный серверы обслуживают все запросы NIS с
помощью даемона ypserv. ypserv
отвечает за получение входящих запросов от клиентов NIS,
распознавание запрашиваемого домена и отображение имени в путь к
соответствующему файлы базы данных, а также передаче информации из
базы данных обратно клиенту.Настройка основного сервера NISNISнастройка сервераНастройка основного сервера NIS может оказаться сравнительно
простой, в зависимости от ваших потребностей. В поставку FreeBSD
сразу включена поддержка NIS. Все, что вам нужно, это добавить
следующие строки в файл /etc/rc.conf, а
FreeBSD сделает за вас всё остальное..nisdomainname="test-domain"
В этой строке задается имя домена NIS, которое будет
test-domain, еще до настройки сети
(например, после перезагрузки).nis_server_enable="YES"
Здесь указывается FreeBSD на запуск процессов серверов NIS,
когда дело доходит до сетевых настроек.nis_yppasswdd_enable="YES"
Здесь указывается на запуск даемона
rpc.yppasswdd, который, как это отмечено
выше, позволит пользователям менять свой пароль NIS с
клиентской машины.В зависимости от ваших настроек NIS, вам могут понадобиться
дополнительные строки. Обратитесь к разделу о серверах NIS,
которые являются и клиентами NIS ниже для получения
подробной информации.После добавления вышеприведенных строк, запустите команду
/etc/netstart, работая как администратор. По
ней произойдет настройка всего, при этом будут использоваться
значения, заданные в файле /etc/rc.conf.
И наконец, перед инициализацией карт NIS, запустите вручную
демон ypserv:&prompt.root; /etc/rc.d/ypserv startИнициализация карт NISNISкартыКарты NIS являются файлами баз данных,
которые хранятся в каталоге /var/yp.
Они генерируются из конфигурационных файлов, находящихся в каталоге
/etc основного сервера NIS, за одним
исключением: файл /etc/master.passwd.
На это есть весомая причина, вам не нужно распространять пароли
пользователя root и других административных
пользователей на все серверы в домене NIS. По этой причине, прежде
чем инициализировать карты NIS, вы должны сделать вот что:&prompt.root; cp /etc/master.passwd /var/yp/master.passwd
&prompt.root; cd /var/yp
&prompt.root; vi master.passwdВы должны удалить все записи, касающиеся системных
пользователей (bin, tty,
kmem, games и так далее), а
также записи, которые вы не хотите распространять клиентам NIS
(например, root и другие пользователи с UID,
равным 0 (администраторы)).Проверьте, чтобы файл
/var/yp/master.passwd был недоступен для
записи ни для группы, ни для остальных пользователей (режим
доступа 600)! Воспользуйтесь командой chmod,
если это нужно.Tru64 UNIXКогда с этим будет покончено, самое время инициализировать
карты NIS! В поставку FreeBSD включен скрипт с именем
ypinit, который делает это (обратитесь к его
справочной странице за дополнительной информацией). Отметьте, что
этот скрипт имеется в большинстве операционных систем &unix;, но не
во всех. В системе Digital Unix/Compaq Tru64 UNIX он называется
ypsetup. Так как мы генерируем карты для
главного сервера NIS, то при вызове программы
ypinit мы передаем ей параметр
. Для генерации карт NIS в предположении, что
вы уже сделали шаги, описанные выше, выполните следующее:ellington&prompt.root; ypinit -m test-domain
Server Type: MASTER Domain: test-domain
Creating an YP server will require that you answer a few questions.
Questions will all be asked at the beginning of the procedure.
Do you want this procedure to quit on non-fatal errors? [y/n: n] n
Ok, please remember to go back and redo manually whatever fails.
If you don't, something might not work.
At this point, we have to construct a list of this domains YP servers.
rod.darktech.org is already known as master server.
Please continue to add any slave servers, one per line. When you are
done with the list, type a <control D>.
master server : ellington
next host to add: coltrane
next host to add: ^D
The current list of NIS servers looks like this:
ellington
coltrane
Is this correct? [y/n: y] y
[..вывод при генерации карт..]
NIS Map update completed.
ellington has been setup as an YP master server without any errors.Программа ypinit должна была создать файл
/var/yp/Makefile из
/var/yp/Makefile.dist. При создании этого
файла предполагается, что вы работаете в окружении с единственным
сервером NIS и только с машинами FreeBSD. Так как в домене
test-domain имеется также и вторичный сервер,
то вы должны отредактировать файл
/var/yp/Makefile:ellington&prompt.root; vi /var/yp/MakefileВы должны закомментировать строку, в которой указаноNOPUSH = "True"(она уже не раскомментирована).Настройка вторичного сервера NISNISвторичный серверНастройка вторичного сервера NIS осуществляется ещё проще,
чем настройка главного сервера. Войдите на вторичный сервер и
отредактируйте файл /etc/rc.conf точно также,
как вы делали это ранее. Единственным отличием является то, что
при запуске программы ypinit мы теперь должны
использовать опцию . Применение опции
требует также указание имени главного сервера
NIS, так что наша команда должна выглядеть так:coltrane&prompt.root; ypinit -s ellington test-domain
Server Type: SLAVE Domain: test-domain Master: ellington
Creating an YP server will require that you answer a few questions.
Questions will all be asked at the beginning of the procedure.
Do you want this procedure to quit on non-fatal errors? [y/n: n] n
Ok, please remember to go back and redo manually whatever fails.
If you don't, something might not work.
There will be no further questions. The remainder of the procedure
should take a few minutes, to copy the databases from ellington.
Transferring netgroup...
ypxfr: Exiting: Map successfully transferred
Transferring netgroup.byuser...
ypxfr: Exiting: Map successfully transferred
Transferring netgroup.byhost...
ypxfr: Exiting: Map successfully transferred
Transferring master.passwd.byuid...
ypxfr: Exiting: Map successfully transferred
Transferring passwd.byuid...
ypxfr: Exiting: Map successfully transferred
Transferring passwd.byname...
ypxfr: Exiting: Map successfully transferred
Transferring group.bygid...
ypxfr: Exiting: Map successfully transferred
Transferring group.byname...
ypxfr: Exiting: Map successfully transferred
Transferring services.byname...
ypxfr: Exiting: Map successfully transferred
Transferring rpc.bynumber...
ypxfr: Exiting: Map successfully transferred
Transferring rpc.byname...
ypxfr: Exiting: Map successfully transferred
Transferring protocols.byname...
ypxfr: Exiting: Map successfully transferred
Transferring master.passwd.byname...
ypxfr: Exiting: Map successfully transferred
Transferring networks.byname...
ypxfr: Exiting: Map successfully transferred
Transferring networks.byaddr...
ypxfr: Exiting: Map successfully transferred
Transferring netid.byname...
ypxfr: Exiting: Map successfully transferred
Transferring hosts.byaddr...
ypxfr: Exiting: Map successfully transferred
Transferring protocols.bynumber...
ypxfr: Exiting: Map successfully transferred
Transferring ypservers...
ypxfr: Exiting: Map successfully transferred
Transferring hosts.byname...
ypxfr: Exiting: Map successfully transferred
coltrane has been setup as an YP slave server without any errors.
Don't forget to update map ypservers on ellington.Теперь у вас должен быть каталог с именем
/var/yp/test-domain. Копии карт главного
сервера NIS должны быть в этом каталоге. Вы должны удостовериться,
что этот каталог обновляется. Следующие строки в
/etc/crontab вашего вторичного сервера должны
это делать:20 * * * * root /usr/libexec/ypxfr passwd.byname
21 * * * * root /usr/libexec/ypxfr passwd.byuidЭти две строки заставляют вторичный сервер синхронизировать
свои карты с картами главного сервера. Эти строки не являются
обязательными, так как главный сервер автоматически пытается
передать вторичным серверам все изменения в своих картах NIS.
Однако, учитывая важность информации о паролях для клиентов,
зависящих от вторичного сервера, рекомендуется выполнять частые
обновления карт с паролями. Это особенно важно в загруженных
сетях, в которых обновления карт могут не всегда завершаться
успешно.А теперь точно также запустите команду
/etc/netstart на вторичном сервере, по которой
снова выполнится запуск сервера NIS.Клиенты NISКлиент NIS выполняет так называемую привязку к конкретному
серверу NIS при помощи даемона ypbind.
ypbind определяет домен, используемый в системе
по умолчанию (тот, который устанавливается по команде
domainname), и начинает широковещательную рассылку
запросов RPC в локальной сети. В этих запросах указано имя домена,
к серверу которого ypbind пытается осуществить
привязку. Если сервер, который был настроен для обслуживания
запрашиваемого домена, получит широковещательный запрос, он ответит
ypbind, который, в свою очередь запомнит адрес
сервера. Если имеется несколько серверов (например, главный и
несколько вторичных), то ypbind будет использовать
адрес первого ответившего. С этого момента клиентская система будет
направлять все свои запросы NIS на этот сервер. Время от времени
ypbind будет пинать сервер для
проверки его работоспособности.
Если на один из тестовых пакетов не удастся получить ответа за
разумное время, то ypbind пометит этот домен как
домен, с которым связка разорвана, и снова начнет процесс посылки
широковещательных запросов в надежде найти другой сервер.Настройка клиента NISNISнастройка клиентаНастройка машины с FreeBSD в качестве клиента NIS достаточно
проста.Отредактируйте файл /etc/rc.conf,
добавив туда следующие строки для того, чтобы задать имя домена
NIS и запустить ypbind во время запуска
сетевых служб:nisdomainname="test-domain"
nis_client_enable="YES"Для импортирования всех возможных учётных записей от сервера
NIS, удалите все записи пользователей из вашего файла
/etc/master.passwd и воспользуйтесь
командой vipw для добавления следующей строки
в конец файла:+:::::::::Эта строчка даст всем пользователям с корректной учетной
записью в картах учетных баз пользователей доступ к этой
системе. Есть множество способов настроить ваш клиент NIS,
изменив эту строку. Посмотрите ниже текст, касающийся сетевых групп, чтобы
получить более подробную информацию. Дополнительная информация
для изучения находится в книге издательства O'Reilly под
названием Managing NFS and NIS.Вы должны оставить хотя бы одну локальную запись (то есть
не импортировать ее через NIS) в вашем
/etc/master.passwd и эта запись должна
быть также членом группы wheel. Если
с NIS что-то случится, эта запись может использоваться для
удаленного входа в систему, перехода в режим администратора и
исправления неисправностей.Для импортирования всех возможных записей о группах с
сервера NIS, добавьте в ваш файл
/etc/group такую строчку:+:*::Для немедленного запуска клиента NIS выполните следующую
команду с правами пользователя root:&prompt.root; /etc/netstart
&prompt.root; /etc/rc.d/ypbind startПосле завершения выполнения этих шагов у вас должно получиться
запустить команду ypcat passwd и увидеть
карту учетных записей сервера NIS.Безопасность NISВ общем-то любой пользователь, зная имя вашего домена, может
выполнить запрос RPC к &man.ypserv.8; и получить содержимое ваших карт
NIS. Для предотвращения такого неавторизованного обмена &man.ypserv.8;
поддерживает так называемую систему securenets, которая может
использоваться для ограничения доступа к некоторой группе хостов. При
запуске &man.ypserv.8; будет пытаться загрузить информацию, касающуюся
securenets, из файла /var/yp/securenets.Имя каталога зависит от параметра, указанного вместе с опцией
. Этот файл содержит записи, состоящие из
указания сети и сетевой маски, разделенных пробелом. Строчки,
начинающиеся со знака #, считаются комментариями.
Примерный файл securenets может иметь примерно такой вид:# allow connections from local host -- mandatory
127.0.0.1 255.255.255.255
# allow connections from any host
# on the 192.168.128.0 network
192.168.128.0 255.255.255.0
# allow connections from any host
# between 10.0.0.0 to 10.0.15.255
# this includes the machines in the testlab
10.0.0.0 255.255.240.0Если &man.ypserv.8; получает запрос от адреса, который соответствует
одному из этих правил, он будет отрабатывать запрос обычным образом.
Если же адрес не подпадает ни под одно правило, запрос будет
проигнорирован и в журнал будет записано предупреждающее сообщение. Если
файл /var/yp/securenets не существует,
ypserv будет обслуживать соединения от любого
хоста.Программа ypserv также поддерживает пакет программ
TCP Wrapper от Wietse Venema. Это позволяет
администратору для ограничения доступа вместо
/var/yp/securenets использовать конфигурационные
файлы TCP Wrapper.Хотя оба этих метода управления доступом обеспечивают некоторую
безопасность, они, как основанные на проверке привилегированного
порта, оба подвержены атакам типа IP spoofing. Весь
сетевой трафик, связанный с работой NIS, должен блокироваться вашим
брандмауэром.Серверы, использующие файл /var/yp/securenets,
могут быть не в состоянии обслуживать старых клиентов NIS с древней
реализацией протокола TCP/IP. Некоторые из этих реализаций при
рассылке широковещательных запросов устанавливают все биты машинной
части адреса в ноль и/или не в состоянии определить маску подсети при
вычислении адреса широковещательной рассылки. Хотя некоторые из этих
проблем могут быть решены изменением конфигурации клиента, другие
могут привести к отказу от использования
/var/yp/securenets.Использование /var/yp/securenets на сервере
с такой архаичной реализацией TCP/IP является весьма плохой идеей, и
приведёт к потере работоспособности NIS в большой части вашей
сети.TCP WrapperИспользование пакета TCP Wrapper увеличит
время отклика вашего сервера NIS. Дополнительной задержки может
оказаться достаточно для возникновения тайм-аутов в клиентских
программах, особенно в загруженных сетях или с медленными серверами
NIS. Если одна или более ваших клиентских систем страдают от таких
проблем, вы должны преобразовать такие клиентские системы во вторичные
серверы NIS и сделать принудительную их привязку к самим себе.Запрет входа некоторых пользователейВ нашей лаборатории есть машина basie, о которой
предполагается, что она является исключительно факультетской рабочей
станцией. Мы не хотим исключать эту машину из домена NIS, однако
файл passwd на главном сервере NIS содержит
учетные записи как для работников факультета, так и студентов. Что мы
можем сделать?Есть способ ограничить вход некоторых пользователей на этой машине,
даже если они присутствуют в базе данных NIS. Чтобы это сделать, вам
достаточно добавить
-username в конец файла
/etc/master.passwd на клиентской машине, где
username является именем пользователя,
которому вы хотите запретить вход. Рекомендуется сделать это с помощью
утилиты vipw, так как vipw
проверит ваши изменения в /etc/master.passwd, а
также автоматически перестроит базу данных паролей по окончании
редактирования. Например, если мы хотим запретить пользователю
bill осуществлять вход на машине
basie, то мы сделаем следующее:basie&prompt.root; vipw[add -bill to the end, exit]
vipw: rebuilding the database...
vipw: done
basie&prompt.root; cat /etc/master.passwd
root:[password]:0:0::0:0:The super-user:/root:/bin/csh
toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh
daemon:*:1:1::0:0:Owner of many system processes:/root:/sbin/nologin
operator:*:2:5::0:0:System &:/:/sbin/nologin
bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/sbin/nologin
tty:*:4:65533::0:0:Tty Sandbox:/:/sbin/nologin
kmem:*:5:65533::0:0:KMem Sandbox:/:/sbin/nologin
games:*:7:13::0:0:Games pseudo-user:/usr/games:/sbin/nologin
news:*:8:8::0:0:News Subsystem:/:/sbin/nologin
man:*:9:9::0:0:Mister Man Pages:/usr/share/man:/sbin/nologin
bind:*:53:53::0:0:Bind Sandbox:/:/sbin/nologin
uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico
xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/sbin/nologin
pop:*:68:6::0:0:Post Office Owner:/nonexistent:/sbin/nologin
nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/sbin/nologin
+:::::::::
-bill
basie&prompt.root;UdoErdelhoffТекст предоставил Использование сетевых группсетевые группыСпособ, описанный в предыдущем разделе, работает достаточно хорошо,
если вам нужны особые правила для очень малой группы пользователей или
машин. В более крупных сетях вы забудете о
запрете входа определенных пользователей на важные машины или даже
будете настраивать каждую машину по отдельности, теряя таким образом
главное преимущество использования NIS:
централизованное администрирование.Ответом разработчиков NIS на эту проблему являются
сетевые группы. Их назначение и смысл можно
сравнить с обычными группами, используемыми в файловых системах &unix;.
Главное отличие заключается в отсутствии числового идентификатора и
возможности задать сетевую группу включением как пользователей, так и
других сетевых групп.Сетевые группы были разработаны для работы с большими, сложными
сетями с сотнями пользователей и машин. С одной стороны, хорошо, если
вам приходится с такой ситуацией. С другой стороны, эта сложность
делает невозможным описание сетевых групп с помощью простых примеров.
Пример, используемый в дальнейшем, демонстрирует эту проблему.Давайте предположим, что успешное внедрение системы NIS в вашей
лаборатории заинтересовало ваше руководство. Вашим следующим заданием
стало расширение домена NIS для включения в него некоторых других
машин студенческого городка. В двух таблицах перечислены имена
новых машин и пользователей, а также их краткое описание.Имена пользователейОписаниеalpha, betaОбычные служащие IT-департаментаcharlie, deltaПрактиканты IT-департаментаecho, foxtrott, golf, ...Обычные сотрудникиable, baker, ...Проходящие интернатуруИмена машинОписаниеwar, death, famine, pollutionВаши самые важные серверы. Только служащим IT позволяется
входить на эти машины.pride, greed, envy, wrath, lust, slothМенее важные серверы. Все сотрудники департамента IT могут
входить на эти машины.one, two, three, four, ...Обычные рабочие станции. Только
реально нанятым служащим позволяется
использовать эти машины.trashcanОчень старая машина без каких-либо критичных данных. Даже
проходящим интернатуру разрешено ее использовать.Если вы попытаетесь реализовать эти требования, ограничивая
каждого пользователя по отдельности, то вам придется добавить на каждой
машине в файл passwd по одной строчке
-user для каждого пользователя, которому
запрещено входить на эту систему. Если вы забудете даже одну строчку,
у вас могут начаться проблемы. Гораздо проще делать это правильно во
время начальной установки, однако вы постепенно будете
забывать добавлять строчки для новых пользователей во время
повседневной работы. В конце концов, Мерфи был оптимистом.Использование в этой ситуации сетевых групп дает несколько
преимуществ. Нет необходимости описывать по отдельности каждого
пользователя; вы ставите в соответствие пользователю одну или
несколько сетевых групп и разрешаете или запрещаете вход всем членам
сетевой группы. Если вы добавляете новую машину, вам достаточно
определить ограничения на вход для сетевых групп. Если добавляется
новый пользователь, вам достаточно добавить его к одной или большему
числу сетевых групп. Эти изменения независимы друг от друга: нет
больше комбинаций для каждого пользователя и машины.
Если настройка вашей системы NIS тщательно спланирована, то для
разрешения или запрещения доступа к машинам вам нужно будет
модифицировать единственный конфигурационный файл.Первым шагом является инициализация карты NIS по имени netgroup.
Программа &man.ypinit.8; во FreeBSD по умолчанию этой карты не
создаёт, хотя реализация NIS будет её поддерживает, как только она
будет создана. Чтобы создать пустую карту, просто наберитеellington&prompt.root; vi /var/yp/netgroupи начните добавлять содержимое. Например, нам нужно по крайней
мере четыре сетевых группы: сотрудники IT, практиканты IT, обычные
сотрудники и интернатура.IT_EMP (,alpha,test-domain) (,beta,test-domain)
IT_APP (,charlie,test-domain) (,delta,test-domain)
USERS (,echo,test-domain) (,foxtrott,test-domain) \
(,golf,test-domain)
INTERNS (,able,test-domain) (,baker,test-domain)IT_EMP, IT_APP и так далее
являются именами сетевых групп. Несколько слов в скобках служат для
добавления пользователей в группу. Три поля внутри группы обозначают
следующее:Имя хоста или хостов, к которым применимы последующие записи.
Если имя хоста не указано, то запись применяется ко всем хостам.
Если же указывается имя хоста, то вы получите мир темноты, ужаса
и страшной путаницы.Имя учетной записи, которая принадлежит этой сетевой
группе.Домен NIS для учетной записи. Вы можете импортировать в вашу
сетевую группу учетные записи из других доменов NIS, если вы один
из тех несчастных, имеющих более одного домена NIS.Каждое из этих полей может содержать шаблоны, подробности даны в
странице справочника по &man.netgroup.5;.сетевые группыНе нужно использовать имена сетевых групп длиннее 8 символов,
особенно если в вашем домене NIS имеются машины, работающие под
управлением других операционных систем. Имена чувствительны к
регистру; использование заглавных букв для имен сетевых групп
облегчает распознавание пользователей, имен машин и сетевых
групп.Некоторые клиенты NIS (отличные от FreeBSD) не могут работать
с сетевыми группами, включающими большое количество записей.
Например, в некоторых старых версиях &sunos; возникают проблемы, если
сетевая группа содержит более 15 записей. Вы
можете обойти это ограничение, создав несколько подгрупп с 15 или
меньшим количеством пользователей и настоящую сетевую группу,
состоящую из подгрупп:BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...]
BIGGRP2 (,joe16,domain) (,joe17,domain) [...]
BIGGRP3 (,joe31,domain) (,joe32,domain)
BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3Вы можете повторить этот процесс, если вам нужно иметь более 225
пользователей в одной сетевой группе.Активация и распространение вашей карты NIS проста:ellington&prompt.root; cd /var/yp
ellington&prompt.root; makeЭто приведет к созданию трех карт NIS
netgroup, netgroup.byhost и
netgroup.byuser. Воспользуйтесь утилитой
&man.ypcat.1; для проверки доступности ваших новых карт NIS:ellington&prompt.user; ypcat -k netgroup
ellington&prompt.user; ypcat -k netgroup.byhost
ellington&prompt.user; ypcat -k netgroup.byuserВывод первой команды должен соответствовать содержимому файла
/var/yp/netgroup. Вторая команда не выведет
ничего, если вы не зададите сетевые группы, специфичные для хоста.
Третья команда может использоваться пользователем для получения
списка сетевых групп.Настройка клиента достаточно проста. Чтобы настроить сервер
war, вам достаточно запустить &man.vipw.8;
и заменить строку+:::::::::на+@IT_EMP:::::::::Теперь только данные, касающиеся пользователей, определенных в
сетевой группе IT_EMP, импортируются в
базу паролей машины war и только этим
пользователям будет разрешен вход.К сожалению, это ограничение также касается и функции ~ командного
процессора и всех подпрограмм, выполняющих преобразование между
именами пользователей и их числовыми ID. Другими
словами, команда cd ~user
работать не будет, команда ls -l будет выдавать
числовые идентификаторы вместо имён пользователей, а
find . -user joe -print работать откажется, выдавая
сообщение No such user. Чтобы это исправить,
вам нужно будет выполнить импорт всех записей о пользователях
без разрешения на вход на ваши серверы.Это можно сделать, добавив еще одну строку в файл
/etc/master.passwd. Эта строка должна
содержать:+:::::::::/sbin/nologin, что означает
Произвести импортирование всех записей с заменой командного
процессора на /sbin/nologin в импортируемых
записях. Вы можете заменить любое поле в строке с паролем,
указав значение по умолчанию в вашем
/etc/master.passwd.Проверьте, что строка
+:::::::::/sbin/nologin помещена после
+@IT_EMP:::::::::. В противном случае все
пользовательские записи, импортированные из NIS, будут иметь
/sbin/nologin в качестве оболочки.После этого изменения при появлении нового сотрудника IT вам будет
достаточно изменять только одну карту NIS. Вы можете применить
подобный метод для менее важных серверов, заменяя
старую строку +::::::::: в их файлах
/etc/master.passwd на нечто, подобное
следующему:+@IT_EMP:::::::::
+@IT_APP:::::::::
+:::::::::/sbin/nologinСоответствующие строки для обычных рабочих станций могут иметь
такой вид:+@IT_EMP:::::::::
+@USERS:::::::::
+:::::::::/sbin/nologinИ все было прекрасно до того момента, когда через несколько
недель изменилась политика: Департамент IT начал нанимать интернатуру.
Интернатуре в IT позволили использовать обычные рабочие станции и
менее важные серверы; практикантам позволили входить на главные
серверы. Вы создали новую сетевую группу IT_INTERN, добавили в нее
новую интернатуру и начали изменять настройки на всех и каждой
машине... Как говорит старая мудрость: Ошибки в
централизованном планировании приводят к глобальному
хаосу.Возможность в NIS создавать сетевые группы из других сетевых
групп может использоваться для предотвращения подобных ситуаций. Одним
из вариантов является создание сетевых групп на основе ролей.
Например, вы можете создать сетевую группу с именем
BIGSRV для задания ограничений на вход на
важные серверы, другую сетевую группу с именем
SMALLSRV для менее важных серверов и третью
сетевую группу под названием USERBOX для
обычных рабочих станций. Каждая из этих сетевых групп содержит
сетевые группы, которым позволено входить на эти машины. Новые записи
для вашей карты NIS сетевой группы должны выглядеть таким
образом:BIGSRV IT_EMP IT_APP
SMALLSRV IT_EMP IT_APP ITINTERN
USERBOX IT_EMP ITINTERN USERSЭтот метод задания ограничений на вход работает весьма хорошо,
если вы можете выделить группы машин с одинаковыми ограничениями. К
сожалению, такая ситуация может быть исключением, но не правилом. В
большинстве случаев вам нужна возможность определять ограничения на
вход индивидуально для каждой машины.Задание сетевых групп в зависимости от машин является другой
возможностью, которой можно воспользоваться при изменении политики,
описанной выше. При таком развитии событий файл
/etc/master.passwd на каждой машине содержит две
строки, начинающиеся с +. Первая из них добавляет
сетевую группу с учётными записями, которым разрешено входить на эту
машину, а вторая добавляет все оставшиеся учетные записи с
/sbin/nologin в качестве командного процессора.
Хорошей идеей является использование ИМЕНИ МАШИНЫ заглавными буквами
для имени сетевой группы. Другими словами, строки должны иметь такой
вид:+@BOXNAME:::::::::
+:::::::::/sbin/nologinКак только вы завершите эту работу для всех ваших машин, вам не
нужно будет снова модифицировать локальные версии
/etc/master.passwd. Все будущие изменения могут
быть выполнены изменением карты NIS. Вот пример возможной карты
сетевой группы для этого случая с некоторыми полезными
дополнениями:# Сначала определяем группы пользователей
IT_EMP (,alpha,test-domain) (,beta,test-domain)
IT_APP (,charlie,test-domain) (,delta,test-domain)
DEPT1 (,echo,test-domain) (,foxtrott,test-domain)
DEPT2 (,golf,test-domain) (,hotel,test-domain)
DEPT3 (,india,test-domain) (,juliet,test-domain)
ITINTERN (,kilo,test-domain) (,lima,test-domain)
D_INTERNS (,able,test-domain) (,baker,test-domain)
#
# Теперь задаем несколько групп на основе ролей
USERS DEPT1 DEPT2 DEPT3
BIGSRV IT_EMP IT_APP
SMALLSRV IT_EMP IT_APP ITINTERN
USERBOX IT_EMP ITINTERN USERS
#
# И группы для специальных задач
# Открыть пользователям echo и golf доступ к антивирусной машине
SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain)
#
# Сетевые группы, специфичные для машин
# Наши главные серверы
WAR BIGSRV
FAMINE BIGSRV
# Пользователю india необходим доступ к этому серверу
POLLUTION BIGSRV (,india,test-domain)
#
# Этот очень важен и ему требуются большие ограничения доступа
DEATH IT_EMP
#
# Антивирусная машина, упомянутая выше
ONE SECURITY
#
# Ограничить машину единственным пользователем
TWO (,hotel,test-domain)
# [...далее следуют другие группы]Если вы используете какие-либо базы данных для управления
учетными записями ваших пользователей, вы должны смочь создать первую
часть карты с помощью инструментов построения отчетов вашей базы
данных. В таком случае новые пользователи автоматически получат
доступ к машинам.И последнее замечание: Не всегда бывает разумно использовать
сетевые группы на основе машин. Если в студенческих лабораториях вы
используете несколько десятков или даже сотен одинаковых машин, то
вам нужно использовать сетевые группы на основе ролей, а не основе
машин, для того, чтобы размеры карты NIS оставались в разумных
пределах.Важные замечанияЕсть некоторые действия, которые нужно будет выполнять по-другому,
если вы работаете с NIS.Каждый раз, когда вы собираетесь добавить пользователя в
лаборатории, вы должны добавить его только на
главном сервере NIS и обязательно перестроить карты
NIS. Если вы забудете сделать это, то новый
пользователь не сможет нигде войти, кроме как на главном сервере
NIS. Например, если в лаборатории нам нужно добавить нового
пользователя jsmith, мы делаем вот что:&prompt.root; pw useradd jsmith
&prompt.root; cd /var/yp
&prompt.root; make test-domainВместо pw useradd jsmith вы можете также
запустить команду adduser jsmith.Не помещайте административные учетные записи в карты
NIS. Вам не нужно распространять административных
пользователей и их пароли на машины, которые не должны иметь доступ
к таким учётным записям.Сделайте главный и вторичные серверы NIS безопасными
и минимизируйте их время простоя. Если кто-то либо
взломает, либо просто отключит эти машины, то люди без права
входа в лабораторию с легкостью получат доступ.Это основное уязвимое место в любой централизованно
администрируемой системе. Если вы не
защищаете ваши серверы NIS, вы будете иметь дело с толпой
разозлённых пользователей!Совместимость с NIS v1ypserv из поставки FreeBSD имеет
встроенную поддержку для обслуживания клиентов NIS v1. Реализация
NIS
во FreeBSD использует только протокол NIS v2, хотя другие реализации
имеют поддержку протокола v1 для совместимости со старыми системами.
Даемоны ypbind, поставляемые с такими
системами, будут пытаться осуществить привязку к серверу NIS v1, даже
если это им не нужно (и они будут постоянно рассылать широковещательные
запросы в поиске такого сервера даже после получения ответа от сервера
v2). Отметьте, что хотя имеется поддержка обычных клиентских вызовов,
эта версия ypserv не отрабатывает запросы на передачу карт v1;
следовательно, она не может использоваться в качестве главного или
вторичного серверов вместе с другими серверами NIS, поддерживающими
только протокол v1. К счастью, скорее всего, в настоящий момент
такие серверы практически не используются.Серверы NIS, которые также являются клиентами NISОсобое внимание следует уделить использованию
ypserv в домене со
многими серверами, когда серверные машины являются также клиентами
NIS.
Неплохо бы заставить серверы осуществить привязку к самим себе,
запретив рассылку запросов на привязку и возможно, перекрестную
привязку друг к другу. Если один сервер выйдет из строя, а другие
будут зависеть от него, то в результате могут возникнуть странные
ситуации. Постепенно все клиенты попадут в тайм-аут и попытаются
привязаться к другим серверам, но полученная задержка может быть
значительной, а странности останутся, так как серверы снова могут
привязаться друг к другу.Вы можете заставить хост выполнить привязку к конкретному серверу,
запустив команду ypbind с флагом
. Если вы не хотите делать это вручную каждый
раз при перезагрузке
вашего сервера NIS, то можете добавить в файл
/etc/rc.conf такие строки:nis_client_enable="YES" # run client stuff as well
nis_client_flags="-S NIS domain,server"Дополнительную информацию можно найти на странице справки по
&man.ypbind.8;.Форматы паролейNISформаты паролейОдним из общих вопросов, которые возникают в начале работы с NIS,
является вопрос совместимости форматов паролей. Если ваш сервер NIS
использует пароли, зашифрованные алгоритмом DES, то он будет
поддерживать только тех клиентов, что также используют DES. К
примеру, если в вашей сети имеются клиенты NIS, использующие &solaris;,
то вам, скорее всего, необходимо использовать пароли с шифрованием по
алгоритму DES.Чтобы понять, какой формат используют ваши серверы и клиенты,
загляните в файл /etc/login.conf. Если хост
настроен на использование паролей, зашифрованных по алгоритму DES,
то класс default будет содержать запись вроде
следующей:default:\
:passwd_format=des:\
:copyright=/etc/COPYRIGHT:\
[Последующие строки опущены]Другими возможными значениями для passwd_format
являются blf и md5 (для паролей,
шифруемых по стандартам Blowfish и MD5 соответственно).Если вы внесли изменения в файл
/etc/login.conf, то вам также нужно перестроить
базу данных параметров входа в систему, что достигается запуском
следующей команды пользователем root:&prompt.root; cap_mkdb /etc/login.confФормат паролей, которые уже находятся в файле
/etc/master.passwd, не будет изменён до тех пор,
пока пользователь не сменит свой пароль после
перестроения базы данных параметров входа в систему.После этого, чтобы удостовериться в том, что пароли зашифрованы
в том формате, который выбран вами, нужно проверить, что строка
crypt_default в /etc/auth.conf
указывает предпочтение выбранного вами формата паролей. Для этого
поместите выбранный формат первым в списке. Например, при
использовании DES-шифрования паролей строка будет выглядеть так:crypt_default = des blf md5Выполнив вышеперечисленные шаги на каждом из серверов и клиентов
NIS, работающих на FreeBSD, вы можете обеспечить их согласованность
относительно используемого в вашей сети формата паролей. Если у вас
возникли проблемы с аутентификацией клиента NIS, начать
её решать определённо стоит отсюда. Запомните: если вы хотите
использовать сервер NIS в гетерогенной сети, вам, наверное, нужно
будет использовать DES на всех системах в силу того, что это
минимальный общий стандарт.GregSutterТекст написал Автоматическая настройка сети (DHCP)Что такое DHCP?Dynamic Host Configuration ProtocolDHCPInternet Systems Consortium (ISC)DHCP, или Dynamic Host Configuration Protocol (Протокол
Динамической Конфигурации Хостов), описывает порядок, по которому
система может подключиться к сети и получить необходимую информацию
для работы в ней. Во FreeBSD используется
dhclient, импортированный из OpenBSD 3.7.
Вся информация здесь, относительно dhclient относится
либо к ISC, либо к DHCP клиентам. DHCP сервер включён в ISC
дистрибутив.Что описывается в этом разделеВ этом разделе описываются, как компоненты клиентской части ISC или OpenBSD
DHCP клиента, так и компоненты ISC DHCP системы со стороны сервера.
Программа, работающая на клиентской
стороне, dhclient, интегрирована в поставку FreeBSD,
а серверная часть доступна в виде порта net/isc-dhcp42-server. Кроме ссылок ниже,
много полезной информации находится на страницах справочной системы,
описывающих &man.dhclient.8;, &man.dhcp-options.5; и
&man.dhclient.conf.5;.Как это работаетUDPКогда на клиентской машине выполняется программа
dhclient, являющаяся клиентом DHCP, она начинает
широковещательную рассылку запросов на получение настроечной информации.
По умолчанию эти запросы делаются на 68 порт UDP. Сервер отвечает на UDP
67, выдавая клиенту адрес IP и другую необходимую информацию, такую, как
сетевую маску, маршрутизатор и серверы DNS. Вся эта информация даётся в
форме аренды DHCP и верна только определенное время (что
настраивается администратором сервера DHCP). При таком подходе
устаревшие адреса IP тех клиентов, которые больше не подключены к сети,
могут автоматически использоваться повторно.Клиенты DHCP могут получить от сервера очень много информации.
Подробный список находится в странице Справочника
&man.dhcp-options.5;.Интеграция с FreeBSDDHCP клиент от OpenBSD, dhclient, полностью
интегрирован во &os;. Поддержка клиента DHCP есть как в программе
установки, так и в самой системе, что исключает необходимость в
знании подробностей конфигурации сети в любой сети, имеющей сервер
DHCP.sysinstallDHCP поддерживается утилитой sysinstall.
При настройке сетевого интерфейса из программы
sysinstall второй
вопрос, который вам задается: Do you want to try DHCP
configuration of the interface? (Хотите ли вы попробовать
настроить этот интерфейс через DHCP?). Утвердительный ответ
приведёт к запуску программы dhclient, и при удачном
его выполнении к автоматическому заданию информации для настройки
интерфейса.Есть две вещи, которые вы должны сделать для того, чтобы ваша
система использовала DHCP при загрузке:DHCPтребованияУбедитесь, что устройство bpf
включено в компиляцию вашего ядра. Чтобы это сделать, добавьте
строчку device bpf в конфигурационный
файл ядра и перестройте ядро. Более подробная информация о
построении ядер имеется в .Устройство bpf уже является частью
ядра GENERIC, которое поставляется вместе с
FreeBSD, так что, если вы не используете другое ядро, то вам и
не нужно его делать для того, чтобы работал DHCP.Те, кто беспокоится о безопасности, должны иметь в виду, что
устройство bpf является также тем самым
устройством, которое позволяет работать программам-снифферам
пакетов (хотя для этого они должны быть запущены пользователем
root). Наличие устройства
bpfнеобходимо для
использования DHCP, но если вы чересчур беспокоитесь о
безопасности, то вам нельзя добавлять устройство
bpf в ядро только для того, чтобы
в неопределённом будущем использовать DHCP.По умолчанию, конфигурирование &os; по протоколу DHCP
выполняется фоновым процессом, или асинхронно.
Остальные стартовые скрипты продолжают работу не ожидая завершения
процесса конфигурирования, тем самым ускоряя загрузку системы.Фоновое конфигурирование не создает проблем в случае, если
сервер DHCP быстро отвечает на запросы, и процесс конфигурирования
происходит быстро. Однако, в некоторых случаях настройка по DHCP
может длиться значительное время. При этом запуск сетевых сервисов
может потерпеть неудачу, если будет произведен ранее завершения
конфигурирования по DHCP. Запуск DHCP
в синхронном режиме предотвращает проблему,
откладывая выполнение остальных стартовых скриптов до момента
завершения конфигурирования по DHCP.Для осуществления фонового конфигурирования по DHCP
(асинхронный режим), используйте значение
DHCP
в /etc/rc.conf:ifconfig_fxp0="DHCP"Для откладывания запуска стартовых скриптов до завершения
конфигурирования по DHCP (синхронный режим), укажите значение
SYNCDHCP:ifconfig_fxp0="SYNCDHCP"Замените используемое в этих примерах имя
fxp0 на имя интерфейса, который
необходимо сконфигурировать динамически, как это описано
в .Если dhclient в вашей системе находится
в другом месте или если вы хотите задать дополнительные параметры для
dhclient, то также укажите следующее (изменив так,
как вам нужно):dhclient_program="/sbin/dhclient"
dhclient_flags=""DHCPсерверСервер DHCP, dhcpd, включён как часть порта
net/isc-dhcp42-server в коллекцию
портов. Этот порт содержит DHCP-сервер от ISC и документацию.ФайлыDHCPконфигурационные файлы/etc/dhclient.confdhclient требует наличия конфигурационного
файла, /etc/dhclient.conf. Как правило, файл
содержит только комментарии, а настройки по умолчанию достаточно
хороши. Этот настроечный файл описан на страницах справочной
системы по &man.dhclient.conf.5;./sbin/dhclientdhclient скомпонован статически и находится
в каталоге /sbin. На страница Справочника
&man.dhclient.8; дается более подробная информация о
dhclient./sbin/dhclient-scriptdhclient-script является специфичным для
FreeBSD скриптом настройки клиента DHCP. Он описан в
&man.dhclient-script.8;, но для нормального функционирования
никаких модификаций со стороны пользователя не требуется./var/db/dhclient.leasesВ этом файле клиент DHCP хранит базу данных выданных к
использованию адресов в виде журнала. На странице
&man.dhclient.leases.5; дается гораздо более подробное
описание.Дополнительная литератураПолное описание протокола DHCP дается в RFC 2131. Кроме
того, дополнительная информация есть на сервере .Установка и настройка сервера DHCPЧему посвящён этот разделЭтот раздел даёт информацию о том, как настроить систему
FreeBSD для работы в качестве сервера DHCP на основе реализации
пакета DHCP от ISC (Internet Systems Consortium).Серверная часть пакета не поставляется как часть FreeBSD, так
что вам потребуется установить порт net/isc-dhcp42-server для получения
этого сервиса. Обратитесь к для получения
более полной информации об использовании коллекции портов.Установка сервера DHCPDHCPустановкаДля того, чтобы настроить систему FreeBSD на работу в качестве
сервера DHCP, вам необходимо обеспечить присутствие устройства
&man.bpf.4;, вкомпилированного в ядро. Для этого
добавьте строку device bpf в файл
конфигурации вашего ядра. Для получения более полной информации о
построении ядер, обратитесь к .Устройство bpf уже входит в состав
ядра GENERIC, поставляемого с FreeBSD, так что
вам не нужно создавать собственное ядро для обеспечения работы
DHCP.Те, кто обращает особое внимание на вопросы безопасности,
должны заметить, что bpf является тем
устройством, что позволяет нормально работать снифферам пакетов
(хотя таким программам требуются привилегированный доступ).
Наличие устройства bpfобязательно для использования DHCP, но если
вы очень обеспокоены безопасностью, наверное, вам не нужно
включать bpf в ваше ядро только потому,
что в отдалённом будущем вы собираетесь использовать DHCP.Следующим действием, которое вам нужно выполнить, является
редактирование примерного dhcpd.conf, который
устанавливается в составе порта net/isc-dhcp42-server. По умолчанию это
файл /usr/local/etc/dhcpd.conf.sample, и вы
должны скопировать его в файл
/usr/local/etc/dhcpd.conf перед тем, как его
редактировать.Настройка сервера DHCPDHCPdhcpd.confdhcpd.conf состоит из деклараций
относительно подсетей и хостов, и проще всего описывается на
примере:option domain-name "example.com";
option domain-name-servers 192.168.4.100;
option subnet-mask 255.255.255.0;
default-lease-time 3600;
max-lease-time 86400;
ddns-update-style none;
subnet 192.168.4.0 netmask 255.255.255.0 {
range 192.168.4.129 192.168.4.254;
option routers 192.168.4.1;
}
host mailhost {
hardware ethernet 02:03:04:05:06:07;
fixed-address mailhost.example.com;
}Этот параметр задаёт домен, который будет выдаваться
клиентам в качестве домена, используемого по умолчанию при
поиске. Обратитесь к страницам справочной системы по
&man.resolv.conf.5; для получения дополнительной информации о
том, что это значит.Этот параметр задаёт список разделённых запятыми серверов
DNS, которые должен использовать клиент.Маска сети, которая будет выдаваться клиентам.Клиент может запросить определённое время, которое будет
действовать выданная информация. В противном случае сервер
выдаст настройки с этим сроком (в секундах).Это максимальное время, на которое сервер будет выдавать
конфигурацию. Если клиент запросит больший срок, он будет
подтверждён, но будет действовать только
max-lease-time секунд.Этот параметр задаёт, будет ли сервер DHCP пытаться
обновить DNS при выдаче или освобождении конфигурационной
информации. В реализации ISC этот параметр является
обязательным.Это определение того, какие IP-адреса должны использоваться
в качестве резерва для выдачи клиентам. IP-адреса между и
включая границы, будут выдаваться клиентам.Объявление маршрутизатора, используемого по умолчанию,
который будет выдаваться клиентам.Аппаратный MAC-адрес хоста (чтобы сервер DHCP мог
распознать хост, когда тот делает запрос).Определение того, что хосту всегда будет выдаваться один и
тот же IP-адрес. Заметьте, что указание здесь имени хоста
корректно, так как сервер DHCP будет разрешать имя хоста
самостоятельно до того, как выдать конфигурационную
информацию.Когда вы закончите составлять свой
dhcpd.conf, нужно разрешить запуск сервера DHCP
в файле /etc/rc.conf, добавив в него
строкиdhcpd_enable="YES"
dhcpd_ifaces="dc0"Замените dc0 именем интерфейса (или именами
интерфейсов, разделяя их пробелами), на котором(ых) сервер DHCP
должен принимать запросы от клиентов.Затем вы можете стартовать сервер DHCP при помощи команды&prompt.root; /usr/local/etc/rc.d/isc-dhcpd startЕсли в будущем вам понадобится сделать изменения в настройке
вашего сервера, то важно заметить, что посылка сигнала
SIGHUP приложению
dhcpdне приведёт к
перезагрузке настроек, как это бывает для большинства даемонов.
Вам нужно послать сигнал SIGTERM для остановки
процесса, а затем перезапустить его при помощи вышеприведённой
команды.ФайлыDHCPконфигурационный файлы/usr/local/sbin/dhcpddhcpd скомпонован статически и
расположен в каталоге /usr/local/sbin.
Страницы справочной системы &man.dhcpd.8;,
устанавливаемые портом, содержат более полную информацию о
dhcpd./usr/local/etc/dhcpd.confdhcpd требует наличия
конфигурационного файла,
/usr/local/etc/dhcpd.conf, до того, как
он будет запущен и начнёт предоставлять сервис клиентам.
Необходимо, чтобы этот файл содержал все данные, которая
будет выдаваться обслуживаемым клиентам, а также информацию о
работе сервера. Этот конфигурационный файл описывается на
страницах справочной системы &man.dhcpd.conf.5;, которые
устанавливаются портом./var/db/dhcpd.leasesСервер DHCP ведёт базу данных выданной информации в этом
файле, который записывается в виде протокола. Страницы
справочной системы &man.dhcpd.leases.5;, устанавливаемые портом,
дают гораздо более подробное описание./usr/local/sbin/dhcrelaydhcrelay используется в сложных
ситуациях, когда сервер DHCP пересылает запросы от клиента
другому серверу DHCP в отдельной сети. Если вам нужна такая
функциональность, то установите порт net/isc-dhcp42-relay. На страницах
справочной системы &man.dhcrelay.8;, которые устанавливаются
портом, даётся более полное описание.ChernLeeТекст предоставил TomRhodesDanielGerzoDomain Name System (DNS)ОбзорBINDПо умолчанию во FreeBSD используется одна из версий программы BIND
(Berkeley Internet Name Domain), являющейся самой распространенной
реализацией протокола DNS. DNS -
это протокол, при помощи которого имена преобразуются в
IP-адреса и наоборот. Например, в ответ на запрос о
www.FreeBSD.org будет получен IP-адрес
веб-сервера Проекта &os;, а запрос о ftp.FreeBSD.org возвратит
IP-адрес соответствующей машины с
FTP-сервером. Точно также происходит и обратный
процесс. Запрос, содержащий IP-адрес машины, возвратит имя хоста. Для
выполнения запросов к DNS вовсе не обязательно иметь
в системе работающий сервер имён.&os; в настоящее время поставляется с сервером
DNS BIND9, предоставляющим
расширенные настройки безопасности, новую схему расположения файлов
конфигурации и автоматические настройки для &man.chroot.8;.DNSВ сети Интернет DNS управляется через
достаточно сложную систему авторизированных корневых серверов имён,
серверов доменов первого уровня (Top Level Domain,
TLD) и других менее крупных серверов имён, которые
содержат и кэшируют информацию о конкретных доменах.На данный момент пакет BIND поддерживается Internet Systems
Consortium .Используемая терминологияДля понимания этого документа нужно понимать значения некоторых
терминов, связанных с работой DNS.резолверобратный DNSкорневая зонаТерминОпределениеПрямой запрос к DNS (forward DNS)Преобразование имён хостов в адреса IPОриджин (origin)Обозначает домен, покрываемый конкретным файлом
зоныnamed, bindОбщеупотребительные названия для обозначения пакета BIND,
обеспечивающего работу сервера имён во &os;.РезолверСистемный процесс, посредством которого машина обращается
к серверу имён для получения информации о зонеОбратный DNS (reverse
DNS)Преобразование адресов IP в имена
хостовКорневая зонаНачало иерархии зон Интернет. Все зоны находятся под
корневой зоной, подобно тому, как все файлы располагаются ниже
корневого каталога.ЗонаОтдельный домен, поддомен или часть
DNS, управляемая
одним сервером.зоныпримерыПримеры зон:. — так обычно обозначается
в документации корневая зона.org. — домен верхнего уровня
(TLD) в корневой зоне.example.org. является
зоной в домене верхнего уровня (TLD)
org..1.168.192.in-addr.arpa является зоной, в которую
включены все IP-адреса, формирующие пространство адресов
192.168.1.*.Как можно видеть, уточняющая часть имени хоста появляется слева.
Например, example.org. более точен, чем
org., также, как org. более
точен, чем корневая зона. Расположение каждой части имени хоста сильно
похоже на файловую систему: каталог /dev
расположен в корневой файловой системе, и так далее.Причины, по которым вам может понадобиться сервер имёнСервера имён обычно используются в двух видах: авторитетный сервер
имён и кэширующий сервер имён, также называемый распознавателем
(resolver).Авторитетный сервер имён нужен, когда:нужно предоставлять информацию о DNS
остальному миру, отвечая на запросы авторизированно.зарегистрирован домен, такой, как
example.org и в этом домене требуется
поставить имена машин в соответствие с их адресами
IP.блоку адресов IP требуется обратные записи
DNS (IP в имена
хостов).резервный (slave) сервер имён должен отвечать на запросы.Кэширующий сервер имён нужен, когда:локальный сервер DNS может кэшировать информацию и отвечать на
запросы быстрее, чем это происходит при прямом опросе внешнего
сервера имён.Например, когда кто-нибудь запрашивает информацию о
www.FreeBSD.org, то обычно резолвер обращается к
серверу имён вашего провайдера, посылает запрос и ожидает ответа. С
локальным кэширующим сервером DNS запрос во внешний мир будет делаться
всего один раз. Последующие запросы не будут посылаться за
пределы локальной сети, потому что информация уже имеется в
кэше.Как это работаетВо &os; даемон BIND называется
named.ФайлОписание&man.named.8;Даемон BIND&man.rndc.8;Программа управления даемоном сервера имён/etc/namedbКаталог, в котором располагается вся информация о зонах
BIND/etc/namedb/named.confКонфигурационный файл для даемонаФайлы зон обычно располагаются в каталоге
/etc/namedb и содержат информацию о зоне DNS,
за которую отвечает сервер имён.В зависимости от способа конфигурации зоны на сервере файлы
зон могут располагаться в подкаталогах master, slave или dynamic иерархии
/etc/namedb.
Эти файлы содержат DNS информацию, которую и будет
сообщать в ответ на запросы сервер имен.Запуск BINDBINDзапускТак как сервер имён BIND устанавливается по умолчанию, его
настройка сравнительно проста.Стандартная конфигурация named
запускает простой кэширующий сервер в ограниченной среде
&man.chroot.8;, который прослушивает запросы на интерфейсе обратной
связи (loopback) с адресом (127.0.0.1).
Для одноразового запуска даемона в этой
конфигурации используйте команду&prompt.root; /etc/rc.d/named onestartЧтобы даемон named запускался во
время загрузки, поместите в /etc/rc.conf
следующую строку:named_enable="YES"Разумеется, существует множество различных конфигураций
/etc/namedb/named.conf, лежащих за рамками
данного документа. Разнообразные опции запуска
named во &os; описаны в переменных
named_* файла
/etc/defaults/rc.conf и странице справочника
&man.rc.conf.5;. Кроме того, полезной может оказаться
.Конфигурационные файлыBINDконфигурационные файлыФайлы конфигурации даемона named
расположены в каталоге
/etc/namedb и, за исключением
случая, когда вам требуется просто резолвер, требуют модификации./etc/namedb/named.conf// $FreeBSD$
//
// If you are going to set up an authoritative server, make sure you
// understand the hairy details of how DNS works. Even with
// simple mistakes, you can break connectivity for affected parties,
// or cause huge amounts of useless Internet traffic.
options {
// All file and path names are relative to the chroot directory,
// if any, and should be fully qualified.
directory "/etc/namedb/working";
pid-file "/var/run/named/pid";
dump-file "/var/dump/named_dump.db";
statistics-file "/var/stats/named.stats";
// If named is being used only as a local resolver, this is a safe default.
// For named to be accessible to the network, comment this option, specify
// the proper IP address, or delete this option.
listen-on { 127.0.0.1; };
// If you have IPv6 enabled on this system, uncomment this option for
// use as a local resolver. To give access to the network, specify
// an IPv6 address, or the keyword "any".
// listen-on-v6 { ::1; };
// These zones are already covered by the empty zones listed below.
// If you remove the related empty zones below, comment these lines out.
disable-empty-zone "255.255.255.255.IN-ADDR.ARPA";
disable-empty-zone "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA";
disable-empty-zone "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA";
// If you've got a DNS server around at your upstream provider, enter
// its IP address here, and enable the line below. This will make you
// benefit from its cache, thus reduce overall DNS traffic in the Internet.
/*
forwarders {
127.0.0.1;
};
*/
// If the 'forwarders' clause is not empty the default is to 'forward first'
// which will fall back to sending a query from your local server if the name
// servers in 'forwarders' do not have the answer. Alternatively you can
// force your name server to never initiate queries of its own by enabling the
// following line:
// forward only;
// If you wish to have forwarding configured automatically based on
// the entries in /etc/resolv.conf, uncomment the following line and
// set named_auto_forward=yes in /etc/rc.conf. You can also enable
// named_auto_forward_only (the effect of which is described above).
// include "/etc/namedb/auto_forward.conf";Как и говорится в комментариях, если вы хотите получить эффект от
использования кэша провайдера, то можно включить раздел
forwarders. В обычном случае сервер имён будет
рекурсивно опрашивать определённые серверы имён Интернет до тех пор,
пока не получит ответ на свой запрос. При включении этого раздела
он будет автоматически опрашивать сервер имён вашего провайдера (или
тот, который здесь указан), используя преимущества его кэша.
наличия нужной информации. Если соответствующий сервер имён провайдера
работает быстро и имеет хороший канал связи, то в результате такой
настройки вы можете получить хороший результат.127.0.0.1 здесь
работать не будет. Измените
его на IP-адрес сервера имён провайдера./*
Modern versions of BIND use a random UDP port for each outgoing
query by default in order to dramatically reduce the possibility
of cache poisoning. All users are strongly encouraged to utilize
this feature, and to configure their firewalls to accommodate it.
AS A LAST RESORT in order to get around a restrictive firewall
policy you can try enabling the option below. Use of this option
will significantly reduce your ability to withstand cache poisoning
attacks, and should be avoided if at all possible.
Replace NNNNN in the example with a number between 49160 and 65530.
*/
// query-source address * port NNNNN;
};
// If you enable a local name server, don't forget to enter 127.0.0.1
// first in your /etc/resolv.conf so this server will be queried.
// Also, make sure to enable it in /etc/rc.conf.
// The traditional root hints mechanism. Use this, OR the slave zones below.
zone "." { type hint; file "/etc/namedb/named.root"; };
/* Slaving the following zones from the root name servers has some
significant advantages:
1. Faster local resolution for your users
2. No spurious traffic will be sent from your network to the roots
3. Greater resilience to any potential root server failure/DDoS
On the other hand, this method requires more monitoring than the
hints file to be sure that an unexpected failure mode has not
incapacitated your server. Name servers that are serving a lot
of clients will benefit more from this approach than individual
hosts. Use with caution.
To use this mechanism, uncomment the entries below, and comment
the hint zone above.
As documented at http://dns.icann.org/services/axfr/ these zones:
"." (the root), ARPA, IN-ADDR.ARPA, IP6.ARPA, and ROOT-SERVERS.NET
are available for AXFR from these servers on IPv4 and IPv6:
xfr.lax.dns.icann.org, xfr.cjr.dns.icann.org
*/
/*
zone "." {
type slave;
file "/etc/namedb/slave/root.slave";
masters {
192.5.5.241; // F.ROOT-SERVERS.NET.
};
notify no;
};
zone "arpa" {
type slave;
file "/etc/namedb/slave/arpa.slave";
masters {
192.5.5.241; // F.ROOT-SERVERS.NET.
};
notify no;
};
*/
/* Serving the following zones locally will prevent any queries
for these zones leaving your network and going to the root
name servers. This has two significant advantages:
1. Faster local resolution for your users
2. No spurious traffic will be sent from your network to the roots
*/
// RFCs 1912 and 5735 (and BCP 32 for localhost)
zone "localhost" { type master; file "/etc/namedb/master/localhost-forward.db"; };
zone "127.in-addr.arpa" { type master; file "/etc/namedb/master/localhost-reverse.db"; };
zone "255.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// RFC 1912-style zone for IPv6 localhost address
zone "0.ip6.arpa" { type master; file "/etc/namedb/master/localhost-reverse.db"; };
// "This" Network (RFCs 1912 and 5735)
zone "0.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// Private Use Networks (RFCs 1918 and 5735)
zone "10.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "16.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "17.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "18.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "19.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "20.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "21.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "22.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "23.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "24.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "25.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "26.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "27.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "28.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "29.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "30.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "31.172.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "168.192.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// Link-local/APIPA (RFCs 3927 and 5735)
zone "254.169.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IETF protocol assignments (RFCs 5735 and 5736)
zone "0.0.192.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// TEST-NET-[1-3] for Documentation (RFCs 5735 and 5737)
zone "2.0.192.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "100.51.198.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "113.0.203.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IPv6 Range for Documentation (RFC 3849)
zone "8.b.d.0.1.0.0.2.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// Domain Names for Documentation and Testing (BCP 32)
zone "test" { type master; file "/etc/namedb/master/empty.db"; };
zone "example" { type master; file "/etc/namedb/master/empty.db"; };
zone "invalid" { type master; file "/etc/namedb/master/empty.db"; };
zone "example.com" { type master; file "/etc/namedb/master/empty.db"; };
zone "example.net" { type master; file "/etc/namedb/master/empty.db"; };
zone "example.org" { type master; file "/etc/namedb/master/empty.db"; };
// Router Benchmark Testing (RFCs 2544 and 5735)
zone "18.198.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "19.198.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IANA Reserved - Old Class E Space (RFC 5735)
zone "240.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "241.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "242.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "243.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "244.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "245.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "246.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "247.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "248.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "249.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "250.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "251.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "252.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "253.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "254.in-addr.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IPv6 Unassigned Addresses (RFC 4291)
zone "1.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "3.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "4.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "5.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "6.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "7.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "8.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "9.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "a.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "b.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "c.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "d.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "e.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "0.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "1.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "2.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "3.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "4.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "5.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "6.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "7.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "8.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "9.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "a.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "b.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "0.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "1.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "2.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "3.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "4.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "5.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "6.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "7.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IPv6 ULA (RFC 4193)
zone "c.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "d.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IPv6 Link Local (RFC 4291)
zone "8.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "9.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "a.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "b.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IPv6 Deprecated Site-Local Addresses (RFC 3879)
zone "c.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "d.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "e.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
zone "f.e.f.ip6.arpa" { type master; file "/etc/namedb/master/empty.db"; };
// IP6.INT is Deprecated (RFC 4159)
zone "ip6.int" { type master; file "/etc/namedb/master/empty.db"; };
// NB: Do not use the IP addresses below, they are faked, and only
// serve demonstration/documentation purposes!
//
// Example slave zone config entries. It can be convenient to become
// a slave at least for the zone your own domain is in. Ask
// your network administrator for the IP address of the responsible
// master name server.
//
// Do not forget to include the reverse lookup zone!
// This is named after the first bytes of the IP address, in reverse
// order, with ".IN-ADDR.ARPA" appended, or ".IP6.ARPA" for IPv6.
//
// Before starting to set up a master zone, make sure you fully
// understand how DNS and BIND work. There are sometimes
// non-obvious pitfalls. Setting up a slave zone is usually simpler.
//
// NB: Don't blindly enable the examples below. :-) Use actual names
// and addresses instead.
/* An example dynamic zone
key "exampleorgkey" {
algorithm hmac-md5;
secret "sf87HJqjkqh8ac87a02lla==";
};
zone "example.org" {
type master;
allow-update {
key "exampleorgkey";
};
file "dynamic/example.org";
};
*/
/* Example of a slave reverse zone
zone "1.168.192.in-addr.arpa" {
type slave;
file "/etc/namedb/slave/1.168.192.in-addr.arpa";
masters {
192.168.1.1;
};
};
*/Это примеры описаний прямой и обратной зон из файла
named.conf для вторичных серверов.Для каждого новой зоны, которую будет обслуживать сервер имён,
в файл named.conf должна быть добавлена
запись.К примеру, самая простая запись для домена example.org может выглядеть вот так:zone "example.org" {
type master;
file "master/example.org";
};Зона является первичной, что отражается в поле
, и информация о зоне хранится в файле
/etc/namedb/master/example.org, что указывается в
поле .zone "example.org" {
type slave;
file "slave/example.org";
};В случае вторичной зоны информация о ней передается с основного
сервера имён для заданной зоны и сохраняется в указанном файле. Если
и когда основной сервер имён выходит и строя или недосягаем, то
скачанная информация о зоне будет находиться на вторичных серверах, и
они смогут обслуживать эту зону.Файлы зонBINDфайлы зонПример файла зоны example.org
для основного
сервера (располагающийся в файле
/etc/namedb/master/example.org) имеет такой
вид:$TTL 3600 ; 1 hour default TTL
example.org. IN SOA ns1.example.org. admin.example.org. (
2006051501 ; Serial
10800 ; Refresh
3600 ; Retry
604800 ; Expire
300 ; Negative Response TTL
)
; DNS Servers
IN NS ns1.example.org.
IN NS ns2.example.org.
; MX Records
IN MX 10 mx.example.org.
IN MX 20 mail.example.org.
IN A 192.168.1.1
; Machine Names
localhost IN A 127.0.0.1
ns1 IN A 192.168.1.2
ns2 IN A 192.168.1.3
mx IN A 192.168.1.4
mail IN A 192.168.1.5
; Aliases
www IN CNAME example.org.Заметьте, что все имена хостов, оканчивающиеся на .,
задают полное имя, тогда как все имена без символа . на
конце считаются заданными относительно origin. Например,
ns1 преобразуется в
ns1.example.org.Файл зоны имеет следующий формат:recordname IN recordtype valueDNSзаписиНаиболее часто используемые записи DNS:SOAначало зоны ответственностиNSавторитативный сервер именAадрес хостаCNAMEканоническое имя для алиасаMXобмен почтойPTRуказатель на доменное имя (используется в обратных
зонах DNS)example.org. IN SOA ns1.example.org. admin.example.org. (
2006051501 ; Serial
10800 ; Refresh after 3 hours
3600 ; Retry after 1 hour
604800 ; Expire after 1 week
300 ) ; Negative Response TTLexample.org.имя домена, а также ориджин для этого файла зоны.ns1.example.org.основной/авторитативный сервер имён для этой зоны.admin.example.org.человек, отвечающий за эту зону, адрес электронной почты с
символом @ замененным на точку.
(admin@example.org
становится admin.example.org)2006051501последовательный номер файла. При каждом изменении файла
зоны это число должно увеличиваться. В настоящее время для
нумерации многие администраторы предпочитают формат
ггггммддвв. 2006051501
будет означать, что
файл последний раз изменялся 15.05.2006, а последнее число
01
означает, что это была первая модификация файла за день.
Последовательный номер важен, так как он служит для того, чтобы
вторичные серверы узнавали об обновлении зоны. IN NS ns1.example.org.Это NS-запись. Такие записи должны иметься для
всех серверов имён, которые будут отвечать за зону.localhost IN A 127.0.0.1
ns1 IN A 192.168.1.2
ns2 IN A 192.168.1.3
mx IN A 192.168.1.4
mail IN A 192.168.1.5Записи типа A служат для обозначения имён машин. Как это видно
выше, имя ns1.example.org будет
преобразовано в 192.168.1.2. IN A 192.168.1.1Эта строка присваивает IP адрес
192.168.1.1 текущему ориджину,
в данном случае домену
example.org.www IN CNAME @Записи с каноническими именами обычно используются для присвоения
машинам псевдонимов. В этом примере www является
псевдонимом для главной машины, имя которой по воле
случая совпало с именем домена
example.org (192.168.1.1).
Записи типа CNAME нельзя использовать совместно с другими
типами записей для одного и того же имени хоста (recordname).MX record IN MX 10 mail.example.org.MX-запись указывает, какие почтовые серверы
отвечают за обработку входящей электронной почты для зоны. mail.example.org является именем почтового
сервера, а 10 обозначает приоритет этого почтового сервера.Можно иметь несколько почтовых серверов с приоритетами,
например, 10, 20 и так далее.
Почтовый сервер, пытающийся доставить почту для example.org,
сначала попробует связаться с машиной, имеющий MX-запись с самым
большим приоритетом (наименьшим числовым значением в поле MX),
затем с приоритетом поменьше и так далее, до тех
пор, пока почта не будет отправлена.Для файлов зон in-addr.arpa (обратные записи DNS) используется тот
же самый формат, отличающийся только использованием записей
PTR вместо A или CNAME.$TTL 3600
1.168.192.in-addr.arpa. IN SOA ns1.example.org. admin.example.org. (
2006051501 ; Serial
10800 ; Refresh
3600 ; Retry
604800 ; Expire
300 ) ; Negative Response TTL
IN NS ns1.example.org.
IN NS ns2.example.org.
1 IN PTR example.org.
2 IN PTR ns1.example.org.
3 IN PTR ns2.example.org.
4 IN PTR mx.example.org.
5 IN PTR mail.example.org.В этом файле дается полное соответствие имён хостов IP-адресам в
нашем описанном ранее вымышленном домене.Следует отметить, что все имена в правой части PTR-записи должны
быть полными доменными именами (то есть, заканчиваться точкой
.).Кэширующий сервер имёнBINDкэширующий сервер имёнКэширующий сервер имён — это сервер имен, чья главная
задача — разрешение рекурсивных запросов. Он просто выполняет
запросы от своего имени и сохраняет результаты для последующего
использования.* DNSSECBINDDNS security extensionsЭтот раздел не переведен.БезопасностьХотя BIND является самой распространенной реализацией DNS, всегда
стоит вопрос об обеспечении безопасности. Время от времени
обнаруживаются возможные и реальные бреши в безопасности.&os; автоматически запускает named
в ограниченном окружении (&man.chroot.8;); помимо этого, есть
еще несколько механизмов, помогающих защититься от возможных
атак на сервис DNS.Весьма полезно прочесть сообщения безопасности CERT и подписаться на
&a.security-notifications; для того, чтобы быть в курсе
текущих проблем с обеспечением безопасности Internet и &os;.Если возникает проблема, то наличие последних исходных текстов
и свежесобранного named может
способствовать её решению.Дополнительная литератураСправочная информация по BIND/named:
&man.rndc.8;, &man.named.8;, &man.named.conf.5;, &man.nsupdate.8;,
&man.dnssec-signzone.8;, &man.dnssec-keygen.8;
Официальная страница ISC BIND
Официальный форум ISC BIND
Книга издательства O'Reilly DNS and BIND 5th EditionRoot
DNSSECDNSSEC Trust Anchor Publication for the Root
ZoneRFC1034
- Domain Names - Concepts and FacilitiesRFC1035
- Domain Names - Implementation and SpecificationRFC4033
- DNS Security Introduction and RequirementsRFC4034
- Resource Records for the DNS Security ExtensionsRFC4035
- Protocol Modifications for the DNS Security
ExtensionsRFC4641
- DNSSEC Operational PracticesRFC5011
- Automated Updates of DNS Security (DNSSEC
Trust AnchorsMurrayStokelyПредоставил Apache HTTP сервервеб серверынастройкаApacheОбзор&os; используется в качестве платформы для многих из самых
нагруженных серверов в мире. Большинство серверов в интернет
используют Apache HTTP сервер.
Пакеты Apache должны быть включены
в поставку FreeBSD. Если вы не установили их во вместе с
системой, воспользуйтесь портами www/apache13 или www/apache22.Как только Apache был успешно
установлен, его необходимо настроить.В этом разделе рассказывается о версии 1.3.X
Apache HTTP сервера, поскольку
эта версия наиболее широко используется в &os;.
Apache 2.X
содержит много новых технологий, но здесь они не обсуждаются.
За дополнительной информацией о
Apache 2.X, обращайтесь к .НастройкаApacheфайл настройкиВ &os; основной файл настройки Apache HTTP сервера
устанавливается в
/usr/local/etc/apache/httpd.conf.
Это обычный текстовый &unix; файл настройки с строками
комментариев, начинающимися с символа #.
Исчерпывающее описание всех возможных параметров настройки
находится за пределом рассмотрения этой книги, поэтому
здесь будут описаны только наиболее часто модифицируемые
директивы.ServerRoot "/usr/local"Указывает верхний каталог установки
Apache по
умолчанию. Бинарные файлы находятся в
bin и
sbin, подкаталоги
расположены относительно корневого каталога сервера, файлы
настройки находятся в
etc/apache.ServerAdmin you@your.addressАдрес, на который должны будут отправляться
сообщения о проблемах с сервером. Этот адрес
выводится на некоторые генерируемые сервером
страницы, например с сообщениями об ошибках.ServerName www.example.comServerName позволяет вам устанавливать имя хоста,
которое отправляется обратно клиентам, если оно
отличается от того, с которым настроен хост
(например, использование www вместо реального
имени хоста).DocumentRoot "/usr/local/www/data"DocumentRoot: Каталог, внутри которого будут храниться
документы. По умолчанию, все запросы обрабатываются внутри
этого каталога, но символические ссылки и синонимы могут
использоваться для указания на другие каталоги.Хорошей идеей будет сделать резервные копии настроек
Apache перед внесением изменений. Как только вы будете
удовлетворены первоначальной настройкой, можно запускать
Apache.Запуск ApacheApacheзапуск или остановкаApache не запускается из
inetd, как это делают многие
другие сетевые серверы. Он настроен для автономного запуска,
чтобы обеспечивать большую производительность при обработке
HTTP запросов от браузеров клиентов. Для упрощения запуска,
остановки и перезапуска сервера существует shell скрипт.
Для запуска Apache в первый раз
просто выполните:&prompt.root; /usr/local/sbin/apachectl startВы можете остановить сервер в любой момент, выполнив:&prompt.root; /usr/local/sbin/apachectl stopПосле внесения любых изменений в файл настроек, вам потребуется
перезапустить сервер:&prompt.root; /usr/local/sbin/apachectl restartДля перезапуска Apache без
прерывания имеющихся соединений, выполните:&prompt.root; /usr/local/sbin/apachectl gracefulДополнительная информация находится на странице
справочного руководства &man.apachectl.8;.Для запуска Apache при старте системы,
добавьте в /etc/rc.conf следующую строку:apache_enable="YES"или для Apache 2.2:apache22_enable="YES"Если вы хотите передать программе Apachehttpd дополнительные параметры командной
при загрузке системы, они могут быть помещены в дополнительную
строку rc.conf:apache_flags=""Теперь, когда веб сервер запущен, вы можете просмотреть свой веб
сайт, задав в строке браузера адрес
http://localhost/. По умолчанию отображается
веб страница
/usr/local/www/data/index.html.Виртуальный хостингApache поддерживает два различных
типа виртуального хостинга (Virtual Hosting). Первый метод
основан на именах (Name-based Virtual Hosting). Он использует
полученные от клиента заголовки HTTP/1.1 для определения имени
хоста. Это позволяет многим различным доменам использовать
один и тот же IP адрес.Для настройки Apache на использование
этого типа хостинга добавьте в httpd.conf
запись подобную следующей:NameVirtualHost *Если веб сервер назывался www.domain.tld и
вы хотите настроить виртуальный домен для
www.someotherdomain.tld, необходимо добавить
в httpd.conf следующие записи:<VirtualHost *>
ServerName www.domain.tld
DocumentRoot /www/domain.tld
</VirtualHost>
<VirtualHost *>
ServerName www.someotherdomain.tld
DocumentRoot /www/someotherdomain.tld
</VirtualHost>Замените адреса и пути к документам на те, что вы будете
использовать.За дополнительной информацией по настройке виртуальных хостов
обращайтесь к официальной документации
Apache: .Модули ApacheApacheмодулиСуществуют множество различных модулей
Apache,
которые добавляют функциональность к основному
серверу. Коллекция портов FreeBSD предоставляет
простой способ установки Apache
с некоторыми наиболее популярными дополнительными
модулями.mod_sslвеб серверызащитаSSLкриптографияМодуль mod_ssl использует
библиотеку OpenSSL для
сильной криптографии через протоколы Secure Sockets Layer
(SSL v2/v3) и Transport Layer Security (TLS v1).
Этот модуль содержит все необходимое для запроса
подписанного сертификата из центра сертификации
для защищенного веб сервера на &os;.Если вы еще не установили
Apache, версия
Apache 1.3.X с
mod_ssl может быть установлена
через порт www/apache13-modssl.
Поддержка SSL также доступна для
Apache 2.X
через порт www/apache22,
где она включена по умолчанию.Apache и скриптовые языкиДля большинства скриптовых языков созданы модули Apache.
На базе таких модулей возможно создание других модулей Apache,
написанных полностью на скриптовом языке. Они также часто
используются как встроенные в сервер интерпретаторы, что исключает
накладные расходы на запуск внешнего интерпретатора и сокращает
время построения динамических страниц.Построение динамических сайтовweb serversdynamicВ последнее десятилетие
все большее число компаний обращает внимание
на Интернет как площадку для ведения и расширения бизнеса.
Среди прочего, этот процесс подчеркивает потребность в
интерактивном содержимом сайтов. Некоторые компании, такие как
µsoft;, представляют свои закрытые решения; сообщество
разработчиков открытых программ отвечает на вызов.
Среди современных решений для предоставления динамического
контента следует отметить Django, Ruby on Rails,
mod_perl и
mod_php.DjangoPythonDjangoDjango — это распространяемая под лицензией BSD
инфраструктура, позволяющая разработчикам быстро создавать
элегантные, высокопроизводительные веб-приложения. Она
предоставляет в распоряжение разработчика объектно-реляционное
отображение (object-relational mapper), таким образом типы данных
разрабатываются как объекты Python. Для этих объектов
предоставляется богатый интерфейс доступа к базам данных, при этом
у разработчика не возникает необходимости написания SQL-запросов.
Django также предоставляет расширяемую систему шаблонов,
так что логика приложения отделена от его
HTML-представления.Для Django требуются следующие компоненты:
mod_python,
Apache и одна из нескольких возможных
SQL СУБД. Укажите соответствующие опции сборки, и порт установит
всё необходимое.Установка Django совместно с Apache2, mod_python3 и
PostgreSQL&prompt.root; cd /usr/ports/www/py-django; make all install clean -DWITH_MOD_PYTHON3 -DWITH_POSTGRESQLПосле установки Django и всех необходимых ему компонентов
вам потребуется создать каталог для проекта Django. Далее
потребуется настроить Apache для определенных URL адресов на вашем
сайте выполнять ваше приложение встроенным интерпретатором
Python.Конфигурация Apache для Django/mod_pythonЧтобы настроить Apache отправлять запросы для определенных
URL адресов вашему веб-приложению, вам потребуется внести
несколько строк в конфигурационный файл
httpd.conf:<Location "/">
SetHandler python-program
PythonPath "['/dir/to/your/django/packages/'] + sys.path"
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonAutoReload On
PythonDebug On
</Location>Ruby on RailsRuby on RailsRuby on Rails это еще одна веб инфраструктура с открытым
исходным кодом, которая предоставляет полный стек разработки
и которая оптимизированa для продуктивного и быстрого создания
мощных веб-приложений. Ruby on Rails может быть легко установлена
из коллекции портов.&prompt.root; cd /usr/ports/www/rubygem-rails; make all install cleanmod_perlmod_perlPerlПроект интеграции
Apache/Perl объединяет мощь
языка программирования Perl и HTTP сервера
Apache.
С модулем mod_perl возможно
написание модулей Apache
полностью на Perl. Кроме того, постоянно
запущенный встроенный в сервер интерпретатор
позволяет не тратить ресурсы на запуск внешнего
интерпретатора и время на запуск Perl.mod_perl можно использовать
различными способами. Помните, что
mod_perl 1.0 работает только с
Apache 1.3, тогда как
mod_perl 2.0 совместим только с
Apache 2.X.
mod_perl 1.0 доступен как порт www/mod_perl, а также в виде статически
скомпилированной версии в www/apache13-modperl.
mod_perl 2.0 доступен как www/mod_perl2.TomRhodesНаписал mod_phpmod_phpPHPPHP, также известный как Препроцессор гипертекста
(Hypertext Preprocessor), —
это скриптовый язык общего назначения, в основном предназначенный
для веб разработки. Этот язык может быть встроен в
HTML, его синтаксис заимствован из C, &java;
и Perl, и он позволяет веб разработчикам быстро писать динамически
генерируемые страницы.Добавление поддержки PHP5 к веб серверу
Apache производится путем установки
порта lang/mod_php5.Если порт lang/php5
устанавливается впервые, то автоматически отобразятся все доступные
опции (OPTIONS). Если меню не отображается,
так как порт lang/php5 устанавливался ранее, всегда
можно повторно вызвать диалог меню выполнив следующую команду
в каталоге порта:&prompt.root; make configВыберите в меню опцию APACHE,
тем самым вы построите загружаемый модуль
mod_php5 для веб сервера
Apache.Множество сайтов по разным причинам (например, из-за
проблем совместимости или из-за наличия уже развёрнутых
веб приложений)
всё еще используют PHP4. Если требуется
mod_php4 вместо
mod_php5, то воспользуйтесь
портом lang/php4.
Порт lang/php4 поддерживает
многие из конфигурационных и установочных опций порта
lang/php5.Этот порт устанавливает и настраивает модули, необходимые
для поддержки динамических PHP веб страниц.
Убедитесь, что в файл
/usr/local/etc/apache/httpd.conf были
добавлены следующие секции:LoadModule php5_module libexec/apache/libphp5.soAddModule mod_php5.c
<IfModule mod_php5.c>
DirectoryIndex index.php index.html
</IfModule>
<IfModule mod_php5.c>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
</IfModule>Для загрузки модуля PHP
после этого просто вызовите команду
apachectl с параметром graceful:&prompt.root; apachectl gracefulПри дальнейших обновлениях PHP команда
make config больше не потребуется; выбранные
опции сохраняются автоматически инфраструктурой портов &os;Поддержка PHP в &os; построена по
модульному принципу, поэтому базовая установка обладает очень
ограниченной функциональностью. Дополнительная функциональность
может быть легко добавлена при помощи порта lang/php5-extensions, управляющего набором
расширений PHP через меню, либо просто путем
установки дополнительных портов.Например, для добавления поддержки
MySQL к PHP5,
просто установите порт
databases/php5-mysql.После установки новых расширений сервер
Apache должен быть рестартован,
чтобы изменения в конфигурации вступили в силу:&prompt.root; apachectl gracefulMurrayStokelyПредоставил Файл сервер и печать для µsoft.windows; клиентов
(Samba)Samba серверMicrosoft Windowsфайл серверWindows клиентыпринт серверWindows клиентыОбзорSamba это популярный пакет
программ с открытыми исходными текстами, которая предоставляет
файловые и принт-сервисы µsoft.windows; клиентам.
Эти клиенты могут подключаться и использовать файловое
пространство FreeBSD, как если бы это был локальный диск,
или принтеры FreeBSD, как если бы это были локальные
принтеры.Пакет Samba должен быть включен
в поставку FreeBSD. Если вы не установили
Samba при первой установке системы,
ее можно установить из порта или пакета net/samba34.НастройкаФайл настройки Samba по умолчанию
устанавливается в
/usr/local/share/examples/samba34/smb.conf.default.
Этот файл необходимо скопировать в
/usr/local/etc/smb.conf и отредактировать
перед использованием Samba.В файле smb.conf находится информация,
необходимая для работы Samba,
например определение принтеров и общих каталогов,
которые будут использоваться совместно с &windows; клиентами.
В пакет Samba входит программа с
веб интерфейсом, называемая swat,
которая дает простой способ редактирования файла
smb.conf.Использование Samba Web Administration Tool (SWAT)Программа веб администрирования Samba (Samba Web
Administration Tool, SWAT) запускается как даемон из
inetd. Следовательно, в
/etc/inetd.conf необходимо снять комментарий
перед тем, как использовать swat для
настройки Samba:swat stream tcp nowait/400 root /usr/local/sbin/swat swatКак описано в ,
после изменения настроек inetd
необходимо перечитать конфигурацию.Как только swat был включен
inetd.conf, вы можете использовать
браузер для подключения к .
Сначала необходимо зарегистрироваться с системной
учетной записью root.После успешного входа на основную страницу настройки
Samba, вы можете просмотреть
документацию или начать настройку, нажав на кнопку
Globals. Раздел Globals
соответствует переменным,
установленным в разделе [global] файла
/usr/local/etc/smb.conf.Глобальные настройкиНезависимо от того, используете ли вы
swat, или редактируете
/usr/local/etc/smb.conf непосредственно,
первые директивы, которые вы скорее всего встретите при
настройке Samba, будут
следующими:workgroupИмя домена или рабочей группы NT для компьютеров,
которые будут получать доступ к этому серверу.netbios nameNetBIOSУстанавливает имя NetBIOS, под которым будет
работать Samba сервер. По
умолчанию оно устанавливается
равным первому компоненту DNS имени хоста.server stringУстанавливает строку, которая будет показана командой
net view и некоторыми другими сетевыми
инструментами, которые отображают строку описания
сервера.Настройки безопасностиДве из наиболее важных настроек в
/usr/local/etc/smb.conf отвечают за
выбор модели безопасности и за формат паролей для
клиентов. Эти параметры контролируются следующими
директивами:securityДва наиболее часто используемых параметра это
security = share и security
= user. Если имена пользователей для клиентов
совпадают с их именами на компьютере &os;, вы возможно
захотите включить безопасность уровня пользователя (user).
Это политика безопасности по умолчанию, она требует,
чтобы клиент авторизовался перед доступом к совместно
используемым ресурсам.На уровне безопасности share клиенту не требуется
входить на сервер перед подключением к ресурсу.
Эта модель безопасности использовалась по умолчанию
в старых версиях Samba.passdb backendNIS+LDAPSQL база данныхSamba поддерживает
несколько различных подсистем аутентификации. Вы можете
аутентифицировать клиентов с помощью LDAP, NIS+,
базы данных SQL, или через модифицированный файл
паролей. Метод аутентификации по умолчанию
smbpasswd, и здесь рассматривается
только он.Предполагая, что используется подсистема по умолчанию
smbpasswd, необходимо создать файл
/usr/local/etc/samba/smbpasswd, чтобы
Samba могла аутентифицировать
клиентов. Если вы хотите разрешить к учетным записям
&unix; доступ с &windows; клиентов, используйте следующую
команду:&prompt.root; smbpasswd -a usernameНыне рекомендуемой подсистемой аутентификации является
tdbsam, поэтому для добавления пользователей
используйте следующую команду:&prompt.root; pdbedit usernameПожалуйста, обратитесь к Official Samba HOWTO
за дополнительной информацией о параметрах настройки.
Основные настройки, рассмотренные здесь, достаточны для
первого запуска Samba.Запуск SambaПорт net/samba34 добавляет
новый стартовый сценарий, который может быть использован для контроля
Samba. Для того, чтобы им можно было
запускать, останавливать или перезапускать сервер
Samba, добавьте следующую запись
в файл /etc/rc.conf:samba_enable="YES"Или, для более тонкого контроля:nmbd_enable="YES"smbd_enable="YES"Внесение этих записей в /etc/rc.conf
также обеспечит автоматический запуск сервера
Samba во время старта системы.Теперь становится возможным запустить сервер
Samba, для чего наберите следующую
команду:&prompt.root; /usr/local/etc/rc.d/samba start
Starting SAMBA: removing stale tdbs :
Starting nmbd.
Starting smbd.За дальнейшей информацией об использовании rc скриптов
обратитесь к .Samba состоит из трех
отдельных даемонов. Вы можете видеть, что
nmbd и smbd
запускаются скриптом samba.
Если вы включили сервис разрешения имен winbind
в smb.conf, то увидите также
запуск даемона winbindd.Вы можете остановить Samba в любой
момент, набрав:&prompt.root; /usr/local/etc/rc.d/samba stopSamba это сложный программный
набор с функциональностью, позволяющей полную интеграцию в сети
µsoft.windows;. За дальнейшей информацией о функциях,
выходящих за рамки описанной здесь базовой установки,
обращайтесь к .MurrayStokelyПредоставил Протокол передачи файлов (FTP)FTP серверыОбзорПротокол передачи файлов (File Transfer Protocol, FTP) дает
пользователям простой путь передачи файлов на и с FTP сервера. В &os;
серверная программа FTP,
ftpd, включена в базовую систему.
Это упрощает настройку и администрирование FTP сервера в
FreeBSD.НастройкаНаиболее важный шаг заключается в определении того,
каким учетным записям будет позволено получать доступ
к FTP серверу. В обычной системе FreeBSD есть множество
системных учетных записей, используемых различными даемонами,
но пользователям должно быть запрещен вход с использованием
этих учетных записей. В файле /etc/ftpusers
находится список пользователей, которым запрещен доступ по
FTP. По умолчанию он включает упомянутые системные учетные
записи, но в него можно добавить и определенных пользователей,
которым будет запрещен доступ по FTP.Вам может понадобиться ограничить доступ определенных
пользователей без полного запрета использования FTP.
Это можно сделать через файл /etc/ftpchroot.
В нем находится список пользователей и групп, к которым
применяется ограничение доступа. На странице справочника
&man.ftpchroot.5; дана подробная информация, и она не будет
дублироваться здесь.FTPанонимныйЕсли вы захотите разрешить анонимный FTP доступ на
сервер, в системе &os; необходимо создать пользователя
ftp. Этот пользователь сможет
входить на FTP сервер с именем пользователя
ftp или anonymous,
с любым паролем (существует соглашение об использовании
почтового адреса пользователя в качестве пароля).
FTP сервер выполнит &man.chroot.2; при входе пользователя
anonymous для ограничения доступа только домашним каталогом
пользователя ftp.Существуют два текстовых файла, определяющих сообщение,
отправляемое FTP клиентам. Содержимое файла
/etc/ftpwelcome будет выведено пользователям
перед приглашением на вход. После успешного входа
будет выведено содержимое файла /etc/ftpmotd.
Обратите внимание, что путь к этому файлу задается относительно
домашнего каталога пользователя, так что анонимным пользователям
будет отправляться ~ftp/etc/ftpmotd.Как только FTP сервер был правильно настроен, он должен
быть включен в /etc/inetd.conf. Все, что
необходимо, это удалить символ комментария
# из начала существующей строки
ftpd:ftp stream tcp nowait root /usr/libexec/ftpd ftpd -lКак описано в ,
inetd должен перечитать конфигурацию
после того, как этот файл настройки был изменен. Пожалуйста
обратитесь к за деталями
по запуску inetd на вашей системе.В качестве альтернативы, демон ftpd
может быть запущен как самостоятельный сервер. В этом случае
достаточно установить соответствующую переменную в файле
/etc/rc.conf:ftpd_enable="YES"Демон будет запущен автоматически при следующей загрузке системы.
Также демон можно запустить вручную, для чего выполните следующую
команду как пользователь root:&prompt.root; /etc/rc.d/ftpd startТеперь вы можете войти на FTP сервер, введя:&prompt.user; ftp localhostПоддержкаsyslogлог файлыFTPДля протоколирования даемон ftpd
использует сообщения &man.syslog.3;. По умолчанию, &man.syslog.3;
поместит сообщения, относящиеся к FTP, в файл
/var/log/xferlog. Местоположение
лог файла FTP может быть изменено путем изменения следующей
строки в файле /etc/syslog.conf:ftp.info /var/log/xferlogFTPанонимныйУчитывайте потенциальные проблемы, возникающие с
анонимным FTP сервером. В частности, вы должны дважды
подумать, прежде чем позволить анонимным пользователям
загружать файлы на сервер. Вы можете обнаружить, что
FTP сайт стал форумом, на котором происходит обмен
нелицензионным коммерческим программным обеспечением
или чем-то еще хуже. Если вам необходимо разрешить
анонимную выгрузку файлов на FTP, права должны быть настроены
таким образом, чтобы эти файлы не могли прочитать другие
анонимные пользователи до их рассмотрения администратором.TomHukinsТекст предоставил Синхронизация часов через NTPNTPОбзорС течением времени часы компьютера имеют тенденцию отставать.
Network Time
Protocol - Сетевой Протокол Времени (NTP) является одним из способов
вести точное время.Многие сервисы Интернет опираются или сильно зависят от точности
часов компьютеров. К примеру, веб-сервер может получать запрос на
посылку файла, который был недавно модифицирован. В локальной сети
необходимо, чтобы часы компьютеров, совместно использующих файлы,
были синхронизированы, чтобы время модификации файлов устанавливалось
правильно. Такие службы, как
&man.cron.8;, также зависят от правильности установки системных
часов, поскольку запускают команды в определенное время.NTPntpdFreeBSD поставляется с сервером NTP &man.ntpd.8;, который можно
использовать для опроса других серверов NTP для установки часов на
вашей машине или предоставления услуг точного времени.Выбор подходящих серверов NTPNTPвыбор серверовДля синхронизации ваших часов вам нужно найти для использования
один или большее количество серверов NTP. Ваш сетевой администратор
или провайдер могут иметь сервер NTP для этой цели—обратитесь к
ним, так ли это в вашем случае. Существует онлайн список
общедоступных серверов NTP, которым можно воспользоваться для
поиска ближайшего к вам сервера NTP. Не забудьте выяснить политику
выбранного вами сервера и спросить разрешения, если это
требуется.Выбор нескольких несвязанных серверов NTP является хорошей идеей в
том случае, если один из используемых вами серверов станет недоступным
или его часы неточны. &man.ntpd.8; использует ответы, которые он
получает от других серверов с умом—он делает предпочтение
надежным серверам.Настройка вашей машиныNTPнастройкаБазовая конфигурацияntpdateЕсли вам нужно только синхронизировать ваши часы при загрузке
машины, вы можете воспользоваться утилитой &man.ntpdate.8;. Это
может подойти для некоторых настольных машин, которые часто
перезагружаются и только требуют изредка синхронизироваться, но
на большинстве машин должен работать &man.ntpd.8;.Использование &man.ntpdate.8; при загрузке также хорошо для
машин, на которых запущен даемон &man.ntpd.8;. Программа
&man.ntpd.8; изменяет время постепенно, тогда как &man.ntpdate.8;
устанавливает время вне
зависимости от того, насколько велика разница между текущим временем
машины и точным временем.Для включения &man.ntpdate.8; во время загрузки, добавьте строчку
ntpdate_enable="YES" в файл
/etc/rc.conf. Вам также потребуется указать
все серверы, с которыми вы хотите синхронизироваться, и все
параметры, которые передаются в &man.ntpdate.8;, в
ntpdate_flags.Общие настройкиNTPntp.confNTP настраивается в файле /etc/ntp.conf,
формат которого описан в &man.ntp.conf.5;. Вот простой
пример:server ntplocal.example.com prefer
server timeserver.example.org
server ntp2a.example.net
driftfile /var/db/ntp.driftПараметр server задает, какие серверы будут
использоваться, по одному в каждой строке. Если сервер задан с
аргументом prefer, как ntplocal.example.com, то этому серверу отдается
предпочтение перед остальными. Ответ от предпочтительного сервера
будет отброшен, если он значительно отличается от ответов других
серверов, в противном случае он будет использоваться безотносительно
к другим ответам. Аргумент prefer обычно
используется для серверов NTP, о которых известно, что они очень
точны, такими, на которых используется специальное оборудование
точного времени.Параметр driftfile задает файл, который
используется для хранения смещения частоты системных часов.
Программа &man.ntpd.8; использует его для автоматической компенсации
естественного смещения часов, позволяя ему поддерживать достаточно
правильную настройку, даже если он на некоторый период отключается от
внешнего источника информации о времени.Параметр driftfile задает, какой файл
используется для сохранения информации о предыдущих ответах от
серверов NTP, которые вы используете. Этот файл содержит внутреннюю
информацию для NTP. Он не должен изменяться никакими другими
процессами.Управление доступом к вашему серверуПо умолчанию ваш сервер NTP будет доступен всем хостам в
Интернет. Параметр restrict в файле
/etc/ntp.conf позволяет вам контролировать,
какие машины могут обращаться к вашему серверу.Если вы хотите запретить всем машинам обращаться к вашему серверу
NTP, добавьте следующую строку в
файл /etc/ntp.conf:restrict default ignoreЭта строка конфигурации также предотвратит доступ вашего
сервера
к другим серверам, перечисленным в вашей локальной конфигурации.
Если вам необходимо синхронизировать ваш сервер с внешним
сервером NTP, вам необходимо будет изменить настройки
относительно этого конкретного сервера. За более детальной
информацией обратитесь к странице руководства
&man.ntp.conf.5;.Если вы хотите разрешить синхронизировать свои часы с вашим
сервером только машинам в вашей сети, но запретить им настраивать
сервер или быть равноправными участниками синхронизации времени, то
вместо указанной добавьте строчкуrestrict 192.168.1.0 mask 255.255.255.0 nomodify notrapгде 192.168.1.0 является адресом
IP вашей сети, а 255.255.255.0 её
сетевой маской./etc/ntp.conf может содержать несколько
директив restrict. Для получения подробной
информации обратитесь к подразделу Access Control
Support (Поддержка Управления Доступом) в
&man.ntp.conf.5;.Запуск сервера NTPДля того, чтобы сервер NTP запускался при загрузке, добавьте строку
ntpd_enable="YES" в файл
/etc/rc.conf. Если вы хотите передать
дополнительные опции в &man.ntpd.8;, то отредактируйте параметр
ntpd_flags в файле
/etc/rc.conf.Для запуска сервера без перезагрузки вашей машины, выполните
команду ntpd, не забыв задать дополнительные
параметры из переменной ntpd_flags в файле
/etc/rc.conf. К примеру:&prompt.root; ntpd -p /var/run/ntpd.pidИспользование ntpd с временным подключением к
ИнтернетДля нормальной работы программе &man.ntpd.8; не требуется
постоянное подключение к Интернет. Однако если ваше временное
подключение к Интернет настроено для дозвона по требованию, хорошо бы
запретить трафику NTP вызывать дозвон или поддерживать соединение
постоянно. Если вы используете пользовательский PPP, то можете
воспользоваться директивами filter в файле
/etc/ppp/ppp.conf. К примеру: set filter dial 0 deny udp src eq 123
# Prevent NTP traffic from initiating dial out
set filter dial 1 permit 0 0
set filter alive 0 deny udp src eq 123
# Prevent incoming NTP traffic from keeping the connection open
set filter alive 1 deny udp dst eq 123
# Prevent outgoing NTP traffic from keeping the connection open
set filter alive 2 permit 0/0 0/0Более подробную информацию можно найти в разделе PACKET
FILTERING (ФИЛЬТРАЦИЯ ПАКЕТОВ) в &man.ppp.8;, а примеры в
/usr/share/examples/ppp/.Некоторые провайдеры Интернет блокируют трафик по портам с
маленькими номерами, что приводит к неработоспособности NTP, так как
ответы никогда не достигают вашей машины.Дополнительная литератураДокументация по серверу NTP может быть найдена в каталоге
/usr/share/doc/ntp/ в формате HTML.TomRhodesТекст предоставил * Remote Host Logging with syslogdЭтот раздел не переведен.