Sunday, May 11, 2008

Postfix Basic Setup

https://help.ubuntu.com/community/PostfixBasicSetupHowto

Introduction

This document will teach you how to set up a basic Postfix mail server with IMAP and POP3 services. It does not included advanced topics such as integrating virus-checking and spam-filtering, which are dealt with in PostfixVirtualMailBoxClamSmtpHowto and PostfixCompleteVirtualMailSystemHowto.

Setup Overview

In our setup, Postfix sends and receives mail from Internet and stores them in the user mailboxes while clients in the Internet can retrieve their mails via Courier IMAP or POP3. The user authentication is done by Courier Authdaemon. The following diagram shows this process.

SetupOverview.jpg

Anatomy of Postfix

Components

The Following figure shows the main Postfix system components, and the main information flows between them.

PostfixComponentsNw.gif

  • Yellow ellipsoids are mail programs.

  • Yellow boxes are mail queues or files.

  • Blue boxes are lookup tables.

  • Programs in the large box run under control by the Postfix resident master daemon.

  • Data in the large box is property of the Postfix mail system.

Receiving Mail

When a message enters the Postfix mail system, the first stop on the inside is the incoming queue. The figure below shows the main components that are involved with new mail.

PosfixRecieving.gif

  • Mail is posted locally. The Postfix [WWW] sendmail program invokes the privileged [WWW] postdrop program which deposits the message into the maildrop directory, where the message is picked up by the [WWW] pickup daemon. This daemon does some sanity checks, in order to protect the rest of the Postfix system.

  • Mail comes in via the network. The Postfix [WWW] SMTP server receives the message and does some sanity checks, in order to protect the rest of the Postfix system.

  • Mail is generated internally by the Postfix system itself, in order to return undeliverable mail to the sender. The [WWW] bounce or defer daemon brings the bad news.

  • Mail is forwarded by the [WWW] local delivery agent, either via an entry in the system-wide [WWW] alias database, or via an entry in a per-user [WWW] .forward file. This is indicated with the unlabeled arrow.

  • Mail is generated internally by the Postfix system itself, in order to [WWW] notify the postmaster of a problem (this path is also indicated with the unlabeled arrow).The Postfix system can be configured to notify the postmaster of SMTP protocol problems, [WWW] UCE policy violations, and so on.

  • The [WWW] cleanup daemon implements the final processing stage for new mail. It adds missing From: and other message headers, arranges for address rewriting to the standard [MAILTO] user@fully.qualified.domain form, and optionally extracts recipient addresses from message headers. The cleanup daemon inserts the result as a single queue file into the incoming queue, and notifies the [WWW] queue manager of the arrival of new mail. The cleanup daemon can be configured to transform addresses on the basis of [WWW] canonical and [WWW] virtua table lookups.

  • On request by the cleanup daemon, the [WWW] trivial-rewrite daemon rewrites addresses to the standard [MAILTO] user@fully.qualified.domain form.

Install Postfix

In this setup I assume that your domain is yourdomain.com and it has a valid MX record call mail.yourdomain.com. Remember to replace yourdomain.com with your actual domain in the example codes in this howto. Also I assume that you know what an MX record is. To find out MX your type in a terminal:

dig mx yourdomain.com

To install postfix

sudo apt-get install postfix

Intall mailx package for use as command mail utility program. Mail command is installed with this package.

sudo apt-get install mailx

Test your default setup

Add a user before you start this.

sudo useradd -m -s /bin/bash fmaster
sudo passwd fmaster

Test your default installation using the following code segment.

telnet localhost 25

Postfix will prompt like following in the terminal so that you can use to type SMTP commands.

Trying 127.0.0.1...
Connected to mail.fossedu.org.
Escape character is '^]'.
220 localhost.localdomain ESMTP Postfix (Ubuntu)

Type the following code segment in Postfix's prompt.

ehlo localhost
mail from: root@localhost
rcpt to: fmaster@localhost
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
. (Type the .[dot] in a new Line and press Enter )
quit

Check the mailbox of fmaster

su - fmaster
mail

When you type mail command an output like follows display in your terminal.

Mail version 8.1.2 01/15/2001.  Type ? for help.
"/var/mail/fmaster": 2 messages 2 new
>N 1 root@localhost Mon Mar 6 12:49 13/479 Just a test
N 2 root@localhost Mon Mar 6 12:51 15/487 My first mail
&

You will observe that mails are indexed by numbers and you can type the number of which the mail that you want to read. For example type no "2" to read the 2nd mail. The type "q" to quit. The mail will be written to a file called mbox in user's home directory. According to our example it will be /home/fmaster/mbox.

All messages in an mbox type of mailbox are concatenated and stored in a single file. The beginning of each message is indicated by a line whose first five characters are "From " and a blank line is appended to the end of each message

Setting Postfix Support for Maildir-style Mailboxes

Maildir is a format for an e-mail spool that does not require file locking to maintain message integrity because the messages are kept in separate files with unique names. A Maildir is a directory (often named Maildir) with three subdirectories named tmp, new, and cur. The subdirectories should all reside on the same filesystem.

Another reason to use Maildir format is that Courier IMAP/POP3 servers only work with Maildir format of mailboxes.

Please find out more about Maildir [WWW] here

Instruct Postfix to use Maildirs instead of Mboxes:

 sudo postconf -e "home_mailbox = Maildir/"

Ensure Procmail isn't used: (if the step was taken during dpkg-reconfigure, by mistake)

sudo postconf -e "mailbox_command = "

Restart Postfix to make changes effect.

sudo  /etc/init.d/postfix restart

Test your setup again

Installing courier IMAP and POP3

sudo apt-get install courier-pop
sudo apt-get install courier-imap

Adding your local domains to postfix

Add your domains to mydestination:

sudo postconf -e "mydestination = mail.fossedu.org, localhost.localdomain, localhost, yourdoamin.com"

Add your local networks, too:

Postfix comes with the localhost (127.0.0.1) entry; you may have others, here we assume your LAN is on 192.168.1.0/24. Make changes to suit your situation.

sudo postconf -e "mynetworks = 127.0.0.0/8, 192.168.1.0/24"

Make Postfix to receive mail from the Internet

Instruct Postfix to receive on all interfaces:

sudo postconf -e "inet_interfaces = all"

(optional) Make Postfix accept IPv4, IPv6 protocols

If you're not using IPv6 yet, and you're paranoid, use "ipv4" instead of "all". Again, this is to suit your own network sensibilities.

