Ajax-Based Web Application

Published on July 2016 | Categories: Documents | Downloads: 40 | Comments: 0 | Views: 286
of 4
Download PDF   Embed   Report

Comments

Content

Race Condition in Ajax-based Web Application
Kai Qian Internal Report July, 2008 School of Computing and Software Engineering Southern Polytechnic State University Marietta, Georgia, USA

Abstract— The automicity is an important issue in asynchronous based data communication. In the modern web application today, asynchronous introduces hazardous effect causing unexpected results. This paper discusses the race condition occurred between the user request and server response due to the asynchronous nature of the web application using Ajax. A race condition occurs when multiple threads in a process try to modify the critical section data at the same time. The data will depend on which thread arrived last. Concurrent requests will be running asynchronously and it is impossible to predict which will return first. The locking mechanism is not a very effective way but may avoid race condition. Our future project develop a more effective way to detect the race conditions while parsing.
Index Terms— Ajax, Race condition, concurrency, Dynamic Web application, Lock.

With AJAX you can retrieve data from the server without refreshing the page and rebuilding it again. And that data is updated on the Document Object Model (DOM) page and manipulated by JavaScript programs. New DOM objects are updated when its page is updated, new JavaScript objects are created based on those data, and new events are attached to all this objects. Once you close a page a lot of work is done behind the scene to clear unreferenced objects. One of the main problems we discuss here is about the race condition. This brings a major problem as it is unnoticed and the latency occurs between user request and server response and needs to be considered carefully during Ajax development. There is no proper handling of the XMLHttpRequest object and the user might experience unexpected results due to many delays in the interface of the web application
2. ASYNCHRONOUS WEB APPLICATION FRAMEWORK:

1.

INTRODUCTION

Ajax may have been initially defined as Asynchronous JavaScript and XML[9] for a set of modern web application development technologies, previously known as Dynamic HTML (DHTML) and remote scripting, to provide a more interactive and effective web-based user interface. However this technique might be used to transport data in plain text, XML, or JavaScript Object Notation (JSON) formats. The problem is not AJAX in itself as a programming paradigm but in what it can do for the application.

An Ajax-based server request is made with an object of XMLHttpRequest type. It then validates and sends the request to the server. The difference from the traditional web page is that in Ajax the HTTP page can asynchronously make calls to the server from which it was loaded and fetched that may be formatted as xml documents, HTML content, plain text or as JSON. In the web application there has always been a client side processing and a server side processing. On the client side which is the browser, JavaScript manipulates the currently loaded page. Fig.1 shows the concept of Ajax.

Client
Browser UI
Time

XMLHttpRequest

Server
Service Provide r

Ajax Engine
Response

Multiple Events &Updates

Figure 1. Asynchronous Web application

On the server side, the sever side scripting like PHP, JSP, ASP are used. Traditionally, the only way for the server to send back a response was to serve up a new web page .Whenever the web browser needed something

from the server, a request is sent to the server and a corresponding response had to sent back to the client. Now, due to the Ajax technology the content is loaded without refreshing the page. Using JavaScript, a request is sent from the client to this Ajax engine, instead of going all the way back to the server. The request is then passed along to the server. The server sends a response back to the Ajax engine. This response is then passed on to the client where multiple pages can be processed using JavaScript. In the Ajax application, the architecture of the web application introduces an intermediary part called the Ajax engine between the user and the server. It is a separate layer to the application between the browser and the server which is part of the client. In the dynamic web application, instead of loading the webpage, at the start of the session, the browser loads an Ajax engine. This engine is responsible for the interaction between the user and the server by rendering communication instead of browser. The Ajax engine allows multiple pages at a time which builds up user’s interaction with the application to happen asynchronously, so the user never start with the blank browser window. Every user action would generate an HTTP request for the client takes from the JavaScript call to Ajax engines and the response is sent back to the user. Ajax Engine handles everything like if it’s sending events from the client for data processing or retrieving new data from the server, the engine makes those requests asynchronously, usually using xmlhttprequests, without stalling a user’s interaction with the application.
3.
RACE CONDITION IN DYNAMIC WEB APPLICATION:

to read the same value in the file. When two threads fight for the CPU time periodically interrupt each other thus the outcome shows an unpredictable result.

Browser sends two Asynchronous requests simultaneously to the server Value=0 R1 reads the value: 0
Request 1 tries to increment the value in the file

R2 reads the value: 0
Request 2 tries to increment the value in the file

Results in Race condition and the Value is stored as 1 instead of 2

4.

OBSERVING RACE CONDITION IN AJAX:

A race condition is a situation when the result of the output returns unexpectedly. This occurs when the system attempts to perform two or more requests at the same time depending on the sequence of the events [8]. This condition occurs when the client requests a multiple thread within the processes and manipulates the same data concurrently, henceforth the output is unpredictable and it occurs randomly. This anomalous behavior depends on the timing of the multiple events that are requested causes an unexpected outcome. It is a most serious problem because the code would be fine and it would be difficult to find the problem. It will be more difficult to fix the problem due to unawareness of the problem. Fig 2 shows a race condition we created and an example is given based on PHP. When two Asynchronous requests are sent from the browser to the server, the page loads with the valid count which is initially set to zero. When the web page initiates two asynchronous requests, request 1 and request 2 attempts

As webpage is no longer served as a single unit but fragmented into responses to various separate calls, timing issues may occur. Ajax is different from synchronous requests that it allows multiple entrance points, resulting in numerous small scripts on the server. This may lead to increased security and maintenance problems, as all checks must be made for every single call, reducing total performance. Each Ajax call may come at any time and unrelated from all others. Keeping a state on the server is therefore more difficult. Because of this, Ajax scripts, especially asynchronous ones, should in general not modify the server state [11]. If two xmlhttprequests are sent from the client and access the same file on the server the PHP script considers the two events separately and creates a race condition.
xmlhttp1.open (' GET'' , http://localhost/session.php?event1'true); , xmlhttp2.open (' GET'' , http://localhost/session.php?event2'true); ,

In the PHP script on the server, using set_time_limit(1) the delay is set. counter.txt file contains values which are set to zero at start. Then we try to increment with two requests.
<?php set_time_limit (1); $count= ("counter.txt"); $x = file($count); $x[0]++;

