FreeBSD for Devs #04
Tags: freebsd, os, developers, development
Published: 2024-04-20 21:51:24

Thanks for joining me for another segment of our FreeBSD journey. Today, in our fourth article, we’re going to focus on an absolutely essential part of configuring your FreeBSD system: mastering the `/etc/rc.conf` file. This file is central to customizing how your system starts up and runs various services. So, let’s break it down and learn how to utilize it effectively!

## Table of Contents

- [System Configuration](#system-configuration)
  - [Key Configurations](#key-configurations)
- [Creating Your Own Configuration](#creating-your-own-configuration)
- [Shells](#shells)
  - [Getting to Know the Default Shell in FreeBSD and Setting Up Zsh](#getting-to-know-the-default-shell-in-freebsd-and-setting-up-zsh)
    - [Installing Zsh](#installing-zsh)
    - [Making Zsh Your Default Shell](#making-zsh-your-default-shell)
    - [Configuring Zsh](#configuring-zsh)
    - [Installing Oh My Zsh](#installing-oh-my-zsh)
- [Using FreeBSD’s Package](#using-freebsds-package)
    - [Managing Your Software with pkg](#managing-your-software-with-pkg)
    - [Deciding Between Quarterly and Latest Ports Branches](#deciding-between-quarterly-and-latest-ports-branches)
    - [Troubleshooting with pkg](#troubleshooting-with-pkg)
- [Advanced Package Management with pkg](#advanced-package-management-with-pkg)
    - [Automatically Removing Unused Dependencies: pkg autoremove](#automatically-removing-unused-dependencies-pkg-autoremove)
    - [Listing Explicitly Installed Packages: pkg prime-list](#listing-explicitly-installed-packages-pkg-prime-list)
    - [Finding the Origin of Installed Packages: pkg prime-origins](#finding-the-origin-of-installed-packages-pkg-prime-origins)
    - [Cleaning the Package Cache: pkg clean](#cleaning-the-package-cache-pkg-clean)
- [Modifying Package Metadata in FreeBSD](#modifying-package-metadata-in-freebsd)
    - [Why Modify Package Metadata?](#why-modify-package-metadata)
    - [Practical Examples](#practical-examples)
    - [When to Use Metadata Modification](#when-to-use-metadata-modification)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cg3khuzjxb0xzfjm8gy.png)

## System Configuration

The `/etc/rc.conf` file in FreeBSD is crucial for system configuration. It controls a variety of system settings, including which services start at boot time, system security measures, and much more. 

By editing this file, you can ensure that your FreeBSD system behaves exactly how you want it to, tailoring it to fit your development needs perfectly.

Before you dive into editing `/etc/rc.conf`, I highly recommend familiarizing yourself with its capabilities by consulting the FreeBSD manual. You can access this wealth of information by typing `man rc.conf` in your terminal. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bkuc7gzlyerj6lg20mx.png)

This command pulls up a manual page that not only lists all the configurable settings but also provides a description for each. It’s an invaluable resource for both new and seasoned FreeBSD users.

**Key Configurations**

While we avoid network and hostname settings this time, there are plenty of other configurations that are incredibly useful for developers:

- **Enable SSH**: For secure remote access, enabling SSH is crucial. This setting allows you to manage your machine from afar, which is especially handy in a multi-user or server environment.

  ```bash
  sshd_enable="YES"
  ```

- **Setting Up a Firewall**: Enhancing security with a firewall is a good practice. FreeBSD makes it straightforward.

  ```bash
  firewall_enable="YES"
  firewall_type="SIMPLE"
  ```

- **Managing Time with NTP**: Keeping your system time accurate is important, especially when dealing with timed events or logs.

  ```bash
  ntpd_enable="YES"
  ```

## Creating Your Own Configuration

One great tip for managing your `rc.conf` is to start by reviewing `/etc/defaults/rc.conf`. This file holds all the default system settings. By copying it to your own `rc.conf` file, you have a solid baseline from which you can start customizing. 

This approach is less error-prone than starting from an empty file, as it allows you to see all the default configurations at a glance and understand the typical structure and syntax used.

Although copying the entire `/etc/defaults/rc.conf` might seem like a time-saver, be aware that this can lead to unnecessary bloat in your configuration file. A cluttered `rc.conf` can be harder to manage and troubleshoot. 

A better strategy is to incrementally add only the settings you understand and need. This keeps your system configuration clean and maintainable.

Here is the organized and integrated `/etc/rc.conf` configuration, blending both the previous settings and the newly provided ones. The settings are grouped by their functional context to improve clarity and manageability.

```bash
############################## System Initialization ##############################

rc_startmsgs="YES" # Enables display of boot-time messages
cleanvar_enable="YES" # Clean the /var directory
clear_tmp_enable="YES" # Clear /tmp at startup
root_rw_mount="YES" # Root file system is mounted read-write
background_fsck="YES" # run fsck in the background
savecore_enable="YES" # Save/extract core from dump devices if any
dumpdev="AUTO" # Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
crashinfo_enable="YES" # Automatically generate crash dump summary
update_motd="YES" # Update version info in /etc/motd
cron_dst="YES" # Handle DST transitions intelligently
devfs_load_rulesets="YES" # Enable automatic loading of default device filesystem rulesets

############################## Network Configuration ##############################

hostname="scovl" # Set system hostname
# Set default gateway
# defaultrouter="192.168.0.1" (commented out for example purposes)
gateway_enable="YES" # Set network gateway

############################## Device Management ##############################

devd_enable="YES" # Run devd, to trigger programs on device tree changes
devmatch_enable="YES" # Automatically load kernel modules based on device identification
devmatch_blacklist="if_iwm if_iwlwifi" # Exclude specific devices from automatic module loading
kldxref_enable="YES" # Build linker.hints files with kldxref(8)
geli_autodetach="YES" # Automatically detach GELI devices on last close
kld_list="i915kms acpi_video" # Video driver and ACPI video support

# Device drivers for webcams
#cuse_load="YES"
#webcamd_enable="YES"
#webcamd_0_flags="-d ugen0.5"

############################## Logging and Monitoring ##############################

syslogd_enable="YES" # Run the syslog daemon
syslogd_oomprotect="YES" # Don't kill syslogd when swap space is exhausted
newsyslog_enable="YES" # Run newsyslog at startup

############################## Time Synchronization ##############################

ntpdate_enable="YES" # Enable NTP to sync time on boot
# ntpdate_hosts="b.st1.ntp.br"
ntpd_enable="YES" # Run the Network Time Protocol daemon
# ntpd_sync_on_start="YES"

############################## Power Management ##############################

powerd_enable="YES" # Enable power management

############################## Resolver and DNS Configuration ##############################

local_unbound_enable="YES" # Enable local DNS resolver

############################## SSH and Remote Access ##############################

sshd_enable="YES" # Enable SSH daemon

############################## Hardware Enhancements ##############################
# Enable device access bus, necessary for hardware components
dbus_enable="YES"
hald_enable="YES"
vm_enable="YES" # Enable virtual memory management

# Load sound drivers
sound_load="YES"
snd_hda_load="YES"

# Enable temporary file system with a size limit
tmpfs_enable="YES"
tmpfs_size="2G"

############################## Linux Compatibility ##############################
# This setting is specific to whether Linux compatibility is needed
linux_enable="NO"
```

- **System Initialization**: General settings that relate to how the system boots and handles critical operations.
- **Network Configuration**: Settings for hostname, network interfaces, and gateway configuration.
- **Device Management**: Handles automatic device detection, module loading, and special drivers like video and webcam.
- **Logging and Monitoring**: Manages system logs and ensures that critical logging processes are preserved in low-memory situations.
- **Time Synchronization**: Ensures that the system clock is accurate by syncing with NTP servers.
- **Power Management**: Adjustments for system power usage to optimize energy efficiency.
- **Resolver and DNS Configuration**: Manages local DNS resolving services for network operations.
- **SSH and Remote Access**: Settings for remote system access via SSH.
- **Hardware Enhancements**: Supports additional hardware functionalities like dbus and hardware abstraction layers.
- **Linux Compatibility**: Maintains settings for running Linux-compatible applications.

---

## Shells

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r3vr5prm7za56ealn09.png)

### Default Shell in FreeBSD and Setting Up Zsh

When you first dive into FreeBSD, you'll start off with `sh` as the default shell. It’s pretty good for everyday tasks and scripting, but maybe you’ve heard about `zsh` or you've used it before and you love the extra features it offers, like better auto-completion and nice themes. If that's the case, switching to `zsh` on your FreeBSD system can make your command line experience a lot more enjoyable. Let’s walk through how to install and set up `zsh` in an easy, laid-back way.

### Installing Zsh

First things first, you need to install `zsh`. FreeBSD makes this super straightforward with its package manager. Just open your terminal and run:

```bash
doas pkg install zsh
```

This command tells FreeBSD to grab the `zsh` package and install it on your system. It might ask if you're okay with the installation, just hit `y` for yes and let it do its thing.

### Making Zsh Your Default Shell

Once `zsh` is installed, you’ll probably want to make it your default shell, so you don't have to manually start it every time you open the terminal. Here’s how you can do that:

```bash
chsh -s /usr/local/bin/zsh
```

This command changes your default shell to `zsh`. The `chsh` (change shell) command updates your user profile to start `zsh` whenever you log in.

### Configuring Zsh

Now for the fun part—making `zsh` work the way you want it to. A lot of folks like to use **Oh My Zsh**, a community-driven framework for managing your `zsh` configuration. It includes tons of helpful functions, helpers, plugins, themes, and more.

### Installing Oh My Zsh

You can install Oh My Zsh right from your new `zsh` prompt by running:

```bash
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
```

This command downloads the install script with `curl` and runs it. The script takes care of everything, and you’ll end up with a `.zshrc` file in your home directory, which is where all your `zsh` configurations live.

Once Oh My Zsh is installed, you can start tweaking things to your liking. Open up your `.zshrc` file in a text editor:

```bash
vi ~/.zshrc
```

Here, you can change your theme by modifying the `ZSH_THEME` variable, add plugins by editing the `plugins` line, or tweak other settings. Oh My Zsh has a huge variety of themes and plugins to choose from, so you can really make your terminal work for you.

Absolutely, let’s spice up that explanation with some practical, everyday examples that can really showcase how software developers can use FreeBSD’s package and port systems effectively.

## Using FreeBSD’s Package

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpnqpghg64cyhyuir937.png)

When you dive into FreeBSD, you find two cool ways to get your software up and running: **Packages** and **Ports**. Each serves a different purpose, depending on what you're after:

These are pre-built binaries. Think of them like the apps you quickly install on your smartphone. You use a command, and bam! The software is ready to use. This method is perfect when you need to get tools up and running without any hassle.

Say you want to install the text editor `nano`. Instead of wrestling with source code, you simply open your terminal and type:

  ```bash
  doas pkg ins -y nano
  ```

This single line fetches the latest stable version of `nano`, installs it, and gets you back to coding in no time.

### Managing Your Software with pkg

FreeBSD’s `pkg` system is a powerhouse for managing packages. Here’s how you might use it in your day-to-day development tasks:

- **Updating Software**: Keeping your tools up-to-date is crucial for security and functionality. With `pkg`, you can update all installed packages with:

  ```bash
  doas pkg upgrade
  ```

This command checks for updates and upgrades all your installed packages to the latest versions available.

- **Searching for Software**: Need a specific tool or library for your project? You can search the entire repository with:

  ```bash
  pkg search git
  ```

This command lists all the packages related to Git, helping you find new tools or necessary libraries.

### Deciding Between Quarterly and Latest Ports Branches

You can choose how cutting-edge or stable you want your packages to be:

- **Quarterly Branch**: For those who prefer stability over having the very latest versions. This branch only receives critical updates and security patches.
  
Set your system to use the Quarterly branch to ensure that you only get updates that are deemed stable and extensively tested:

  ```bash
  mkdir -p /usr/local/etc/pkg/repos
  echo 'FreeBSD: { url: "pkg+http://pkg.FreeBSD.org/${ABI}/quarterly" }' > /usr/local/etc/pkg/repos/FreeBSD.conf
  ```

- **Latest Branch**: If you're developing software that benefits from the latest features of tools and libraries, switch to the Latest branch:

  ```bash
  mkdir -p /usr/local/etc/pkg/repos
  echo 'FreeBSD: { url: "pkg+http://pkg.FreeBSD.org/${ABI}/latest" }' > /usr/local/etc/pkg/repos/FreeBSD.conf
  ```

### Troubleshooting with pkg

Sometimes, things might not go as planned:

- **Checking for Issues**: If you suspect an issue with your installed packages or want to check their integrity, you can use:

  ```bash
  pkg check
  ```

This tool will scan through your installed packages and report any problems or inconsistencies.

Sure, let’s expand on those handy `pkg` commands that can help you manage your FreeBSD system more efficiently. Each of these commands serves a specific purpose in keeping your system clean and well-organized.

### Advanced Package Management with pkg

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgatrnua0zfvhfci8jcp.png)

As you install and remove software, your system can accumulate packages that were only needed as dependencies for other applications and are no longer required. Cleaning these up can save space and reduce clutter.

- **Command**: `pkg autoremove`
  
Say you’ve removed a software that had dependencies that aren't required by any other installed packages. Simply run:

  ```bash
  doas pkg autoremove
  ```

This command reviews the installed packages, identifies any that were installed only as dependencies, and removes them if they are no longer needed by any other packages.

### Listing Explicitly Installed Packages: `pkg prime-list`

Sometimes, you want to see a list of packages that you explicitly installed yourself, not including the ones pulled in as dependencies. This can be useful for auditing your installation.

- **Command**: `pkg prime-list`
  
To see a list of packages that were directly installed by you (not as dependencies), you can use:

  ```bash
  pkg prime-list
  ```

This will display all the packages that you have intentionally installed, helping you track and manage your direct installations.

### Finding the Origin of Installed Packages: `pkg prime-origins`

If you need to know the ports directory from which your installed packages originated, this command comes in handy.

- **Command**: `pkg prime-origins`
  
When planning upgrades or reporting issues, you might need to know where your packages came from:

  ```bash
  pkg prime-origins
  ```

This outputs the ports directories for all your explicitly installed packages, which is useful for tracing back to the source port for each package.

### Cleaning the Package Cache: `pkg clean`

Over time, the package cache can grow, holding onto the archives of packages that have been installed or upgraded. Cleaning this cache frees up disk space.

- **Command**: `pkg clean`
  
If you find that your package cache is using too much space, you can clean it up by running:

  ```bash
  doas pkg clean
  ```

This command removes all the cached package files from your system, clearing up space. If you want to only remove obsolete packages (those that are no longer in the repositories or have been replaced by updated versions), you can use:

  ```bash
  doas pkg clean -a
  ```

This removes only the outdated package files, which helps in maintaining a lean system without losing the ability to quickly reinstall packages from the cache.

## Modifying Package Metadata in FreeBSD

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75x4o8422a2jdw3tlo9w.png)

In FreeBSD, managing package metadata is an important aspect of maintaining your system, especially when dealing with package origins and customizations. Modifying package metadata can be crucial for several reasons, including compatibility and system administration efficiency.

Package metadata includes information about a package such as its name, version, dependencies, origin, and other crucial data that helps the package management system handle installations, upgrades, and removals correctly. 

Modifying this metadata can be particularly useful when dealing with major version changes in software or resolving repository inconsistencies.

### Why Modify Package Metadata?

1. **Version and Origin Updates**: When upstream repositories update the names or versions of packages, you might need to realign the installed packages to match these updates. This ensures that future updates, dependency resolutions, and compatibility checks proceed without errors.
  
2. **Maintaining Consistency**: In some scenarios, packages might be renamed or split into multiple parts, requiring updates to the package metadata on user systems to maintain consistency with repository changes.

3. **Custom Development Needs**: Developers who maintain their own custom FreeBSD ports or packages might need to adjust package metadata to manage how their custom solutions integrate and update with the rest of the FreeBSD ports collection.

### Practical Examples

Here are some practical examples of how you might use package metadata modification commands:

Suppose a package named `lang/python3` is updated in the FreeBSD ports to `lang/python311` to reflect a version update, and you want to keep everything tidy and in line with the ports tree. You can change the package origin with:

  ```bash
  pkg set -o lang/python3:lang/python311
  ```

This command tells the package manager that your installed `lang/python3` package should now be considered as `lang/python311`. This is essential after updates to package naming in the ports tree to ensure seamless upgrades and compatibility.

If changing a package's origin affects other packages that depend on it, you might need to force a reinstallation to resolve any conflicts or dependencies that are tied to the package origin.

  For example, if you change the origin of a library that many other applications depend on, you might run:

  ```bash
  pkg install -Rf lang/python311
  ```

This command forces a reinstallation of the `lang/python311` package and all packages that depend on it, ensuring that all dependent packages correctly recognize the updated origin and version.

### When to Use Metadata Modification

- **During Major System Updates**: When major updates or changes are made in the FreeBSD ports tree.
- **After Renaming or Reorganizing Ports**: If ports are reorganized, renamed, or otherwise significantly altered in the repository.
- **Custom Package Management**: When managing custom-built packages or ports in a development environment, especially when these packages are intended to integrate with the broader system or other custom software.

Understanding and utilizing the modification of package metadata in FreeBSD is a valuable skill, especially for system administrators and software developers who need to maintain a clean, efficient, and well-organized system. It ensures that your package management system remains robust, flexible, and capable of handling the dynamic nature of software dependencies and repository changes.

---

## References

- [FreeBSD Handbook - `rc.conf`](https://www.freebsd.org/doc/handbook/configtuning-rcd.html): Official FreeBSD Handbook section on using and understanding the `rc.conf` system file.
- [FreeBSD Man Pages - `rc.conf`](https://www.freebsd.org/cgi/man.cgi?query=rc.conf&sektion=5): Detailed manual page providing specifics on the settings available in `rc.conf`.
- [DigitalOcean Tutorial on FreeBSD's rc.conf](https://www.digitalocean.com/community/tutorials/how-to-configure-a-freebsd-12-0-web-server): A tutorial by DigitalOcean that covers basics to advanced configuration steps for setting up a web server using `rc.conf`.
- [FreeBSD Forums](https://forums.freebsd.org/): A place to discuss and ask questions about FreeBSD, including topics about `rc.conf` and system configuration.
- [FreeBSD Journal](http://freebsdjournal.com/): A professional journal covering FreeBSD topics, including system administration and the use of `rc.conf`.
- [Configuring FreeBSD with `rc.conf` by Michael W Lucas](https://mwl.io/nonfiction/os#cfbsd): A comprehensive guide by Michael W Lucas on configuring FreeBSD, focusing on practical examples and deep dives into `rc.conf`.

### Additional Tools and Resources

- [Oh My Zsh](https://ohmyz.sh/): Homepage for Oh My Zsh, a popular framework for managing `zsh` configurations.
- [Zsh Documentation](https://zsh.sourceforge.io/Doc/): Official documentation for `zsh`, providing a deep dive into customization and usage.
- [pkg Primer from FreeBSD](https://www.freebsd.org/doc/handbook/pkgng-intro.html): Official guide to using the `pkg` package management tool in FreeBSD.

### Community Contributions and Discussions

- [Reddit r/FreeBSD](https://www.reddit.com/r/freebsd/): Subreddit for discussions on FreeBSD, where users share tips and configuration snippets for `rc.conf`.
- [FreeBSD Wiki](https://wiki.freebsd.org/): The community-driven FreeBSD wiki that offers practical advice and configuration tips.