Bash: Using an alias in an alias

I’ve been helping set up some VPSs (Virtual Private Server) and at the moment they don’t have domain names assigned. I can use the history command to find the right IP address to ssh in but that can be cumbersome. So I decided to write an alias for each server. These lines are in my extended bash config file that is called when my .profile runs.

My login is the same on each server so I could hard code this, but I made it general so I can share it with other users. I don’t like to hard code things so I thought I’d let bash find my user id and then use it in the ssh command. My first thought was to just create an alias for my login and use it in an alias for each server. But I couldn’t get it to work. I tried using just the alias since examples of creating aliases seem to work this way with builtin commands. Then I thought that maybe I need to escape the alias so that bash knows that it should process it.


alias myID='who am i | cut -d\  -f 1'
alias myserver='ssh myID@192.245.184.221'      #Doesn’t work
alias myserver='ssh $(myID)@192.245.184.221'   #Works fine

It turns out that the second line works, but I did had a problem with aliases being set and it didn’t work for me. So I started playing around with things that did work and making small adjustments. FYI, One thing you need to do if you redefine aliases and functions is to make sure that you clear out the old ones. If you don’t then you may not be running the function you thought you were or you could be running an alias when you thought you were running a function.

You can use unset to remove them from memory. Use the -f flag for functions.


unset myID
unset -f dave

For myserver, I put the alias command in parens and prefixed it with a $. Bash executes this first and then uses it in the ssh command. If you don’t do this, bash thinks that the first argument for ssh is ‘who’ and fails. That worked, but I don’t like the idea of having duplicate code in login alias. So I thought I’d try a function. In the first function, I define a variable and then use it. The third function looks an awful lot like a failed alias in the example above, but since it is a function, it works. I think what is happening is that when bash sees $(myID) it thinks, I should process whatever is inside the parens. So it finds the alias and runs it.


#   Log in to other systems
alias myID='who am i | cut -d\  -f 1'

alias myserver='ssh $(who am i | cut -d\  -f 1)@192.245.184.221'
dave() { id=$(who am i | cut -d\  -f 1); ssh $id@192.233.221.11; }
dana()  { ssh $(myID)@192.149.142.163 ; }

alias bigserver='ssh "echo $(myID)"@192.255.174.220'

It finally occurred to me that the .profile script is a full blown shell script. So that means I can use variables in it. I define an id variable that is the result of the shell executing the commands that are in it. When the .profile is run, bash assigns id to my login. Then I can use it anywhere I want with $id. I don’t need to use ${id} since my login is one word and since the @ cannot be in a variable name, bash knows to stop processing when it hits the @. This is what I wanted to do with aliases. I thought about making it a local variable since I don’t need it to hang around outside of this script. But the alias isn’t resolved until it is used, so it needs to resolve the variable when it is called.


#   Log in to other systems
id=$(who am i | cut -d\  -f 1)
alias myserver='ssh $id@192.245.184.221'
alias dave='ssh $id@192.233.221.11'
alias dana='ssh $id@192.149.142.163'

I started playing around with aliases again and got strictly aliases to work as well.


#   Log in to other systems
alias myID='who am i | cut -d\  -f 1'
alias myserver='ssh $(myID)@192.245.184.221'
alias dave='ssh $(myID)@192.233.221.11'
alias dana='ssh $(myID)@192.149.142.163'

Update: I was playing with printenv and it turns out that one of the environment variables is LOGNAME. So you can replace the $id with $LOGNAME in the code above.

100,000 MySQL injection attacks in a few days

Recently my site has been hit with huge numbers of injection attacks. Right now, I trap them and return a static page.

Here’s what my URL looks like:


/products/product.php?id=1

This is what an attack looks like:


/products/product.php?d=-3000%27%20IN%20BOOLEAN%20MODE%29%20
UNION%20ALL%20SELECT%2035%2C35%2C35%2C35%2C35%2C35%2C35%2C35
%2C35%2C35%2C35%2C35%2C35%2C%27qopjq%27%7C%7C%27ijiJvkyBhO%27
%7C%7C%27qhwnq%27%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35
%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35
%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35%2C35

I know for sure that this isn’t just a bad link or fat-fingered typing so I don’t want to send them to an overview page. I also don’t want to use any resources on my site delivering a ‘missing’ page.