Consider the following two tasks, in the code:
if (isset($_GET['event1'])){ $fp = fopen($count, "w"); fwrite($fp , "$x[0]"); fclose($fp); print” ".$x[0]." at Time".date('i:s');} else if (isset($_GET['event2'])){ $fp = fopen($count, "w");

in multiple Ajax asynchronous requests within the same session. Implementation of it is very difficult. Although there are not multiple Ajax requests directly explicit updating same session data within the same session, but there may still have indirect implicit contention on the same resource. [1][2] The best solution to race condition problem should be found on the server side of Ajax requests. For example, early version of PHP provides default session handler on the session data for the entire session so that the degree of concurrency is reduced. The locking is a synchronization mechanism for enforcing restrictions on access to a shared resource in a server environment where there are multiple threads of concurrent execution. Each thread cooperates by acquiring the lock before accessing the corresponding data. [1][2][3] Such lock is called the advisory locks. After processing the corresponding data the lock must be released (implicitly or explicitly). The new version of PHP server provides session data with per-variable semaphore binary lock shown in the following. [14] $_SESSION->acquire (<variable name>); <critical section> $_SESSION->release (<variable name>); In some cases the data is shared by many sessions. The shared data is stored in a file or database. We can apply the flock method to synchronize the shared count data in a file or database. The flock () can perform a simple reader/writer model which can be used on virtually every platform. The flock() can also release the lock on the file. Any lock is released by fclose() automatically. [13]. The flock is given as follows: [13] bool flock ( resource $handle , int $operation );

fwrite($fp , "$x[0]"); fclose($fp); print” ".$x[0]." at Time".date(' );} i:s' ?> In the PHP code event1 and event 2 variables are set using isset function. The two requests try to open the same file in the server counter.txt and try to increment the count in the file. Initially the counter.txt file is set to zero, if event 1 is the first, then the counter value will increment to 1, then the event 2 changes the count to 2, but if event 2 is fired first, if it increments to 1, event 1 changes and prints the count to 2 before event1 request runs, then both of them print the count to 2 thus causing vulnerability at the fraction of a second. In the multiple request web application, all the requests run at a fraction of second and wait for no time until the other thread requests from the server. The Output would look something like:

In the counter example the event1 and event 2 fights for the CPU time and 5 occurs concurrently as we see in the output.
5. SUGGESTION TO AVOID RACE CONDITION

Where the handle is an open file pointer and operation is one of the following: • LOCK_SH to acquire a shared lock (reader). • LOCK_EX to acquire an exclusive lock (writer). • LOCK_UN to release a lock (shared or exclusive). The following is a simple PHP fragment showing the file locking processing
<?php $fp = fopen("count.txt", "w+");

Solving the Ajax race condition problem is a challenge. We can prevent the Ajax race condition on the critical section of shared data either on client Ajax request or on server request handling. We can also detect and test the race condition on server and handle the contention case once it is detected. On the client side, client can try its best to avoid the race problem by not modify same session data of server page

if (flock($fp, LOCK_EX)) { // acquire an exclusive lock fwrite($fp, $count); flock($fp, LOCK_UN); // release the lock } else { echo "error message"; } fclose($fp);

?> While the introduction of locking and other process/thread synchronization approaches helps avoiding AJAX racing conditions, the concurrency resident in AJAX applications, nevertheless, brings about potentially hard-to-reproduce and hence hard-todebug problems. One potential danger is that the use of locks might lead to deadlock, livelock, and starvation. To diagnose and test AJAX applications against such problems can be very challenging. Since the 1970’s, the progress in the area of temporal logic [4] and model checking [5] has shed a light on validating concurrent programs. Applying state of the art model checking techniques can help to detect concurrency problems of AJAX applications. We propose the following paradigm to verify the freedom of deadlock (and other desired system properties) of AJAX applications. 1. At server side, use Java model checkers such as Java Path Finder (JPF) to verify the freedom of deadlock among Java Servlets. 2. At client side, use JavaScript parser such as Rhino JavaScript Compiler to parser JavaScript functions used by an AJAX application at client side. Then translate the model into the language accepted by model checkers such as SPIN.
5 CONCLUSIONS

[3] Harry Fuecks, AJAX and Session “Race Conditions”, http://www.sitepoint.com/blogs/2006/02/27/ajax-andsession-race-conditions/ [4] A. Pnueli. The temporal semantics of concurrent programs. In Proceedings of the 18th Symposium on Foundations of Computer Science, 1977. [5] M. Y. Vardi and P. Wolper. An automata-theoretic approach to automatic program verification. In Proceedings of the First Symposium on Logic in Computer Science, pages 322-331, Cambridge, June 1986. [6] Subverting Ajax, Stefano Di Paola [email protected], Giorgio Fedon [email protected] December 2006 [7] Dom Scripting, Jeremy Keith [8] http://en.wikipedia.org/wiki/Race_condition [9] J. J. Garrett, Ajax: A New Approach to Web Applications, http://www.adaptivepath.com/publications/essays/archiv es/000385.php [10] Building Secure Software: Race Conditions,Gary McGraw, John Viega. [11] Ajax Security in Groupware, Michael Sonntag, Institute for Information Processing and Microprocessor Technology, Johannes Kepler University Linz, Altenbergerstr [12] An Architectural Style for Ajax, Ali Mesbah, Arie van Deursen Software Evolution Research Laboratory, Delft University of Technology. [13] PHP Manuel [14] Semaphore, http://en.wikipedia.org/wiki/Semaphore_%28programmi ng%29

This work is still in progress. This paper discusses the race condition in Ajax-based web application and proposes paradigms for the future work. 6. REFERENCES [1] Race Conditions with Ajax and PHP Session, http://thwartedefforts.org/2006/11/11/race-conditionswith-ajax-and-php-sessions/ [2]. Macwan, Troubles with Asynchronous Ajax Requests and PHP Sessions, http://www.chipmunkninja.com/article/asyncsessions

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close