Monday, November 2, 2009

Chapter 7: Privileges and Roles



















Chapter 7: Privileges and Roles



This chapter discusses database privileges and roles. Understanding privileges and how they can be granted is important to employing effective security. Roles allow administrators to grant users the necessary privileges needed to perform their job. Roles are a powerful and manageable way to provide a least-privileged environment, which is important to ensuring a sound and secure database.


The intent of this chapter is not to duplicate the Oracle product documentation, which discusses both privileges and roles. The objective here is to point out some of the important and subtle aspects that are associated with privileges and roles. This is a very important chapter because database access, and to a large extent database security, relies on user privileges.




Access Control, Authorizations, and Privileges


We’ll begin by reviewing a few terms: access control, authorizations, and privileges. You will find these terms littered throughout security policies. These terms, while sometimes used interchangeably, are in fact different. A good understanding is helpful and often necessary in discussions about security policies and implementations.




Access Control



Access control is the process of allowing or preventing access to a resource. There are many ways to determine access or implement access control. A simple way to describe access control is to associate it with a commonly understood implementation called access control lists.



Access control lists (ACLs) are a common way for people to describe the security policy associated with a given application or database. The list is conceptual in most cases and describes who can access what and how they can do it. The ACLs are derived from the organization’s security policies. It’s important to understand that the list is not the enforcement mechanism. The enforcement mechanism is something inside the application or database engine that refers to the list to determine access.





Enforcing Access Control


Think of access control mechanisms as the sentry standing guard at an entry portal. The guard’s job is simply to permit or restrict people from entering the portal. The decision to allow entry may be based on anything, such as a list of approved names, proof of an organizational affiliation, or possession of some kind of permission slip or token. The important thing is that the role of the guard is well defined and narrowly focused. The job is to grant or deny access based on something. As people wish to gain entry, the guard will either allow entry or disallow entry.


The access control mechanisms in the database “stand guard” over database objects, such as tables, views, and procedures. The database decides who gets access to what based on privileges. Privileges, however, can be obtained in multiple ways. Effective security design implies the importance of understanding how privileges can be given, obtained, and managed.





Authorizations


A person is considered authorized when they are allowed to perform an action as described by some governing policy. A boarding pass may authorize a person to get on an airplane. A special badge may authorize a person to enter a secure area. That is, the sentry standing guard should allow them access because they are approved and allowed to gain entry. This doesn’t mean the guard has to let them pass, only that the guard should let them pass.


An authorization translates into one or more privileges, such as the privilege to be in a secure area or the privilege to access a database. The access control mechanisms of the application or database are actually implemented by checking a user’s privileges. Authorizations are abstractions. They represent a binding between a security policy and the actual privileges a user has in a specific context.




















9.2 Obtaining the Source








 

 












9.2 Obtaining the Source





Since Tomcat is a moving target (each

release changes slightly, and point releases happen fairly

frequently), this is only a general description of the build process.







9.2.1 Downloading Source Code





If you want a simpler start, you can get a release source TAR for

Tomcat 4 from the Jakarta Tomcat 4 releases directory at http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release.

Choose a release, navigate into that release's

src/ directory, download the compressed archives

of the source code, and unpack them all in a directory where you want

to build it.









9.2.2 Obtaining Source Code with CVS





If you are very brave and like to

live on the edge, you can update your source tree periodically

between point releases and help the Tomcat development team test out

new features that are in development. To do this you must use the

Concurrent Versions System (CVS); see the CVS Pocket