sudo postconf -e "inet_protocols = all"

Finally, restart Postfix;

sudo  /etc/init.d/postfix restart

Test your setup again using following code:

telnet mail.yourdomain.com 25
ehlo yourdomain.com
mail from: root@yourdomain.com
rcpt to: fmaster@yourdomain.com
data
Subject: My first mail for my domain

Hi,
Are you there?
regards,
Admin
. (and Enter In a new Line)
quit

Check the mailbox of fmaster

su - fmaster
cd Maildir/new
ls

Now you will see mail has a separate file.

Testing Courier POP3

Type in a terminal:

telnet mail.yourdomain.com 110

Use the following example code segment for your test. Be intelligent to tweak the changes appropriately to your environment. An output like follows will display in your terminal.

Connected to mail.yourdomain.com (208.77.188.166).
Escape character is '^]'.
+OK Hello there.

Type the following code segment in the prompt provided by the Courier POP3 server. I assume that you are intelligent enough not to type the lines which starts from +OK

user fmaster
+OK Password required.
pass password
+OK logged in.
quit

Testing Courier IMAP

Type in a terminal:

telnet mail.yourdomain.com 143

Use the following example code segment for your test. Be intelligent to tweak the changes appropriately to your environment. An output like follows will display in your terminal.

* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS XCOURIEROUTBOX=INBOX.Outbox] Courier-IMAP ready. Copyright 1998-2005 Double Precision, Inc.  See COPYING for distribution information.

Type the following code segment in the prompt provided by the Courier IMAP server.

a login fmaster password
a OK LOGIN Ok.
a logout

Local Alias database

When mail is to be delivered locally, the local delivery agent runs each local recipient name through the aliases database. The mapping does not affect addresses in message headers. Local aliases are typically used to implement distribution lists, or to direct mail for standard aliases such as postmaster to real people. The table can also be used to map Firstname.Lastname addresses to login names.

Alias lookups are enabled by default and you will see following code segment in main.cf file.

...
alias_maps = hash:/etc/aliases
...

Creating an alias for an account

The following codes illustrate how you can setup an alias. This step is optional since we are going to configure virtual mail domains later in this howto. I have added this step to make understand how you can do this in case of a requirement.

Create a user

sudo useradd -m -s /bin/bash sysadmin
sudo passwd sysadmin

Edit the alias table

Open the alias file with:

sudo vi /etc/aliases

Add the following code:

fmaster: sysadmin

To make your changes effect type:

sudo newaliases

To test your changes send a mail to fmaster and check the mail in /home/sysadmin/Maildir/new folder.

Per User .forward Files

Users can control their own mail delivery by specifying destinations in a file called .forward in their home directories. The syntax of these files is the same as with system aliases, except that the lookup key and colon are not present.

I will illustrate an example here:

Assume that you need to for all the mails which comes sysadmin account to an another account do like this

su - sysadmin
touch .forward

Then open the .forward file

vi .forward

Add the following code:

fossedu@example.com

Remember to use email address which exists in this exercise.

Now send a mail to sysadmin and mail should come to [MAILTO] fossedu@example.com

Postfix virtual Aliases for separate domains and Linux system accounts

With this approach, every hosted domain can have its own info etc. email address. However, it still uses LINUX system accounts for local mailbox deliveries.

With virtual alias domains, each hosted address is aliased to a local UNIX system account or to a remote address. The example below shows how to use this mechanism for the fossedu.org and linuxelabs.com domains.

Inside the main.cf file, we tell it how to handle these virtual domains:

sudo postconf -e "virtual_alias_domains = fossedu.org linuxelabs.com"
sudo postconf -e "virtual_alias_maps = hash:/etc/postfix/virtual"

Edit the /etc/postfix/virtual file:

Add two Linux system accounts

sudo useradd -m -s /bin/bash sigiri
sudo useradd -m -s /bin/bash kala

Set Password for the above users.

sudo passwd sigiri
sudo passwd kala
sudo vi /etc/postfix/virtual

Add the following code segment:

info@fossedu.org       sigiri
info@linuxelabs.com kala

To create a Map Database type :

sudo postmap /etc/postfix/virtual

The postmap is utility program that will convert /etc/postfix/virtual to /etc/postfix/virtual.db Berkley DB format, so that Postfix can access the data faster.

Restart Postfix to make changes effect:

sudo /etc/init.d/postfix restart

Saturday, May 10, 2008

disk killer - bug in ubuntu

behaviour of drives (high Load_Cycle_Count numbers) on (laptop) harddrives.

Because the bug report has 150 comments already, I've tried to summarize it here.

