Pesquisar este blog

sexta-feira, 21 de janeiro de 2011

Apache 2 e PHP 5

Apache 2 and PHP Installation

The following notes are how I got Apache 2 and PHP 5 (or PHP 4) working together on Linux. These instructions also apply, mostly, for any UNIX-like system, especially other Linux distributions. If you have a recent Linux distribution (say since 2002), you already have Apache 2 and PHP, so you don't need to do this unless you want the latest Apache 2 or PHP release or need to customize the Apache or PHP software. Don't forget to remove (or at least disable) the Apache rpm package if you install your own custom Apache.

Apache 2 Version Tip: Beginning with Apache 2.0.42 the API will be kept stable (yeah!). That means you will NOT have to recompile modules (and possibly upgrade/fix source) every time you install a new Apache release. This assumes you stay in the same Apache release series. For example, upgrading from 2.2.0 to 2.2.2 should work. This will not apply to upgrading to the next series (e.g., "development" 2.3.x or "stable" 2.4.x).

I was only able to get PHP working with Apache 2 as a *.so DSO ("dynamic shared object"), as opposed to compiled into Apache (with a static *.a library). I think DSO is the only way PHP is supported now on Apache 2.

I first used httpd-2.0.43 and php-4.3.0 with RedHat 7.3. I am now using httpd-2.2.3 and php-5.2.0 with SUSE 10.1.

Note: If you have problems with PHP and think it's a recent bug, you may want to consider using the latest http://snaps.php.net/ snapshot. Beware that snapshots frequently have regression and are not for production use. Usually problems are because of mis-configuration, not bugs, so snapshots will probably hurt more than help.

1. Download/unpack Apache2 source from the Apache httpd server website, http://httpd.apache.org/

2. In the Apache 2 source directory, create a Makefile by typing:

./configure --prefix=/usr/local/apache \
--enable-so \
--enable-cgi \
--enable-info \
--enable-rewrite \
--enable-speling \
--enable-usertrack \
--enable-deflate \
--enable-ssl \
--enable-mime-magic

You only need the enable-so line above. For information on other options, type ./configure --help and see "Compiling and Installing" in the Apache 2 Documentation, http://httpd.apache.org/

3. Make Apache from the just-created Makefile:

make

4. If make is successful, install Apache as root:

make install

5. Download/unpack PHP source from the PHP website, http://www.php.net/
Pick the latest from the 4.x series or 5.x series.

6. In the PHP source directory, create a Makefile by typing:

./configure \
--with-apxs2=/usr/local/apache/bin/apxs \
--with-mysql \
--prefix=/usr/local/apache/php \
--with-config-file-path=/usr/local/apache/php \
--enable-force-cgi-redirect \
--disable-cgi \
--with-zlib \
--with-gettext \
--with-gdbm