Based on a couple of comments on Stackoverflow, I looked up how to return ‘page not found’. This Stackoverflow answer by icktoofay suggests using a 404 and then the die(); – the bot thinks that there isn’t a page and might even go away, and no resources are used to display a page not found message.

Here’s what mostly works.


header("HTTP/1.0 404 Not Found");
die();

I still get attempts, but they usually only try 20 or so times and then they go away for a few days.

Ternary operator

Ternary operators are a concise way to write conditional statements that have two possible outcomes. Rather than writing a longer series of if/then/else statements you can write one line that makes it clear what the two choices are.

In this example from iOS, I use a string for direction—either clockwise or counterclockwise—and translate it to a number for use in the formula. That way I don’t have to remember whether -1 is clockwise or counterclockwise when calling the method. I can use natural language to call the method and let the ternary operator take care of the conversion to the value I need in my formula. And I can change my formula at a later date without having to go back and find all the method calls.

Here’s the method call and the operator


- (void)spin:(NSString *)direction withDuration:(float)duration withScale:(float)scale {
    
    int rotation = ([direction isEqualToString:@"clockWise"] ? 1 : -1);

And then use rotation later to determine which way the object rotates


view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 1.0, 1.0), rotation * 2*M_PI/3);

Here’s another example, where I want to pass in a value, but make sure that it isn’t less than one. In this case I’m passing in an integer and rather than doing a series of complicated if/then/else statements I just put the ternary operator in where the integer goes.


self.showRewards = [[ShowRewards alloc] initWithParentView:self.view withLevel:(rewardLevel > 0 ? rewardLevel : 1) ];

I also use it in PHP code for plurals. Something like this is what I use.

$text = "The update was successful. $recordsUpdated " . ($recordsUpdated > 1 ? 'records were updated.' : 'record was updated.');
echo $text;

And I use it to write one set of code that works for two inputs. In this case I have a page that displays all of the titles that are downloadable from Gumroad. Since people are only interested in the Mac or Windows version, I put them on two different pages—but I use the same code. The first part reads in the page type from the URL and puts up a title for Macintosh or Windows.


if ( isset($_GET['page']) ) { $MacWin  = mysql_real_escape_string($_GET['page']); }  else { $MacWin  = 'Win';} 

echo "<div id='wideMargins'>";
$MacintoshWindows = ($MacWin == 'Mac' ? 'Macintosh' : 'Windows');
echo "<h2 class='NewSection'>Download $MacintoshWindows Compatible Titles from Gumroad</h2>";

Then in the SQL statements I pull the appropriate titles. My column names are GumroadURL_Mac and GumroadURL_Win so the $MacWin variable is substituted into the SELECT statement.


$qry = "SELECT *
        FROM product, product_instance
        WHERE product.id = product_id
        AND GumroadURL_$MacWin IS NOT NULL
        ORDER BY name";

I use a full ternary operator to get the right column from the row.