Reference
, by Gregor N. Purdy (O'Reilly)

for details.





If you want to use CVS, the Tomcat CVS modules are

jakarta-tomcat-4.0 (even for Tomcat 4.1!),

jakarta-tomcat-jasper, and

jakarta-tomcat-connectors.

















If you don't have CVS installed, get it from

http://www.cvshome.org/. Like

Tomcat, CVS is free software; anybody can use it without having to

pay a fee.







Starting in a clean directory or your normal source directory, log

into CVS as the anonymous user:





$ cvs -d :pserver:anoncvs@cvs.apache.org:/home/cvspublic login

Password: anoncvs




In order to pull a copy of the Tomcat 4 source code, you should

request a specific version by referring to its version tag in CVS. If

you pull the source without specifying a tag, what

you'll get is an untagged (and potentially untested)

copy of the source, and it may not build.















Always be sure to specify a version tag; this is one of the most

common causes for a broken build.







You can see a

list of tags by viewing the revision history of the

LICENSE file at http://cvs.apache.org/viewcvs/jakarta-tomcat-4.0/LICENSE.

For example, if you want to pull a copy of the Tomcat 4.1.24 source,

use these tags:





$ cvs -d :pserver:anoncvs@cvs.apache.org:/home/cvspublic checkout -r TOMCAT_4_1_24 \

jakarta-tomcat-4.0 jakarta-tomcat-jasper jakarta-tomcat-connectors




Pulling all of the source will probably take a little while, but when

CVS is done transferring, you'll have all three

source directories, straight out of the source code repository.





Once you have the code, the jakarta-tomcat-4.0,

jakarta-tomcat-jasper, and

jakarta-tomcat-connectors directories all reside

within the same base directory. You can place these directories in

other places, but if you do, you must edit the

jakarta-tomcat-4.0/build.properties file (if it

doesn't yet exist, copy

build.properties.sample to

build.properties) and change these lines:





# ----- Jakarta Tomcat Connectors source path -----

#jtc.home=../../jakarta-tomcat-connectors





# ----- Jakarta Tomcat Jasper source path -----

#jasper.home=../jakarta-tomcat-jasper/jasper2


All of these directories reside within the same base directory by

default, so you do not need to modify these

lines if this is your setup.


















     

     


    PHP




    I l@ve RuBoard










    PHP


    Let's move on to PHP, easily my favorite web development language. This section provides a brief overview of PHP's history, capabilities, and applications.


    PHP (the name actually is a recursive acronym for PHP: Hypertext Pre-Processor�you know how geeks are!) began life as a glint in the eye of Rasmus Lerdorf in late 1994. (For the full story, visit http://www.php.net/manual/phpfi2.php#history.) Rasmus needed a tool to log visitors to his personal web page; his solution, using a C wrapper and special tags embedded into the HTML code, became the first version of PHP.


    PHP hit the big time between 1997 and 2000 as more and more sites adopted it. The release of PHP 4.0 in late 2000 only served to widen its fan base. As a complete rewrite of the PHP engine, PHP 4.0 is faster, more scalable, and more full-featured than any of its predecessors. It is in use on more than six million web sites today, and that number is climbing rapidly.


    Still wondering what exactly PHP is? Well, to quote its authors, PHP is "...a serverside HTML-embedded scripting language...".[1] In English, this means that PHP code is typically embedded within HTML documents; this code�variables, functions, commands�is interpreted and executed by the server, with the resulting output returned to the browser. Special PHP tags are used to distinguish between PHP commands and regular HTML markup.


    [1] Stig Sæther Bakken, Egon Schmid, et al. PHP Manual. Available from Internet: http://www.php.net/manual/en


    That's not all, though�PHP also happens to be the most fun language I've had the opportunity to work with over the past few years.


    Unlike other scripting languages, which seem to delight in convoluted syntax and tortuous structures, PHP code is clean, easy to read and understand, and incredibly user-friendly. The language comes with great documentation, a friendly and knowledgeable user community, and a feature set that would turn most other web scripting languages green. And its development team (more than 300 people across the globe) is constantly innovating and adding support for new technologies, thereby ensuring that it's on the cutting edge of new technology. What's more, PHP's huge library of built-in functions ensures that even the most complex tasks can be accomplished in less time than you thought possible.


    All this, of course, would come to naught without the active support of realworld developers. Fortunately, PHP has that too. The latest Netcraft survey (http://www.netcraft.com/survey/) reveals that PHP usage is growing at the rate of more than 20 percent per month, with over 40 percent of the web's Apache servers running PHP. This widespread acceptance can only be music to the ears of PHP's many devotees, who have elevated PHP's developers to the status of gods and the language itself to the forefront of the popularity sweepstakes.



    Language Features


    PHP is a remarkably full-featured programming language, making it the ideal tool for developers looking to build complex, high-traffic web sites. Here's why:




    • Portability.
      PHP distributions are available for a wide variety of platforms, including Windows, Macintosh, OS/2, and most flavors of UNIX, including Linux. Because PHP code written on one platform usually works "as is" on any other supported platform, using PHP can significantly reduce development time in a multiplatform environment. (Some PHP functions are platform-specific.)




    • Performance.
      Independent evaluations have demonstrated that PHP is faster and more reliable that most other scripting languages. Both Fortune 500 companies and Mom-and-Pop businesses use it to run their web sites. And the completely reworked engine in PHP 4.0 raises the performance bar even further. Zend Technologies, Ltd. (http://zend.com/zend/aboutphp.php), which played a pivotal role in the development of PHP 4.0, claims a 50-fold performance increase over previous versions; the reality is a little less staggering, but still impressive. (For numbers and benchmarks, visit the research done at http://www.linuxplanet.com/linuxplanet/reviews/1891/2/.)




    • Ease of use.
      PHP is easy to learn�even a novice developer can pick up the basics in a few hours, and there are many online tutorials and books available to speed up the process. (I've even written a few myself. See the resources listed at http://www.xmlphp.com or http://www.newriders.com for more information.) PHP code is elegant and easy on the eyes, and the language comes with extensive documentation and usage examples. Because PHP is so easy to use, but packs so much power under its unassuming surface, it's become extremely popular as a tool for rapid application development, with more and more developers using it to construct high-traffic web sites and complex web-based applications.




    • Open source.
      PHP is a child of the open source community�its source code is freely available, and developers are encouraged to make their own contributions to it. This open source approach has been the single most important factor responsible for the widespread acceptance of PHP all over the world. By sharing the code with other developers, the PHP development team has been able to stay abreast of current technologies and incorporate them into the language faster than their more traditional counterparts. And this open source approach has also given rise to a network of skilled PHP developers, who throng mailing lists and chat rooms with questions, comments, and knowledgeable advice.




    • Modular extensions.
      Support for new technologies can easily be added to PHP through its modular extensions, which make it possible for developers to quickly incorporate new features and capabilities into their PHP build. Extensions available today allow developers to use PHP to perform FTP, IMAP, and POP3 operations; dynamically generate GIF, JPEG, and PNG images, Shockwave Flash files and Adobe PDF documents; validate credit card transactions; perform encryption of sensitive data; connect to Java; and process XML-encoded data.




    • Database support.
      With most of today's web pages built dynamically from a database, PHP, with its out-of-the-box support for a variety of different databases, comes as a breath of fresh air. PHP comes with built-in support for MySQL, the extremely popular open-source database system, and can easily be configured to support a variety of other databases, including IBM DB2, mSQL, Oracle, PostgreSQL, Sybase, dBase, and ODBC. And, to simplify things even further, PHP 4.0 includes a database abstraction layer (conceptually similar to Perl's DBI module) that makes it possible to easily migrate from one DBMS to another.




    • OOP support.
      Classes and objects have been available to PHP developers since version 3.0 of the languages; however, PHP's OO support has always been a little incomplete.Version 4.0 takes PHP closer to being a true object-oriented language. Among the new features, you'll find operator overloading, object nesting, and reference counting.




    • Built-in session management.
      Unlike many other languages, PHP comes with native session management support, making it possible to track individual client sessions on a web site and create web applications that respond to the needs of individual users. With personalization features now almost de facto on popular web sites, PHP's built-in session management can significantly reduce both the time spent on developing and testing such sites.




    Listing 1.3 demonstrates some of these features.



    Listing 1.3 A simple PHP script


    <?php
    //////////////////////////////////////////////////////////////
    //
    // this is a simple login script that accepts a username
    // and password and validates them against a database
    //
    // if the validation is successful, a new session is
    // created and a customized template generated
    //
    // if the validation fails, the user is redirected
    // to an error page
    //
    //////////////////////////////////////////////////////////////

    // includes
    // DB variables are sourced from db_config.php
    include("db_config.php");
    include("TemplateClass.php");

    // check login and password
    // connect and execute query
    $connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
    $query = "SELECT id, username, nickname FROM user WHERE username = '$frmuser' AND
    password = PASSWORD('$frmpass')";
    mysql_select_db($database) or die ("Unable to select database!");
    $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());

    // if row exists - login/pass is correct
    if (mysql_num_rows($result) == 1)
    {

    // initiate a session
    session_start();

    // register the user's ID as a session variable
    session_register("SESSION_UID");
    list($id, $username, $nickname) = mysql_fetch_row($result);
    $SESSION_UID = $id;
    $welcome_msg = "Welcome back, " . $nickname;

    // close connection
    mysql_close($connection);

    // create an instance of the Template object
    $obj = new Template("welcome.tmpl", "#000000", "#FFFF00");

    // and execute some class methods
    $obj->set_welcome_msg($welcome_msg);
    $obj->print_template();
    }
    else
    // login/pass check failed
    {
    mysql_close($connection);
    // redirect to error page
    header("Location: error.php?ec=0");
    exit;
    }
    ?>

    Listing 1.3 demonstrates many of the most common PHP features. PHP's native MySQL support simplifies the task of connecting to a database to validate the user's account, although the built-in session functions make it easy to retain important user information as the user browses from page to page within the site. Object support is demonstrated by the use of a custom Template object, which creates the final web page seen by the user and provides developers with a robust and portable mechanism for page generation throughout the site.



    Applications


    In the old days, web sites consisted of static HTML pages with a few images thrown in for variety. That is no longer the case: today's web sites are complex and demanding, with movie-quality animation, high-res audio and video, and web pages built on-the-fly from immense databases churning away in the background. And, as you might imagine, PHP's ease of use, performance, and proven track record ensure that the language's primary application lies in the field of these dynamic, high-traffic web sites and applications.


    PHP is well-suited to such complex web applications for a number of reasons. The language's built-in database capabilities ensure that it can connect easily to a variety of different databases for dynamic page generation; its payment processing and validation capabilities make it a good choice for online commerce; and its portability across platforms and support for important web technologies like Java and Flash make it suitable for a diverse range of other applications.


    Today, PHP is used by businesses (such as Mitsubishi and Ericsson), government organizations (such as the United States Naval Research Laboratory), and popular open-source portals (for example, freshmeat.net and phpbuilder.com) for applications ranging from content management to wireless data transfer. This fact again demonstrates the versatility of the language.


    If you're interested in PHP's numerous applications for business, you'll find some very interesting case studies at http://www.zend.com/zend/cs/.


    I'm not going to get into the details of PHP's syntax and structure here, but will assume you know the basics. If you don't, you should take a look at PHP Functions Essential Reference by Zak Greant, Greame Merral, Torben Wilson, and Brett Michlitsch (New Riders Publishing, 2001) ISBN: 073570970X.







      I l@ve RuBoard



      Chapter 15

      Team-Fly
       

       

      TCP/IP Illustrated, Volume 2: The Implementation
      By
      Gary R. Wright, W. Richard Stevens
      Table of Contents

      Appendix A. 
      Solutions to Selected Exercises




      Chapter 15


      15.1


      The socket could be shared across a fork or passed to a process through a Unix domain socket ([Stevens 1990]).

      15.2


      The sa_len member of the structure is larger than the size of the buffer after accept returns. This is usually not a problem with the fixed-length Internet address, but it can be when using variable-length addresses supported by the OSI protocols, for example.

      15.4


      The call to soqremque is only made when so_qlen is not equal to 0. If soqremque returns a null pointer there must be an error in the socket queueing code so the kernel panics.

      15.5


      The copy is made so that bzero can clear the structure while it is locked and so that dom_dispose and sbrelease can be called after splx. This minimizes the amount of time the CPU is kept at splimp and therefore the amount of time that network interrupts are blocked.

      15.6


      The sbspace macro will return 0. As a result, the sbappendaddr and sbappendcontrol functions (used by UDP) will refuse to queue additional packets. TCP uses sbappend, which assumes that the caller has checked for space first. TCP calls sbappend even when sbspace returns 0. The data placed in the receive queue is not available to a process because the SS_CANTRCVMORE flag prevents the read system calls from returning any data.




        Team-Fly
         

         
        Top
         


        Recipe 15.22. Unit Testing Your Web Site










        Recipe 15.22. Unit Testing Your Web Site







        Problem


        You want to create a suite of automated tests that test the functionality of your Rails application.




        Solution


        Rails can't write your test code any more than it can write your views and controllers for you, but it does make it easy to organize and run your automated tests.


        When you use the ./script/generate command to create controllers and models, not only do you save time, but you also get a generated framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write.


        So far, all the examples in this chapter have run against a Rails application's development database, so you only needed to make sure that the development section of your config/database.yml file was set up correctly. Unit test code runs on your application's test database, so now you need to set up your test section as well. Your
        mywebapp_test
        database doesn't have to have any tables in it, but it must exist and be accessible to Rails.


        When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the mywebapp_test database. This is the data against which your unit tests will run:



        ./script/generate model User
        exists app/models/
        exists test/unit/
        exists test/fixtures/
        create app/models/user.rb
        create test/unit/user_test.rb
        create test/fixtures/users.yml
        create db/migrate
        create db/migrate/001_create_users.rb



        When you generate a controller with generate, Rails creates a functional test script for the controller:



        ./script/generate users list
        exists app/controllers/
        exists app/helpers/
        create app/views/users
        exists test/functional/
        create app/controllers/users_controller.rb
        create test/functional/users_controller_test.rb
        create app/helpers/users_helper.rb
        create app/views/users/list.rhtml



        As you write code in the model and controller classes, you'll write corresponding tests in these files.


        To run the unit and functional tests, invoke the rake command in your home directory. The default Rake task runs all of your tests. If you run it immediately after generating your test files, it'll look something like this:



        $ rake
        (in /home/lucas/mywebapp)
        /usr/bin/ruby1.8 "test/unit/user_test.rb"
        Started
        .
        Finished in 0.048702 seconds.
        1 tests, 1 assertions, 0 failures, 0 errors
        /usr/bin/ruby1.8 "test/functional/users_controller_test.rb"
        Started
        .
        Finished in 0.024615 seconds.

        1 tests, 1 assertions, 0 failures, 0 errors





        Discussion


        All the lessons for writing unit tests in other languages and in other Ruby programs (see Recipe 17.7) apply to Rails. Rails does some accounting for you, and it defines some useful new assertions (see below), but you still have to do the work. The rewards are the same, too: you can modify and refactor your code with confidence, knowing that if something breaks, your tests will break. You'll hear about the problem immediately and you'll be able to fix it more quickly.


        Let's see what Rails has generated for us. Here's a generated test/unit/user_test.rb:



        require File.dirname(__FILE__) + '/../test_helper'

        class UserTest < Test::Unit::TestCase
        fixtures :users

        # Replace this with your real tests.
        def test_truth
        assert true
        end
        end



        A good start, but test_truth is kind of tautological. Here's a slightly more realistic test:



        class UserTest
        def test_first
        assert_kind_of User, users(:first)
        end
        end



        This code fetches the first element from the users table, and asserts that ActiveRecord turns it into a User object. This isn't testing our User code (we haven't written any) so much as it's testing Rails and ActiveRecord, but it shows you the kind of assertion that makes for good unit tests.


        But how does users(:first) return anything? The test suite runs against the
        mywebapp_test
        database, and we didn't even put any tables in it, much less sample data.


        We didn't, but Rails did. When you run the test suite, Rails copies the schema of the development database to the test database. Instead of running every test against whatever data happens to exist in the development database, Rails loads special test data from YAML files called fixtures. The fixture files contain whatever database data you need to test: objects that only exist to be deleted by a test, strange relationships between rows in different tables, or anything else you need.


        In the example above, the fixture for the users table was loaded by the line fixtures :users. Here's the generated fixture for the User model, in test/fixtures/users.yml:



        first:
        id: 1
        another:
        id: 2



        Before running the
        unit tests, Rails reads this file, creates two rows in the users table, and defines aliases for them (:first and :another) so you can refer to them in your unit tests. It then defines the users method (like so much else, this method name is based on the name of the model). In test_first, the call to users(:first) retrieves the User object corresponding to :first in the fixture: the object with ID 1.


        Here's another unit test:



        class UserTest
        def test_another
        assert_kind_of User, users(:another)
        assert_equal 2, users(:another).id
        assert_not_equal users(:first), users(:another)
        end
        end



        Rails adds the following Rails-specific assertions to Ruby's Test::Unit:


        • assert_dom_equal

        • assert_dom_not_equal

        • assert_generates

        • assert_no_tag

        • assert_recognizes

        • assert_redirected_to

        • assert_response

        • assert_routing

        • assert_tag

        • assert_template

        • assert_valid




        See Also


        • "Testing the Rails" is a guide to unit and functional testing in Rails (http://manuals.rubyonrails.com/read/book/5)

        • Rails 1.1 supports integration testing as well, for testing the interactions between controllers and actions; see http://rubyonrails.com/rails/classes/ActionController/IntegrationTest.html and http://jamis.jamisbuck.org/articles/2006/03/09/integration-testing-in-rails-1-1

        • The ZenTest library inclues Test::Rails, which lets you write separate tests for your views and controllers (http://rubyforge.org/projects/zentest/)

        • Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html

        • Read about the assertions that Rails adds to Test::Unit at http://rails.rubyonrails.com/classes/Test/Unit/Assertions.html

        • Recipe 15.6, "Integrating a Database with Your Rails Application"

        • Recipe 17.7, "Writing Unit Tests"

        • Chapter 19













        Chapter 14. Firing up Firefox









        Chapter 14. Firing up Firefox







        In This Chapter

        • Introducing Mozilla Firefox

        • Discovering what you can do with Firefox

        • Setting some preferences and installing plug-ins



        Mozilla Firefox is the most advanced and powerful Web browser on the market today. Firefox has pioneered many technologies that other browsers are still trying to catch up with.


        This chapter describes many, but not all, of Firefox's basic and advanced capabilities. It also explores how to use and configure Firefox.


        If you'd like even more information on using Firefox, check out Firefox For Dummies, by Blake Ross (Wiley Publishing).




        Introducing the Firefox Browser


        The Internet was a sleepy, quite place back in the early 1990s. Nothing much was going on in that placid place. Nerds and engineers used it to communicate using a fairly novel system called electronic mail, and some file sharing took place. You could also communicate with like-minded individuals using things called bulletin boards and news.


        Then something earth-shattering took place. Tim Berners-Lee took a concept he originated back in the 1980s and designed a thing called HyperText Markup Language (HTML). A client and server system was devised to use the protocol, and soon it was possible to view text and, most importantly, graphics from any computer that wanted to provide such a service. The World Wide Web (WWW) was born.


        One of the first browsers to find commercial success was the Netscape Navigator browser. Netscape provided its browser free of charge but soon spun off an open source version called Mozilla. Mozilla grew and grew like a monster and became the monster we know as Mozilla Firefox. Firefox is the Linux browser of choice and is distributed with Ubuntu.


        Mosaic was one of the original Web browsers. Netscape's internal name for its Navigator browser was Mozilla. The name Mozilla was — in typical technogeekology — a contraction of Mosaic Killer. Killer became killa, and you could make the two into Mos-illa or Mozilla; it didn't hurt that Mozilla sounded like Godzilla. You gotta love technology!









        TOC

           
          
        • Table of Contents
        Oracle® PL/SQL® Interactive Workbook, Second Edition
        By
        Benjamin Rosenzweig, Elena Silvestrova
         
        Publisher: Prentice Hall PTR
        Pub Date: October 29, 2002
        ISBN: 0-13-047320-0
        Pages: 688


           Copyright
           THE PRENTICE HALL PTR ORACLE SERIES
           Acknowledgments
           
         
        Acknowledgments from Ben Rosenzweig
           
         
        Acknowledgments from Elena Silvestrova
           About the Authors
           Introduction
           
         
        Who This Book Is For
           
         
        How This Book Is Organized
           
         
        About The Companion Web Site
           
         
        What You Will Need
           
         
        Using SQL*Plus
           
         
        Conventions Used In This Book
           About Prentice Hall Professional Technical Reference
           
        Chapter 1. 
        Programming Concepts
           
         
        Lab 1.1 The Nature of a Computer Program and Programming Languages
           
         
        Lab 2.1 Good Programming Practices
           
         
        Chapter 1 Test Your Thinking
           
        Chapter 2. 
        PL/SQL Concepts
           
         
        Lab 2.1 PL/SQL In Client-Server Architecture
           
         
        Lab 2.2 PL/SQL in SQL*Plus
           
         
        Chapter 2 Test Your Thinking
           
        Chapter 3. 
        General Programming Language Fundamentals
           
         
        Lab 3.1 PL/SQL Programming Fundamentals
           
         
        Chapter 3 Test Your Thinking
           
        Chapter 4. 
        SQL in PL/SQL
           
         
        Lab 4.1 Making Use of DML in PL/SQL
           
         
        Lab 4.2 Making Use of SAVEPOINT
           
         
        Chapter 4 Test Your Thinking
           
        Chapter 5. 
        Conditional Control: IF Statements
           
         
        Lab 5.1 IF Statements
           
         
        Lab 5.2 ELSIF Statements
           
         
        Lab 5.3 Nested IF Statements
           
         
        Chapter 5 Test Your Thinking
           
        Chapter 6. 
        Conditional Control: Case Statements
           
         
        Lab 6.1 CASE Statements
           
         
        Lab 6.2 CASE Expressions
           
         
        Lab 6.3 NULLIF and COALESCE Functions
           
         
        Chapter 6 Test Your Thinking
           
        Chapter 7. 
        Error Handling and Built-In Exceptions
           
         
        Lab 7.1 Handling Errors
           
         
        Lab 7.2 Built-In Exceptions
           
         
        Chapter 7 Test Your Thinking
           
        Chapter 8. 
        Iterative Control
           
         
        Lab 8.1 Simple Loops
           
         
        LAB 8.2 WHILE Loops
           
         
        Lab 8.3 Numeric for Loops
           
         
        Lab 8.4 Nested Loops
           
         
        Chapter 8 Test Your Thinking
           
        Chapter 9. 
        Introduction to Cursors
           
         
        Lab 9.1 Cursor Manipulation
           
         
        Lab 9.2 Using Cursor for Loops and Nesting Cursors
           
         
        Chapter 9 Test Your Thinking
           
        Chapter 10. 
        Exceptions
           
         
        Lab 10.1 Exception Scope
           
         
        Lab 10.2 User-Defined Exceptions
           
         
        Lab 10.3 Exception Propagation
           
         
        Chapter 10 Test Your Thinking
           
        Chapter 11. 
        Exceptions: Advanced Concepts
           
         
        Lab 11.1 RAISE_APPLICATION_ERROR
           
         
        Lab 11.2 EXCEPTION_INIT Pragma
           
         
        Lab 11.3 SQLCODE and SQLERRM
           
         
        Chapter 11 Test Your Thinking
           
        Chapter 12. 
        Procedures
           
         
        PL/SQL Stored Code
           
         
        Lab 12.1 Creating Procedures
           
         
        Lab 12.2 Passing Parameters In and Out of Procedures
           
         
        Chapter 12 Test Your Thinking
           
        Chapter 13. 
        Functions
           
         
        Lab 13.1 Creating and Using Functions
           
         
        Chapter 13 Test Your Thinking
           
        Chapter 14. 
        Packages
           
         
        Lab 14.1 The Benefits of Utilizing Packages
           
         
        Chapter 14 Test Your Thinking
           
        Chapter 15. 
        Advanced Cursors
           
         
        Lab 15.1 Using Parameters with Cursors and for Update Cursors
           
         
        Lab 15.2 Cursor Variables
           
        Chapter 16. 
        Stored Code
           
         
        Lab 16.1 Gathering Stored Code Information
           
         
        Chapter 16 Test Your Thinking
           
        Chapter 17. 
        Triggers
           
         
        Lab 17.1 What Triggers Are
           
         
        Lab 17.2 Types of Triggers
           
         
        Lab 17.3 Mutating Table Issues
           
         
        Chapter 17 Test Your Thinking
           
        Chapter 18. 
        Collections
           
         
        Lab 18.1 PL/SQL Tables
           
         
        Lab 18.2 Varrays
           
         
        Lab 18.3 Multilevel Collections
           
         
        Chapter 18 Test Your Thinking
           
        Chapter 19. 
        Records
           
         
        Lab 19.1 Records
           
         
        Lab 19.2 Nested Records
           
         
        Lab 19.3 Collections of Records
           
         
        Chapter 19 Test Your Thinking
           
        Appendix A. 
        Answers to Self-Review Questions
           
         
        Chapter 1 Programming Concepts
           
         
        Chapter 2 PL/SQL Concepts
           
         
        Chapter 3 General Programming Language Fundamentals
           
         
        Chapter 4 SQL in PL/SQL
           
         
        Chapter 5 Conditional Control: IF Statements
           
         
        Chapter 6 Conditional Control: CASE Statements
           
         
        Chapter 7 Error Handling and Built-In Exceptions
           
         
        Chapter 8 Iterative Control
           
         
        Chapter 9 Introduction to Cursors
           
         
        Chapter 10 Exceptions
           
         
        Chapter 11 Exceptions: Advanced Concepts
           
         
        Chapter 12 Procedures
           
         
        Chapter 13 Functions
           
         
        Chapter 14 Packages
           
         
        Chapter 15 Advanced Cursors
           
         
        Chapter 16 Stored Code
           
         
        Chapter 17 Triggers
           
         
        Chapter 18 Collections
           
         
        Chapter 19 Records
           
        Appendix B. 
        PL/SQL Formatting Guide
           
         
        PL/SQL Code Naming Conventions and Formatting Guidelines
           
         
        Other Suggestions
           
        Appendix C. 
        Student Database Schema
           
         
        Table and Column Descriptions
           
        Appendix D. 
        Answers to Test Your Thinking Sections
           
         
        Chapter 1 Programming Concepts
           
         
        Chapter 2 PL/SQL Concepts
           
         
        Chapter 3 General Programming Language Fundamentals
           
         
        Chapter 4 SQL in PLSQL
           
         
        Chapter 5 Conditional Control: IF Statements
           
         
        Chapter 6 Conditional Control: CASE Statements
           
         
        Chapter 7 Error Handling and Built-In Exceptions
           
         
        Chapter 8 Iterative Control
           
         
        Chapter 9 Introduction to Cursors
           
         
        Chapter 10 Exceptions
           
         
        Chapter 11 Exceptions: Advanced Concepts
           
         
        Chapter 12 Procedures
           
         
        Chapter 13 Functions
           
         
        Chapter 14 Packages
           
         
        Chapter 15 Stored Code
           
         
        Chapter 17 Triggers
           
         
        Chapter 18 Collections
           
         
        Chapter 19 Records
           
        Appendix E. 
        Oracle 9i SQL New Features
           
         
        SQL Standards
           
         
        JOINs
           
         
        Scalar Subquery

        Top

         


        Capture Functions












        Capture Functions

        The majority of libpcap's code revolves around reading packets from the network. The following first three functions accomplish the actual packet capturing, and they all call the same underlying internal libpcap function, pcap_read(). Each offer different functionality, however.





        int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback,
        u_char *user);




        pcap_dispatch() is the main function used to gather and process packets. The first argument, p, specifies the libpcap descriptor from which to read packets. The second argument, cnt, specifies the maximum number of packets that pcap_dispatch() should process before returning. A cnt of -1 processes all packets received in one buffer when reading from a live capture (pcap_open_live()) or all of the packets in the savefile from a dead capture (pcap_open_dead()). The callback argument specifies a function to call in order to process each packet with three arguments, two of which pcap automatically generates:




        1. A u_char pointer to user data. This data is arbitrary, specified by the application programmer, and passed into the callback function. The constituency of the callback function dictates its use (if at all).




        2. A pointer to the pcap_pkthdr structure. This structure contains useful statistical information about the captured packet, including a microsecond granularity timestamp and packet capture length.




        3. A u_char pointer to the start of the actual packet. This pointer refers to the actual packet.




        The final argument to pcap_dispatch(), user, is the aforementioned user data. Upon success, the function returns the number of packets read; upon failure, the function returns -1 and you can use one of the pcap_*err() functions to find the reason. The function may return 0 if no packets were read for one of the following reasons:




        • No packets were read because they were all discarded because they did not pass the packet filter rules.




        • No packets were read because the read timeout expired before any packets arrived on the interface.




        • No packets were read because the file descriptor for the capture device was in non-blocking mode, and no packets were available to be read at that time.




        • No packets were read because the savefile is out of packets.







        int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user);




        pcap_loop() has the same functionality as pcap_dispatch() except that it keeps reading packets from p until callback receives and processes cnt packets or until an error occurs. A cnt of -1 causes the function to loop indefinitely or until an error occurs. The function will not return if the timer expires and read times out.




        u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h);



        pcap_next() returns the next packet available. It is actually a wrapper to pcap_dispatch() with a cnt of 1 and a callback function that extracts the pcap packet header structure and separates the actual packet. h is a pointer to the pcap_pkthdr structure, which fills in with the relevant statistics. Upon success, the function returns a u_char pointer to the captured packet. Upon failure, it returns 0, and you can use one of the pcap_*err() functions to find out the reason. Like pcap_dispatch(), this function returns NULL if the pcap timer expires and there is no data in the read buffer, so it is important to check for this scenario.





        int pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf);




        pcap_setnonblock() sets or removes non-blocking mode on the underlying descriptor referenced by p. If nonblock is 0, the function attempts to set the descriptor to be non-blocking; if nonblock is 1, the function attempts to remove it from being non-blocking. This function only works with pcap descriptors opened with pcap_open_live() and with the pcap_dispatch() capturing functionality. In non-blocking mode, an attempt to read from p returns immediately to the caller if no packets are available, rather than blocking until network traffic arrives. Upon success, the function returns 0; upon failure, the function returns -1 and errbuf contains the reason.




        int pcap_getnonblock(pcap_t *p, char *errbuf);



        pcap_getnonblock() returns the current blocking status of the descriptor that p references. If the descriptor is in blocking mode, the function returns 0, and if the function is in non-blocking mode, the function returns 1. Upon failure, the function returns -1 and errbuf contains the reason.















        Speed, Velocity, and Acceleration

        Speed, Velocity, and Acceleration


        You may not know the difference between speed and velocity, but you probably have at least some idea of what speed, velocity, and acceleration are. In this section I'll introduce you to these concepts and point out the differences between them.


        Speed and Velocity


        Velocity is a vector; speed is the magnitude of that vector. In Chapter 3, "Trigonometry 101," we introduced vectors. If you're a linear reader, this concept may be fresh in your mind. But to review, vectors are mathematical objects that contain two pieces of information: a magnitude (also called a scalar value) and a direction. For instance, the velocity 30 kilometers per hour (kph) southeast is a vector. Its magnitude (the speed) is 30, and its direction is southeast.


        Let's dig a little deeper into the definitions of these important concepts.


        Speed:
        The ratio of distance covered and the time taken to cover this distance. Mathematically, this is written as the equation speed = distance/time. For example, if a car travels 30 kilometers in 2 hours, then its speed is 30 kilometers/2 hours = 15 kilometers/hour.


        TIP
        As defined above, speed is distance divided by time. When you read "15 kilometers/hour," you say "15 kilometers per hour."


        Velocity:
        A vector formed by combining speed with a direction.


        Now let's see how to use this concept of speed and velocity to find the distance traveled in a certain amount of time. If we know the speed at which a car is traveling, how do we know how far it has traveled in, say, 3 hours? Above we said:



        speed = distance/time

        By doing simple algebra (multiplying both sides by time), we arrive at this equation:



        distance = speed*time

        With this equation we can find how far a car (or any object) traveled if we know its speed and the amount of time it moved. In the same way, if we know how far the car traveled and the speed of the car, then we can calculate the travel time using the final permutation of this equation:



        time = distance/speed

        Applying Speed with ActionScript


        So now you understand what speed and velocity are. And you understand how if you know any two of the following variables�speed, distance, or time�you can find the remaining value. In many games you are going to need to program movie clips (such as a ball, a car, or a rocket ship) to move. So how do you apply speed to a movie clip? You are about to find out.


        We have been talking and thinking about speed as being measured in units of distance/time (distance divided by time). But Flash is not a time-based environment�it is a frame-based environment. To Flash users, one frame can be assumed to be one unit of time. So (as you'll see on your screen if all goes well), it is OK for us to replace every occurrence of a time variable in equations with a variable for frames. For instance, if distance = speed*time, then the new form is distance = speed*frames. (In other words, speed is no longer 10 miles/hour, it's 10 units/frame.) In Flash we are going to change the definition of speed by replacing time with frames. So let's look at our definition of speed again, this time with our new twist:


        Speed:
        The ratio of distance covered and the frames taken to cover this distance. Mathematically, this is written as the equation speed = distance/frames. For example, if a movie clip travels 30 units in two frames, then its speed is 30 units/2 frames = 15 units/frame.


        As seen in the new definition above, the unit of distance measurement is not meters but simply units, or pixels. (I prefer to use the word unit, because if the Flash movie is scaled to a larger or smaller size, then unit is the only word that still applies.) At a scaled size, the pixel dimensions do not change, but the unit dimensions do.



        ON THE CD
        To see a simple application of speed, open up car1.fla in the Chapter04 directory on the CD-ROM. Notice that the frame rate has been set to 24 frames per second (fps) to ensure smooth playback. On the stage you'll see one movie clip with an instance name of Car. There are a few lines of ActionScript on frame 1 of the Actions layer. They read as follows:


        1 xmov = 3;
        2 _root.onEnterFrame = function () {
        3 car._x += xmov;
        4 }

        TIP
        Throughout the rest of the book, you'll see that I call all x direction speeds xmov and all y direction speeds ymov, or some variation of these basic names (such as tempxmov or xmov1).

        Line 1 sets a variable for the speed called xmov with a value of 3. Line 2 sets up an onEnterFrame clip event. All of the actions listed within an onEnterFrame event are called one time in every frame. Line 3 is where we apply the speed to the object. It takes the current position of the car�car._x�and adds the value of the speed to it. Remember that the speed is units per frame. So a speed of 3 means that we will move the car along the x-axis three units in every frame.



        When you generate a SWF file to test this movie, you will see the car move relatively smoothly. Actually, the car is being redrawn in a new position 24 times per second. In that way, it's a lot like one of those flip books you might have had when you were a kid, with static images giving the illusion of movement. The frame rate is the vehicle (no pun intended) through which we trick the human eye into seeing what appears to be a continuously moving car, although the movement is actually happening in discrete chunks.



        ON THE CD
        Now, what if you want to make this car move in two directions at once? To see how you'd add a second dimension, y speed, open car2.fla. This FLA file has the same setup as the previous example. The only difference you'll find is in the ActionScript used. Open the Actions panel to view the ActionScript on frame 1.


        1 xmov = 3;
        2 ymov = 2;
        3 _root.onEnterFrame = function () {
        4 car._x += xmov;
        5 car._y += ymov;
        6 }

        This differs from the ActionScript in the previous example by two lines of code. Line 2 defines a variable to represent the speed in the y direction, and line 5 controls the placement of the car by adding the value of ymov to the car's y position. This is done 24 times a second, so the result is what looks like a moving car.



        You may have already picked up on a visual problem in this case, though. The car is moving diagonally, but it's facing horizontally. To see how to get the car to face the correct direction, open car3.fla. You will notice that, once more, there are two new lines of code just before the onEnterFrame event. They are:



        1 angle = Math.atan2(ymov, xmov)*180/Math.PI;
        2 car._rotation = angle;

        In short, line 1 calculates the angle that the car should be rotated, and line 2 rotates the car. Summoning up what we discussed in the last chapter (remember trigonometry?), we know that we can use two sides of a right triangle to find the angle made by the trajectory of the car with the x-axis. The key is to think about the horizontal and vertical sides of the triangle as the ones made by xmov and ymov, respectively.


        Before rotation, the car forms an angle of 0° with the x-axis. Here we are figuring out how much the car needs to be rotated in order to point in the direction in which it is moving. Knowing the x side length (the x speed) and the y side length (the y speed), we can find the angle using the inverse tangent Math.atan2(). This returns an angle in radians�the angle we'll use to rotate the movie clip. To do this, we must use the _rotation property. Simple enough�but just to keep things interesting, the _rotation property only accepts angles in degrees! That's what's going on in line 1; we're converting the angle into degrees by multiplying by the conversion factor 180/Math.PI.


        ON THE CD
        For a slightly more advanced practical example, see shooter.fla in the Chapter04 directory on the CD.



        Acceleration


        Put quite simply, acceleration occurs whenever the velocity changes. Remember that velocity contains a speed and a direction. So if the speed or the direction of something changes, then it has accelerated.


        Acceleration, like velocity, is a vector. It has a magnitude and a direction. More specifically, it's a vector with a magnitude that is the ratio of the difference in velocity and the difference in time over which this difference occurred, and the direction in which the acceleration occurred. (If this sounds like three items instead of two, read it again with careful obedience to the commas.)



        Acceleration = (velocity2 - velocity1)/(time2 - time1)

        where velocity2 is the velocity at time2, and velocity1 is the velocity at time1. The units of acceleration are measured as distance/time2.



        If you know the acceleration of an object and its current velocity, then you can find or project the velocity of that object at any time in the future. Here is the equation to do this:



        velocity_future = velocity_now + acceleration*time

        The quantity time in the equation above is how far into the future you are looking. Remember that both velocity and acceleration are vectors. In Flash, we have to resolve vectors into their x and y components before we can use them. After we find the xspeed, yspeed, xacceleration, and yacceleration (using the techniques used in Chapter 3 and reintroduced earlier in this section), then we can write the following equations:



        xspeed_future = xspeed_now + xacceleration*time

        and



        yspeed_future=yspeed_now + yacceleration*time

        If you know the current position and velocity of an object, then you can find its position at any time in the future. You can find the future position by using the following equations:



        xposition_future = xposition_now + xspeed_now*time
        + 1/2*(xacceleration)*time2

        and



        yposition_future = yposition_now + yspeed_now*time
        + 1/2*(yacceleration)*time2

        Applying Acceleration with ActionScript


        The equations you've just been looking at may seem messy, but their application in Flash is quite easy. Remember that we can replace time with frames in all of our equations. We will always be calculating new values for just one frame later. This is good news for us, because it means we can replace the time with 1 everywhere. Using that trick, we can rewrite the four x- and y-component equations shown in the previous section.


        For future speed:



        xspeed_future = xspeed_now + xacceleration

        and



        yspeed_future = yspeed_now + yacceleration

        For future position:



        xposition_future = xposition_now + xspeed_now
        + 1/2*(xacceleration)

        and



        yposition_future = yposition_now + yspeed_now
        + 1/2*(yacceleration)

        As you probably know, you cannot add two quantities that have different units. For instance, 10 meters plus 12 ounces makes … no sense. In the above equations, we appear to be adding quantities that have different units (with apologies to any physicists, mathematicians, and engineers out there). What happened is that we dropped the frame variable from the equations. We're getting away with this because we assumed the value of the frame variable is always going to be 1 (see the previous paragraph), and since multiplying anything by 1 gives a result of the original value (3*1 = 3), then we just left out that factor. So if you were concerned about the units, you can now rest assured that things are consistent.


        After all this theoretical discussion of acceleration, now it's time to apply it within the context of your games. To use acceleration in programming, here is what you should do.








        1. Create a variable to contain the acceleration. For instance, accel = 2.
        2. Create initial velocity variables for the x and y directions. For instance:



          xmov = 0;
          ymov = 0;

        3. When acceleration should be applied (such as when a certain key is being pressed), modify the speed. For instance:



          xmov += accel;
          ymov += accel;

        4. For every frame, set the new position of the object.



          car._x += xmov;
          car._y += ymov;


        ON THE CD
        Open up car4.fla from the Chapter04 directory on the CD. This is the next evolutionary step in the chain of car examples given earlier in this chapter. Here, the car starts with a slow initial speed and accelerates when the up arrow key is pressed. (As you might expect, when the down arrow key is pressed, the car decelerates.) Here is the ActionScript that accomplishes this.


        1 xmov = 1;
        2 ymov = 1;
        3 accel = 2;
        4 angle = Math.atan2(ymov, xmov)*180/Math.PI;
        5 car._rotation = angle;
        6 _root.onEnterFrame =function () {
        7 if(Key.isDown(Key.UP)) {
        8 xmov += accel;
        9 ymov += accel;
        10 } else if (Key.isDown(Key.DOWN)) {
        11 xmov -= accel;
        12 ymov -= accel;
        13 }
        14 car._x += xmov;
        15 car._y += ymov;
        16 }

        Line 3 initializes the acceleration variable. Other than that, the only differences between this example and car3.fla are in lines 7�13. That's where the ActionScript dictates that if the up arrow key is pressed, then the xmov and ymov variables are increased by the value of the accel variable. If the down arrow key is pressed, then the xmov and ymov variables are decreased by the value of the accel variable.