You only need the --with-apxs2, and prefix lines. --with-mysql adds MySql (you need to specify the directory if it's in a unusual location (e.g., --with-mysql=/usr/local ), --with-config-file moves the php.ini file location, disable-cgi disables the CGI version, which is not needed if you use Apache modules. It also enables and installs the command line interface (CLI) version. --with-zlib allows use of gzip-type compression, --with-gettext is for internationalization, and --with-gdbm allows access to GDBM databases. For more information, type ./configure --help and see the "Installation" chapter in the PHP Manual, http://ww.php.net/docs.php

7. Make PHP from the just-created Makefile:

make

8. If make is successful, type this as root to install PHP:

make install

If you are not root (I do not perform makes while root, for security and safety reasons), become root and type the following:

make install-su

9. If file /usr/local/apache/modules/libphp5.so does not exist or is an older version, type this (change this to libphp4.so for PHP 4):

cp -p .libs/libphp5.so /usr/local/apache/modules

10. Install the php.ini file:

cp -p php.ini-recommended /usr/local/apache/php/php.ini

11. Add these directives are in /usr/local/apache/conf/httpd.conf (if already there, verify they are correct):

# Make sure there's only **1** line for each of these 2 directives:
# Use for PHP 4.x:
#LoadModule php4_module modules/libphp4.so
#AddHandler php-script php

# Use for PHP 5.x:
LoadModule php5_module modules/libphp5.so
AddHandler php5-script php

# Add index.php to your DirectoryIndex line:
DirectoryIndex index.html index.php

AddType text/html php

# PHP Syntax Coloring
# (optional but useful for reading PHP source for debugging):
AddType application/x-httpd-php-source phps


Note 1: The php documentation recommends AddType application/x-httpd-php php instead of the above. However, it causes problems with the "MultiViews" feature of HTTP. That is, if the .php extension is left off a URL, and with certain browser Accept headers, Apache will not know .php (application/x-httpd-php) is HTML and will return a 406 Not Acceptable error. Using the AddType and AddHandler as shown above fixes this problem. For details see Mark Tranchant's webpage, "Using Apache's MultiViews with PHP whilst avoid 406 errors," and PHP bug 28023.

Note 2: PHP Syntax coloring isn't required, but it's very nice for looking at your php source while debugging. Here's an example.

Note 3: just for completeness I'll mention that you should be able to use SetOutputFilter / SetInputFilter instead of AddType, but you can't use both. However, SetOutputFilter / SetInputFilter no longer works for me. It used to work with an earlier PHP 4.x or Apache 2 version, but not with Apache 2.0.47/PHP 4.3.3. I understand this (PHP as an Apache 2 filter) is experimental, so I don't use it anymore:


SetOutputFilter PHP
SetInputFilter PHP


12. You're now ready to try it out. Start Apache (httpd) as root:

/usr/local/apache/bin/apachectl start

13. Perform these sanity checks to verify your install went OK:

$ /usr/local/apache/bin/httpd -t
Syntax OK

$ /usr/local/apache/bin/httpd -v
Server version: Apache/2.2.2
Server built: May 29 2006 12:40:55


$ /usr/local/apache/bin/httpd -V
Server version: Apache/2.2.2
Server built: May 29 2006 12:40:55
Server's Module Magic Number: 20051115:2
Server loaded: APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture: 32-bit
Server MPM: Prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
-D APACHE_MPM_DIR="server/mpm/prefork"
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=128
-D HTTPD_ROOT="/usr/local/apache"
-D SUEXEC_BIN="/usr/local/apache/bin/suexec"
-D DEFAULT_PIDLOG="logs/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_LOCKFILE="logs/accept.lock"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="conf/mime.types"
-D SERVER_CONFIG_FILE="conf/httpd.conf"

$ /usr/local/apache/bin/httpd -S
VirtualHost configuration:
. . .

$ /usr/local/apache/bin/httpd -l
Compiled in modules:
core.c
. . .
mod_so.c

$ /usr/local/apache/bin/httpd -M
Loaded Modules:
. . .
php5_module (shared)
Syntax OK

(the above works for Apache 2.2.x and higher only)

$ ps -ef |grep httpd
root 24069 1 0 09:17 ? 00:00:08 /usr/local/apache/bin/httpd -k s
apache 29917 24069 0 15:30 ? 00:00:00 /usr/local/apache/bin/httpd -k s
. . .


Note: on BSD-based UNIX systems, you need to use "ps -aux" instead of "ps -ef".
14. Access your webserver with telnet. Type HEAD / HTTP/1.0 followed by a blank line:

$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Date: Mon, 29 May 2006 23:28:18 GMT
Server: Apache/2.2.2 (Unix) mod_ssl/2.2.2 OpenSSL/0.9.7a PHP/5.1.4
X-Powered-By: PHP/5.1.4
Last-Modified: Wed, 15 Mar 2006 06:53:17 GMT
Vary: Accept-Encoding
Connection: close
Content-Type: text/html; charset=ISO-8859-1
Content-Language: en

Connection closed by foreign host.

15. Access your webserver with your favorite browser. The following is a good test page to use for PHP. You only need the one line in bold is needed to display PHP configuration information. Name the file anything you want, but it must end with .php, such as phpinfo.php, and move the file to your web server content directory (for me /usr/local/apache/htdocs), with read permission set:


php logo Tips and Notes

• Disabling Existing Apache Software

If Apache is already installed with your Linux distribution you have to disable it before installing your own custom version. To do this, type the following under RedHat Linux:

/sbin/chkconfig --del httpd
/etc/init.d/httpd stop

You may also remove the httpd and php rpm packages, and dependent packages, if you wish.

• Automatic Startup of Apache

To start Apache automatically, follow these steps:

* Copy Apache startup file to the startup directory:

cp /usr/local/apache/bin/apachectl /etc/init.d/

* Edit /etc/init.d/apachectl by inserting these 2 lines in bold:

#!/bin/sh
#
# chkconfig: - 85 15
# description: Apache is a Web server used to serve HTML files and CGI.
#
# Copyright 2000-2005 The Apache Software Foundation or its licensors, as
# applicable.
. . .
# Apache control script designed to allow an easy command line interface
# to controlling Apache. Written by Marc Slemko, 1997/08/23
. . .

* Enable httpd to startup automatically:

/sbin/chkconfig --add apachectl
/sbin/chkconfig --level 2 apachectl on

This works for RedHat Linux, Mandrake, SuSE, and Sun Java Desktop System. The equivalent of chkconfig for Debian is:
update-rc.d apachectl defaults
For other distributions, make appropriate softlinks to directories /etc/rc*.d/

* Reboot Linux to verify Apache starts

[Thanks to Beriah Dutcher and others]

• Make doesn't make dynamic library libphp5.so, just static library libphp5.a

First make sure libphp5.so isn't there. It's usually in the libs or .libs subdirectory. Run find from the PHP source directory root: find . -name libphp5.so If that doesn't work, make sure you use the --with-apxs2 option with the correct directory in ./configure. For example:
./configure --with-mysql --with-apxs2=/path/to/apache/apxs
When re-running ./configure always start with a fresh, clean source directory (no object).

(For PHP 4, substitute libphp4.so and libphp4.a for libphp5.so and libphp5.a, respectively.)

• PHP 5: My PHP scripts that worked with PHP 4 now ignores input variables

If you have old PHP 4 scripts you don't want to convert to PHP 5, change this line in your php.ini file:

register_long_arrays = On

For the long term, you may want to upgrade your PHP software or convert the PHP source code to use new-style variables. E.g., use $_REQUEST[i] instead of $i

• PHP 5.2.0 Upgrade from 5.1.x (November 2006)
I had one problem with upgrading from PHP 5.1.x to 5.2.0. The Phorum 3 software I use has a function date_format that now conflicts with a new PHP 5.2 internal function, also called date_format. This new function is used for PHP 5.2.x's new "datetime support". I fixed this by renaming Phorum's date_format function to not conflict with PHP's function. See also PHP 5.2 Update Info for more PHP 5.2 upgrade information.

• PHP 5.x: you may need to upgrade libxml2 to use XML

To use PHP 5 and XML (--with-xml), you need the libxml2 library version 2.6.0 or greater. You may need to upgrade if you have an older Linux distribution. Check with rpm -q libxml2
If it's not installed, check your installation disks for the libxml2 package. If it's too old, you can get the library from XMLSoft.org. You will probably need to compile and install it yourself.

• PHP 4.3.5 / 4.3.6 / 5.0RC1 PCRE Regression (March 2004)

If you use PHP 4.3.5, 4.3.6, or PHP 5.0 RC1 with PCRE (Perl Regular Expressions, the default), you get a core dump when you try and restart (SIGHUP) Apache (at least with Apache 2.0.49). The cause is from adding a new version of PCRE, 4.5, in PHP. This is fixed in PHP 4.3.7 and 5.0.

The symptom are these messages in error_log (which is also a symptom for lots of other memory-type bugs in Apache):

[Wed Mar 31 17:14:43 2004] [notice] SIGHUP received. Attempting to restart
[Wed Mar 31 17:14:43 2004] [notice] seg fault or similar nasty error detected in the parent process
[Wed Mar 31 17:14:48 2004] [warn] pid file /var/run/httpd.pid overwritten -- Unclean shutdown of previous Apache run?

To fix, upgrade to PHP 4.3.7 or higher, which fixes it (PHP 5.0 or higher also fixes the bug). A workaround is to stop/start Apache, instead of restarting Apache. For details, see PHP bug 27810.

• ServerRoot Installation Directory

By default, Apache is installed in ServerRoot, as specified in httpd.conf or the httpd -d option:
ServerRoot "/usr/local/apache"
Some packagers and distributions move the location to /usr/local/httpd or /usr/local/apache2 so check that Apache is installed where you say it is, and check that you don't have two separate Apache installations by mistake.

• PHP-required Apache files must be present

PHP expects certain files to be present. They may be missing for some Linux distributions, which tend to separate files among the /var, /etc, and other directories. The apxs program expects to find httpd under the bin directory where apache is installed (by default /usr/local/apache/bin). PHP expects to find the os.h and unixd.h header files under the include directory where apache is installed (by default /usr/local/apache/include).

• MySQL

Use the --with-mysql configure option to build PHP with PHP's version of MySql. If you want the system's MySQL, or are also using MySql with another apache module (e.g., mod_perl), use this: with-mysql=/usr

Make sure the MySQL developent headers are installed. This is usually package mysql-devel (thanks to Dev for the tip)

• Custom OpenSSL and SSL

When using "--enable-ssl" (i.e, build with OpenSSL), the configure script will try to guess the location of OpenSSL. If you're using your own custom SSL, you must specify the location. For example, "--with-ssl=/usr/local/ssl" (of course, you can use the SSL and PHP that comes with Redhat 9 and other distributions).

Please note that mod_ssl is only for Apache 1.x. Apache 2.x does not use mod_ssl—SSL is built into Apache 2.x.

Jason reports that with RedHat 9 on his system, the make failed at mod_ssl. It needed a missing krb5.h header file. The fix is to Add an environment variable, $CFLAGS, before making PHP. That is:
"-I/usr/kerberos/include/ -L/usr/kerberos/lib"

• gdbm
If you get this error when using "--with-gdbm":
configure: error: DBA: Could not find necessary header file(s).
then you are probably missing the gdbm-devel rpm package.

• Apache 1.x and Apache 2 Configuration Directives
The "AddModule," "AgentLog," "ReferrerLog," "RefererIgnore," "BindAddress," "ClearModuleList," "Port," "FancyIndexing," "ServerType," "AccessConfig," and "ResourceConfig" directives in Apache 1.x no longer exist in Apache 2. Also, "HAVE_*" httpd.conf definitions no longer exist. Comment them out of your httpd.conf for Apache 2. Most of these directives have been replaced by other directive(s).

• Error after glibc library upgrade

Apache should still work after upgrading glibc with security and bug fixes for the same release. If you use another architecture (say from or to i386/i686), you need to recompile. One symptom is an error like this in your Apache error_log:
[error] (38)Function not implemented:

• make clean

Kåre Olaussen adds this note: If you're compiling php4 for both Apache 1.3 and Apache 2, use a separate php source directory for each version of Apache. "The module wouldn't load into Apache 2, because I had forgotten to run make clean in between." [Ed. note: I recommend untaring the source from scratch in another directory, that way you are sure no old state information is left behind from previous makes. Do this for any configuration or version changes.]

• Enabling register_globals for Apache 2

From Duke: For those of you that are desperately trying to enable register_globals on a per-directory basis using Apache 2 with PHP 4 [or PHP 5] using .htaccess files, the syntax is different from Apache 1.x. In the directory you want to enable register_globals (or pretty much any other on/off setting), add an .htaccess file containing:

php_value register_globals 1

Note that php_flag does not work with Apache 2. Neither does on / off — you must use 0 (off) or 1 (on).

[Editor's note: To enable globally, add register_globals=off to your php.ini file.]

To enable register_globals on a per-directory basis, you can add to a stanza or create a .htaccess configuration file in the directory. To use .htaccess, you must first enable it by adding AllowOverride All (or some combination of AllowOverride options within the correct stanza. Also newer PHP software, such as SquirrelMail, no longer require register_globals to be enabled. Keeping register_globals disalbed makes the system much more secure (as it's harder to set internal php variables through submitting html forms). ]

• Multi-Processing Module (MPM): don't use multi-threading MPMs

MPMs is how Apache 2 handles multiple web server requests. That is, with multiple processes or multiple threads or some combination. For now, on Linux (and even UNIX) you should only use the (default) prefork module with PHP. This is specified at compile time. Other MPM modules (any involving threads) break PHP. This is partly because PHP uses a great number of external libraries, and many or most of them are not thread-safe or thread-aware. In any case, Linux 2.4 doesn't handle threads efficiently yet—multiple processes are better (this changes with Linux 2.6, or RedHat 9 with 2.6 threads backported to Linux 2.4).

• API module structure `php5_module' in file . . . is garbled
If you get a message like this:

httpd: Syntax error on line 195 of /usr/local/apache/conf/httpd.conf: API module
structure `php5_module' in file /usr/local/apache/modules/libphp5.so is garbled
- perhaps this is not an Apache module DSO

it's because your version of PHP wasn't built for the version of Apache you are using (For PHP 4, substitute php4_module . . . libphp4.so). Recompile PHP in a "fresh" source directory (where you haven't built PHP before) and make sure --prefix, --with-config-file and --with-apxs2 points to the correct Apache directories you are using and the libphp4.so file has been copied to your /usr/local/apache/modules directory.

• PATH_INFO

Dan Fitzpatrick notes that he uses PATH_INFO for many PHP scripts like /index.php/go/do/something (where parameters are passed to PHP as "fake" subdirectories). He received a 404 Not Found errors with Apache 2 but not Apache 1.3.27. He had to add "AcceptPathInfo On" to file httpd.conf. For details, see http://httpd.apache.org/docs-2.2/mod/core.html#acceptpathinfo

• Using style tags in addition to style tags

If you want to also use the old-style (or MS ASP-like) tags then add this line to your php.ini file. This is the default starting with PHP 5:

short_open_tag = On

• GD library now built-in PHP

PHP 4.3.0 has gd built-in, just pass --with-gd to PHP configure.

• --with-apache

If you don't have Apache source at the default directory at /usr/local/apache, then use --with-apache=DIR with PHP configure, where DIR is the root source directory, This tells PHP where to look for the Apache source.

• Redhat 9
Apache 2 and PHP is built-in RedHat 9 (packages httpd 2.0.40, and php 4.2.2). Apache is mostly under /usr/lib/httpd and /usr/sbin/httpd. PHP is at /usr/lib/httpd/modules/libphp4.so For a complete file listing, type: rpm -ql httpd php

For RedHat 9, PHP 4.3.1 gives a compiler errors with RedHat 9 similar to: my_malloc.c:24: undefined reference to `errno'
The problem is with mysql and will have to wait for a fix from them. Until then, add this line:
#include
to the beginning of file ./ext/mysql/libmysql/mysql.h in your PHP source and remake PHP (from scratch).

• Notes about Gentoo Linux and Apache2 with PHP

LoadModule php5_module modules/libphp5.so
becomes:
LoadModule php5_module /usr/lib/apache2-extramodules/libphp5.so

To start automatically under Gentoo:
rc-update add apache2 default
(change php5 to php4 for PHP 4)

[Thanks to Phillip Temple]
php logo References

* Apache and PHP
* Original posting on USENET newsgroup comp.lang.php, 1b7cbdd3.0210181532.68d981cb%40posting.google.com
* "Compiling PHP 4 and Apache 2 from source on Linux OS", a document similar to this one, with more details and options, by Sukhwinder Singh.
* Install & Configure Apache, PHP, JSP, Ruby on Rails, MySQL, PHPMyAdmin & WordPress on Windows XP/2000
* OnLAMP.com: Good source of PHP and Apache tutorials (O'Reilly)

* Apache
* Apache httpd server website: Links to documentation and source
o How to upgrade from Apache 1.3 to 2.0
o How to upgrade from Apache 2.0 to 2.2
o Why should you upgrade (Apache 2.0 features)
* Migrating Apache HTTP Server 1.3 Configuration Files (Redhat)
* Sites Reject Apache2 commentary on Slashdot about slow adoption of Apache 2 due to a lack of 3rd-party modules (9/2002).
* ApacheWeek has the best updates on Apache development effort.
* Apache on Slashdot also has news on Apache and related efforts.

* PHP
* PHP website: Has links to documentation, source, mailing lists, and news groups
* PHP Weekly Summary, is a good source on the latest PHP developments.
* PHP FAQ: Old, but still useful. Note that the newsgroup has moved to USENET newsgroup comp.lang.php. (also available at Google Groups)

* PHP Security
o Secure Programming in PHP by Thomas Oertli (Zend.com, 1/2002)
o Security Notes by JeffCT (DevShed.com, 1/2001)

Retirado de: http://dan.drydog.com/apache2php.html
Todos os direitos ao autor.


quarta-feira, 8 de dezembro de 2010

Understanding SIP-Based VoIP

Understanding SIP-Based VoIP
Version 1.0

1. What Does VoIP Mean

Since people started using digital voice coding, such as ISDN, they have thought about convergence between telephony and IT environment in order to transmit data, voice and video applications using one and the same medium. Unfortunately, each of these applications has different needs. Data transmission requires variable line bandwidths and doesn't care for reliability of connection, and, on the contrary, voice and video transmissions need a constant bandwidth and guaranteed time of delivery.

The structures of available networks are different and only meet the needs of the application they have been created for. In data networks, everyone can use the available bandwidth to the maximum extent, which means that the line capacity is exploited efficiently. On the contrary, telephone network reserves a channel per call regardless of data transmission (e.g. one party is speaking only during a standard call -> there is no data transmission from the non-speaking party but the channel keeps busy).

A lot of voice and video transmission technologies using real-time IP networks (Internet), generally called VoIP(Voice over IP), have been developed as an alternative to the standard circuit-switching telephone network. As a result of natural selection, only two of them are now implemented in telecommunications, which improves interaction and compatibility of products from different companies. These two technologies are H.323 and SIP.

2. Signal and Voice Paths

Voice and signal communication channels are strictly separated in the VoIP network. Signal sessions are mostly administered by a server, which replaces a standard PBX in the IP environment. The voice stream is created point-to-point between end sides. For better understanding see the following diagram.


2.1 Voice and Video Transmission in VoIP

As mentioned above, constant bandwidth, guaranteed time of packet delivery (also called jitter) and correct sequence are necessary for successful voice transmission. We need not worry about delivery of any packet during voice transmission because mathematical methods used for voice signal coding and decoding can make approximation when a packet has not been delivered. Thus, we can use the UDP for voice stream transmission, which has no acknowledgement of delivered packets, but in any case we need a protocol that is responsible for voice coding, jitter, sequence order and bandwidth. This protocol is called RTP (Realtime Transport Protocol) and is widely used for voice transmission in modern VoIP networks. Its task is to transmit data (voice) from the source to the proper destination at real time. So-called codecs are used to save the data bandwidth by reducing the transmission rate using a complex algorithm. The level of compression used by the codec affects the quality of the transmitted voice. This means that the wider the data bandwidth (the higher the transmission rate), the higher the voice transmission quality. The voice transmission quality is measured by the MOS (Mean Opinion Score), where 1 means the worst and 5 the best quality. For a list of VoiceBlue-supported codecs see the table below:

Standard Algorithm Transmission Rate MOS
G.711 PCM 64 4.1
G.726 ADPCM 32 3.85
G.729 CS-ACELP 8 3.92
G723.1 ACELP 5.3 3.56
2.2 SIP as a Signalling Protocol

The SIP (Session Initiation Protocol) is a text-based protocol, similar to the HTTP and SMTP, designed for initiating, maintaining and terminating of interactive communication sessions between users. Such sessions include voice, video, chat, interactive games, and virtual reality.

The SIP defines and uses the following components:

UAC (User agent client) – client in the terminal that initiates SIP signalling
UAS (User agent server) – server in the terminal that responds to the SIP signalling from the UAC
UA (User Agent) – SIP network terminal (SIP telephones, or gateway to other networks), contains UAC and UAS
Proxy server – receives connection requests from the UA and transfers them to another proxy server if the particular station is not in its administration
Redirect server – receives connection requests and sends them back to the requester including destination data instead of sending them to the calling party
Location Server – receives registration requests from the UA and updates the terminal database with them.
All server sections (Proxy, Redirect, Location) are typically available on a single physical machine called proxy server, which is responsible for client database maintenance, connection establishing, maintenance and termination, and call directing.

Basic messages sent in the SIP environment

INVITE – connection establishing request
ACK – acknowledgement of INVITE by the final message receiver
BYE – connection termination
CANCEL – termination of non-established connection
REGISTER – UA registration in SIP proxy
OPTIONS – inquiry of server options
Answers to SIP messages are in the digital format like in the http protocol. Here are the most important ones:

1XX – information messages (100 – trying, 180 – ringing, 183 – progress)
2XX – successful request completion (200 – OK)
3XX – call forwarding, the inquiry should be directed elsewhere (302 – temporarily moved, 305 – use proxy)
4XX – error (403 – forbidden)
5XX – server error (500 – Server Internal Error, 501 – not implemented)
6XX – global failure (606 – Not Acceptable)
Connection establishing and terminating procedures in the SIP proxy server environment:



Todos os direitos ao autor:
Jan Mastalir, DiS.
Technical support
2N TELEKOMUNIKACE a.s.

Retirado de:
http://www.packetizer.com/ipmc/sip/papers/understanding_sip_voip/

terça-feira, 9 de novembro de 2010

Migrando Sistemas Empresariais para VoIP.

O Voip é uma tecnologia que nasceu a partir da comunicação entre maquinas através de uma rede, essa seria a definição mais básica ou mais simplista e assim não nos deteremos em conceitos hipóteses ou teses.
Seu uso e aproveitamento esta a disposição de todos os tipos de usuários não sendo propriamente desenvolvido para uma casta seja ela qual for, quero crer que seja democrático na definição mais purista.

O Voip enquanto ferramenta para negócios apresenta várias facetas e varias aplicações propiciando ao seu usuário facilidades nunca antes imaginadas, mas tem também seus percalços.

1. Aparelho de Fax - A maioria dos modelos de aparelhos de fax devem ser capazes de trabalhar com o seu sistema de VoIP, mas você terá que conectá-los a um adaptador apropriado ao seu fax.
Alguns provedores VoIP podem fornecer números de fax separado do número usado para comunicação de Voz, gratuitamente, como parte do contrato de serviços.
Verifique com seu provedor de serviços VoIP como é o serviço de fax que ele coloca a sua disposição e não se esqueça de se certificar que seu modelo de fax é compatível antes de cancelar o sistema convencional.

2. Lista Telefônica - números de telefone Voip nem sempre estão a disposição em listas locais ou mesmo em páginas amarelas.
Algumas empresas prestadoras de serviço Voip podem ter uma lista com os números Voip de seus clientes muitas vezes é so autoriza-los que eles publicam o seu.
Outros, mesmo algumas empresas maiores, não fornecem o serviço de listas telefônicas e talvez seja necessário procurar um meio para fazer a divulgação de seu número.

3. Máquinas de Cartão de Crédito - Se você estiver usando VoIP para o seu negócio verifique junto a empresa de Cartão de crédito qual a proposta ou mesmo solução que ela possui para quem esta pretendendo usar Voip, claro que hoje os sistemas de pagamentos usando-se Internet já resolvem grande parte do problema.
Algumas máquinas de cartão de credito mais antiga só funcionam com sistemas analógicos, outras podem trabalhar com linhas VoIP, mas é necessário se informar sobre a velocidade das operações que podem ser reduzidas.
Verifique com seu provedor de VoIP e coloque para ele as suas preocupações com o sistema. Em alguns casos adaptadores podem estar disponíveis, em outros casos pode ser necessário a manutenção de uma linha tradicional.

4.Desconexão - alguns serviços VoIP não enviam um sinal para desligar do modo tradicional e isso poderá fazer as com que uma das pontas da conexão fique travada e não desligue quando deveria.
Isto pode causar problemas quando você deixar uma mensagem de voz ou se você usar um atendimento automatizado de discagem direta ramal.
A incapacidade para o desligar poderá causar longos atrasos após envio de mensagens de telefones. Teste estes sistemas completamente antes de fazer a transição total para VoIP.

5. Negócios e as necessidades - Antes de você mudar a sua comunicação de seu negócio para VoIP, certifique-se e faça uma investigação ampla para verificar se é ou não adequado para a sua empresa a mudança e em que percentual.
Embora você tenha possibilidade de economizar em encargos de telefonia, ele também poderá ter as suas desvantagens.
A transição para VoIP irá muito provavelmente exigir um investimento em equipamento, e existe a possibilidade de que o VoIP possa não funcionar com alguns de seus equipamentos e sistemas existentes.
Faça alguns testes usando apenas alguns usuários e alguns setores de sua empresa antes de tomar qualquer decisão, seja a favor da mudança para o Voip ou contra, lembre-se que devemos estar sempre abertos aos avanços tecnológicos sobre pena de ficarmos atrás de nosso concorrente ao não analisarmos todas as nossas possibilidades.


Retirado de:
http://josempinto.blogspot.com/2008/05/migrando-sistemas-empresariais-para.html
Todos os créditos ao autor.

segunda-feira, 17 de agosto de 2009

Samba PDC - Fácil e Rápido

Instalando os pacotes

Começamos instalando os pacotes necessários para o funcionamento de seu Samba como servidor e cliente.

  1. apt-get install samba samba-common smbclient smbfs

Após a instalação, não se preocupe com as opções que forem pedidas, pois iremos configurar o arquivo manualmente. Primeiro passo é fazer um backup do arquivo de configuração do Samba.

  1. cp /etc/samba/smb.conf /etc/samba/smb.bkp.conf

Agora apague todo o conteúdo dentro do arquivo /etc/samba/smb.conf com o comando:

  1. echo "" > /etc/samba/smb.conf

Agora edite o arquivo:

  1. vim /etc/samba/smb.conf

Copie e cole o conteúdo a seguir em seu arquivo:

global

# Nome do seu Servidor

comment = Servidor SAMBA PDC

# Domínio do servidor PDC

workgroup = domínio

# Indica ser obrigatório o uso de usuário e senha

security = user

os level = 100

announce as = NT Server

domain logons = yes

# Qual script será executa a ser logado %U significa nome do usuário

logon script = %U.bat

# Opções principais para se tornar o PDC

domain master = yes

local master = yes

preferred master = yes

encrypt passwords = yes

keep alive = 20

debug level = 3

log file = /var/log/samba_log.%u

null passwords = no

unix password sync = yes

socket options = IPTOS_LOWDELAY TCP_NODELAY

# Hosts Liberados

hosts allow = 192.168.1. 127. 192.168.0.

# Hosts Bloqueados

hosts deny = 192.168.0.3 192.168.0.4

#=========== Compartilhamento de Diretórios ===============

homes

comment = Pastas dos Usuários

public = no

browseable = no

writeable = yes

#Caminho para os scripts de logon

netlogon

comment = Compartilhamento de Scripts

# Não esquece de criar a pastas e colocar os scripts dentro

path = /etc/samba/scripts/

public = no

browseable = no

writeable = no

Diretório Compartilhado

comment = Compartilhamento

path = /mnt/compartilhado

browseable = yes

valid users = @grupos

writeable = yes

write list = @users

force create mode = 0770

force directory mode = 0770

Reinicie o serviço Samba:

  1. /etc/init.d/samba stop
  2. /etc/init.d/samba start

Configurando o Samba para receber Windows XP

Primeiro passo é adicionar usuários no Linux:

  1. adduser usuário

Logo após adicione ao Samba:

  1. smbpasswd -a usuário

O parâmetro "-a" indica para adicionar o usuário.

Este comando é "o pulo do gato", é o ponto chave para que as máquinas funcionem. É necessário adicionar o hostname das máquinas Windows XP para que funcione o domínio nas mesmas. Se você não sabe como ver isso no Windows XP, siga os passos a seguir:

Clique no menu "Iniciar", logo após clique em "Configurações", "Painel de Controle", depois em "Sistema".

Iniciar -> Configurações -> Painel de Controle -> Sistema

Agora nas etiquetas em cima, clique em "Nome do Computador".

Em Frente ao "Nome completo do Computador" é o hostname.

Voltando ao Samba...

Primeiro crie o grupo "maquinas":

  1. addgroup maquinas

Agora adicione a máquina no Linux, não esqueça do "$" após o nome, pois isso indica que é uma máquina e não um usuário.

  1. useradd -d /dev/null -g maquinas -s /bin/false nome_da_maquina$

Agora adicione ao Samba, perceba que não é necessário colocar o "$" após o nome do host:

  1. smbpasswd -a -m nome_da_maquina

Pronto, seu Samba PDC com Windows XP já está adicionado e funcionando!

Configurando o Windows XP para domínio

Clique no menu "Iniciar", logo após clique em "Configurações", "Painel de Controle", depois em "Sistema".

Iniciar -> Configurações -> Painel de Controle -> Sistema

Agora nas etiquetas em cima clique em "Nome do Computador".

Clique em "Alterar".

Na opção "Membro de", selecione "Domínio".

Coloque o nome do domínio que você escolheu no Samba.

Clique em OK e pronto.


Fonte: http://sergioaraujo.pbworks.com/Servidor-Samba-PDC-para-windows-em-3-passos

todos os créditos ao autor.

quinta-feira, 6 de agosto de 2009

Utilizando o TCPdump

O tcpdump é um dos mais, se não o mais "famoso" sniffer para sistemas GNU/Linux. Com ele podemos realizar análises de redes e solucionar problemas. Sua utilização é simples e sem mistérios, bastando apenas ter os conhecimentos básicos de redes TCP/IP. Esta dica é apenas uma introdução deste sniffer, maiores informações e documentação à seu respeito podem ser encontradas em seu site oficial:
A instalação do tcpdump em sistemas Debian é super simples, bastando executar o comando abaixo como super usuário (root):

# apt-get install tcpdump

Para iniciarmos a utilização do tcpdump precisamos especificar a interface de rede que queremos analisar com o parâmetro -i seguido da interface desejada, por exemplo, se quisermos analisar todo o tráfego que passa pela interface eth0, executaríamos a seguinte linha de comando:

# tcpdump -i eth0

Conexões de origem podem ser monitoradas utilizando o parâmetro src host, um exemplo simples seria monitorarmos o tráfego que vem de 192.168.0.9 para nosso computador, com o ip 192.168.0.2. A linha de comando ficaria da seguinte forma:

# tcpdump -i eth0 src host 192.168.0.9

Se quisermos monitorar as conexões especificando um host de destino, poderíamos fazê-lo com o parâmetro dst host, o exemplo abaixo mostra todo o tráfego do host 192.168.0.2 com 192.168.0.1, no caso, 192.168.0.1 é nosso gateway.

# tcpdump -i eth0 dst host 192.168.0.1

Com tcpdump também podemos especificar exceções com o parâmetro not host, por exemplo, em nosso servidor queremos ver todo o tráfego que se passa em sua interface, exceto o de 192.168.0.8, faríamos da seguinte forma:

# tcpdump -i eth0 not host 192.168.0.9

No tcpdump podemos também especificar portas de origem e destino com os comandos src port e dst port, um exemplo seria monitorarmos o tráfego destinado à porta 80 (http), para isso utilizaríamos a linha de comandos abaixo e navegaríamos em um site qualquer:

# tcpdump -i eth0 dst port 80

Para verificarmos o tráfego da porta de origem 32881 por exemplo, faríamos da seguinte forma:

# tcpdump -i eth0 src port 32881

Muitas opções avançadas podem ser obtidas com o tcpdump, essas são algumas opções básicas, porém fundamentais para quem quer aprender sobre sniffers.

Retirado de:
http://www.vivaolinux.com.br/dica/tcpdump-Monitorando-conexoes/
todos os créditos ao autor.

terça-feira, 21 de julho de 2009

Instalação do Debian para iniciantes.

Linux -
Linux é um termo utilizado para designar o kernel (núcleo) de sistemas operacionais desenvolvido pelo finlandês Linus Torvalds. Este termo também é utilizado para designar os sistemas operacionais baseados no núcleo linux agregado a outros programas (distribuições linux).

O GNU/Linux é um sistema operacional de livre distribuição e utilização, regido pela GPL:

A GPL (General Public License) é baseada em quatro liberdades:

1. A liberdade de executar o programa, para qualquer propósito (liberdade nº 0)
2. A liberdade de estudar como o programa funciona e adaptá-lo para às suas necessidades (liberdade nº 1).
O acesso ao código-fonte é um pré-requisito para esta liberdade.
3. A liberdade de redistribuir cópias de modo que você possa ajudar ao seu próximo (liberdade nº 2).
4. A liberdade de aperfeiçoar o programa, e liberar os seus aperfeiçoamentos, de modo que toda a
comunidade se beneficie deles (liberdade nº 3). O acesso ao código-fonte é um pré-requisito para
esta liberdade.

Com a garantia destas liberdades, a GPL permite que os programas sejam distribuídos e reaproveitados, mantendo, porém, os direitos do autor por forma a não permitir que essa informação seja usada de uma maneira que limite as liberdades originais.

Instalação do Debian

Apresentados aos conceitos básicos, vamos à instalação do sistema:

Os arquivos do debian estão disponíveis para download no site oficial:
http://www.debian.org/

O sistema possui diversas versões, chamadas de ports que são otimizadas para cada arquitetura de processamento, portanto deve-se escolher para download a versão correta para sua arquitetura. As principais são:

x86 - são suportados praticamente todos os processadores baseados em x86 (IA-32). Pode ser utilizada
com todos os processadores da serie Pentium e Core da Intel e também AMD como Athlon e Phenom.
AMD 64 - O objetivo é dar suporte para programas do espaço de usuário em 32-bit e 64-bit nesta
arquitetura. Este porte dá suporte para os processadores Opteron, Athlon e Sempron 64-bit da AMD
e processadores da Intel com suporte a EM64T, incluindo o Pentium D e várias séries Xeon e Core 2.
Processadores de 32 bits têm uma limitação de endereçamento de memória RAM de 4GB. Portanto, se você
possui mais do que 4GB de memória RAM, utilize este port.

Após escolher sua arquitetura, é hora de gravar uma mídia a iniciar a instalação. O debian pode ser instalado a partir de diversos tipos de mídia: cd, dvd, pen drive, pela internet ou até mesmo pode ser iniciado em um executável windows.

Para iniciar a instalação basta iniciar o computador e configurá-lo para que inicie a partir da mídia que contém o Debian.

Na primeira tela digite install. Em caso de falha, pode-se recorrer à opção acpi=off.

#install
#install acpi=off

Selecione o idioma do sistema na tela abaixo:

A tela abaixo contém as opções de teclado.


O próximo passo será a configuração da rede.
Em caso de uma rede onde exista um serviço de DHCP ativo, a rede será configurada automaticamente.

Ao selecionar a opção de configurar manualmente a rede, surgirão as seguintes opções:
Endereço IP:

Máscara de Rede:

Gateway:

Servidor de nomes (DNS):

Hostname (nome do computador):

Informe o nome do dominio local (caso exista):

Particionamento dos discos:
O particionador utilizado na instalação do debian é o cfdisk:
Para a correta utilização do sistema, precisamos criar no mínimo duas partições: Uma partição swap e uma partição para os arquivos do sistema (EXT3).
A partição swap é destinada a troca de arquivos pelo sistema operacional, ela funciona como uma extensão da RAM.
EXT3 é o sistema de arquivos mais utilizados nos sistemas operacionais linux atuais. O ext3 está para o linux como o NTFS está para o windows XP.

Para uma intalação básica, selecione a opção todos os arquivos em uma unica partição:
Para finalizar, selecione a opção Finalizar o particionamento e gravar as mudançar no disco.

Confirme as alterações e o particionador as executará.


Instalando o Sistema em seu disco já particionado.
O GNU GRUB é um gerenciador de boot, utilizado para controlar o início dos sistemas operacionais do computador. No caso de dual boot, ou seja, a possibilidade de utilizar mais de um sistema operacional no computador, faz-se necessário o uso de um gerenciador como o GNU GRUB ou LILO.
Remova a mídia e utilize a opção continuar.




Ao selecionar sim, o sistema operacional assumirá que o relógio da sua máquina está configurado com o horário mundial de Greenwich e, portanto, fará a tradução necessária para o seu fuso horário. Neste caso devemos selecionar a opção Não.

Ao selecionar Leste, o configurador utilizará o horário de Brasília.

Defina a senha para o root (superusuário).
O usuário root é o administrador do sistema, aquele que possui permissões totais.

A senha deverá ser informada duas vezes a fim de evitar erros de digitação.


O usuário root deverá ser utilizado apenas para funçõe de administração do sistema, as demais atividades devem ser realizadas por um usuário comum (sem permissões de alteração de configurações) que será criado nas próximas telas:


Repita o nome do novo usuário.


Informe a senha do novo usuário.


Repita a senha do novo usuário.


Você poderá carregar mais opções ou programas ao adicionar um cd de aplicativos à instalação. Neste caso, esta opção não será necessária:


O sistema irá tentar instalar atualizações e drivers a partir de um espelho de rede, caso ele não consiga conexão com este espelho a instalação pode continuar normalmente.


Selecione os serviços que deseja instalar em seu computador:

Finalizada a configuração, basta reiniciar a máquina
e o sistema será conduzido à seguinte tela de login:



quarta-feira, 1 de julho de 2009

Como configurar o arquivo .qmail

Como configurar o arquivo .qmail

Explicação sobre o que é o .qmail: quando chega uma mensagem (e-mail) para um usuário, o sistema procura um arquivo chamado .qmail no diretório HOME do usuário, onde cada linha desse arquivo é usada pelo sistema como uma instrução sobre o que fazer com essa mensagem (e-mail).

SE não existir arquivo .qmail, a mensagem é entregue num arquivo chamado Mailbox, onde ficarão acumuladas todas as mensagens recebidas.

Como criar e configurar o .qmail

O .qmail é um arquivo texto, e pode ser editado com qualquer editor de texto (emacs, vi, textedit, pico, nano, etc.). Se ele não existe, você pode criá-lo como costuma fazer com arquivos comuns.

Instruções no .qmail

Cada linha do .qmail é vista como uma instrução. A linha não tem limite de comprimento e não pode ser continuada, ao contrário de arquivos contendo scripts. O sistema seguirá essas instruções em seqüência e caso haja várias instruções de entrega, a mensagem será entregue várias vezes.

Instruções de entrega direta

Quando existe um arquivo .qmail, uma mensagem só é entregue se houver uma instrução de entrega. Existem duas formas de entrega direta:

* Arquivo

Cada mensagem será adicionada a esse arquivo, e o formato de armazemamento é o mbox (para mais informações sobre esse formato, digite man mbox em uma linha de comando).Esse arquivo pode ser lido por qualquer programa leitor de mail. O formato da linha:

caminho-do-arquivo/nome-do-arquivo

Essa linha NÃO deve terminar com o caracter barra (”/”) e nome-do-arquivo é o arquivo do tipo mbox que conterá as mensagens, caso ele não exista o qmail irá criá-lo assim que uma mensagem chegar. O uso mais comum é um arquivo chamado Mailbox, no diretório HOME do usuário. A linha correspondente é:

./Mailbox

Cuidado: se no .qmail aparecerem 284 linhas ./Mailbox, cada mensagem será entregue 284 vezes nessa caixa de correio.

* Diretório

Cada mensagem será gravada em um arquivo separado dentro desse diretório. Esse diretório deverá tem o formato maildir (para mais informações sobre esse formato, digite man maildir em uma linha de comando) , que deverá ser criado usando o comando: maildirmake nome-do-diretório . Esse diretório pode ser lido por programas como por exemplo o pinq. O formato dessa linha deve ser:

caminho-do-diretório/nome-do-diretório/

Essa linha deve terminar com o caracter barra (”/”).O comando usepop3 cria um diretório com o formato maildir chamado Maildir dentro do HOME do usuário e também cria o arquivo .qmail para salvar as mensagens nesse diretório

Instruções de redirecionamento

Isto é simplesmente um endereço (completo) de e-mail. O efeito é mandar uma cópia de cada mensagem para esse endereço.O formato dessa linha deve ser:

nome@dominio

Envio para programas

Uma linha que começa com o caractere | diz para enviar cada mensagem para um programa; mais especificamente, o que segue o | é interpretado como uma linha do shell, com a mensagem na entrada padrão. Para aprender a usar isso com detalhes, digite man qmail-command em uma linha de comando. O formato da linha deve ser:

|caminho-do-programa/nome-do-programa

Abaixo seguem algumas linhas bastante populares:

./Mailbox

Envia os e-mails para o arquivo Mailbox que está no diretório HOME do usuário.

./Maildir/

Envia os e-mails para o diretório Maildir que está no diretório HOME do usuário. Essa linha é necessária para pegar os e-mails usando o protocolo POP (o Thunderbird é um exemplo de programa para ler e-mails que usa esse protocolo), e também para acessar os e-mails pelo webmail.

minhacasa@saopaulo.com.br

Envia os e-mails para o endereço minhacasa@saopaulo.com.br.

| ./scripts/mailfilter

Executa o script mailfilter que está no diretório scripts dentro do HOME do usuário.

Cuidados e observações:

1. Lembre, para cada linha do arquivo .qmail será gerada uma cópia do e-mail.

2. Se o primeiro caractere da linha for um # , a linha é ignorada.

3. A primeira linha não pode estar em branco.

4. O .qmail não pode ter permissão de execução


Conteúdo retirado de: http://si.ime.usp.br , todos os direitos ao autor.