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