There appear to be two issues here: HDD spin down and "Power cycling", whereas the first one has a [WWW] relative short default (60 seconds), but the latter one gets the most complains (it's about Load_Cycle_Count).

The disk Load_Cycle_Count issue appears to be caused by a combination of two problems -- The first is overly-aggressive power management from what might be considered buggy hardware. The second is that Ubuntu appears to be touching the hard drive on a regular basis for one reason or another.

Note: In sections below relating to how to prevent damage to your hard disk, you should replace $HDD everywhere with your device, e.g. "/dev/sda" or "/dev/hda". If you have several harddrives, you need to change it accordingly and duplicate lines in workarounds.

Affected hardware

Machine

Hard Disk

Ubuntu

Other OS

Workaround

Notes

HP nx6325

Samsung HM250JI

Hardy=YES

Vista=NO

-B 254


HP nx6325

Fujitsu MHV2060BH

Gutsy=YES

N/A

-B 255


Dell XPS M1330

Western Digital WD1200BEVS-75UST0

Hardy=YES

N/A

-B 255


HP nc8430

Samsung 250GB

Hardy=YES

N/A

N/A


HP nw9440

Seagate ST910021AS

Edgy=YES

N/A

N/A


Gateway MT6451

Western Digital WD1200VE

Gutsy=YES

N/A

N/A


Thinkpad Z60m

Hitachi HTS541080G9SA00

Gutsy=YES

N/A

N/A


Toshiba P205

Fujitsu MHW2120BH

Gutsy=YES

N/A

-B 255


N/A

Hitachi HTS541210H9SA00

Ubuntu=YES

N/A

N/A


Dell Inspiron 1501

N/A

Ubuntu=YES

N/A

N/A


Dell XPS 1530

N/A

Ubuntu=YES

N/A

N/A


Thinkpad R52

Hitachi HTS541060G9AT00

Gutsy=YES

N/A

-B 192


Thinkpad 600E

Hitachi DK239A-65B

Ubuntu=YES

N/A

N/A


N/A

Hitachi HTS541010G9SA00

Ubuntu=YES

N/A

N/A


Compaq Evo600N

N/A

Ubuntu=YES

N/A

N/A


Dell Latitude C640

Western Digital 40GB

Gutsy=YES

XP=NO

N/A


Acer Aspire 1662wlm

Hitachi 5k100 60 GB

Ubuntu=YES

N/A

N/A


MacBook Pro C2D

Fujitsu 160GB

Gutsy=YES

MACOSX=YES

N/A


N/A

Travelstar 7K100 60GB

Ubuntu=YES

N/A

N/A


Dell Insipron 9400

Samsung 120GB

Ubuntu=YES

N/A

N/A


N/A

Toshiba MK8037GSX

Ubuntu=YES

Fedora=NO

OpenSUSE=NO


Dell Inspiron 6400

Samsung HM120JI

Gutsy=YES

N/A

N/A


Dell D620

N/A

Ubuntu=YES

N/A

N/A


N/A

Seagate ST9160821AS

Ubuntu=YES

N/A

N/A


Acer Aspire 1642 WLMi

N/A

Ubuntu=YES

N/A

N/A


Asus G1S-A1

Hitachi HTS541616J9SA00

Ubuntu=YES

N/A

N/A


HP NX6325

Hitachi HTS541080G9SA00

Ubuntu=YES

N/A

N/A


Dell latitude c840

Hitachi DK23EA-30

Ubuntu=YES

N/A

N/A


Thinkpad Z61t

Toshiba MK1032GSX

Gutsy=YES

N/A

N/A


Thinkpad T60

Hitachi HTS541080G9SA00

Gutsy=YES

N/A

N/A


Toshiba A100

Toshiba MK1234GSX

Ubuntu=YES

N/A

-B 254

On battery power

VIA Epia EX10000EG

Western Digital WD10EACS

Feisty=YES

N/A

N/A


Thinkpad T23

Seagate ST92811A

Ubuntu=YES

N/A

N/A


N/A

Toshiba MK3006GAL

Ubuntu=YES

N/A

-B 254


Thinkpad R50e

Hitachi HTS541060G9AT00

Feisty=YES

N/A

N/A


Powerbook G4

Seagate Momentus 5400.2 100GB

Ubuntu=YES

N/A

N/A


Dell Vostro 1000

Seagate ST9120822AS

Ubuntu=YES

N/A

N/A


HP dv6500

Western Digital WD800BEVS

Ubuntu=YES

N/A

-B 255


Thinkpad T42

Samsung HD

Ubuntu=YES

N/A

-B 254


Dell Vostro 1500

Seagate ST9160823AS

Gutsy=YES

XP=YES



Dell Latitude D630

N/A

Ubuntu=YES

N/A

-B 254


HP dv6602au

N/A

Ubuntu=YES

N/A

N/A


Acer Travelmate 4010

Hitachi IC25N060ATMR04

Ubuntu=YES

XP=YES

N/A


Thinkpad R61

Seagate ST9160821AS

Hardy=YES

N/A

N/A


Acer 3610

N/A

Ubuntu=YES

N/A

N/A


N/A

WDC WD5000AACS-00ZUB0

N/A

N/A

N/A


N/A

Seagate ST9100824AS

Ubuntu=YES

Vista=YES

XP=YES


Asus A6Q

Seagate ST980811AS

Hardy=YES

XP=NO

-B 254


HP 6820s

Hitachi HTS541616J9SA00

Hardy=YES

Vista=NO

-B 255


N/A

Hitachi HTS541616J9SA00

Ubuntu=YES

Vista=YES

N/A


N/A

ST9120822AS

Hardy=YES

XP=NO

N/A


Dell Inspiron 1525n

WDC WD2500BEVS-75UST0

Hardy=YES

Gutsy=NO

-B 255


Dell XPS m1330

N/A

Hardy=YES

N/A

-B 254


Check

You can check the current value of Load_Cycle_Count of your harddrive(s) using:

  • sudo smartctl -a $HDD | grep Load_Cycle_Count

(You need the smartmontools package for this. I also had to enable SMART monitoring for my drives using sudo smartctl -s on $HDD)

The values for this differ a lot (e.g. it's 0 on my desktop), but it goes up to > 600.000 for others, depending on the lifetime. TODO: add a section with sample values (including the value of Power_On_Hours).

What Ubuntu does

It [WWW] appears to be the official policy of Ubuntu that by default, Ubuntu should not adjust any power management settings of the harddisk. Unfortunately, this policy has two negative effects: It leaves quite a few people with broken hard drives that would otherwise not be broken, and it quite simply makes people who love Ubuntu feel neglected. This issue has been going on a long time.

The problem appears to be that some manufacturers' defaults are too aggressive and that Ubuntu might cause too many unbuffered disk accesses -- the combination of which can cause over a thousand parks a day on some systems.

In /etc/acpi/power.sh, laptop mode gets handled. If it gets enabled, hdparm is called with "-B 1", if it gets disabled with "-B 254". 254 is the least aggressive setting. 255 is off, but does not work for all disks.

In power.sh also the spindown timeout gets set, according to SPINDOWN_TIME from /etc/default/acpi-support (default: 12). This results in spinning down the harddrive after 12*5=60 seconds of inactivitiy. This does not influence Load_Cycle_Count however.

apm

[WWW] "/etc/apm" is not supposed to be used, but if it would get, it sets spindown to 60 seconds - but does not affect the general APM setting (hdparm -B). (there's a bug, which also used "power_conserve" here, if on_ac_power return "don't know" - [WWW] bug 156893)

Debug

[WWW] Blue has created a script, which acts as a wrapper around hdparm and logs, where it's called (including its arguments) From his report, it appears that hdparm always gets called through apm or the init script (the logfile excerpt appears to be from booting).

TODO: provide said helper script, allowing others to help to debug this.

Workaround

Various workarounds have been provided that involve adjusting or even turning off power-management of the hard drive. Please keep in mind that this can do more harm than good, so only apply them if you exactly understand what you are doing.

Try hdparm -B 255 $HDD or hdparm -B 254 $HDD. (255 is supposed to disable APM, but it does not work for some; so 254 sets it to the less aggressive setting)

There are different methods to keep this setting after reboot/resume. Your mileage may vary. There may be more workarounds in the bug report, but essentially, all are using "hdparm -B" to change the apm handling of the harddrive.

Force hdparm values in acpi hooks

Gilles posted the following workaround: Create a file called 99-fix-park.sh (keep the '99-' and the '.sh', but you can name the file as you like otherwise) with the following two lines:

 #!/bin/sh
hdparm -B 254 $HDD

and copy it to the following directories: /etc/acpi/resume.d/ and /etc/acpi/start.d/ ([WWW] https://launchpad.net/ubuntu/+source/acpi-support/+bug/59695/comments/10)

laptop-mode-tools

Don posted another workaround: Install laptop-mode-tools and set CONTROL_HD_POWERMGMT=1 in /etc/laptop-mode/laptop-mode.conf ([WWW] https://launchpad.net/ubuntu/+source/acpi-support/+bug/59695/comments/19) Here's another more verbose setup of laptop-mode-tools from Michael: [WWW] https://launchpad.net/ubuntu/+source/acpi-support/+bug/59695/comments/63

An easy, step-by-step walkthrough for a situation-sensitive solution (AC/batteries/heat) can be found here: [WWW] http://vale.homelinux.net/wordpress/?p=199

Proposed fixes

  • FIXED: Converted most remaining 255's to 254s, and added an explanation.

Conclusion

This bug report has attracted a lot of concerned Ubuntu users and it seems quite clear from the user feedback, that other operating systems/distributions handle this better. However, the workaround should be quite simple and this wiki page is a first attempt, to fix this for the better.

Misc

ubuntu_demon has put together a list of TODOs: [WWW] https://launchpad.net/ubuntu/+source/acpi-support/+bug/59695/comments/81

Comments

Please leave any comments/additions here. You may also edit the page directly, but please try to be clear and helpful. The problem has been confirmed and we know that it's a critical thing - please do not repeat that the bug status should be critical.

Could you kindly explain how to diagnose whether the settings on a system, at a point of time, are correct. I have followed the instructions but still find the load cycle count increasing. How do I diagnose the problem?

I think the 99-fix-park.sh scripts should be executable. If this is the case then I think we should add a note to the workaround.

Useful Links

Monday, May 05, 2008

ez-ipupdate configuration

http://leaf.sourceforge.net/doc/bucu-ezipupd.html

it works on my ubuntu system ...
as this manual says, default interval is 1800s.  enough~

Chapter 3. ez-ipupdate configuration

Revision History
Revision 0.1 2001-05-20JN
Initial document
Revision 0.22004-02-11kp
Update for Bering-uClibc
Revision 0.32005-02-06kp
Add necessary changes for shorewall

About ez-ipupdate

What is ez-ipupdate?

Ez-ipupdate is a small utility for updating your host name IP for any of the dynamic DNS service offered at:

This package has been developed & is supported by Angus Mackay.

The key features are: support for multiple service types and updating your IP address if it changes.

Feedback

Comment on the LEAF package can be sent to the authors.

Declare the ezipupd.lrp package

Download the ezipupd.lrp package and copy the package to your Bering-uClibc diskette.

Boot a Bering-uClibc floppy image. Once the LEAF menu appears get access to the linux shell by (q)uitting the menu. Edit the lrpkg.cfg (pre Bering-uClibc-2.2.0) or leaf.cfg (Bering-uClibc-2.2.0 onwards) file and add ezipupd.lrp in the list of packages to be loaded at boot. Check the Bering-uClibc Installation Guide to learn how to do that.

Configuring ez-ipupdate

You can edit the ez-ipupdate configuration file through the package configuration menu:

                        ez-ipupd configuration files

1) configuration file
2) startup script

q) quit
----------------------------------------------------------------------------
Selection:

The parameters allowed in the configuration file are the followings:

  address		usage: address=[ip address]
cache-file usage: cache-file=[cache file]
cloak-title usage: cloak-title=[title]
daemon usage: daemon=[command]
execute usage: execute=[shell command]
debug usage: debug
foreground usage: foreground
pid-file usage: pid-file=[file]
host usage: host=[host]
interface usage: interface=[interface]
mx usage: mx=[mail exchanger]
max-interval usage: max-interval=[number of seconds between updates]
notify-email usage: notify-email=[address to email if bad things happen]
offline usage: offline
retrys usage: retrys=[number of trys]
server usage: server=[server name]
service-type usage: service-type=[service type]
timeout usage: timeout=[sec.millisec]
resolv-period usage: resolv-period=[time between failed resolve attempts]
period usage: period=[time between update attempts]
url usage: url=[url]
user usage: user=[user name][:password]
run-as-user usage: run-as-user=[user]
run-as-euser usage: run-as-euser=[user] (this is not secure)
wildcard usage: wildcard
quiet usage: quiet
connection-type usage: connection-type=[connection type]
request usage: request=[request uri]
partner usage: partner=[easydns partner]

Here is how it could look like:

service-type=zoneedit
user=myname:mypassword
interface=eth0
host=mydomain.com
#notify-email=john.doe@mydomain.com
# other options:
#address=<ip address>
#cache-file=/tmp/ez-ipup
#daemon
#debug
#foreground
#host=<host>
#interface=<interface>
#mx=<mail exchanger>
#retrys=<number of trys>
#run-as-user=<user>
#run-as-euser=<user>
#server=<server name>
#timeout=<sec.millisec>
#max-interval=<time in seconds>
#notify-email=<email address>
#period=<time between update attempts>
#url=<url>

The four most important entries for a typical LEAF Bering-uClibc installation will be explained below:

  • service-type - make shure to add the according service-type. See above the list of available services.

  • user - here you have to provide your username and password for the choosen service seperated by a colon.

  • interface - this defines your interface to the internet - the one which is changing from time to time and whose ip should be changed at your dynamic DNS service (usually eth0 or ppp0)

  • host - the host(s) you like to have been updated. It is possible to update more than one host for a service-type. To allow that, add all your hosts separated by a comma.

Please note: The options cache-file and daemon aren't needed. notify-email doesn't work today.

You can also run ez-ipupdate in interractive mode. The commands are:

 null ezip pgpow dhs dyndns dyndns-static dyndns-custom ods
tzo easydns easydns-partner gnudip justlinux dyns hn zoneedit
heipv6tb
usage: ez-ipupdate [options]

Options are:
-a, --address <ip address> string to send as your ip address
-b, --cache-file <file> file to use for caching the ipaddress
-c, --config-file <file> configuration file, almost all arguments can be
given with: <name>[=<value>]
to see a list of possible config commands
try "echo help | ez-ipupdate -c -"
-d, --daemon run as a daemon periodicly updating if
necessary
-e, --execute <command> shell command to execute after a successful
update
-f, --foreground when running as a daemon run in the foreground
-F, --pidfile <file> use <file> as a pid file
-g, --request-uri <uri> URI to send updates to
-h, --host <host> string to send as host parameter
-i, --interface <iface> which interface to use
-L, --cloak_title <host> some stupid thing for DHS only
-m, --mx <mail exchange> string to send as your mail exchange
-M, --max-interval <# of sec> max time in between updates
-N, --notify-email <email> address to send mail to if bad things happen
-o, --offline set to off line mode
-p, --resolv-period <sec> period to check IP if it can't be resolved
-P, --period <# of sec> period to check IP in daemon
mode (default: 1800 seconds)
-q, --quiet be quiet
-r, --retrys <num> number of trys (default: 1)
-R, --run-as-user <user> change to <user> for running, be ware
that this can cause problems with handeling
SIGHUP properly if that user can't read the
config file. also it can't write it's pid file
to a root directory
-Q, --run-as-euser <user> change to effective <user> for running,
this is NOT secure but it does solve the
problems with run-as-user and config files and
pid files.
-s, --server <server[:port]> the server to connect to
-S, --service-type <server> the type of service that you are using
try one of: null ezip pgpow dhs
dyndns dyndns-static dyndns-custom
ods tzo easydns easydns-partner
gnudip justlinux dyns hn zoneedit
heipv6tb
-t, --timeout <sec.millisec> the amount of time to wait on I/O
-T, --connection-type <num> number sent to TZO as your connection
type (default: 1)
-U, --url <url> string to send as the url parameter
-u, --user <user[:passwd]> user ID and password, if either is left blank
they will be prompted for
-w, --wildcard set your domain to have a wildcard alias
-z, --partner <partner> specify easyDNS partner (for easydns-partner
services)
--help display this help and exit
--version output version information and exit
--credits print the credits and exit
--signalhelp print help about signals

Using ez-ipupdate

Through dhclient exit-hook script

reload_all() {
/sbin/shorewall restart
echo "Starting ez-ipupd from dhclient ..."
/etc/init.d/ez-ipupd start

}

Through ppp /etc/ppp/ip-up script

All you need is to add the command /etc/init.d/ez-ipupd -start to /etc/ppp/ip-up.

# Main Script starts here
#
/etc/init.d/ez-ipupd start

run-parts /etc/ppp/ip-up.d
[ -x /bin/beep ] && /bin/beep -f 600 -n -f 900 -n -f1200 -n -f1800
# last line

Configure shorewall

You need to add a rule to allow accessing port 80 from your firewall on the net zone. To make ez-ipupdate work. There for add to /etc/shorewall/rules

ACCEPT         fw       net           tcp      80

Sunday, May 04, 2008

ez-ipupdate

1. Make sure that NSM has DynDNS updating turned on in the Web Admin interface.

2. Populate the hostname, username, and password fields with the information for your first custom host and your account, respectively.

3. Switch back to the NSM box's command line.

4. Copy /etc/dyndns.conf to /etc/ez-ipupdate.conf.

5. Edit /etc/ez-ipupdate.conf as follows:

service-type=dyndns-custom
user=username:password
host=mydomain.com,myseconddomain.com,thirddomain.com
mx=mail.mydomain.com
interface=eth1
max-interval=86400
cache-file=/opt/tmpfs/ez-ipupdate.cache
daemon

(Note: The lines to edit are service-type, host, and if necessary, mx. Leave user, interface, max-interval, cache-file, and the daemon directive as is.)

6. Save the file and exit vi (or your preferred editor).

7. Edit the startup file. The startup file is in the /var/mdw/scripts directory and called dyndns. Change the line that reads ARGS=" -c /etc/dyndns.conf" to read ARGS=" -c /etc/ez-ipupdate.conf"

8. Then, simply hup the ez-ipupdate daemon with:

/var/mdw/scripts/dyndns reload

9. Press Enter and you should be good to go.

Dynamic DNS set

Dynamic DNS

 

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

In This Chapter

Chapter 18

Dynamic DNS

What Is DNS?

What Is Dynamic DNS?

Dynamic DNS And NAT Router/Firewalls

Dynamic DNS Prerequisites

Installing And Using ez-ipupdate

Installing And Using DDclient

Testing Your Dynamic DNS

 

© Peter Harrison, www.linuxhomenetworking.com

 

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

What Is DNS?

As explained on the introduction to networking chapter, DNS is the way in which a URL or domain like www.linuxhomenetworking.com is converted to an IP address. 

If you want to host a website at home you have two DNS options:

Static DNS: This is used when your ISP provides you with unchanging "fixed" or "static" Internet IP addresses. Your DNS server acts as the authoritative source of information for your my-site.com domain. You can consider static DNS as the "traditional" or "regular" form of DNS.

Dynamic DNS: Used when you get a changing "dynamic" Internet IP addresses via DHCP from your ISP. You will have to use the services of a third party DNS provider to provide DNS information for your my-site.com domain.


 

What Is Dynamic DNS?

In many home networking environments, the DSL IP address is provided by DHCP and therefore changes from time to time. Dynamic DNS (DDNS) allows you to host a website such as www.my-site.com in which the IP address is dynamically assigned. 

Before considering using a dynamic DNS solution for hosting a website at home with dynamic IPs:

·     you must make sure your DSL provider will allow inbound connections, specifically HTTP,  or else it will not work

·     be prepared for slower response times for your home based site than if you were using a static IP and a regular DNS service.

·     register your domain name and read your DDNS provider's instructions on how to use their name servers.

DDNS works by having webmasters register their DDNS sites on the DDNS provider's servers. The web masters then register their domains with companies such as Verisign and RegisterFree and tells these registrars to direct queries to www.my-site.com to the servers of the DDNS provider. 

The webserver itself then has a DDNS client program running that updates the DDNS providers name servers with the most current DHCP IP address of the site. 

This chapter describes how to configure the most popular Linux based DDNS software ez-ipupdate and DDclient in the following two configurations:

 

·     on a Linux box directly connected to the Internet

·     on a Linux box when protected by a NAT router / firewall

 

Remember that unlike DSL, most cable modem providers may not allow you to host sites at home. dynDNS.org offers a service to overcome this limitation.

 

Dynamic DNS And NAT Router/Firewalls

As discussed in the introduction to networking chapter, in order to conserve the limited number of IP addresses available for internet purposes, most home router / firewalls will use Network Address translation (NAT) to map a single public DHCP obtained IP addresses to the many private IP addresses within your network.  

NAT can fool the operation of some DDNS client software. In these cases, the software can only report the true IP address of the Linux box's NIC interface. If the Linux box is being protected behind a NAT router / firewall then the NIC will report in its data stream to the DDNS provider a private IP address which no one can reach directly via the Internet. The reported value is therefore invalid. 

Some DDNS providers use more intelligent clients such as DDclient which can be configured to let the DDNS provider record the public IP address from which the data stream is originating. Once this is done, you'll have to also configure your router / firewall to do port forwarding to make all HTTP traffic destined for the IP address of the router / firewall to be exclusively NAT-ed and forwarded to a single server on your home network. An example of port forwarding with a Cisco PIX firewall is given in both the Cisco PIX firewall chapter and Net-Filter chapters. 


 

Dynamic DNS Prerequisites 

Sign Up With A DDNS Provider

First you'll have to register with a DDNS provider, some of which are listed on the Bibliography. This chapter focuses on the services of miniDNS and DynDNS.org. Most DDNS providers assume you are going to create a sub domain of their main domain. For example miniDNS.net will default to a domain such as machine-name.minidns.net.

If you want to create your own domain such as my-site.com, you'll have to do a little extra work.  You'll have to register your domain with a DNS registrar such as www.registerfree.com or www.verisign.com. The cost is about US$20 per year.

 

o        The miniDNS registration for your own domain requires you to use the "add DNS Record" link on the registration page to create your own domain.

o        With dynDNS.org you'll have to go with their paid service to get a customized domain name. They call it Custom DNS and it doesn't support ez-ipupdate, you'll need DDclient in this case.   

First you add your domain such as my-site.com. Then you must add a host record. You can give your machine's name or you can name the machine "www" to create a combined domain-subdomain of www.my-site.com which would be more intuitive to use.

Update Your DNS Registration

If you have your own domain, you'll have to return to www.registerfree.com or www.verisign.com and update the nameserver entries for your domain to point to the name servers of your DDNS provider. DNS queries for my-site.com will eventually query RegisterFree or Verisign which will then refer the query to your DDNS providers name servers which will have the most current IP address of your site because of the DDNS client software you are running at your home site. 

 

Installing And Using ez-ipupdate

Download the tar/gzip file to your server's /tmp directory from the ez-ipupdate site listed in the Bibliography. Use the following commands to extract the contents into a new subdirectory.

 

[root@bigboy]tmp]# gunzip zip-tar-filename

[root@bigboy]tmp]# tar –xvf tar-filename

