No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

occi 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #!/usr/bin/env perl
  2. =head1 NAME
  3. occi - Adafruit Occidentalis Configuration Helper for Raspberry Pi
  4. =head1 DESCRIPTION
  5. occi is a simple utility for applying configuration settings like
  6. hostname and WiFi credentials to your Raspberry Pi.
  7. Settings are stored in a simple text file, usually
  8. F</boot/occidentalis.txt>. The format is:
  9. hostname=somepi
  10. # wifi configuration details:
  11. wifi_ssid=Your Network Here
  12. wifi_password=your password here
  13. Blank lines and comments starting with C<#> will be ignored. Keys are
  14. case-insensitive.
  15. =head1 SYNOPSIS
  16. # apply configuration in /boot/occidentalis.txt
  17. sudo occi
  18. # check current version
  19. occi --version
  20. # apply a different configuration file
  21. sudo occi --file=/home/alternate_occidentalis.txt
  22. =cut
  23. package OcciConfig v0.7.0;
  24. use warnings;
  25. use strict;
  26. use 5.10.0;
  27. use File::Basename;
  28. use File::Copy;
  29. use Getopt::Long;
  30. use IPC::Cmd qw(can_run run);
  31. # Handle CLI options:
  32. my $OCCI_CONFIG = "/boot/occidentalis.txt";
  33. my $show_version_and_exit = 0;
  34. my $install_and_exit = 0;
  35. GetOptions(
  36. "file=s" => \$OCCI_CONFIG,
  37. "version" => \$show_version_and_exit,
  38. "install" => \$install_and_exit
  39. ) or die("Error in command line arguments\n");
  40. diag("Adafruit Occidentalis configuration helper, ${OcciConfig::VERSION}");
  41. if ($show_version_and_exit) {
  42. exit 0;
  43. }
  44. if ($install_and_exit) {
  45. install();
  46. exit 0;
  47. }
  48. have_config_or_exit($OCCI_CONFIG);
  49. my %config = parse_config($OCCI_CONFIG);
  50. diag('file', $OCCI_CONFIG);
  51. {
  52. # This bit of magic will find every sub starting with "handle_".
  53. # It just stands in for explicitly calling:
  54. #
  55. # handle_hostname(%config);
  56. # handle_wifi(%config);
  57. #
  58. # and so on down the line.
  59. no strict 'refs';
  60. my (@handlers) = grep { defined &{"OcciConfig\::$_"} && m/^handle_/ } keys %{"OcciConfig\::"};
  61. diag_push('run');
  62. foreach my $handler (@handlers) {
  63. diag_push($handler);
  64. &{$handler}(%config);
  65. diag_pop();
  66. }
  67. diag_pop();
  68. }
  69. exit 0;
  70. =head1 CONFIGURATION HANDLERS
  71. To add a handler, just write a sub that takes the %config hash, like so,
  72. and returns a list containing one or more log items:
  73. sub handle_foo {
  74. my %config = @_;
  75. return ('nothing to do here');
  76. }
  77. It will automatically be called every time occi runs.
  78. =over
  79. =item handle_selftest()
  80. Run some basic checks to make sure we have necessary stuff.
  81. =cut
  82. sub handle_selftest {
  83. my %config = @_;
  84. my %allowed_keys = map { $_ => 1} qw(
  85. hostname
  86. wifi_password wifi_ssid
  87. );
  88. diag('Checking configuration integrity.');
  89. foreach my $key (sort keys %config) {
  90. if ($allowed_keys{$key}) {
  91. diag('valid', $key, $config{$key});
  92. } else {
  93. diag('error', $key, 'unrecognized configuration key');
  94. }
  95. }
  96. # This is just a bit of a sanity check - do we know whether some
  97. # things we might expect are installed? Currently commented out
  98. # since we no longer rely on apt for installation of these tools.
  99. #
  100. # my @check_packages = qw(occi occidentalis);
  101. # foreach my $package (@check_packages) {
  102. # if (is_installed_package($package)) {
  103. # diag('have package', $package);
  104. # } else {
  105. # diag('no package', $package);
  106. # }
  107. # }
  108. chomp(my $dversion = get_file('/etc/debian_version'));
  109. diag('debian version', $dversion);
  110. }
  111. =item handle_hostname()
  112. Update current hostname and make sure it's set properly at boot.
  113. =cut
  114. sub handle_hostname {
  115. my %config = @_;
  116. return ('no hostname specified')
  117. unless defined $config{hostname};
  118. my $hostname_changed = 0;
  119. # What's the existing configuration?
  120. chomp(my $existing_etc_hostname = get_file('/etc/hostname'));
  121. chomp(my $existing_hostname = capture_string('hostname'));
  122. unless ($existing_etc_hostname eq $config{hostname}) {
  123. # Make sure this is set correctly at next boot
  124. diag('Setting /etc/hostname to ' . $config{hostname});
  125. put_file('/etc/hostname', $config{hostname});
  126. $hostname_changed = 1;
  127. }
  128. unless ($existing_hostname eq $config{hostname}) {
  129. # Make sure this is set correctly right _now_.
  130. diag('Setting current hostname to ' . $config{hostname});
  131. system('hostname', $config{hostname});
  132. $hostname_changed = 1;
  133. }
  134. # Make sure our new hostname is mentioned in /etc/hosts:
  135. my $etc_hosts = get_file('/etc/hosts');
  136. my $new_etc_hosts = $etc_hosts;
  137. my $config_hostline = "127.0.1.1\t$config{hostname}";
  138. $new_etc_hosts =~ s/^(127[.]0[.]1[.]1\s+${existing_hostname})$/$config_hostline/m;
  139. if ($new_etc_hosts !~ /$config_hostline/) {
  140. $new_etc_hosts .= "\n$config_hostline";
  141. }
  142. if ($etc_hosts ne $new_etc_hosts) {
  143. diag('Adding ' . $config_hostline . ' to /etc/hosts');
  144. put_file('/etc/hosts', $new_etc_hosts);
  145. $hostname_changed = 1;
  146. }
  147. if ($hostname_changed && (-f '/etc/init.d/avahi-daemon')) {
  148. diag('restarting avahi-daemon');
  149. my (@restart_log) = capture_list('service', 'avahi-daemon', 'restart');
  150. foreach my $logline (@restart_log) {
  151. diag($logline);
  152. }
  153. }
  154. }
  155. =item handle_wifi()
  156. Configure a wireless network.
  157. =cut
  158. sub handle_wifi {
  159. my %config = @_;
  160. my $conf_file = '/etc/wpa_supplicant/wpa_supplicant.conf';
  161. my $blurb = get_blurb();
  162. return ('no wifi_ssid specified')
  163. unless defined $config{wifi_ssid};
  164. diag('Configuring network :: ' . $config{wifi_ssid});
  165. my ($ifconfig) = capture_string('ifconfig', '-s');
  166. if ($ifconfig !~ /wlan/) {
  167. diag('No wireless hardware found.');
  168. } elsif (defined $config{wifi_password}) {
  169. my $wpa_config = capture_string(
  170. 'wpa_passphrase',
  171. $config{wifi_ssid},
  172. $config{'wifi_password'}
  173. );
  174. $wpa_config = <<"WPA";
  175. # $blurb
  176. ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
  177. update_config=1
  178. $wpa_config
  179. WPA
  180. diag("Writing $conf_file");
  181. my @log = capture_list(
  182. 'wpa_cli',
  183. 'reconfigure'
  184. );
  185. foreach my $logline (@log) {
  186. diag($logline);
  187. }
  188. put_file($conf_file, $wpa_config, $conf_file . '.backup');
  189. } else {
  190. diag("No wifi_password defined, falling back to iwconfig.");
  191. my $iwlog = capture_string(
  192. 'iwconfig',
  193. # TODO: this of course is not always going to be the same...
  194. 'wlan0',
  195. 'essid',
  196. $config{wifi_ssid}
  197. );
  198. }
  199. }
  200. =back
  201. =head1 UTILITY SUBROUTINES
  202. =over
  203. =item capture_string($cmd, @args)
  204. Return a string containing the output of a command, or log an
  205. error.
  206. =cut
  207. sub capture_string {
  208. return join "", capture_list(@_);
  209. }
  210. =item capture_list($cmd, @args)
  211. Return a list containing the output of a command, or log an
  212. error.
  213. =cut
  214. sub capture_list {
  215. my (@cmd) = @_;
  216. my ($success, $error_message, $full_buf, $stdout_buf, $stderr_buf) =
  217. run(command => \@cmd, verbose => 0);
  218. if ($success) {
  219. return @$full_buf;
  220. } else {
  221. diag('error', $error_message);
  222. }
  223. }
  224. =item parse_config($path_to_file)
  225. Grab a hash of configuration options out of some text file,
  226. formatted like so:
  227. key1=value
  228. key2=value2
  229. =cut
  230. sub parse_config {
  231. my %config;
  232. my ($config_path) = @_;
  233. my $config_str = get_file($config_path);
  234. # Crude dos2unix:
  235. $config_str =~ s/\r\n/\n/g;
  236. while ($config_str =~ m{^([a-z_]+) = (.*?)$}ixmg) {
  237. my $key = lc($1); # normalize to lowercase
  238. my $value = $2;
  239. $config{$key} = $value;
  240. }
  241. return %config;
  242. }
  243. =item get_file($path_to_file)
  244. Returns the contents of a given file as a string.
  245. =cut
  246. sub get_file {
  247. my ($path) = @_;
  248. if (! -e $path) {
  249. die "$path doesn't appear to exist."
  250. }
  251. local $/ = undef;
  252. open my $fh, '<', $path
  253. or die "Failed opening $path: $!";
  254. my $contents = <$fh>;
  255. close $fh;
  256. return $contents;
  257. }
  258. =item put_file($path, $content)
  259. Put $content in the file at $path.
  260. =cut
  261. sub put_file {
  262. my ($path, $content, $backup_path) = @_;
  263. # Handle one-time backups - this could use some rethinking.
  264. if (defined $backup_path) {
  265. if (! -e $backup_path) {
  266. if (-e $path) {
  267. my $old_contents = get_file($path);
  268. put_file($backup_path, $old_contents);
  269. }
  270. }
  271. }
  272. open my $fh, '>', $path
  273. or die "Failed opening $path: $!";
  274. print $fh $content;
  275. close $fh;
  276. }
  277. =item is_installed_package($package_name)
  278. Check whether a given package is installed.
  279. =cut
  280. sub is_installed_package {
  281. my ($package_name) = @_;
  282. my $query_result = capture_string(
  283. 'dpkg-query',
  284. '-W',
  285. '-f',
  286. '${Status}',
  287. $package_name
  288. );
  289. return ($query_result =~ /install ok installed/);
  290. }
  291. =item install_package($package_name)
  292. Ensure that a given package is installed. Should be idempotent.
  293. Returns a status string and, if action taken, an install log.
  294. =cut
  295. sub install_package {
  296. my ($package_name) = @_;
  297. return 'already-installed'
  298. if is_installed_package($package_name);
  299. my @install_log = capture_list(
  300. 'apt-get',
  301. '-y',
  302. 'install',
  303. $package_name
  304. );
  305. return ('installed', @install_log);
  306. }
  307. =item uninstall_package($package_name)
  308. Ensure that a given package is not installed. Should be idempotent.
  309. Returns a status string and, if action taken, an uninstall log.
  310. =cut
  311. sub uninstall_package {
  312. my ($package_name) = @_;
  313. return 'already-uninstalled'
  314. unless is_installed_package($package_name);
  315. my @install_log = capture_list(
  316. 'apt-get',
  317. '-y',
  318. 'remove',
  319. $package_name
  320. );
  321. return ('uninstalled', @install_log);
  322. }
  323. =item get_blurb()
  324. Return a useful blurb for inclusion in config file comments.
  325. =cut
  326. sub get_blurb {
  327. return "This file is managed by $OCCI_CONFIG";
  328. }
  329. =item diag(@columns)
  330. Print columns of diagnostic output. Use diag_push() to add a level of
  331. indentation, and diag_pop() to remove it.
  332. =cut
  333. {
  334. # Cheesy retention of state:
  335. my @diag_stack = ();
  336. sub diag {
  337. my (@cols) = @_;
  338. print join " :: ", (@diag_stack, @cols);
  339. print "\n";
  340. }
  341. sub diag_push {
  342. my ($value) = @_;
  343. push @diag_stack, $value;
  344. }
  345. sub diag_pop {
  346. pop @diag_stack;
  347. }
  348. }
  349. =item have_config_or_exit($path)
  350. Check that a given config file exists, and exit with some documentation if not.
  351. =cut
  352. sub have_config_or_exit {
  353. my ($file) = @_;
  354. return 1 if -f $file;
  355. print STDERR <<"HELPTEXT";
  356. It looks like you don't have a $OCCI_CONFIG yet.
  357. In order to create one:
  358. sudo nano $OCCI_CONFIG
  359. And then add configuration keys like:
  360. hostname=somepi
  361. See /usr/share/doc/occi/occidentalis_example.txt for a full example.
  362. HELPTEXT
  363. exit 0;
  364. }
  365. =item install()
  366. Install occi systemwide, including systemd service for running at startup.
  367. =cut
  368. sub install {
  369. diag_push('install');
  370. # Copy this script to /usr/local/bin:
  371. my $src_path = __FILE__;
  372. my $install_path = '/usr/local/bin/' . basename($src_path);
  373. if (copy($src_path, $install_path)) {
  374. diag("copied $src_path -> /usr/local/bin");
  375. capture_string("chmod a+x $install_path");
  376. } else {
  377. diag(
  378. "copy of $src_path to /usr/local/bin failed - do you need to use sudo?"
  379. );
  380. exit(1);
  381. }
  382. # Create a /boot/occidentalis.txt if it doesn't exist:
  383. if (-e $OCCI_CONFIG) {
  384. diag("Found existing $OCCI_CONFIG");
  385. } else {
  386. diag("Creating example $OCCI_CONFIG");
  387. my $occi_text = <<"INI";
  388. # Lines with a leading "#" are comments. Blank lines are ignored.
  389. # Uncomment below to set hostname:
  390. # hostname=somepi
  391. # Uncomment below to configure a wireless network:
  392. # wifi_ssid=somewifinetwork
  393. # wifi_password=somepassword
  394. INI
  395. put_file($OCCI_CONFIG, $occi_text);
  396. }
  397. # 3. set up systemd to run this file
  398. my $unit_path = '/etc/systemd/system/occi.service';
  399. my $unit_text = <<"SYSTEMD";
  400. [Unit]
  401. Description=Adafruit Occidentalis Configuration Helper for Raspberry Pi
  402. [Service]
  403. ExecStart=/usr/local/bin/occi
  404. [Install]
  405. WantedBy=multi-user.target
  406. SYSTEMD
  407. diag("Writing $unit_path");
  408. put_file($unit_path, $unit_text);
  409. capture_string("chmod 664 $unit_path");
  410. diag('Enabling occi.service');
  411. capture_string('systemctl daemon-reload');
  412. capture_string('systemctl enable occi.service');
  413. diag_pop();
  414. }
  415. =back
  416. =head1 AUTHOR
  417. Brennen Bearnes
  418. Todd Treece
  419. =head1 COPYING
  420. The MIT License (MIT)
  421. Copyright (c) 2015 Adafruit Industries
  422. Permission is hereby granted, free of charge, to any person obtaining a copy
  423. of this software and associated documentation files (the "Software"), to deal
  424. in the Software without restriction, including without limitation the rights
  425. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  426. copies of the Software, and to permit persons to whom the Software is
  427. furnished to do so, subject to the following conditions:
  428. The above copyright notice and this permission notice shall be included in
  429. all copies or substantial portions of the Software.
  430. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  431. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  432. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  433. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  434. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  435. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  436. THE SOFTWARE.
  437. =cut