Funtoo Linux Networking/pt-br

From Funtoo
Jump to navigation Jump to search

Esse documento explica como configurar suas configurações de rede ao explicar a funcionalidade de configuração de rede (network configuration functionality) disponível no Funtoo Linux. Também está coberto aqui sobre configuração dhcpcd 5.x, Wi-Fi (IEEE 802.11), e o framework OpenResolv.

{{#layout:doc}}

Apresentação

Funtoo Linux possui seu próprio sistema central de (core network configuration system) que difere um pouco de sistemas de configuração de rede utilizado em Gentoo Linux e em OpenRC.

Nessa documentação, explicarei as únicas adições e alterações no Funtoo network configuration e mostrar como utilizar o sistema para configurar sua rede.

Também explicarei como utilizar o dhcpcd para gerenciar interfaces de rede em redes baseadas em DHCP, e também cobrirei a configuração do OpenRC stacked runlevel configuration, configuração Wi-Fi (IEEE 802.11), e o framework OpenResolv, que é habilitado no Funtoo Linux por padrão.

Uma breve apresentação ao Funtoo Network Configuration

Antes que eu entre em detalhes técnicos de configurar sua rede, é importante entender que o Funtoo Linux possui um número de opções diferentes disponíveis para que você configure a rede, como ainda mais recursos a serem adicionados no futuro. Cada approach é diferente e possui suas próprias forças e fraquezas, e isso, na minha opinião, uma boa coisa.

O Jeito (Dinâmico) Fácil

Quando configurar sua rede, uma opção é pular a configuração de rede tradicional e simplesmente contar depender do DHCP. Esse é de longe o método mais simples de configurar sua rede. Se você estiver em uma rede cabeada, outros passos não são tipicamente exigidos além de habilitar um DHCP client, e o Funtoo Linux inclui dhcpcd 6.x por padrão.

Network Manager, Wicd

Se caso você for utilizar um pacote third party tal qual Network Manager ou Wicd para gerenciar sua rede, então você não precisa configurar DHCP de modo algum. Esses pacotes configuram DHCP para você. Simplesmente execute um emerge no pacote que você quer utilizar e comece a utilizá-lo.

DHCP-Only Systems

Se você não estiver planejando utilizar um pacote third-party para gerenciar suas interfaces de rede, é ainda extremamente fácil configurar rede DHCP, especialmente se você sempre utiliza DHCP para conectar às redes, que é comum para desktops ou laptops. Nesse cenário, podemos simplesmente habilitar dhcpcd para ser executado na inicialização do sistema (system startup). Ele será executado em plano de fundo e automaticamente procurará por servidores DHCP em toda a suas interfaces de rede, e tentará to gerar o enlace de um endereço IP a partir de quaisquer servidor DHCP encontrado.

Se isso soa como o que vocẽ quer fazer, então adicione dhcpcd á suas runlevel padrões como a seguir:

root # rc-update add dhcpcd default

Para habilitar o DHCP imediatamente, você seguiria o comando anterior com um comando rc, que iniciaria o cliente dhcpcd que você acabou de adicionar:

root # rc

Se você estiver em uma rede cabeada e os drivers necessários no seu kernel, então isso deve bastar para você. Para redes sem fio, mois passos são necessários para para utilizar seu hardware de rede sem fio para assim associá-lo a um access point, que terá uma cobertura mais adiante nessa documentação.

Tweaking Dhcpcd

Por hora, é importante notar que o dhcpcd 6.x gerenciará todas as interfaces de rede disponíveis por padrão. Se você quiser executar um cliente DHCP em todas, menos uma interface, ou alguma outra subset de interfaces, você pode adicionar a denyinterfaces apropriada ou allowinterfaces glob pattern no /etc/dhcpcd.conf:

# manage all interfaces but eth0 with dhcpcd (gerencia todas as interfaces, exceto a eth0 com o dhcpcd)
denyinterfaces eth0

Isso pode ser realizado também ao modificar /etc/init.d/dhcpcd diretamente e adicionar -Z ifglob ou -z ifglob (os parâmetros equivalentes para comando) em command_args.

Utilizando os scripts Funtoo para o DHCP

Você pode também utilizar o Funtoo Linux networking scripts para iniciar um cliente DHCP apenas em uma interface específica. Esse acesso é melhor se você está planejando também fazer algum bridging avançado, bonding ou configuração VLAN em sua máquina com o DHCP, já que você estará utilizando o Funtoo Linux networking scripts para isso também.

Para utilizar esse acesso variante, não habilite /etc/init.d/dhcpcd diretamente. Ao invés disso, utilize o Funtoo Linux dhcpcd template que iniciará o dhcpcd em uma única interface. Abaixo, você verá os passos para fazer isso. Isso é muito similar a como realizamos configurações avançadas de interfaces de rede, que cobriremos mais adiante nessa documentação:

root # cd /etc/init.d
root # ln -s netif.tmpl netif.eth0
root # rc-update add netif.eth0 default
root # echo template=dhcpcd > /etc/conf.d/netif.eth0
root # rc

O último comando, rc, faz com que o netif.eth0 seja habilitada.

Configuração de Rede no Servidor

Para servidores e cenários avançados em redes, Funtoo Linux oferece seu próprio sistema de configuração de rede modular baseado em template. Esse sistema oferece um monte de flexibilidade para a configuração de interfaces de rede, essencialmente servindo como um "kit de construção de interface de rede." Esse sistema pode ser utilizado por si só, ou mesmo combinado com o dhcpcd, como mostrado na seção anterior.

Aqui estão os componentes chave do sistema de configuração de rede baseado em template:

/etc/init.d/netif.lo
Um script init que configura a interface localhost. Esse script sempre é habilitado e é parte do processo de boot.
/etc/netif.d
Esse é um diretório que contem vários templates de configuração de rede. cada um desses templates é focado em configurar um tipo particular de interface de rede, tal como uma interface baseada em IP estático, uma interface bridge, uma interface bond, etc.
/etc/init.d/netif.tmpl
Essa é a master init script para sistema de configuração de rede baseada em template. Novas interfaces são adicionadas ao seu sistema ao criar links simbólicos a esse arquivo em /etc/init.d.

Então, se você quisesse utilizar esse sistema para configurar eth0 como um endereço de IP estático, você criaria um symlink netif.eth0 ao netif.tmpl como a seguir:

root # cd /etc/init.d
root # ln -s netif.tmpl netif.eth0

Depois, você criaria um arquivo de configuração /etc/conf.d/netif.eth0 que especificaria qual template utilizar a partir do diretório /etc/netif.d:

template="interface"
ipaddr="10.0.1.200/24"
gateway="10.0.1.1"
nameservers="10.0.1.1 10.0.1.2"
domain="funtoo.org"

Para completar nossa configuração de rede por Ip estático precisaríamos:

root # rc-update add netif.eth0 default

Quando configurar seua própria interface de rede estática, um de ipaddr ou ipaddrs é exigido e deve especificar o(s) endereço(s) IP para configurar para essa interface, no formato "a.b.c.d/netmask". Parâmetros opcionais incluem gateway, que define um gateway padrão para sua rede inteira, e se configuração deve especificar o endereço de IP do gateway. Adicional, domain e nameservers (separado por espaço se mais tiver mais que uma) pode ser utilizado para especificar informação de DNS para essa interface.

Variáveis de Configurações

Variáveis de Interface

As variáveis ipaddr e ipaddrs possuem suporte as templates interface e bridge, e são utilizadas para especificar um único ou múltiplos endereços IPv4 ou IPv6 para a interface. Endereços IP devem ser especificados no formato 'IP/netmask', Tal como 10.0.0.1/24. Múltiplos endereços IP podem ser especificados delimitados com espaço em branco:

ipaddrs="10.0.0.1/24 10.0.0.2/24"
Endereços de Broadcast

Por padrão, um endereço broadcast será calculado ni endereço IP e na mascara de rede (network mask). Se você precisar de manualmente especificar um endereço broadcast, utilize o seguinte formato para o seu endereço:

ipaddrs="10.0.0.1/24;broadcast=10.0.1.255 10.0.0.2/24"
Não Especificando Um Endereço

Note que em alguns casos, você pode escolher não especificar ipaddr ou ipaddrs para um template bridge. Isso é permitido. Se você não quiser especificar um endereço IP para uma interface regular, você pode escolher utilizar o template interface sem um endereço de IP especificado no config, ou utilizar o template interface-noip ao invés disso, por questão de claridade.

Visualizando Todos os Endereços IP Configurados

Note também que se você especificar múltiplos endereços IPv4, ifconfig mostrará somente o primeiro endereço IP. Para visualizar todos os endreços IP associados a interface, utilize o comando ip addr show.

Variáveis Gerais

As variáveis a seguir são habilitadas por padrão por padrão para todos os scripts de rede, e se especificado apontará uma ação de configuração correspondente:

nameservers
Define DNS nameservers utilizando OpenResolv. Especifique múltiplos IPv4 ou IPv6 nameservers assim: "1.2.3.4 1.2.3.5 1.2.3.6". Note que o OpenResolv trata 127.0.0.1 especialmente, e indica que você está executado um local name resolver como dnsmasq ou bind. OpenResolv ignorará todas as outras name servers especificadas ao lado de 127.0.0.1. Veja man resolvconf e man resolvconf.conf para informações adicionais de configuração.
search
Define informação de busca de DNS utilizandoOpenResolv.
domain
Define domínio DNS utilizando OpenResolv.
gateway
Define umgateway IPv4 padrão nessa interface.
gateway6
Define um gateway IPv6 padrão nessa interface.
route
Especifica uma lista de routes IPV4 delimitados por um ponto e vírgula a ser aplicada quando essa interface for inicializada. Será fixado ao ip -4 route add.
route6
Specifica uma lista de routes IPV6 delimitado por ponto e virgula para aplicar quando essa interface for inicializada. Será fixado ao ip -6 route add.
mtu
Defint Maximum Transmit Unit para a interface
mac_replace
Substitui o endereço MAC existente especificado nessa variável.

Variáveis VLAN

O suporte a VLAN é habilitado por padrão para todos os scripts de configuração de rede. Se um script de rede possui um nome no formato netif.ethX.Y, então é presumido que seja uma interface VLAN referencing trunk ethX e VLAN ID Y. Se você deseja um nome personalizado para a sua interface VLAN, você pode nomear sua interface seja para qual nome você gostaria e especificar as seguintes variáveis em seu interface config:

trunk
VLAN trunk interface, e.g. "eth0"
vlan
VLAN id, e.g. "32"

Bridge / Variáveis Tap (Torneira)

As variáveis a seguir para configuração de uma interface bridge funcional com interfaces tap opcionais:

slaves
Define interfaces slave dessa interface (para bridges, etc.) Todas as slaves serão automaticamente dependentes, e também terão automaticamente suas definições mtu para aquela da interface atual, se uma mtu for especificada para a interface atual. Essa configurações são necessária para o template bond e é opcional para o template bridge.
stp
Habilita o protocolo Spanning Tree em uma interface bridge assim "stp=on"
forwarding
Habilita o forwarding em uma interface bridge ao invocar sysctl; como essa interface não existe quando sysctl for invocado pela init, fazemos isso aqui. Se essa for desabilitada, sua bridge não direcionará o tráfego de volta na rede. uso: "forwarding=1"

OpenResolv e resolv.conf

OpenResolv será utilizado para definir informação DNS fornecido pelas variáveis nameservers, domain e search quando uma interface for habilitada. o framework OpenResolv adicionará entradas ao /etc/resolv.conf, e também cuidará de remover essa entradas quando a interface for interrompida. Dessa maneira, /etc/resolv.conf deve sempre conter informações atuais e não deve precisar ser manualmente editada pelo administrador do sistema. dhcpcd utilizara o OpenResolv para a atualização de informação de DNS do sistema também.

Serviços Dependentes de Rede (Network-Dependent Services)

Uma diferença importante entre o Gentoo Linux e o Funtoo Linux é que, no Funtoo Linux, network-dependent services dependem estritamente somente de netif.lo. Isso significa que se outro serviço de rede requer que uma interface seja habilitada, tal como samba necessitado da eth0, então o administrador do sistema deve especificar essa relação ao adicionar a seguinte linha em /etc/conf.d/samba:

rc_need="netif.eth0"

Isso terá o efeito de certificar que netif.eth0 é inicializada prioridade para o samba e que o samba é interrompido is ao parar netif.eth0.

Muitos serviços de rede, especialmente aquelas que escutam em todas as interfaces de rede, não precisa de uma linha rc_need a fim de funcionar corretamente. Evitando o uso do rc_need quando exigido otimizará boot times e permitirá que mais serviços de rede estejam disponíveis quando as interfaces de rede foram habilitadas e desabilitadas/interrompidas pelo administrador do sistema.

Múltiplas Configurações de Rede

Para informações de como obter múltiplas e independente configurações de rede, por favor verifique Stacked Runlevels.

Configs Alternados

Se você precisar executar o mesmo serviço com parâmetros de configurações diferentes dependendo do runlevel, então você será feliz em sabem que você pode especificar arquivos config.d de runlevel específico ao anexar um . <runlevel> suffix. Nesse exemplo em particular, poderíamos imaginar uma situação onde teríamos dois child runlevels nomeados home e work:

/etc/conf.d/netif.eth0.home
/etc/conf.d/netif.eth0.work

Note que esse recurso funciona para todos os scripts init, não somente scripts de configuração de rede.

Interface Renaming

Os scripts de rede do Funtoo agora possuem suporte a interface renaming, então você pode gerar uma interface chamada lan caso queira. Para fazer isso, simplesmente especifiquei o endereço de máquina da interface que você gostaria de renomear utilizando a variável macaddr:

macaddr="00:15:17:19:b6:a3"

se esse endereço de máquina for parte do do arquivo de configuração netif.lan, então quando essa interface inicializar, seja qual for a interface atual que tenha o endereço de máquina de 00:15:17:19:b6:a3 (i.e. eth5) será renomeado para lan prior to the interface being brought up, and will show up in ifconfig and ip commands as being an interface named lan. It is possible to combine this with the mac_replace variable to set a new MAC address, if desired.

Basic VLAN Configuration

The standard interface template supports VLANs. To use VLAN support, first ensure that your kernel was compiled with VLAN support (the module name is 8021q) :

root # grep CONFIG_VLAN /usr/src/linux/.config
CONFIG_VLAN_8021Q=m
CONFIG_VLAN_8021Q_GVRP=y

Then, configure the trunk interface using the interface-noip template. Assuming eth1 is trunked, you would create the file /etc/conf.d/netif.eth1 with the following contents:

template="interface-noip"

Then, create a network interface symlink for the trunk and add it to your default runlevel:

root # cd /etc/init.d
root # ln -s netif.tmpl netif.eth1
root # rc-update add netif.eth1 default

Now, assuming you wanted to configure a VLAN of 32, you would create a config file named /etc/conf.d/netif.eth1.32 that looks something like this:

template="interface"
ipaddr="1.2.3.4/24"
gateway="1.2.3.1"# etc...

Then, create a VLAN network interface symlink and add it to your default runlevel:

root # cd /etc/init.d
root # ln -s netif.tmpl netif.eth1.32
root # rc-update add netif.eth1.32 default

The Funtoo network configuration scripts will automatically recognize the filename netif.eth1.32 as being VLAN 32 of trunk interface netif.eth1.

When the VLAN interface is brought up, it will be named eth1.32.

Custom VLAN Names

However, sometimes you may want to turn off automatic file-based VLAN naming and give your VLAN interface a custom name, such as mgmt. To do this, you would set up the trunk interface in the exact same way as described above, but instead of creating a netif.eth1.32 interface, you would create a netif.mgmt interface, and specify vlan and trunk in the /etc/conf.d/netif.mgmt config file, as follows:

template="interface"
vlan="32"
trunk="eth1"
ipaddr="1.2.3.4/24"
gateway="1.2.3.1"
# etc...

When you specify trunk and vlan in the interface config file, filename-based auto-detecting of VLAN ID and trunk is disabled. Both trunk and vlan must be specified -- you can't specify just one.

Then you would simply create a VLAN network interface symlink for netif.mgmt:

root # cd /etc/init.d
root # ln -s netif.tmpl netif.mgmt
root # rc-update add netif.mgmt default

When the VLAN interface is brought up, it will be named mgmt.

Bonding Configuration

Bonding allows you to aggregate multiple network interfaces into a single logical network interface, allowing for benefits in throughput as well as resiliency in the case that an individual interface may go down. This example shows how you would create a bonding interface (mybond) with a simple static ip setup, containing two slave devices (eth0 and eth1).

First, ensure that your kernel is configured to support bonding (the module name is bonding) :

user $ grep CONFIG_BONDING /usr/src/linux/.config
CONFIG_BONDING=m

You'l want to ensure that CONFIG_BONDING is set to "m" or "y". You can find this kernel configuration option tucked under "Device Drivers" -> "Network Device Support" -> "Bonding driver support". Be sure that ifenslave is emerged (this package included in Funtoo stage3):

root # emerge ifenslave

Once bonding is enabled in the kernel, you will need to choose at least two devices to bond together. These will be set up as "slave" interfaces with no IP address.

root # cd /etc/init.d/
root # ln -s netif.tmpl netif.eth0
root # ln -s netif.tmpl netif.eth1

Then, configure the slave interfaces by creating /etc/conf.d/netif.eth0 and /etc/conf.d/netif.eth1 with the following contents:

template="interface-noip"

Now, we will create the bond interface and make netif.eth0 and netif.eth1 slaves of this interface. Note that our bond interface can have any name. To demonstrate this, we will give it the name of "mybond" below:

root # ln -s netif.tmpl netif.mybond
root # rc-update add netif.mybond default

Now we can configure "mybond" using its configuration file /etc/conf.d/netif.mybond, just as we would a regular interface, except that we specify slaves:

template="bond"
ipaddr="10.0.1.200/24"
gateway="10.0.1.1"
nameservers="10.0.1.1 10.0.1.2"
domain="funtoo.org"
slaves="netif.eth0 netif.eth1"

In a bonded configuration, it is common to set the MTU to the maximum possible value supported by hardware to maximize throughput. In order to do this, simply set the MTU option in /etc/conf.d/netif.mybond to the maximum value supported by your hardware. The network scripts will ensure that this MTU setting is applied to all slave interfaces:

mtu=9000

Bridge Configuration

When hosting virtual machines, it can be convenient to use a bridge setup. This example shows how you would create a bridge (br0) with a simple static ip setup, containing two slave devices (eth0, tap0).

First, ensure that your kernel is configured to support bridging (the module name is bridge) :

user $ grep CONFIG_BRIDGE /usr/src/linux/.config
CONFIG_BRIDGE=m
CONFIG_BRIDGE_IGMP_SNOOPING=y

Second, make sure you have the required software installed:

root # emerge -av bridge-utils usermode-utilities

Then, create the necessary symlinks for the interfaces and add them to your default runlevel :

root # cd /etc/init.d/
root # ln -s netif.tmpl netif.eth0
root # ln -s netif.tmpl netif.br0
root # ln -s netif.tmpl netif.tap0
root # rc-update add netif.br0 default
root # rc-update add netif.tap0 default

Then, configure the slave interface /etc/conf.d/netif.eth0 :

template="interface-noip"

Then, configure the slave interface /etc/conf.d/netif.tap0 - note you only require group OR user, not both :

template="tap"
group="kvm" 
user="kvm"
mac_addr="10:20:30:40:50:66"

... and the bridge interface /etc/conf.d/netif.br0 :

template="bridge"
ipaddr="10.0.1.200/24"
gateway="10.0.1.1"
nameservers="10.0.1.1 10.0.1.2"
domain="funtoo.org"
slaves="netif.eth0 netif.tap0"
stp="on"
forwarding=1

If you are using dhcpcd, you should ensure that it does not attempt to configure eth0 or br0 by adding the following to /etc/dhcpcd.conf :

# don't attempt to pull an ip address for br0 or its slave device
denyinterfaces eth0 br0

More Complex Network Configuration

If the standard templates don't work for your needs, simply create a new template -- I recommend starting from the interface template for most things:

root # cd /etc/netif.d
root # cp interface custom

You can now call whatever commands you need to /etc/netif.d/custom. The following shell functions can be defined in a network script:

netif_create

In netif_create, you should call any commands to create the interface if it does not yet exist.

netif_depend

In netif_depend, you can define dependencies, using the functions need and use.

netif_pre_up

In netif_pre_up, you can define network configuration actions to perform prior to bringing the interface up. You can also ensure certain variables are specified by calling require var1 [var2...] here.

netif_post_up

In netif_post_up, you can define network configuration actions to perform after bringing the interface up.

netif_pre_down

In netif_pre_down, you can define network configuration actions to perform prior to bringing the interface down.

netif_post_down

In netif_post_down, you can define network configuration actions to perform after bringing the interface down.

netif_destroy

In netif_destroy, you can call any commands necessary to destroy/delete the interface if it is dynamic in nature (tun/tap, etc.)

How It Works

You do not specify a function for actually bringing up the interface, because the template-based system does this for you. The template-based system also performs all normal actions required to bring an interface down, so you only need to specify atypical actions that must be performed - such as removing child interfaces or destroying a bridge using brctl.

When you create your own network configuration template, the following capabilities are available for use automatically, as long as the appropriate variables are set in the /etc/conf.d/netif.<ifname> file, without requiring any explicit steps on your part:

  • DNS configuration using domain and nameservers config settings. OpenResolv is used automatically.
  • VLAN configuration using auto-naming (netif.ethX.Y) or via custom naming with trunk and vlan config settings.
  • Default IPv4 gateway and route configuration using the gateway and route settings.
  • Default IPv6 gateway and route configuration using the gateway6 and route6 settings.
  • MTU configuration using the mtu setting.
  • Auto-depend (and auto-MTU configuration) of slave interfaces specified using slaves setting.
  • Renaming of existing network interface (specify MAC address using macaddr setting).

To take advantage of this functionality, simply enable the appropriate variables.

All other necessary network configuration and dependency behavior should be defined using the netif_-prefix functions described above.

Wireless Configuration

The recommended approach for setting up Wi-Fi under Funtoo Linux is to use NetworkManager. Steps are provided in the Wi-Fi section of the Funtoo Linux Installation Guide.

Other Network Configurations

If you have a network configuration template that might be useful to others, please post it to the funtoo-dev mailing list so we can review it and possibly incorporate it into Funtoo.

License

Funtoo Linux networking scripts are released under the following license:

Template:BSD2 Funtoo