[root@bigboy]tmp]# cd /tmp/filename

 

Follow the install instructions for doing the "make" or program compilation. The ez-ipupdate installation will put the executable file in /usr/local/bin and all the files in the /tmp/filename directory will become extraneous.


 

The /etc/ez-ipupdate.conf File

ez-ipupdate uses a configuration file named /etc/ez-ipupdate.conf in which you must specify: 

o        Your registration username and password

o        The host name you have selected for your Linux box

o        The NIC interface which is connected to your DSL line.

 

Here is a sample:

 

service-type=justlinux
user=registration-username:registration-password
host=servername.my-site.com
interface=eth0

 

Note: The service-type line is specific to your dynamic DNS provider which will often provide a customized /etc/ez-ipupdate.conf file for you to use.

ez-ipupdate And NAT

The ez-ipupdate software runs as a daemon in memory continuously checking the IP address of your NIC. If your Linux server is protected behind a firewall using NAT then the IP address of the NIC won't match that of the public IP address of the firewall and DDNS won't work properly, you'll have to use a client like DDclient which doesn't have this limitation.

Installing And Using DDclient

Another highly used solution is DDclient. The developer of DDclient has recognized the limitations of using ez-ipupdate with NAT. DDclient has a simple "web" update mode which tells your DDNS provider to use the source IP address of the data stream used to update your DDNS record. In most Home / SOHO environments this will be the same as that of the firewalls external NAT IP address.

