0

I'm not a parsing guru, and I'm trying to parse /etc/dhcpcd.conf file in php. There are three main cases:

  • dhcp
  • static
  • fallback

Here a simple example with the three options together:

#if 'dhcp' all the following lines are commented or missing

#if 'static' this is the only section enabled
interface eth0
static ip_address=192.168.0.10/24
static routers=192.168.0.1
static domain_name_servers=192.168.0.1 8.8.8.8

#if 'fallback' this is the only section enabled
profile static_eth0
static ip_address=192.168.1.200/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1    
interface eth0
fallback static_eth0

My first attempt was to create a fsm with a state variable that keep track of the mode (dhcp, static, fallback). I would parse the file line by line, skipping comments or blank lines. Example:

$state = "dhcp";
while (!feof($handle)) {
  $line = fgets($handle, 4096);
  if (substr($line, 0, 1) == "#" {
    // skip comments
    continue:
  }

  $tok = strtok($line, " ");
  switch ($state) {
    case "dhcp":
      if ($tok == "interface eth0") {
        $state = "static";
      }
      if ($tok == "profile static_eth0") {
        $state = "fallback";
      }
      break;

     case "static":
       // read next lines and store settings
       break;

     case "fallback":
       // read next lines and store settings
       break;
  }
}

It might work but it's too much trivial and doesn't take in account a lot of things:

  • it relies on that particular order of entries
  • it doesn't allow other interface names
  • defining a profile without adding the fallback static_eth0 line doesn't enable the fallback mode, or in general there is no sanity check of the file

If my approach is correct I have to expand the fsm to take care of all possible cases. But I'm not sure how to detect (or even imagine!) all of them.

Perhaps there is a more convenient way to do this?

Mark
  • 4,338
  • 7
  • 58
  • 120
  • This question boils down to, "How to parse a text file" https://stackoverflow.com/questions/5299471/php-parsing-a-txt-file – Robert Sep 09 '17 at 15:25
  • I don't agree. I'm able to "parse" a text file with a well defined structure as per your link. My question is about how to infer the structure from the file itself and validate the readings. – Mark Sep 09 '17 at 15:30

0 Answers0