for ($i = 0; $i < $numRows; $i++) {
    $row   = $res->fetch_array();
    $name = $row['name'];
    $tagline = $row['tagline'];
    $GumroadURL = ($MacWin == 'Mac' ? $row['GumroadURL_Mac'] :$row['GumroadURL_Win']);

As you can see, it makes the code much easier to read and in this example, I have one page of code that easily generates two web pages.

break;

This is another programming tool that I don’t recall ever using before. Normally in a loop I cycle through the elements and do something with each item. For example, this Objective C method loops through all the words in the shuffledWords array and returns a list of the words. The for loop in this case uses ‘fast enumeration’ to select each object in the array.


- (Word *)getAndOrButWord:(NSString *)group {
    Word *wordToReturn;
    for( Word *aWord in self.shuffledWords ) {
        if ( [group isEqual:aWord.group] ) {
            wordToReturn = aWord;
        }
    }
    return wordToReturn;
    
}

And this is part of a method that uses the more traditional for loop that explicitly loops through all of the items in an array.


for (NSInteger i = 0; i < [self.prefsCategory1 count]; i++) {
            if ( [[self.prefsCategory1 objectAtIndex:i] isEqualToString: @"1"]) {
                NSString *levelAndPart = [NSString stringWithFormat:@"PREFS01_NAME Part %i", i];
                [self.selectedCategories addObject:levelAndPart];
            }
        }

In both of these cases each item is looked at and appropriate action taken. However, you can break out of the loop early if you don’t need to look at each item. In this simplified example, I only need four items that match the criterion so there is no point in looping after I’ve found four.


for ( Word *gWord in wordsInGroup ) {
    [wordListToReturn addObject:gWord];
    if ( [wordListToReturn count] == 4 ) break;
}
NSLog(@"I've broken out of the loop");

Control goes out of the loop entirely, just as if all the items had been looked at.
Here is a real world example with multiple break statements. In this case I have an array of 200 objects (girls with colored backpacks) and I want four items from the array. The backpacks are colored and have a different colored stripe on them. In the game I ask the child to show me the backpack that is, for example, red and green. But I don’t want to display a green and red backpack on the screen since it would be confusing to the child. There are two breaks in this example. First I loop through the ‘wordListToReturn’ array to see if the backpack can be added. If it can’t then there is no point in looking at the rest of the items in the array so I break out. This takes me to the outer loop and I pick the next object in the backpack array. Once I get four items I don’t need to continue, so there is another break that takes me out of the loop entirely.


NSInteger wordsToReturnCount = 1;
    for ( Word *gWord in wordsInGroup ) {
        // Add the first item to the list
        if ( ![wordListToReturn lastObject]) {
            [wordListToReturn addObject:[wordsInGroup objectAtIndex:0]];
            NSLog(@"First Word added %@", [wordListToReturn objectAtIndex:0]);
        // Loop through after the first word in in the list
        } else {
            BOOL addWord = YES; // Assume you'll add the word unless there is a match
            NSLog(@"gword is %@", gWord.image);
            // Look through all the words in the return list and see if this word matches
            for ( Word *lWord in wordListToReturn) {
                NSArray *gWordColors =[NSArray arrayWithObjects:gWord.color1,   gWord.color2, nil];
                NSArray *lWordColors = [NSArray arrayWithObjects:lWord.color1, lWord.color2, nil];
                
                [gWordColors sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
                [lWordColors sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
                
                NSString *sortedgWordColors = [NSString stringWithFormat:@"%@ %@", [gWordColors objectAtIndex:0], [gWordColors objectAtIndex:1] ];
                NSString *sortedlWordColors = [NSString stringWithFormat:@"%@ %@", [lWordColors objectAtIndex:0], [lWordColors objectAtIndex:1] ];
                NSLog(@" gWord: %@, lWord %@", sortedgWordColors, sortedlWordColors);
                if ([sortedgWordColors isEqualToString:sortedlWordColors]) {
                    addWord = NO;
                    break;
                }
            }
            if (addWord) {
                [wordListToReturn addObject:gWord];
                NSLog(@"Word added");
                wordsToReturnCount++;
            }
            if (wordsToReturnCount == 4 ) break;
        }
    }

do } { while

I’ve been coding in coding in various languages since around 1983 and this is the first time I’ve had an occasion to use a do } { while loop.

Here’s the scenario. I have four different kinds of pictures: locomotives, boxcars, tankers, and cabooses. I have eleven versions of each, one for each of eleven colors. I want to display two items on the screen at the same time and ask the child to identify the color. Now if a red boxcar and a red caboose show up on the screen at the same time, both are correct so the child can’t choose the red one. So what I want to do is check to see if the colors are the same and then pick a different object if they are.

I’ve already picked my first object from the list and this is the code I use to pick the second. I always need to pick a second item, so the do { } while construction is perfect. It runs through the code and after the first pass evaluates the conditional. In this case, it checks to see if the color of the first object (leftItem) is the same as the color of the second object (rightItem). If they are equal, it does another iteration and picks another object. I have eleven colors so the loop repeats about 9% of the time, so it doesn’t have any impact on execution. If you only had two or three colors, you’d probably want to use a different method.

Note: The code is Objective C and I changed it a bit from the original to make the loop portion clearer.


  NSInteger randomWord2;
        do {
            // Get another random number between 0 and n-1 
            //and add it to the original number plus 1
            int randomNumber2 = (arc4random() % numItems);
            // If randomNumber2 is not zero then the two words will be different
            if (randomNumber2   == 0) randomNumber2 = self.scoreKeeper.currentScreen + 1;
            randomItem2 = (randomNumber2 + self.scoreKeeper.currentScreen) % numItems;
            self.rightItem = [self.wordList getWord:randomItem2];
        // If the two objects have the same color, look for another rightItem
        } while ( [self.rightItem.color isEqual:self.leftItem.color] );