In cases where "web" mode doesn't work, the DDclient script can also log in and parse out the external IP address of the router. It then communicates this information to your dynamic DNS provider.  DDclient claims to offers support for a wide variety of routers from different manufacturers.

Remember, some routers such as the netgear line may provide automatic DDNS service and you may not have to download the software.

Before installing DDclient, read the README file to give you an idea of what to do. Check the Bibliography for the DDclient URL. Here is an example of the steps used to install it.

 

[root@bigboy tmp]# gunzip ddclient.tar.gz
[root@bigboy tmp]# tar -xvf ddclient.tar
ddclient-3.6.2/
ddclient-3.6.2/COPYRIGHT
ddclient-3.6.2/COPYING

[root@bigboy tmp]# cd dd*
[root@bigboy ddclient-3.6.2]# ll
-rw-r--r-- 1 root root 18007 Jan 3 2002 COPYING
-rw-r--r-- 1 root root 869   Jan 3 2002 COPYRIGHT

 [root@bigboy ddclient-3.6.2]# cp sample-etc_rc.d_init.d_ddclient.redhat /etc/rc.d/init.d/ddclient
[root@bigboy ddclient-3.6.2]# /sbin/chkconfig --add ddclient
[root@bigboy ddclient-3.6.2]# cp ddclient /usr/sbin/

 

