2e2dedb818930d1a30e03666abb93ff9342a88ab
[mirror/scst/.git] / scstadmin / scstadmin
1 #!/usr/bin/perl
2 $Version  = 'SCST Configurator v0.7.1';
3
4 # Configures SCST
5 #
6 # Written by Mark R. Buechler 12/07/04
7
8 sub usage
9   {
10     die <<"EndUsage";
11 $Version
12
13 Usage:
14 General Operations
15      -config <config>     : Configure SCST given the specified configuration file.
16      -ClearConfig         : Clear all SCST configuration.
17      -WriteConfig <file>  : Writes the current configuration out to the specified file.
18      -checkConfig <file>  : Checks the saved configuration in the specified file.
19      -sessions            : List current initiator sessions.
20      
21 Target Driver Operations
22      -enable <wwn|host>   : Enable target mode for driver at specified WWN or host.
23      -disable <wwn|host>  : Disable target mode for driver at specified WWN or host.
24
25 Devices Operations
26      -adddev <device>     : Adds a device to a handler.
27          -handler <handler>
28          -path <path>
29          -options <options>
30          -blocksize <bytes>
31      -RemoveDev <device>  : Remove a device from a handler.
32          -handler <handler>
33  
34 Users Operations
35      -adduser <user>      : Adds a user to a security group.
36          -group <group>
37      -RemoveUser <user>   : Delete a user from a security group.
38          -group <group>
39      -ClearUsers          : Clear all users from a given security group.
40          -group <group>
41
42 Groups Operations
43      -addgroup <group>    : Add a given group to available security groups.
44      -RemoveGroup <group> : Remove a give group from available security groups.
45      
46 Assignments Operations
47      -assigndev <device>  : Assign a given device to a security group.
48          -group <group>
49          -lun <lun>
50      -ReleaseDev <device> : Remove a given device from a security group.
51          -group <group>
52      -ClearDevs           : Clear all device assignments for a security group.
53          -group <group>
54
55 Options
56      -ForceConfig         : Force all confuration changes, even deletions (DANGER!).
57   
58 Debugging (limited support)
59      -debug               : Debug mode - don\'t do anything destructive.
60
61 Available Handlers:
62       disk, vdisk, disk_perf, cdrom, vcdrom, changer, modisk, modisk_perf, tape, tape_perf
63
64 Available Options for create and open:
65       WRITE_THROUGH, READ_ONLY, O_DIRECT, NULLIO, NV_CACHE, BIO
66      
67 Examples:
68      Enable target mode for fibre card specifying its WWN
69        scstadmin -enable 50:06:0B:00:00:39:71:78
70
71      Disable target mode for SCSI host specifying host number
72        scstadmin -disable host4 
73
74      Create a new security group:
75        scstadmin -addgroup HOST01
76        
77      Create a device given an already existing disk file:
78        scstadmin -adddev DISK01 -handler vdisk -path /vdisks/disk01.dsk -options READ_ONLY,WRITE_THROUGH
79        
80      Assign a device to a security group:
81        scstadmin -assigndev DISK01 -group HOST01 -lun 1
82
83 EndUsage
84   }
85
86 use SCST::SCST;
87 use Getopt::Long;
88 use IO::File;
89 use IO::Dir;
90 use POSIX;
91 use strict;
92
93 my $_DEF_CONFIG_ = '/etc/scst.conf';
94
95 my $TRUE  = 1;
96 my $FALSE = 0;
97
98 my $_MAX_LUNS_      = 255;
99 my $_DEFAULT_GROUP_ = 'Default';
100
101 my $_SCSI_CLASS_    = '/sys/class/scsi_host';
102 my $_FC_CLASS_      = '/sys/class/fc_host';
103
104 my $SCST;
105 my $DEVICES;
106 my $TARGETS;
107 my %USERS;
108 my %ASSIGNMENTS;
109 my %HANDLERS;
110 my %GROUPS;
111 my $_DEBUG_;
112
113 my %_HANDLER_MAP_ = ('cdrom' => $SCST::SCST::CDROM_TYPE,
114                      'changer' => $SCST::SCST::CHANGER_TYPE,
115                      'disk' => $SCST::SCST::DISK_TYPE,
116                      'vdisk' => $SCST::SCST::VDISK_TYPE,
117                      'vcdrom' => $SCST::SCST::VCDROM_TYPE,
118                      'disk_perf' => $SCST::SCST::DISKPERF_TYPE,
119                      'modisk' => $SCST::SCST::MODISK_TYPE,
120                      'modisk_perf' => $SCST::SCST::MODISKPERF_TYPE,
121                      'tape' => $SCST::SCST::TAPE_TYPE,
122                      'tape_perf' => $SCST::SCST::TAPEPERF_TYPE,
123                      'processor' => $SCST::SCST::PROCESSOR_TYPE,
124                 # Add in the dev_ names as well
125                      'dev_cdrom' => $SCST::SCST::CDROM_TYPE,
126                      'dev_changer' => $SCST::SCST::CHANGER_TYPE,
127                      'dev_disk' => $SCST::SCST::DISK_TYPE,
128                      'dev_disk_perf' => $SCST::SCST::DISKPERF_TYPE,
129                      'dev_modisk' => $SCST::SCST::MODISK_TYPE,
130                      'dev_modisk_perf' => $SCST::SCST::MODISKPERF_TYPE,
131                      'dev_tape' => $SCST::SCST::TAPE_TYPE,
132                      'dev_tape_perf' => $SCST::SCST::TAPEPERF_TYPE,
133                      'dev_processor' => $SCST::SCST::PROCESSOR_TYPE);
134                      
135 my %_REVERSE_MAP_ = ($SCST::SCST::CDROM_TYPE => 'cdrom',
136                      $SCST::SCST::CHANGER_TYPE => 'changer',
137                      $SCST::SCST::DISK_TYPE => 'disk',
138                      $SCST::SCST::VDISK_TYPE => 'vdisk',
139                      $SCST::SCST::VCDROM_TYPE => 'vcdrom',
140                      $SCST::SCST::DISKPERF_TYPE => 'disk_perf',
141                      $SCST::SCST::MODISK_TYPE => 'modisk',
142                      $SCST::SCST::MODISKPERF_TYPE => 'modisk_perf',
143                      $SCST::SCST::TAPE_TYPE => 'tape',
144                      $SCST::SCST::TAPEPERF_TYPE => 'tape_perf',
145                      $SCST::SCST::PROCESSOR_TYPE => 'processor');
146
147 my %_HANDLER_TYPE_MAP_ = ($SCST::SCST::IOTYPE_PHYSICAL => 'physical',
148                           $SCST::SCST::IOTYPE_VIRTUAL => 'virtual',
149                           $SCST::SCST::IOTYPE_PERFORMANCE => 'performance');
150
151 $SIG{INT} = \&commitSuicide;
152
153 use vars qw($Version);
154
155 POSIX::setsid();
156
157 &main();
158
159 sub getArgs {
160         my $applyConfig;
161         my $forceConfig;
162         my $clearConfig;
163         my $writeConfig;
164         my $checkConfig;
165         my $showSessions;
166         my $addDev;
167         my $devPath;
168         my $removeDev;
169         my $addUser;
170         my $removeUser;
171         my $clearUsers;
172         my $addGroup;
173         my $removeGroup;
174         my $assignDev;
175         my $releaseDev;
176         my $clearDevs;
177         my $devLun;
178         my $handler;
179         my $group;
180         my $options;
181         my $blocksize;
182         my $enable;
183         my $disable;
184
185         my $p = new Getopt::Long::Parser;
186
187         if (!$p->getoptions('config:s'          => \$applyConfig,
188                             'ClearConfig'       => \$clearConfig,
189                             'ForceConfig'       => \$forceConfig,
190                             'WriteConfig=s'     => \$writeConfig,
191                             'checkConfig=s'     => \$checkConfig,
192                             'sessions'          => \$showSessions,
193                             'adddev=s'          => \$addDev,
194                             'path=s'            => \$devPath,
195                             'RemoveDev=s'       => \$removeDev,
196                             'lun=s'             => \$devLun,
197                             'adduser=s'         => \$addUser,
198                             'RemoveUser=s'      => \$removeUser,
199                             'ClearUsers'        => \$clearUsers,
200                             'addgroup=s'        => \$addGroup,
201                             'RemoveGroup=s'     => \$removeGroup,
202                             'assigndev=s'       => \$assignDev,
203                             'ReleaseDev=s'      => \$releaseDev,
204                             'ClearDevs'         => \$clearDevs,
205                             'handler=s'         => \$handler,
206                             'group=s'           => \$group,
207                             'options=s'         => \$options,
208                             'blocksize=s'       => \$blocksize,
209                             'enable=s'          => \$enable,
210                             'disable=s'         => \$disable,
211                             'debug'             => \$_DEBUG_)) {
212                 &usage();
213         }
214
215         if ((defined($enable) && !$enable) || (defined($disable) && !$disable)) {
216                 print "Argument -enable/-disable requires a WWN or host.\n\n";
217                 usage();
218         }
219
220         if ($handler && !$_HANDLER_MAP_{$handler}) {
221                 print "Invalid handler '$handler' specified. Available handlers are:\n\n";
222                 foreach my $_handler (keys %_HANDLER_MAP_) {
223                         print "\t$_handler\n";
224                 }
225                 print "\n";
226                 exit 1;
227         }
228
229         if ($addDev && !($handler && $devPath)) {
230                 print "Please specify -handler and -path with -adddev.\n\n";
231                 usage();
232         }
233
234         if (defined($blocksize) && !$blocksize) {
235                 print "Please specify bytes with -blocksize.\n\n";
236                 usage();
237         }
238
239         if ($blocksize && !$addDev) {
240                 print "Please specify -adddev with -blocksize.\n";
241                 usage();
242         }
243
244         if (defined($forceConfig) && !defined($applyConfig)) {
245                 print "Please specify -config with -ForceConfig.\n\n";
246                 usage();
247         }
248
249         if ($removeDev && !$handler) {
250                 print "Please specify -handler with -RemoveDev.\n\n";
251                 usage();
252         }
253
254         if ($addUser && !defined($group)) {
255                 print "Please specify -group with -adduser.\n\n";
256                 usage();
257         }
258
259         if ($removeUser && !defined($group)) {
260                 print "Please specify -group with -RemoveUser.\n\n";
261                 usage();
262         }
263
264         if ($clearUsers && !defined($group)) {
265                 print "Please specify -group with -ClearUsers.\n\n";
266                 usage();
267         }
268
269         if ($assignDev && !(defined($group) && defined($devLun))) {
270                 print "Please specify -group and -lun with -assigndev.\n\n";
271                 usage();
272         }
273
274         if ($releaseDev && !defined($group)) {
275                 print "Please specify -group with -ReleaseDev.\n\n";
276                 usage();
277         }
278
279         if ($clearDevs && !defined($group)) {
280                 print "Please specify -group with -ClearDevs.\n\n";
281                 usage();
282         }
283
284         if (defined($writeConfig) && !$writeConfig) {
285                 print "Please specify a file name to write configuration to..\n\n";
286                 usage();
287         }
288
289         $_DEBUG_ = $TRUE if (defined($_DEBUG_));
290
291         $forceConfig = $TRUE if (defined($forceConfig));
292         $showSessions = $TRUE if (defined($showSessions));
293
294         $enable =~ tr/A-Z/a-z/; $disable =~ tr/A-Z/a-z/;
295
296         if ((defined($showSessions) + defined($addDev) + defined($removeDev) +
297              defined($addUser) + defined($enable) + defined($disable) +
298              defined($removeUser) + defined($clearUsers) + defined($assignDev) +
299              defined($releaseDev) + defined($clearDevs) + defined($applyConfig) +
300              defined($clearConfig) + defined($writeConfig) + defined($checkConfig)) > 1) {
301                 print "Please specify only one operation at a time.\n";
302                 usage();
303         }
304
305         $applyConfig = $_DEF_CONFIG_ if (defined($applyConfig) && !$applyConfig);
306         $checkConfig = $_DEF_CONFIG_ if (defined($checkConfig) && !$checkConfig);
307
308         return ($enable, $disable, $addDev, $devPath, $devLun, $removeDev, $addUser, $removeUser,
309                 $clearUsers, $addGroup, $removeGroup, $assignDev, $releaseDev, $clearDevs,
310                 $handler, $group, $options, $blocksize, $applyConfig, $forceConfig,
311                 $clearConfig, $writeConfig, $checkConfig, $showSessions);
312 }
313
314 sub main {
315         my $rc;
316
317         STDOUT->autoflush(1);
318
319         # We need to run as root
320         if ( $> ) {die("This program must run as root.\n");}
321
322         my ($enable, $disable, $addDev, $devPath, $devLun, $removeDev, $addUser, $removeUser,
323             $clearUsers, $addGroup, $removeGroup, $assignDev, $releaseDev, $clearDevs,
324             $handler, $group, $options, $blocksize, $applyConfig, $forceConfig,
325             $clearConfig, $writeConfig, $checkConfig, $showSessions) = getArgs();
326
327         $SCST = new SCST::SCST($_DEBUG_);
328
329         readWorkingConfig();
330
331         SWITCH: {
332                 $applyConfig && do {
333                         if ($forceConfig) {
334                                 $rc = applyConfiguration($applyConfig, $FALSE, $TRUE);
335                                 die("Configuration errors found, aborting.\n") if ($rc);
336
337                                 print "\nConfiguration will apply in 10 seconds, type ctrl-c to abort..\n";
338                                 sleep 10;
339                         }
340
341                         readWorkingConfig();
342                         $rc = applyConfiguration($applyConfig, $forceConfig, $FALSE);
343                         last SWITCH;
344                 };
345                 $checkConfig && do {
346                         $rc = applyConfiguration($checkConfig, $FALSE, $TRUE);
347                         last SWITCH;
348                 };
349                 $writeConfig && do {
350                         $rc = writeConfiguration($writeConfig);
351                         last SWITCH;
352                 };
353                 $showSessions && do {
354                         $rc = showSessions();
355                         last SWITCH;
356                 };
357                 defined($clearConfig) && do {
358                         $rc = clearConfiguration();
359                         last SWITCH;
360                 };
361                 $addDev && do {
362                         $rc = addDevice($handler, $addDev, $devPath, $options, $blocksize);
363                         last SWITCH;
364                 };
365                 $removeDev && do {
366                         $rc = removeDevice($handler, $removeDev);
367                         last SWITCH;
368                 };
369                 $addUser && do {
370                         $rc = addUser($group, $addUser);
371                         last SWITCH;
372                 };
373                 $removeUser && do {
374                         $rc = removeUser($group, $removeUser);
375                         last SWITCH;
376                 };
377                 defined($clearUsers) && do {
378                         $rc = clearUsers($group);
379                         last SWITCH;
380                 };
381                 $addGroup && do {
382                         $rc = addGroup($addGroup);
383                         last SWITCH;
384                 };
385                 $removeGroup && do {
386                         $rc = removeGroup($removeGroup);
387                         last SWITCH;
388                 };
389                 $assignDev && do {
390                         $rc = assignDevice($group, $assignDev, $devLun);
391                         last SWITCH;
392                 };
393                 $releaseDev && do {
394                         $rc = releaseDevice($group, $releaseDev);
395                         last SWITCH;
396                 };
397                 defined($clearDevs) && do {
398                         $rc = clearDevices($group);
399                         last SWITCH;
400                 };
401                 $enable && do {
402                         $enable = unformatTarget($enable);
403                         $rc = enableTarget($enable, $TRUE);
404                         last SWITCH;
405                 };
406                 $disable && do {
407                         $disable = unformatTarget($disable);
408                         $rc = enableTarget($disable, $FALSE);
409                         last SWITCH;
410                 };
411
412                 print "No valid operations specified.\n";
413                 usage();
414                 exit $TRUE;
415         }
416
417         print "All done.\n";
418
419         exit $rc;
420 }
421
422 sub readWorkingConfig {
423         my %empty;
424
425         print "Collecting current configuration.. ";
426
427         $TARGETS  = undef;
428         $DEVICES  = undef;
429         %HANDLERS = ();
430         %GROUPS   = ();
431         %USERS    = ();
432
433         my $eHandlers = $SCST->handlers();
434
435         immediateExit($SCST->errorString());
436
437         foreach my $handler (@{$eHandlers}) {
438                 $HANDLERS{$handler}++; # For quick lookups
439         }
440
441         $TARGETS = targets();
442
443         $DEVICES = $SCST->devices();
444         immediateExit($SCST->errorString());
445
446         my $_eGroups = $SCST->groups();
447         immediateExit($SCST->errorString());
448
449         foreach my $group (@{$_eGroups}) {
450                 $GROUPS{$group}++;
451                 $ASSIGNMENTS{$group} = $SCST->groupDevices($group);
452                 my $eUsers = $SCST->users($group);
453
454                 foreach my $user (@{$eUsers}) {
455                         $USERS{$group}->{$user}++; # For quick lookups
456                 }
457                 $USERS{$group} = \%empty if (!$USERS{$group});
458         }
459
460         print "done.\n\n";
461 }
462
463 sub writeConfiguration {
464         my $file = shift;
465
466         if (-f $file) {
467                 if (!unlink $file) {
468                         print "Failed to save current configuration, specified ".
469                           "file exists and cannot be deleted.\n";
470                         return 1;
471                 }
472         }
473
474         my $io = new IO::File $file, O_CREAT|O_WRONLY;
475
476         if (!$io) {
477                 print "Failed to save configuration to file '$file': $!\n";
478                 return 1;
479         }
480
481         print "Writing current configuration to file '$file'.. ";
482
483         print $io "# Automatically generated by $Version.\n\n";
484
485         # Device information
486         foreach my $handler (sort keys %HANDLERS) {
487                 print $io "[HANDLER ".$_REVERSE_MAP_{$handler}."]\n";
488
489                 if ($SCST->handlerType($handler) == $SCST::SCST::IOTYPE_VIRTUAL) {
490                         print $io "#DEVICE <vdisk name>,<device path>";
491                         if ($handler == $SCST::SCST::VDISK_TYPE) {
492                                 print $io ",<options>,<block size>\n";
493                         } else {
494                                 print $io "\n";
495                         }
496                 } else {
497                         print $io "#DEVICE <H:C:I:L>\n";
498                 }
499
500                 my $devices = $SCST->handlerDevices($handler);
501
502                 immediateExit($SCST->errorString());
503
504                 foreach my $device (sort keys %{$devices}) {
505                         my $options = $$devices{$device}->{'OPTIONS'};
506                         $options =~ s/\,/\|/;
507
508                         print $io "DEVICE $device,".$$devices{$device}->{'PATH'};
509                         print $io ",$options";
510                         print $io ",".$$devices{$device}->{'BLOCKSIZE'};
511                         print $io "\n";
512                 }
513
514                 print $io "\n";
515         }
516
517         # User configuration
518         foreach my $group (sort keys %USERS) {
519                 print $io "[GROUP $group]\n";
520                 print $io "#USER <user wwn>\n";
521
522                 foreach my $user (keys %{$USERS{$group}}) {
523                         print $io "USER $user\n";
524                 }
525
526                 print $io "\n";
527         }
528
529         # Assignments configuration
530         foreach my $group (sort keys %ASSIGNMENTS) {
531                 print $io "[ASSIGNMENT $group]\n";
532                 print $io "#DEVICE <device name>,<lun>\n";
533
534                 my $pointer = $ASSIGNMENTS{$group};
535                 foreach my $device (sort keys %{$pointer}) {
536                         print $io "DEVICE $device,".$$pointer{$device}."\n";
537                 }
538
539                 print $io "\n";
540         }
541
542         # Targets configuration
543         foreach my $type ('enable', 'disable') {
544                 print $io "[TARGETS $type]\n";
545                 print $io "#HOST <wwn identifier>\n";
546
547                 foreach my $target (sort keys %{$TARGETS}) {
548                         if ((($type eq 'enable') && $$TARGETS{$target}->{'enabled'}) ||
549                             (($type eq 'disable') && !$$TARGETS{$target}->{'enabled'})) {
550                                 my $f_target = formatTarget($target);
551                                 print $io "HOST $f_target\n" if (!$$TARGETS{$target}->{'duplicate'});
552                         }
553                 }
554
555                 print $io "\n";
556         }
557
558         print "done\n";
559
560         close $io;
561
562         return 0;
563 }
564
565 sub applyConfiguration {
566         my $confile = shift;
567         my $force = shift;
568         my $check = shift;
569         my $config = readConfig($confile);
570         my $errs;
571         my $changes = 0;
572
573         my %used_devs;
574         my %used_users;
575         my %used_assignments;
576         my %empty;
577
578         # Cache device/handler configuration
579         foreach my $entry (keys %{$$config{'HANDLER'}}) {
580                 foreach my $device (@{$$config{'HANDLER'}->{$entry}->{'DEVICE'}}) {
581                         my($vname, undef) = split(/\,/, $device, 2);
582                         $vname = cleanupString($vname);
583                         $used_devs{$vname} = $entry;
584                 }
585         }
586
587         # Cache user/group configuration
588         foreach my $group (keys %{$$config{'GROUP'}}) {
589                 foreach my $user (@{$$config{'GROUP'}->{$group}->{'USER'}}) {
590                         $used_users{$group}->{$user}++;
591                 }
592                 $used_users{$group} = \%empty if (!$used_users{$group});
593         }
594
595         # Cache device association configuration
596         foreach my $group (keys %{$$config{'ASSIGNMENT'}}) {
597                 foreach my $device (@{$$config{'ASSIGNMENT'}->{$group}->{'DEVICE'}}) {
598                         my($vname, $lun) = split(/\,/, $device);
599                         $vname = cleanupString($vname);
600                         $used_assignments{$group}->{$vname} = $lun;
601                 }
602         }
603
604         # If -ForceConfig is used, check for configurations which we've deleted but are still active.
605         if ($force || $check) {
606                 # Associations
607                 foreach my $group (sort keys %ASSIGNMENTS) {
608                         if (!defined($used_assignments{$group}) && (keys %{$ASSIGNMENTS{$group}})) {
609                                 print "\t-> WARNING: Group '$group' has no associations in saved configuration";
610
611                                 if (!$check) {
612                                         print ", clearing all associations.\n";
613                                         if (clearDevices($group)) {
614                                                 $errs++;
615                                         } else {
616                                                 $changes++;
617                                         }
618                                 } else {
619                                         print ".\n";
620                                         $changes++;
621                                 }
622                         } else {
623                                 my $_assignments = $ASSIGNMENTS{$group};
624
625                                 foreach my $device (sort keys %{$_assignments}) {
626                                         if (!defined($used_assignments{$group}->{$device}) ||
627                                            ($$_assignments{$device} != $used_assignments{$group}->{$device})) {
628                                                 if ($$_assignments{$device} != $used_assignments{$group}->{$device}) {
629                                                         print "\t-> WARNING: Device '$device' assigned to group '$group' is at LUN ".
630                                                           $used_assignments{$group}->{$device}.
631                                                           " whereas working configuration reflects LUN ".$$_assignments{$device}; 
632                                                 } else {
633                                                         print "\t-> WARNING: Device '$device' is not associated with group ".
634                                                           "'$group' in saved configuration";
635                                                 }
636
637                                                 if (!$check) {
638                                                         print ", releasing.\n";
639                                                         if (releaseDevice($group, $device)) {
640                                                                 $errs++;
641                                                         } else {
642                                                                 $changes++;
643                                                         }
644                                                 } else {
645                                                         print ".\n";
646                                                         $changes++;
647                                                 }
648                                         }
649                                 }
650                         }
651                 }
652
653                 # Users & Groups
654                 foreach my $group (sort keys %USERS) {
655                         if (!defined($used_users{$group})) {
656                                 print "\t-> WARNING: Group '$group' does not exist in saved configuration";
657
658                                 if (!$check) {
659                                         print ", removing.\n";
660                                         if (clearUsers($group)) {
661                                                 $errs++;
662                                         } else {
663                                                 $changes++;
664                                         }
665
666                                         if (removeGroup($group)) {
667                                                 $errs++;
668                                         } else {
669                                                 $changes++;
670                                         }
671                                 } else {
672                                         print ".\n";
673                                         $changes++;
674                                 }
675                         } else {
676                                 foreach my $user (sort keys %{$USERS{$group}}) {
677                                         if (!defined($used_users{$group}->{$user})) {
678                                                 print "\t-> WARNING: User '$user' is not defined as part of group '$group' ".
679                                                   "in saved configuration";
680
681                                                 if (!$check) {
682                                                         print ", removing.\n";
683                                                         if (removeUser($group, $user)) {
684                                                                 $errs++;
685                                                         } else {
686                                                                 $changes++;
687                                                         }
688                                                 } else {
689                                                         print ".\n";
690                                                         $changes++;
691                                                 }
692                                         }
693                                 }
694                         }
695                 }
696
697                 # Devices
698                 foreach my $device (sort keys %{$DEVICES}) {
699                         if ($$DEVICES{$device} && !defined($used_devs{$device})) {
700                                 # Device gone, but is it still assigned to a group?
701                                 my $isAssigned = $FALSE;
702                                 foreach my $group (sort keys %used_assignments) {
703                                         if (defined($used_assignments{$group}->{$device})) {
704                                                 print "\t-> WARNING: Device '$device' is not defined in saved configuration, ".
705                                                   "however, it is still assigned to group '$group'! Ignoring removal.\n";
706                                                 $isAssigned = $TRUE;
707                                         }
708                                 }
709
710                                 if (!$isAssigned && ($SCST->handlerType($$DEVICES{$device}) == $SCST::SCST::IOTYPE_VIRTUAL)) {
711                                         print "\t-> WARNING: Device '$device' is not defined in saved configuration";
712
713                                         if (!$check) {
714                                                 print ", removing.\n";
715                                                 if (removeDevice($device)) {
716                                                         $errs++;
717                                                 } else {
718                                                         $changes++;
719                                                 }
720                                         } else {
721                                                 print ".\n";
722                                                 $changes++;
723                                         }
724                                 }
725                         } else {
726                                 # Handler change
727                                 if ($_HANDLER_MAP_{$used_devs{$device}} != $$DEVICES{$device}) {
728                                         my $handler = $used_devs{$device};
729
730                                         if ($HANDLERS{$_HANDLER_MAP_{$handler}}) {
731                                                 print "\t-> WARNING: Device '$device' changes handler to '$handler'";
732
733                                                 if (!$check) {
734                                                         print ", changing.\n";
735                                                         if ($SCST->assignDeviceToHandler($device,
736                                                                                          $_HANDLER_MAP_{$handler})) {
737                                                                 $errs++;
738                                                         } else {
739                                                                 $changes++;
740                                                         }
741                                                 } else {
742                                                         print ".\n";
743                                                         $changes++;
744                                                 }
745                                         }
746                                 }
747                         }
748                 }
749         }
750
751         print "Applying configurations additions..\n" if (!$check);
752         print "\n";
753
754         readWorkingConfig() if ($force);
755
756         foreach my $_handler (sort keys %{$$config{'HANDLER'}}) {
757                 if (!$HANDLERS{$_HANDLER_MAP_{$_handler}}) {
758                         print "\t-> WARNING: Handler '$_handler' does not exist.\n";
759                         $errs += 1;
760                         next;
761                 }
762
763                 foreach my $device (@{$$config{'HANDLER'}->{$_handler}->{'DEVICE'}}) {
764                         my($vname, $path, $options, $blocksize) = split(/\,/, $device);
765                         $path = cleanupString($path);
766                         $options =~ s/\s+//; $options =~ s/\|/,/;
767
768                         if (defined($$DEVICES{$vname}) && ($_HANDLER_MAP_{$_handler} == $$DEVICES{$vname})) {
769                                 next;
770                         } elsif (defined($$DEVICES{$vname}) && ($_HANDLER_MAP_{$_handler} != $$DEVICES{$vname})) {
771                                 if ($HANDLERS{$_HANDLER_MAP_{$_handler}}) {
772                                         print "\t-> WARNING: Device '$vname' changes handler from '".
773                                           $_REVERSE_MAP_{$$DEVICES{$vname}}."' to '$_handler'.\n".
774                                           "\t   Use -ForceConfig to change device handler.\n" if (!$force && !$check);
775                                 }
776                                 next;
777                         }
778
779                         if ($check) {
780                                 print "\t-> New device '$_handler:$vname' at path '$path', options '$options', ".
781                                   "blocksize $blocksize.\n";
782                                 $$DEVICES{$vname} = $_HANDLER_MAP_{$_handler};
783                                 $changes++;
784                         } else {
785                                 if (addDevice($_handler, $vname, $path, $options, $blocksize)) {
786                                         $errs++;
787                                 } else {
788                                         $changes++;
789                                 }
790                         }
791                 }
792         }
793
794         # Create new groups and add users..
795         foreach my $group (keys %used_users) {
796                 if (!defined($USERS{$group})) {
797                         if ($check) {
798                                 print "\t-> New group definition '$group.'\n";
799                                 $GROUPS{$group}++;
800                                 $changes++;
801                         } else {
802                                 if (addGroup($group)) {
803                                         $errs++;
804                                 } else {
805                                         $changes++;
806                                 }
807                         }
808                 }
809
810                 foreach my $user (keys %{$used_users{$group}}) {
811                         if (!defined($USERS{$group}->{$user})) {
812                                 if ($check) {
813                                         print "\t-> New user definition '$user' for group '$group'.\n";
814                                         $USERS{$group}->{$user}++;
815                                         $changes++;
816                                 } else {
817                                         if (addUser($group, $user)) {
818                                                 $errs++;
819                                         } else {
820                                                 $changes++;
821                                         }
822                                 }
823                         }
824                 }
825         }
826
827         # Assign new devices to groups..
828         foreach my $group (keys %used_assignments) {
829                 if (!defined($GROUPS{$group})) {
830                         print "\t-> WARNING: Unable to assign to non-existant group '$group'.\n";
831                         $errs += 1;
832                         next;
833                 }
834
835                 foreach my $vname (keys %{$used_assignments{$group}}) {
836                         my $lun = $used_assignments{$group}->{$vname};
837                         my $_assignments = $ASSIGNMENTS{$group};
838
839                         if (defined($$_assignments{$vname}) && ($$_assignments{$vname} == $lun)) {
840                                 next;
841                         } elsif (defined($$_assignments{$vname}) && ($$_assignments{$vname} != $lun)) {
842                                 print "\t-> Device '$vname' assigned to group '$group' is at LUN ".$$_assignments{$vname}.
843                                   ", whereas the working configuration reflects LUN $lun.\n".
844                                   "\t   Use -ForceConfig to force this LUN change.\n" if (!$force && !$check);
845                         } else {
846                                 if ($check) {
847                                         $lun = 'auto' if (!defined($lun));
848                                         print "\t-> New device assignment for '$vname' to group '$group' at LUN $lun.\n";
849                                         $changes++;
850                                 } else {
851                                         if (assignDevice($group, $vname, $lun)) {
852                                                 $errs++;
853                                         } else {
854                                                 $changes++;
855                                         }
856                                 }
857                         }
858                 }
859         }
860
861         # Enable/Disable configured targets
862         foreach my $type (keys %{$$config{'TARGETS'}}) {
863                 my $enable;
864
865                 if ($type eq 'enable') {
866                         $enable = $TRUE;
867                 } elsif ($type eq 'disable') {
868                         $enable = $FALSE;
869                 } else {
870                         print "\t-> WARNING: Ignoring invalid TARGETS specifier '$type'. ".
871                           "Should be one of enable,disable.\n";
872                         next;
873                 }
874
875                 foreach my $target (@{$$config{'TARGETS'}->{$type}->{'HOST'}}) {
876                         my $i_target = unformatTarget($target);
877
878                         if (!defined($$TARGETS{$i_target})) {
879                                 print "\t-> WARNING: Target '$target' not found on system.\n";
880                                 $errs += 1;
881                                 next;
882                         }
883
884                         next if ($enable == targetEnabled($i_target));
885
886                         if (!$enable && targetEnabled($target)) {
887                                 if ($force || $check) {
888                                         print "\t-> WARNING: Target mode for '$target' is currently enabled, ".
889                                           "however configuration file wants it disabled";
890
891                                         if (!$check) {
892                                                 print ", disabling.\n";
893                                                 if (enableTarget($target, $enable)) {
894                                                         $errs++;
895                                                 } else {
896                                                         $changes++;
897                                                 }
898                                         } else {
899                                                 print ".\n";
900                                                 $changes++;
901                                         }
902                                 }
903                         } else {
904                                 print "\t-> Target '$target' is enabled in configuration file, ".
905                                   "however is currently disabled";
906
907                                 if (!$check) {
908                                         print ", enabling.\n";
909                                         if (enableTarget($target, $enable)) {
910                                                 $errs++;
911                                         } else {
912                                                 $changes++;
913                                         }
914                                 } else {
915                                         print ".\n";
916                                         $changes++;
917                                 }
918                         }
919                 }
920         }
921
922         print "\nEncountered $errs error(s) while processing.\n" if ($errs);
923
924         if ($check) {
925                 print "Configuration checked, $changes difference(s) found with working configuration.\n";
926         } else {
927                 $changes = 0 if ($_DEBUG_);
928                 print "Configuration applied, $changes changes made.\n";
929         }
930
931         return $TRUE if ($errs);
932         return $FALSE;
933 }
934
935 sub clearConfiguration {
936         my $errs;
937
938         print "WARNING: This removes ALL applied SCST configuration and may result in data loss!\n";
939         print "If this is not what you intend, press ctrl-c now. Waiting 10 seconds.\n\n";
940         sleep 10;
941
942         print "\nRemoving all user and groups:\n\n";
943         foreach my $group (keys %GROUPS) {
944                 $errs += removeGroup($group) if ($group ne $_DEFAULT_GROUP_);
945         }
946
947         print "\nRemoving all handler devices:\n\n";
948         foreach my $device (keys %{$DEVICES}) {
949                 next if (!$$DEVICES{$device});
950                 next if ($SCST->handlerType($$DEVICES{$device}) != $SCST::SCST::IOTYPE_VIRTUAL);
951                 $errs += removeDevice($_REVERSE_MAP_{$$DEVICES{$device}}, $device);
952         }
953
954         print "\nEncountered $errs error(s) while processing.\n" if ($errs);
955         print "\nConfiguration cleared.\n";
956
957         return $TRUE if ($errs);
958         return $FALSE;
959 }
960
961 sub showSessions {
962         my $sessions = $SCST->sessions();
963         immediateExit($SCST->errorString());
964
965         print "\n\tTarget Name\tInitiator Name\t\t\tGroup Name\t\tCommand Count\n";
966
967         foreach my $target (keys %{$sessions}) {
968                 foreach my $group (keys %{$$sessions{$target}}) {
969                         foreach my $user (keys %{$$sessions{$target}->{$group}}) {
970                                 my $commands = $$sessions{$target}->{$group}->{$user};
971
972                                 print "\t$target\t$user\t\t$group\t\t$commands\n";
973                         }
974                 }
975         }
976
977         print "\n";
978
979         return $FALSE;
980 }
981
982 sub addDevice {
983         my $handler = shift;
984         my $device = shift;
985         my $path = shift;
986         my $options = shift;
987         my $blocksize = shift;
988
989         $options =~ s/\,/ /;
990
991         my $_handler = $_HANDLER_MAP_{$handler};
992         my $htype = $SCST->handlerType($_handler);
993
994         if (!$htype) {
995                 print "WARNING: Internal error occured: ".$SCST->errorString()."\n";
996                 return $TRUE;
997         }
998
999         if ($htype != $SCST::SCST::IOTYPE_VIRTUAL) {
1000                 my $typeString = $_HANDLER_TYPE_MAP_{$htype};
1001                 my $validType = $_HANDLER_TYPE_MAP_{$SCST::SCST::IOTYPE_VIRTUAL};
1002                 print "WARNING: Handler $handler of type $typeString is incapable of ".
1003                   "opening/closing devices. Valid handlers are:\n".
1004                   validHandlerTypes($SCST::SCST::IOTYPE_VIRTUAL)."\n";
1005                 return $TRUE;
1006         }
1007
1008         if (defined($$DEVICES{$device})) {
1009                 print "WARNING: Device '$device' already defined.\n";
1010                 return $TRUE;
1011         }
1012
1013         print "\t-> Opening virtual device '$device' at path '$path' using handler '$handler'..\n";
1014
1015         if ($SCST->openDevice($_handler, $device, $path, $options, $blocksize)) {
1016                 print "WARNING: Failed to open virtual device '$device' at path '$path': ".
1017                   $SCST->errorString()."\n";
1018                 return $TRUE;
1019         }
1020
1021         $$DEVICES{$device} = $_handler;
1022
1023         return $FALSE;
1024 }
1025
1026 sub removeDevice {
1027         my $handler = shift;
1028         my $device = shift;
1029
1030         my $_handler = $_HANDLER_MAP_{$handler};
1031         my $htype = $SCST->handlerType($_handler);
1032
1033         if (!$htype) {
1034                 print "WARNING: Internal error occured: ".$SCST->errorString()."\n";
1035                 return $TRUE;
1036         }
1037
1038         if ($htype != $SCST::SCST::IOTYPE_VIRTUAL) {
1039                 my $typeString = $_HANDLER_TYPE_MAP_{$htype};
1040                 my $validType = $_HANDLER_TYPE_MAP_{$SCST::SCST::IOTYPE_VIRTUAL};
1041                 print "WARNING: Handler $handler of type $typeString is incapable of ".
1042                   "opening/closing devices. Valid handlers are:\n".
1043                   validHandlerTypes($SCST::SCST::IOTYPE_VIRTUAL)."\n";
1044                 return $TRUE;
1045         }
1046
1047         if (!defined($$DEVICES{$device})) {
1048                 print "WARNING: Device '$device' not defined.\n";
1049                 return $TRUE;
1050         }
1051
1052         print "\t-> Closing virtual device '$device'..\n";
1053
1054         if ($SCST->closeDevice($_handler, $device)) {
1055                 print "WARNING: Failed to close virtual device '$device': ".
1056                   $SCST->errorString()."\n";
1057                 return $TRUE;
1058         }
1059
1060         undef $$DEVICES{$device};
1061
1062         return $FALSE;
1063 }
1064
1065 sub addGroup {
1066         my $group = shift;
1067
1068         if (defined($GROUPS{$group})) {
1069                 print "WARNING: Group '$group' already exists.\n";
1070                 return $TRUE;
1071         }
1072
1073         print "\t-> Creating security group '$group'..\n";
1074
1075         if ($SCST->addGroup($group)) {
1076                 print "WARNING: Failed to create security group '$group': ".
1077                   $SCST->errorString()."\n";
1078                 return $TRUE;
1079         }
1080
1081         $GROUPS{$group}++;
1082
1083         return $FALSE;
1084 }
1085
1086 sub removeGroup {
1087         my $group = shift;
1088
1089         if (!defined($GROUPS{$group})) {
1090                 print "WARNING: Group '$group' does not exist.\n";
1091                 return $TRUE;
1092         }
1093
1094         print "\t-> Removing security group '$group'..\n";
1095
1096         if ($SCST->removeGroup($group)) {
1097                 print "WARNING: Failed to remove security group '$group': ".
1098                   $SCST->errorString()."\n";
1099                 return $TRUE;
1100         }
1101
1102         undef $GROUPS{$group};
1103
1104         return $FALSE;
1105 }
1106
1107 sub addUser {
1108         my $group = shift;
1109         my $user = shift;
1110
1111         if (!defined($GROUPS{$group})) {
1112                 print "WARNING: Failed to add user '$user' to group '$group', group does not exist.\n";
1113                 return $TRUE;
1114         }
1115
1116         if (defined($USERS{$group}->{$user})) {
1117                 print "WARNING: User '$user' already exists in security group '$group'.\n";
1118                 return $TRUE;
1119         }
1120
1121         print "\t-> Adding user '$user' to security group '$group'..\n";
1122
1123         if ($SCST->addUser($user, $group)) {
1124                 print "WARNING: Failed to add user '$user' to security group '$group': ".
1125                   $SCST->errorString()."\n";
1126                 return $TRUE;
1127         }
1128
1129         $USERS{$group}->{$user}++;
1130
1131         return $FALSE;
1132 }
1133
1134 sub removeUser {
1135         my $group = shift;
1136         my $user = shift;
1137
1138         if (!defined($GROUPS{$group})) {
1139                 print "WARNING: Failed to remove user '$user' from group '$group', group does not exist.\n";
1140                 return $TRUE;
1141         }
1142
1143         if (!defined($USERS{$group}->{$user})) {
1144                 print "WARNING: User '$user' doesn\'t exist in security group '$group'.\n";
1145                 return $TRUE;
1146         }
1147
1148         print "\t-> Removing user '$user' from security group '$group'..\n";
1149
1150         if ($SCST->removeUser($user, $group)) {
1151                 print "WARNING: Failed to add user '$user' to security group '$group': ".
1152                   $SCST->errorString()."\n";
1153                 return $TRUE;
1154         }
1155
1156         undef $USERS{$group}->{$user};
1157
1158         return $FALSE;
1159 }
1160
1161 sub clearUsers {
1162         my $group = shift;
1163
1164         if (!defined($GROUPS{$group})) {
1165                 print "WARNING: Failed to clear users from group '$group', group does not exist.\n";
1166                 return $TRUE;
1167         }
1168
1169         print "\t-> Clearing users from security group '$group'..\n";
1170
1171         if ($SCST->clearUsers($group)) {
1172                 print "WARNING: Failed to clear users from security group '$group': ".
1173                   $SCST->errorString()."\n";
1174                 return $TRUE;
1175         }
1176
1177         undef $USERS{$group};
1178
1179         return $FALSE;
1180 }
1181
1182 sub assignDevice {
1183         my $group = shift;
1184         my $device = shift;
1185         my $lun = shift;
1186         my %allLuns;
1187
1188         # Put luns into something easier to parse..
1189         foreach my $_group (keys %ASSIGNMENTS) {
1190                 my $_gAssigns = $ASSIGNMENTS{$_group};
1191
1192                 foreach my $_device (keys %{$_gAssigns}) {
1193                         @{$allLuns{$_group}}[$$_gAssigns{$_device}] = $_device;
1194                 }
1195         }
1196
1197         # Use the next available LUN if none specified
1198         if ($lun !~ /\d+/) {
1199                 $lun = ($#{$allLuns{$group}} + 1);
1200                 if ($lun > $_MAX_LUNS_) {
1201                         print "ERROR: Unable to use next available LUN of $lun, lun out of range.\n";
1202                         return $TRUE;
1203                 }
1204
1205                 print "\t-> Device '$device': Using next available LUN of $lun for group '$group'.\n";
1206         }
1207                         
1208         if (($lun < 0) || ($lun > $_MAX_LUNS_)) {
1209                 print "ERROR: Unable to assign device '$device', lun '$lun' is out of range.\n";
1210                 return $TRUE;
1211         }
1212
1213         if (!defined($$DEVICES{$device})) {
1214                 print "WARNING: Unable to assign non-existant device '$device' to group '$group'.\n";
1215                 return $TRUE;
1216         }
1217
1218         if (@{$allLuns{$group}}[$lun]) {
1219                 print "ERROR: Device '$device': Lun '$lun' is already assigned to device '".@{$allLuns{$group}}[$lun]."'.\n";
1220                 return $TRUE;
1221         }
1222
1223         print "\t-> Assign virtual device '$device' to group '$group' at LUN '$lun'..\n";
1224
1225         if ($SCST->assignDeviceToGroup($device, $group, $lun)) {
1226                 print "WARNING: Failed to assign device '$device' to group '$group': ".
1227                   $SCST->errorString()."\n";
1228                 return $TRUE;
1229         }
1230
1231         if (!defined($ASSIGNMENTS{$group})) {
1232                 my %assignments_t;
1233                 $ASSIGNMENTS{$group} = \%assignments_t;
1234         }
1235
1236         my $_assignments = $ASSIGNMENTS{$group};
1237
1238         $$_assignments{$device} = $lun; 
1239
1240         return $FALSE;
1241 }
1242
1243 sub releaseDevice {
1244         my $group = shift;
1245         my $device = shift;
1246
1247         if (!defined($GROUPS{$group})) {
1248                 print "WARNING: Failed to release device '$device' from group '$group', group does not exist.\n";
1249                 return $TRUE;
1250         }
1251
1252         if (!defined($$DEVICES{$device})) {
1253                 print "WARNING: Failed to release device '$device', device not defined.\n";
1254                 return $TRUE;
1255         }
1256
1257         print "\t-> Release virtual device '$device' from group '$group'..\n";
1258
1259         if ($SCST->removeDeviceFromGroup($device, $group)) {
1260                 print "WARNING: Failed to release device '$device' from group '$group': ".
1261                   $SCST->errorString()."\n";
1262                 return $TRUE;
1263         }
1264
1265         my $_assignments = $ASSIGNMENTS{$group};
1266
1267         undef $$_assignments{$device};
1268
1269         return $FALSE;
1270 }
1271
1272 sub clearDevices {
1273         my $group = shift;
1274
1275         if (!defined($GROUPS{$group})) {
1276                 print "WARNING: Failed to clear devices from group '$group', group does not exist.\n";
1277                 return $TRUE;
1278         }
1279
1280         print "\t-> Clear virtual devices from group '$group'..\n";
1281
1282         if ($SCST->clearGroupDevices($group)) {
1283                 print "WARNING: Failed to clear devices from group '$group': ".
1284                   $SCST->errorString()."\n";
1285                 return $TRUE;
1286         }
1287
1288         undef $ASSIGNMENTS{$group};
1289
1290         return $FALSE;
1291 }
1292
1293 sub targets {
1294         my %targets;
1295         my %fcards;
1296         my $root = new IO::Dir $_FC_CLASS_;
1297
1298         if ($root) {
1299                 while (my $entry = $root->read()) {
1300                         next if (($entry eq '.') || ($entry eq '..'));
1301
1302                         my $io = new IO::File "$_FC_CLASS_/$entry/port_name", O_RDONLY;
1303
1304                         if ($io) {
1305                                 my $wwn = <$io>;
1306                                 chomp $wwn;
1307                                 close $io;
1308
1309                                 $fcards{$entry} = $wwn;
1310                         }
1311                 }
1312         }
1313
1314         $root = new IO::Dir $_SCSI_CLASS_;
1315
1316         if ($root) {
1317                 while (my $entry = $root->read()) {
1318                         next if (($entry eq '.') || ($entry eq '..'));
1319
1320                         my $io = new IO::File "$_SCSI_CLASS_/$entry/target_mode_enabled", O_RDONLY;
1321
1322                         if ($io) {
1323                                 my $enabled = <$io>;
1324                                 chomp $enabled;
1325                                 close $io;
1326
1327                                 $targets{$entry}->{'path'} = "$_SCSI_CLASS_/$entry/target_mode_enabled";
1328                                 $targets{$entry}->{'enabled'} = $enabled;
1329
1330                                 if ($fcards{$entry}) {
1331                                         $targets{$fcards{$entry}}->{'enabled'} = $enabled;
1332                                         $targets{$fcards{$entry}}->{'path'} =
1333                                           "$_SCSI_CLASS_/$entry/target_mode_enabled";
1334                                         $targets{$entry}->{'duplicate'} = $TRUE;
1335                                 } else {
1336                                         $targets{$entry}->{'duplicate'} = $FALSE;
1337                                 }
1338                         }
1339                 }
1340         }
1341
1342         return \%targets;
1343 }
1344
1345 sub targetEnabled {
1346         my $target = shift;
1347
1348         return undef if (!defined($$TARGETS{$target}));
1349         return $$TARGETS{$target}->{'enabled'};
1350 }
1351
1352 sub enableTarget {
1353         my $target = shift;
1354         my $enable = shift;
1355
1356         return undef if (!defined($$TARGETS{$target}));
1357
1358         my $io = new IO::File $$TARGETS{$target}->{'path'}, O_WRONLY;
1359         return $TRUE if (!$io);
1360
1361         print $enable ? "\t-> Enabling" : "\t-> Disabling";
1362         print " target mode for SCST host '$target'.\n";
1363
1364         if ($_DEBUG_) {
1365                 print "DBG($$): ".$$TARGETS{$target}->{'path'}." -> $enable\n\n";
1366         } else {
1367                 print $io $enable;
1368         }
1369
1370         close $io;
1371
1372         $$TARGETS{unformatTarget($target)}->{'enabled'} = $enable;
1373
1374         return $FALSE;
1375 }
1376
1377 sub readConfig {
1378         my $confile = shift;
1379         my %config;
1380         my $section;
1381         my $last_section;
1382         my $arg;
1383         my $last_arg;
1384         my %empty;
1385
1386         my $io = new IO::File $confile, O_RDONLY;
1387
1388         die("FATAL: Unable to open specified configuration file $confile: $!\n") if (!$io);
1389
1390         while (my $line = <$io>) {
1391                 ($line, undef) = split(/\#/, $line, 2);
1392                 $line = cleanupString($line);
1393
1394                 if ($line =~ /^\[(.*)\]$/) {
1395                         $last_arg = $arg;
1396                         $last_section = $section;
1397                         ($section, $arg) = split(/\s+/, $1, 2);
1398
1399                         if ($last_arg && ($last_arg ne $arg) && !$config{$last_section}->{$last_arg}) {
1400                                 $config{$last_section}->{$last_arg} = \%empty;
1401                         }   
1402                 } elsif ($section && $arg && $line) {
1403                         my($parameter, $value) = split(/\s+/, $line, 2);
1404
1405                         push @{$config{$section}->{$arg}->{$parameter}}, $value;
1406                 }
1407         }
1408
1409         close $io;
1410
1411         return \%config;
1412 }
1413
1414 sub cleanupString {
1415         my $string = shift;
1416
1417         $string =~ s/^\s+//;
1418         $string =~ s/\s+$//;
1419
1420         return $string;
1421 }
1422
1423 sub formatTarget {
1424         my $target = shift;
1425
1426         if ($target =~ /^0x/) {
1427                 $target =~ s/^0x//;
1428                 my($o1, $o2, $o3, $o4, $o5, $o6, $o7, $o8) = unpack("A2A2A2A2A2A2A2A2", $target);
1429                 $target = "$o1:$o2:$o3:$o4:$o5:$o6:$o7:$o8";
1430         }
1431
1432         $target =~ tr/A-Z/a-z/;
1433
1434         return $target;
1435 }
1436
1437 sub unformatTarget {
1438         my $target = shift;
1439
1440         if ($target =~ /^.{2}\:.{2}\:.{2}\:.{2}\:.{2}\:.{2}\:.{2}\:.{2}/) {
1441                 $target =~ s/\://g;
1442                 $target = "0x$target";
1443         }
1444
1445         $target =~ tr/A-Z/a-z/;
1446
1447         return $target;
1448 }
1449
1450 sub validHandlerTypes {
1451         my $type = shift;
1452         my $buffer = "\n";
1453
1454         foreach my $handler (keys %_REVERSE_MAP_) {
1455                 $buffer .= "\t".$_REVERSE_MAP_{$handler}."\n" if ($SCST->handlerType($handler) == $type);
1456         }
1457
1458         return $buffer;
1459 }
1460
1461 # If we have an unread error from SCST, exit immediately
1462 sub immediateExit {
1463         my $error = shift;
1464
1465         return if (!$error);
1466
1467         print "\n\nFATAL: Received the following error:\n\n\t";
1468         print "$error\n\n";
1469
1470         exit 1;
1471 }
1472
1473 # Hey! Stop that!
1474 sub commitSuicide {
1475         print "\n\nAborting immediately.\n";
1476         exit 1;
1477 }