package votorola.s.line; // Copyright 2007-2010, 2012-2013, Michael Allan. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Votorola Software"), to deal in the Votorola Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Votorola Software, and to permit persons to whom the Votorola Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Votorola Software. THE VOTOROLA SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE VOTOROLA SOFTWARE OR THE USE OR OTHER DEALINGS IN THE VOTOROLA SOFTWARE. import java.io.*; import java.sql.*; import java.util.*; import java.util.regex.*; import javax.script.*; import votorola.a.*; import votorola.a.response.*; import votorola.a.response.line.*; import votorola.a.voter.*; import votorola.g.*; import votorola.g.lang.*; import votorola.g.locale.*; import votorola.g.logging.*; import votorola.g.option.*; import votorola.g.util.*; import votorola.s.mail.*; import static votorola.a.response.line.CommandLine.COMMAND_ARGUMENT_PATTERN; import static votorola.a.voter.IDPair.NOBODY; /** Main class of the executable voter - a shell for issuing service commands * on behalf of a voter. * * @see voter */ public @ThreadRestricted final class VOTer implements VoterInterface { /** Executes from the command line. * * @param argv the command line argument array. */ public static void main( String[] argv ) { execute( argv, null ); } private static void execute( String[] argv, HashMap optionMap ) { final boolean isPiped = optionMap != null; LoggerX.i(VOTer.class).info( "voter shell " + (isPiped? "piped": "running") + " with arguments: " + Arrays.toString( argv )); // Parse arguments. Split argv into argv for the VOTer shell only, and argvCommand // for the command responder. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - final String[] argvCommand; String voterEmail = null; String serviceName = null; boolean tooManyIDs = false; { int a; for( a = 0; a < argv.length; ++a ) { final String arg = argv[a]; if( arg.charAt(0) == '-' ) continue; // skip past VOTer options if( arg.indexOf('@') > 0 ) // swallow VOTER-EMAIL { if( voterEmail == null ) { voterEmail = arg; continue; } else tooManyIDs = true; } if( serviceName == null ) // swallow SERVICE-NAME { serviceName = arg; continue; } break; } argvCommand = Arrays.copyOfRange( argv, a, argv.length ); // argvCommand[0] is the command itself, the arguments proper follow it argv = Arrays.copyOfRange( argv, 0, a ); } // Parse options for VOTer. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if( optionMap == null ) { optionMap = CommandLine.compileBaseOptions(); final String name = "id"; optionMap.put( name, new Option( name, Option.REQUIRED_ARGUMENT )); } final int aFirstNonOption = GetoptX.parse( "voter", argv, optionMap ); if( optionMap.get("help").hasOccured() ) { System.out.print( "Usage: voter [--id=ID|VOTER-EMAIL] SERVICE-NAME COMMAND [OPTION...] [ARGUMENT...]\n" + " or voter < ARGUMENT-FILE\n" + " or cat ARGUMENT-FILE | voter\n" + " or voter SERVICE-NAME help\n" + " or voter --help\n" + "Issue a service command on behalf of a voter.\n" ); return; } final IDPair id; { String name = null; if( !tooManyIDs ) { final Option idOption = optionMap.get( "id" ); if( idOption.hasOccured() ) { if( voterEmail == null && idOption.occurenceCount() == 1 ) { final String idString = idOption.argumentValue(); if( idString.indexOf('@') > 0 ) voterEmail = idString; else name = idString; } else tooManyIDs = true; } } if( tooManyIDs ) { System.err.println( "voter: too many personal identifiers (--id or VOTER-EMAIL)" ); System.err.println( GetoptX.createHelpPrompt( "voter" )); System.exit( 1 ); } if( name != null ) { IDPair id2 = NOBODY; try{ id2 = IDPair.fromUsername( name ); } catch( final javax.mail.internet.AddressException x ) { System.err.println( "voter: malformed id option: " + x.getMessage() ); System.exit( 1 ); } id = id2; // just to prevent compiler error } else if( voterEmail != null ) id = IDPair.fromEmail( voterEmail ); else id = NOBODY; } // Execute. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - try { if( serviceName == null ) { if( !id.equals(NOBODY) && !isPiped ) // pipe in multiple commands one line at a time { final BufferedReader in = new BufferedReader( new InputStreamReader( System.in, "UTF-8" )); try { for( ;; ) { final String s = in.readLine(); if( s == null ) return; final String[] argvPiped; { final ArrayList argList = new ArrayList( /*initial capacity*/8 ); final Matcher m = COMMAND_ARGUMENT_PATTERN.matcher( s ); while( m.find() ) argList.add( m.group( 1 )); argvPiped = new String[argList.size()]; argList.toArray( argvPiped ); } execute( argvPiped, new HashMap(optionMap) ); // carrying over the basic command-line options to each // command execution } } finally{ in.close(); } } else { System.err.println( "voter: missing SERVICE-NAME argument" ); System.err.println( GetoptX.createHelpPrompt( "voter" )); System.exit( 1 ); } } else // single command { final VOTer voTer = new VOTer( id, serviceName, argvCommand ); voTer.run(); } } catch( RuntimeException x ) { throw x; } catch( final Exception x ) // various per VOTer.run { System.err.print( "voter: fatal error" + Votorola.unmessagedDetails(x) + ": " ); // System.err.println( x ); x.printStackTrace( System.err ); System.exit( 1 ); } } private VOTer( IDPair _id, String _serviceName, String[] _argvCommand ) throws java.io.IOException, ScriptException, SQLException, java.net.URISyntaxException { id = _id; serviceName = _serviceName; argvCommand = _argvCommand; if( vsRun == null ) { vsRun = new VoteServer( System.getProperty( "user.name" )).new Run( /*isSingleThreaded*/true ); vsRun.singleServiceLock().lock(); // no need to unlock, single access } } // - V o t e r - I n t e r f a c e ---------------------------------------------------- /** @return the voter command to access the service from the command line. */ public String serviceAccessDescriptor( final VoterService s ) { return "$ voter " + s.name() + " help"; } //// P r i v a t e /////////////////////////////////////////////////////////////////////// private final String[] argvCommand; private VoterService ensureVoterMetaService( final String metaServiceName ) throws IOException, ScriptException, SQLException { assert metaServiceName.equals( "mail" ); return vsRun.init_ensureVoterService( new File( vsRun.voteServer().votorolaDirectory(), "mail" + File.separator + "mail-meta-service.js" ), MailMetaService.class ); } private VoterService ensureVoterService( final String serviceName ) throws IOException, ScriptException, SQLException { // Trustserver // --------------------------------------------------------------------------------- if( serviceName.equals( vsRun.trustserver().name() )) return vsRun.trustserver(); // Meta // --------------------------------------------------------------------------------- final String metaServiceName = "mail"; if( serviceName.equals( metaServiceName )) return ensureVoterMetaService( metaServiceName ); // Poll (assumed) // --------------------------------------------------------------------------------- return vsRun.scopePoll().ensurePoll( serviceName ); } private final IDPair id; private void run() throws Exception // ScriptException, IOException, SQLException, { // URISyntaxException and soft Exception from dispatch() if( argvCommand.length == 0 ) { System.err.println( "voter: missing COMMAND argument" ); System.err.println( GetoptX.createHelpPrompt( "voter" )); System.exit( 1 ); } VoterService voterService = null; try { voterService = ensureVoterService( serviceName ); } catch( VoterService.NoSuchServiceException x ) { System.err.println( "voter: unrecognized SERVICE-NAME argument '" + serviceName + "'" ); System.err.println( GetoptX.createHelpPrompt( "voter" )); System.exit( 1 ); } final ReplyBuilder replyB = new ReplyBuilder( Locale.getDefault() ); final BundleFormatter bunA = new BundleFormatter( ResourceBundle.getBundle( "votorola.a.locale.A", replyB.locale(), new BundleControlU() )); int trustLevel = 0; if( !id.equals(NOBODY) ) { trustLevel = vsRun.trustserver().getTraceNode( /*list ref*/null, id ).trustLevel(); } final CommandResponder.Session commandSession = new CommandResponder.Session( VOTer.this, id.email(), trustLevel, bunA, replyB ); try { final Exception x = voterService.dispatch( argvCommand, commandSession ); if( x != null ) throw x; } catch( CommandResponder.AnonymousIssueException x ) { System.err.println( "voter: missing VOTER-EMAIL (" + x.getMessage() + ")" ); System.err.println( GetoptX.createHelpPrompt( "voter" )); System.exit( 1 ); } System.out.print( replyB.chomplnn().toString() ); System.out.flush(); } private final String serviceName; private static VoteServer.Run vsRun; // final after init }