The /etc/ddclient.conf File

DDclient uses a configuration file named /etc/ddclient.conf in which you must specify: 

o        Your registration username and password

o        The host name you have selected for your Linux box. This is referenced on the line labeled "server".

o        The NIC interface which is connected to your DSL line.

 

Here is a sample using interface eth0:

 

## dyndns.org custom addresses
##
## (supports variables: wildcard,mx,backupmx)
##
use=if, if=eth0 # via interfaces
login=your-login # default login
password=your-password # default password
custom=yes \
server=members.dyndns.org, \
protocol=dyndns2 \
your-domain.top-level,your-other-domain.top-level # Your domains here
 

Before updating the file you can use DDclient with the "-query" option to tell you which is the best mode to use. Here is an example.

 

[root@bigboy ddclient-3.6.2]# ddclient -daemon=0 -query
use=if, if=lo address is 127.0.0.1
use=if, if=wlan0 address is 192.168.1.100
use=web, web=dyndns address is 97.158.253.26
[root@bigboy ddclient-3.6.2]#

 

In this case, the simple web mode provides an acceptable value for your external IP address. You can then configure your /etc/ddclient.conf file to use "web"

 

#use=if, if=eth0 # via interfaces

use=web # via web

 

Testing Your Dynamic DNS

You can test your dynamic DNS by:

·     Looking at the status page of your DNS provider and making sure the IP address that matches your "www" site is the same as your router / firewall's public IP address.

·     Using the nslookup www.my-site.com command from your Linux command prompt and see whether you are getting a valid response. If you failed to add your host record, you will get an error message like this:

 

[root@bigboy tmp]# nslookup www.my-site.com
 

Server: 127.0.0.1
Address: 127.0.0.1#53

** server can't find www.my-site.com: NXDOMAIN

 

Note: This error could also be due to the fact that your domain hasn't propagated fully throughout the Internet. You can test to make sure everything is OK by forcing NS lookup to query the nameservers directly. The example below queries the miniDNS name server:

 

[root@bigboy tmp]# nslookup
> server ns1.minidns.net
Default server: ns1.minidns.net
Address: 202.64.51.214#53
> www.my-site.com
Server: ns1.minidns.net
Address: 202.64.51.214#53

Name: www.my-site.com
Address: 12.235.194.96

Testing Port Forwarding

Remember to read the configuration manual of your router / firewall to activate port forwarding. Test it by asking a friend to access your web server by pointing their browser to the external IP address of your router / firewall.

 

Saturday, May 03, 2008

Virtual Host Examples from Apache


http://httpd.apache.org/docs/2.0/vhosts/examples.html

Running several name-based web sites on a single IP address.

Your server has a single IP address, and multiple aliases (CNAMES) point to this machine in DNS. You want to run a web server for www.example1.com and www.example2.org on this machine.

Note

Creating virtual host configurations on your Apache server does not magically cause DNS entries to be created for those host names. You must have the names in DNS, resolving to your IP address, or nobody else will be able to see your web site. You can put entries in your hosts file for local testing, but that will work only from the machine with those hosts entries.

Server configuration

# Ensure that Apache listens on port 80
Listen 80

# Listen for virtual host requests on all IP addresses
NameVirtualHost *:80

<VirtualHost *:80>
DocumentRoot /www/example1
ServerName www.example1.com

# Other directives here

</VirtualHost>

<VirtualHost *:80>
DocumentRoot /www/example2
ServerName www.example2.org

# Other directives here

</VirtualHost>

The asterisks match all addresses, so the main server serves no requests. Due to the fact that www.example1.com is first in the configuration file, it has the highest priority and can be seen as the default or primary server. That means that if a request is received that does not match one of the specified ServerName directives, it will be served by this first VirtualHost.

Note

You can, if you wish, replace * with the actual IP address of the system. In that case, the argument to VirtualHost must match the argument to NameVirtualHost:

NameVirtualHost 172.20.30.40

<VirtualHost 172.20.30.40>
# etc ...

However, it is additionally useful to use * on systems where the IP address is not predictable - for example if you have a dynamic IP address with your ISP, and you are using some variety of dynamic DNS solution. Since * matches any IP address, this configuration would work without changes whenever your IP address changes.

The above configuration is what you will want to use in almost all name-based virtual hosting situations. The only thing that this configuration will not work for, in fact, is when you are serving different content based on differing IP addresses or ports.

top

Name-based hosts on more than one IP address.

Note

Any of the techniques discussed here can be extended to any number of IP addresses.

The server has two IP addresses. On one (172.20.30.40), we will serve the "main" server, server.domain.com and on the other (172.20.30.50), we will serve two or more virtual hosts.

Server configuration

Listen 80

# This is the "main" server running on 172.20.30.40
ServerName server.domain.com
DocumentRoot /www/mainserver

# This is the other address
NameVirtualHost 172.20.30.50

<VirtualHost 172.20.30.50>
DocumentRoot /www/example1
ServerName www.example1.com

# Other directives here ...

</VirtualHost>

<VirtualHost 172.20.30.50>
DocumentRoot /www/example2
ServerName www.example2.org

# Other directives here ...

</VirtualHost>

Any request to an address other than 172.20.30.50 will be served from the main server. A request to 172.20.30.50 with an unknown hostname, or no Host: header, will be served from www.example1.com.

top

Serving the same content on different IP addresses (such as an internal and external address).

The server machine has two IP addresses (192.168.1.1 and 172.20.30.40). The machine is sitting between an internal (intranet) network and an external (internet) network. Outside of the network, the name server.example.com resolves to the external address (172.20.30.40), but inside the network, that same name resolves to the internal address (192.168.1.1).

The server can be made to respond to internal and external requests with the same content, with just one VirtualHost section.

Server configuration

NameVirtualHost 192.168.1.1
NameVirtualHost 172.20.30.40

<VirtualHost 192.168.1.1 172.20.30.40>
DocumentRoot /www/server1
ServerName server.example.com
ServerAlias server
</VirtualHost>

Now requests from both networks will be served from the same VirtualHost.

Note:

On the internal network, one can just use the name server rather than the fully qualified host name server.example.com.

Note also that, in the above example, you can replace the list of IP addresses with *, which will cause the server to respond the same on all addresses.

top

Running different sites on different ports.

You have multiple domains going to the same IP and also want to serve multiple ports. By defining the ports in the "NameVirtualHost" tag, you can allow this to work. If you try using <VirtualHost name:port> without the NameVirtualHost name:port or you try to use the Listen directive, your configuration will not work.

Server configuration

Listen 80
Listen 8080

NameVirtualHost 172.20.30.40:80
NameVirtualHost 172.20.30.40:8080

<VirtualHost 172.20.30.40:80>
ServerName www.example1.com
DocumentRoot /www/domain-80
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
ServerName www.example1.com
DocumentRoot /www/domain-8080
</VirtualHost>

<VirtualHost 172.20.30.40:80>
ServerName www.example2.org
DocumentRoot /www/otherdomain-80
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
ServerName www.example2.org
DocumentRoot /www/otherdomain-8080
</VirtualHost>

top

IP-based virtual hosting

The server has two IP addresses (172.20.30.40 and 172.20.30.50) which resolve to the names www.example1.com and www.example2.org respectively.

Server configuration

Listen 80

<VirtualHost 172.20.30.40>
DocumentRoot /www/example1
ServerName www.example1.com
</VirtualHost>

<VirtualHost 172.20.30.50>
DocumentRoot /www/example2
ServerName www.example2.org
</VirtualHost>

Requests for any address not specified in one of the <VirtualHost> directives (such as localhost, for example) will go to the main server, if there is one.

top

Mixed port-based and ip-based virtual hosts

The server machine has two IP addresses (172.20.30.40 and 172.20.30.50) which resolve to the names www.example1.com and www.example2.org respectively. In each case, we want to run hosts on ports 80 and 8080.

Server configuration

Listen 172.20.30.40:80
Listen 172.20.30.40:8080
Listen 172.20.30.50:80
Listen 172.20.30.50:8080

<VirtualHost 172.20.30.40:80>
DocumentRoot /www/example1-80
ServerName www.example1.com
</VirtualHost>

<VirtualHost 172.20.30.40:8080>
DocumentRoot /www/example1-8080
ServerName www.example1.com
</VirtualHost>

<VirtualHost 172.20.30.50:80>
DocumentRoot /www/example2-80
ServerName www.example1.org
</VirtualHost>

<VirtualHost 172.20.30.50:8080>
DocumentRoot /www/example2-8080
ServerName www.example2.org
</VirtualHost>

top

Mixed name-based and IP-based vhosts

On some of my addresses, I want to do name-based virtual hosts, and on others, IP-based hosts.

Server configuration

Listen 80

NameVirtualHost 172.20.30.40

<VirtualHost 172.20.30.40>
DocumentRoot /www/example1
ServerName www.example1.com
</VirtualHost>

<VirtualHost 172.20.30.40>
DocumentRoot /www/example2
ServerName www.example2.org
</VirtualHost>

<VirtualHost 172.20.30.40>
DocumentRoot /www/example3
ServerName www.example3.net
</VirtualHost>

# IP-based
<VirtualHost 172.20.30.50>
DocumentRoot /www/example4
ServerName www.example4.edu
</VirtualHost>

<VirtualHost 172.20.30.60>
DocumentRoot /www/example5
ServerName www.example5.gov
</VirtualHost>

top

Using Virtual_host and mod_proxy together

The following example allows a front-end machine to proxy a virtual host through to a server running on another machine. In the example, a virtual host of the same name is configured on a machine at 192.168.111.2. The ProxyPreserveHost On directive is used so that the desired hostname is passed through, in case we are proxying multiple hostnames to a single machine.

<VirtualHost *:*>
ProxyPreserveHost On
ProxyPass / http://192.168.111.2/
ProxyPassReverse / http://192.168.111.2/
ServerName hostname.example.com
</VirtualHost>

top

Using _default_ vhosts

_default_ vhosts for all ports

Catching every request to any unspecified IP address and port, i.e., an address/port combination that is not used for any other virtual host.

Server configuration

<VirtualHost _default_:*>
DocumentRoot /www/default
</VirtualHost>

Using such a default vhost with a wildcard port effectively prevents any request going to the main server.

A default vhost never serves a request that was sent to an address/port that is used for name-based vhosts. If the request contained an unknown or no Host: header it is always served from the primary name-based vhost (the vhost for that address/port appearing first in the configuration file).

You can use AliasMatch or RewriteRule to rewrite any request to a single information page (or script).

_default_ vhosts for different ports

Same as setup 1, but the server listens on several ports and we want to use a second _default_ vhost for port 80.

Server configuration

<VirtualHost _default_:80>
DocumentRoot /www/default80
# ...
</VirtualHost>

<VirtualHost _default_:*>
DocumentRoot /www/default
# ...
</VirtualHost>

The default vhost for port 80 (which must appear before any default vhost with a wildcard port) catches all requests that were sent to an unspecified IP address. The main server is never used to serve a request.

_default_ vhosts for one port

We want to have a default vhost for port 80, but no other default vhosts.

Server configuration

<VirtualHost _default_:80>
DocumentRoot /www/default
...
</VirtualHost>

A request to an unspecified address on port 80 is served from the default vhost any other request to an unspecified address and port is served from the main server.

top

Migrating a name-based vhost to an IP-based vhost

The name-based vhost with the hostname www.example2.org (from our name-based example, setup 2) should get its own IP address. To avoid problems with name servers or proxies who cached the old IP address for the name-based vhost we want to provide both variants during a migration phase.
The solution is easy, because we can simply add the new IP address (172.20.30.50) to the VirtualHost directive.

Server configuration

Listen 80
ServerName www.example1.com
DocumentRoot /www/example1

NameVirtualHost 172.20.30.40

<VirtualHost 172.20.30.40 172.20.30.50>
DocumentRoot /www/example2
ServerName www.example2.org
# ...
</VirtualHost>

<VirtualHost 172.20.30.40>
DocumentRoot /www/example3
ServerName www.example3.net
ServerAlias *.example3.net
# ...
</VirtualHost>

The vhost can now be accessed through the new address (as an IP-based vhost) and through the old address (as a name-based vhost).

top

Using the ServerPath directive

We have a server with two name-based vhosts. In order to match the correct virtual host a client must send the correct Host: header. Old HTTP/1.0 clients do not send such a header and Apache has no clue what vhost the client tried to reach (and serves the request from the primary vhost). To provide as much backward compatibility as possible we create a primary vhost which returns a single page containing links with an URL prefix to the name-based virtual hosts.

Server configuration

NameVirtualHost 172.20.30.40

<VirtualHost 172.20.30.40>
# primary vhost
DocumentRoot /www/subdomain
RewriteEngine On
RewriteRule ^/.* /www/subdomain/index.html
# ...
</VirtualHost>

<VirtualHost 172.20.30.40>
DocumentRoot /www/subdomain/sub1
ServerName www.sub1.domain.tld
ServerPath /sub1/
RewriteEngine On
RewriteRule ^(/sub1/.*) /www/subdomain$1
# ...
</VirtualHost>

<VirtualHost 172.20.30.40>
DocumentRoot /www/subdomain/sub2
ServerName www.sub2.domain.tld
ServerPath /sub2/
RewriteEngine On
RewriteRule ^(/sub2/.*) /www/subdomain$1
# ...
</VirtualHost>

Due to the ServerPath directive a request to the URL http://www.sub1.domain.tld/sub1/ is always served from the sub1-vhost.
A request to the URL http://www.sub1.domain.tld/ is only served from the sub1-vhost if the client sent a correct Host: header. If no Host: header is sent the client gets the information page from the primary host.
Please note that there is one oddity: A request to http://www.sub2.domain.tld/sub1/ is also served from the sub1-vhost if the client sent no Host: header.
The RewriteRule directives are used to make sure that a client which sent a correct Host: header can use both URL variants, i.e., with or without URL prefix.