Slide Ads

Showing posts with label Operating Systems. Show all posts
Showing posts with label Operating Systems. Show all posts

Tuesday, July 21, 2009

How to escape special characters in java? /StringEscapeUtils

Often times, we encountered some special characters or arbitrary text placed in an HTML tag that resulting an invalid HTML output. The special characters often needs to be altered or escape to ensure the resulting HTML is still valid.

Special characters as follow
1) <
2) >
3) ”
4) ‘
5) \
6) &

Here i want to introduce a handy-ready java library call StringEscapeUtils which included in commons-lang.jar library, and used to escape special characters in Java.

P.S Please download the commons-lang.jar library in http://commons.apache.org/lang/

Here is the source code to demonstrate how to escape special characters with StringEscapeUtils class.

import org.apache.commons.lang.StringEscapeUtils;

public class testEscapeHTML{

public static void main(String args[]){

String testStr = "< > \" &";

System.out.println("Original : " + testStr);

System.out.println("Escaped : " + StringEscapeUtils.escapeHtml(testStr));

}
}

Result

Original : < > " &
Escaped : < > " &

PostgreSQL – How to change default schema /postgresql.conf

“public” is PostgreSQL default scheme, i have to change it because i had migrated a new database data into another new schema call “new_public”.
Before start to change, i have to check what is current PostgreSQL default schema?

1) Command

SHOW search_path

2) Check postgresql.conf

#---------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#---------------------------------------------------------------------------

# - Statement Behavior -

#search_path = '"$user",public' # schema names
#default_tablespace = '' # a tablespace name, '' uses
# the default
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off

Here i show how to change Postgresql default schema.

SET search_path = new_schema

However above command is apply to current session only, next time schema will change back to public. If we want to make effect permanently, we have to change in postgresql.conf file like following.

#---------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#---------------------------------------------------------------------------

# - Statement Behavior -

#search_path = '"$user",public' # schema names
search_path = '"$user",new_schema' # NEW SCHEMA HERE
#default_tablespace = '' # a tablespace name, '' uses
# the default
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off

After that just restart PostgreSQL service. Done.


Friday, July 17, 2009

Problem solution MSTSC.exe /CONSOLE launch command parameters

Thats' right. No more /console switch on the Windows Remote Desktop Connection tool, MSTSC.exe, starting from Windows XP Service Pack 3, Windows Vista Service Pack 1 and Windows Server 2008.

This is because of the design enhancements in Windows Vista and Windows Server 2008, by virtue of which you cannot connect to Session 0, which is the default session. Running services and user applications together in Session 0 poses a security risk because services in Session 0 run at elevated privileges and therefore can be targeted by malware that attack by attempting and exploiting a privilege escalation.

The new generation of the Windows operating system mitigates this security risk by isolating services in Session 0 and making Session 0 non-interactive to the user. In Windows Vista (and Windows Server 2008), only system processes and services run in Session 0. The first user logs on to Session 1. Subsequent users log on to subsequent sessions (Session 2, Session 3 etc). This means that services (like printer drivers loaded by spooler service, UMDF drivers, user/window interactive services, etc) never run in the same session as users' applications and are therefore protected from attacks that originate in application code.


Session Zero in Windows XP/Windows Server 2003: The first user logs in to Session Zero itself.


Session Zero Isolation in Windows XP SP3/Windows Vista SP1/Windows Server 2008: First user's Session is not within Session Zero, a separate session is created, thereby improving security.

Since there is no longer the ability to connect to Session 0, the /console switch is no longer required. But, what if I want to connect to Session 0 on a Windows Server 2003/XP or earlier machine using RDP 6.1? Let's find out.

When I typed "mstsc /?" on my Windows Server 2008 machine, these are the options that are available to me:



Notice that the /console option is not available, but there is a /admin option. The /admin option lets you connect to Session 0 on a remote computer that doesn't have Windows Vista SP1, Windows XP SP3 or Windows Server 2008 or later installed.

However, if you try to pull the /console switch on a Windows Server 2008 or Vista SP1 machine, you get an error "An unknown parameter was specified in the computer name field".

mstsc.exe allows you to initiate terminal services commands via the command line, and forms an important part of this additional Windows service. "This program is a non-essential process, but should not be terminated unless suspected to be causing problems.\r"


Creates connections to terminal servers or other remote computers, edits an existing Remote Desktop Connection (.rdp) configuration file, and migrates legacy connection files that were created with Client Connection Manager to new .rdp connection files.

IIS Server Error- HTTP Status Codes

When you are checking your IIS log files you can find a field which defines the status of the request. This status can be very useful when you are trying to diagnose a problem such as a user being denied access to your site.

#Software: Microsoft Internet Information Services 5.1
#Version: 1.0
#Date: 2005-08-26 18:19:49
#Fields: date time c-ip cs-username s-sitename s-computername s-ip s-port cs-method cs-uri-stem cs-uri-query sc-status sc-win32-status sc-bytes cs-bytes time-taken cs-version cs-host

2005-08-26 18:19:49 127.0.0.1 - W3SVC1 CHRIS 127.0.0.1 80 GET /images/ - 302 0 285 586 62 HTTP/1.1 localhost
2005-08-26 18:19:49 127.0.0.1 - W3SVC1 CHRIS 127.0.0.1 80 GET /images/ - 403 5 334 587 16 HTTP/1.1 localhost

From the above log entries we can see we have a status of 302 (Object moved) for the first request, and a status of 403 (Forbidden) for the second request. But we do not know why the user was denied access. In this case I tried to browse an image directory and it did not have directory browsing enabled which should have logged a 403.14 error but IIS 5.1 and earlier do not support storing the sub status code.

Doing something similar with IIS 6 on Windows 2003 Server we get these log file entries.

#Software: Microsoft Internet Information Services 6.0
#Version: 1.0
#Date: 2005-08-26 00:03:26
#Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes
2005-08-26 18:33:30 W3SVC68783193 SBS2003 192.168.2.2 GET /images - 80 - 192.168.2.1 HTTP/1.1 301 0 0 399 432
2005-08-26 18:33:30 W3SVC68783193 SBS2003 192.168.2.2 GET /images/ - 80 - 192.168.2.1 HTTP/1.1 403 14 5 412 433

In the IIS 6 log file example above you can see that I am logging two status fields sc-status and sc-substatus

This time the first request is returning a status of 301 (Object Moved Permanently) and a sub status of 0 which is not used.
The second request returns a status of 403 (Forbidden) and a sub status of 14 (Directory Listing Denied)

1xx - Informational

These status codes indicate a provisional response. The client should be prepared to receive one or more 1xx responses before receiving a regular response.

100 - Continue.
101 - Switching protocols.

2xx - Success

This class of status codes indicates that the server successfully accepted the client request.

200 - OK. The client request has succeeded.
201 - Created.
202 - Accepted.
203 - Non-authoritative information.
204 - No content.
205 - Reset content.
206 - Partial content.

3xx - Redirection

The client browser must take more action to complete the request. For example, the browser may have to request a different page on the server or repeat the request by using a proxy server.

301 - Moved Permanently
302
- Object moved Temporarily
303 - See Other
304 - Not modified.
307 - Temporary redirect.

4xx - Client Error

An error occurs, and the client appears to be at fault. For example, the client may request a page that does not exist, or the client may not provide valid authentication information.

400 - Bad request.
401 - Access denied. IIS defines a number of different 401 errors that indicate a more specific cause of the error. These specific error codes are displayed in the browser but are not displayed in the IIS log:

401.1 - Logon failed.
401.2 - Logon failed due to server configuration.
401.3 - Unauthorized due to ACL on resource.
401.4 - Authorization failed by filter.
401.5 - Authorization failed by ISAPI/CGI application.
401.7 – Access denied by URL authorization policy on the Web server. This error code is specific to IIS 6.0.

403 - Forbidden. IIS defines a number of different 403 errors that indicate a more specific cause of the error:

403.1 - Execute access forbidden.
403.2 - Read access forbidden.
403.3 - Write access forbidden.
403.4 - SSL required.
403.5 - SSL 128 required.
403.6 - IP address rejected.
403.7 - Client certificate required.
403.8 - Site access denied.
403.9 - Too many users.
403.10 - Invalid configuration.
403.11 - Password change.
403.12 - Mapper denied access.
403.13 - Client certificate revoked.
403.14 - Directory listing denied.
403.15 - Client Access Licenses exceeded.
403.16 - Client certificate is untrusted or invalid.
403.17 - Client certificate has expired or is not yet valid.
403.18 - Cannot execute requested URL in the current application pool. This error code is specific to IIS 6.0.
403.19 - Cannot execute CGIs for the client in this application pool. This error code is specific to IIS 6.0.
403.20 - Passport logon failed. This error code is specific to IIS 6.0.

404 - Not found. 404.0 - (None) – File or directory not found.

404.1 - Web site not accessible on the requested port.
404.2 - Web service extension lockdown policy prevents this request.
404.3 - MIME map policy prevents this request.
404.4 - No Handler (IIS 7)
404.5 - Request Filtering: URL Sequence Denied (IIS 7)
404.6 - Request Filtering: Verb denied (IIS 7)
404.7 - Request Filtering: File extension denied (IIS 7)
404.8 - Request Filtering: Denied by hidden namespace (IIS 7)
404.9 - Denied since hidden file attribute has been set (IIS 7)
404.10 - Request Filtering: Denied because request header is too long (IIS 7)
404.11- Request Filtering: Denied because URL doubled escaping (IIS 7)
404.12 - Request Filtering: Denied because of high bit characters (IIS 7)
404.13 - Request Filtering: Denied because content length too large (IIS 7)
404.14 - Request Filtering: Denied because URL too long (IIS 7)
404.15- Request Filtering: Denied because query string too long (IIS 7)

405 - HTTP verb used to access this page is not allowed (method not allowed.)
406 - Client browser does not accept the MIME type of the requested page.
407 - Proxy authentication required.
412 - Precondition failed.
413 – Request entity too large.
414 - Request-URI too long.
415 – Unsupported media type.
416 – Requested range not satisfiable.
417 – Execution failed.
423 – Locked error.

5xx - Server Error

The server cannot complete the request because it encounters an error.

500 - Internal server error.

500.12 - Application is busy restarting on the Web server.
500.13 - Web server is too busy.
500.15 - Direct requests for Global.asa are not allowed.
500.16 – UNC authorization credentials incorrect. This error code is specific to IIS 6.0.
500.18 – URL authorization store cannot be opened. This error code is specific to IIS 6.0.
500.100 - Internal ASP error.

501 - Header values specify a configuration that is not implemented.
502 - Web server received an invalid response while acting as a gateway or proxy.

502.1 - CGI application timeout.
502.2 - Error in CGI application.

503 - Service unavailable. This error code is specific to IIS 6.0.
504 - Gateway timeout.
505 - HTTP version not supported.

Wednesday, July 15, 2009

Data File Metaformats -DSV Style-RFC 822 Format

A data file metaformat is a set of syntactic and lexical conventions that is either formally standardized or sufficiently well established by practice that there are standard service libraries to handle marshaling and unmarshaling it.

Unix has evolved or adopted metaformats suitable for a wide range of applications. It is good practice to use one of these (rather than an idiosyncratic custom format) wherever possible. The benefits begin with the amount of custom parsing and generation code that you may be able to avoid writing by using a service library. But the most important benefit is that developers and even many users will instantly recognize these formats and feel comfortable with them, which reduces the friction costs of learning new programs.

In the following discussion, when we refer to "traditional Unix tools" we are intending the combination of grep(1), sed(1), awk(1), tr(1), and cut(1) for doing text searches and transformations. Perl and other scripting languages tend to have good native support for parsing the line-oriented formats that these tools encourage.

Here, then, are the standard formats that can serve you as models.

5.2.1 DSV Style

DSV stands for Delimiter-Separated Values. Our first case study in textual metaformats was the /etc/passwd file, which is a DSV format with colon as the value separator. Under Unix, colon is the default separator for DSV formats in which the field values may contain whitespace.

/etc/passwd format (one record per line, colon-separated fields) is very traditional under Unix and frequently used for tabular data. Other classic examples include the /etc/group file describing security groups and the /etc/inittab file used to control startup and shutdown of Unix service programs at different run levels of the operating system.

Data files in this style are expected to support inclusion of colons in the data fields by backslash escaping. More generally, code that reads them is expected to support record continuation by ignoring backslash-escaped newlines, and to allow embedding nonprintable character data by C-style backslash escapes.

This format is most appropriate when the data is tabular, keyed by a name (in the first field), and records are typically short (less than 80 characters long). It works well with traditional Unix tools.

One occasionally sees field separators other than the colon, such as the pipe character | or even an ASCII NUL. Old-school Unix practice used to favor tabs, a preference reflected in the defaults for cut(1) and paste(1); but this has gradually changed as format designers became aware of the many small irritations that ensue from the fact that tabs and spaces are not visually distinguishable.

This format is to Unix what CSV (comma-separated value) format is under Microsoft Windows and elsewhere outside the Unix world. CSV (fields separated by commas, double quotes used to escape commas, no continuation lines) is rarely found under Unix.

In fact, the Microsoft version of CSV is a textbook example of how not to design a textual file format. Its problems begin with the case in which the separator character (in this case, a comma) is found inside a field. The Unix way would be to simply escape the separator with a backslash, and have a double escape represent a literal backslash. This design gives us a single special case (the escape character) to check for when parsing the file, and only a single action when the escape is found (treat the following character as a literal). The latter conveniently not only handles the separator character, but gives us a way to handle the escape character and newlines for free. CSV, on the other hand, encloses the entire field in double quotes if it contains the separator. If the field contains double quotes, it must also be enclosed in double quotes, and the individual double quotes in the field must themselves be repeated twice to indicate that they don't end the field.

The bad results of proliferating special cases are twofold. First, the complexity of the parser (and its vulnerability to bugs) is increased. Second, because the format rules are complex and underspecified, different implementations diverge in their handling of edge cases. Sometimes continuation lines are supported, by starting the last field of the line with an unterminated double quote—but only in some products! Microsoft has incompatible versions of CSV files between its own applications, and in some cases between different versions of the same application (Excel being the obvious example here).

5.2.2 RFC 822 Format

The RFC 822 metaformat derives from the textual format of Internet electronic mail messages; RFC 822 is the principal Internet RFC describing this format (since superseded by RFC 2822). MIME (Multipurpose Internet Media Extension) provides a way to embed typed binary data within RFC-822-format messages. (Web searches on either of these names will turn up the relevant standards.)

In this metaformat, record attributes are stored one per line, named by tokens resembling mail header-field names and terminated with a colon followed by whitespace. Field names do not contain whitespace; conventionally a dash is substituted instead. The attribute value is the entire remainder of the line, exclusive of trailing whitespace and newline. A physical line that begins with tab or whitespace is interpreted as a continuation of the current logical line. A blank line may be interpreted either as a record terminator or as an indication that unstructured text follows.

Under Unix, this is the traditional and preferred textual metaformat for attributed messages or anything that can be closely analogized to electronic mail. More generally, it's appropriate for records with a varying set of fields in which the hierarchy of data is flat (no recursion or tree structure).

Usenet news uses it; so do the HTTP 1.1 (and later) formats used by the World Wide Web. It is very convenient for editing by humans. Traditional Unix search tools are still good for attribute searches, though finding record boundaries will be a little more work than in a record-per-line format.

One weakness of RFC 822 format is that when more than one RFC 822 message or record is put in a file, the record boundaries may not be obvious—how is a poor literal-minded computer to know where the unstructured text body of a message ends and the next header begins? Historically, there have been several different conventions for delimiting messages in mailboxes. The oldest and most widely supported, leading each message with a line that begins with the string "From " and sender information, is not appropriate for other kinds of records; it also requires that lines in message text beginning with "From " be escaped (typically with >)—a practice which not infrequently leads to confusion.

Some mail systems use delimiter lines consisting of control characters unlikely to appear in messages, such as several ASCII 01 (control-A) characters in succession. The MIME standard gets around the problem by including an explicit message length in the header, but this is a fragile solution which is very likely to break if messages are ever manually edited. For a somewhat better solution, see the record-jar style described later in this chapter.

For examples of RFC 822 format, look in your mailbox.

Unix Textual File Format Conventions e.g stanza formats

There are long-standing Unix traditions about how textual data formats ought to look. Most of these derive from one or more of the standard Unix metaformats we've just described. It is wise to follow these conventions unless you have strong and specific reasons to do otherwise

  • One record per newline-terminated line, if possible. This makes it easy to extract records with text-stream tools. For data interchange with other operating systems, it's wise to make your file-format parser indifferent to whether the line ending is LF or CR-LF. It's also conventional to ignore trailing whitespace in such formats; this protects against common editor bobbles.

  • Less than 80 characters per line, if possible. This makes the format browseable in an ordinary-sized terminal window. If many records must be longer than 80 characters, consider a stanza format (see below).

  • Use # as an introducer for comments. It is good to have a way to embed annotations and comments in data files. It's best if they're actually part of the file structure, and so will be preserved by tools that know its format. For comments that are not preserved during parsing, # is the conventional start character.

  • Support the backslash convention. The least surprising way to support embedding nonprintable control characters is by parsing C-like backslash escapes—\n for a newline, \r for a carriage return, \t for a tab, \b for backspace, \f for formfeed, \e for ASCII escape (27), \nnn or \onnn or \0nnn for the character with octal value nnn, \xnn for the character with hexadecimal value nn, \dnnn for the character with decimal value nnn, \\ for a literal backslash. A newer convention, but one worth following, is the use of \unnnn for a hexadecimal Unicode literal.

  • In one-record-per-line formats, use colon or any run of whitespace as a field separator. The colon convention seems to have originated with the Unix password file. If your fields must contain instances of the separator(s), use a backslash as the prefix to escape them.

  • Do not allow the distinction between tab and whitespace to be significant. This is a recipe for serious headaches when the tab settings on your users' editors are different; more generally, it's confusing to the eye. Using tab alone as a field separator is especially likely to cause problems; allowing any run of tabs and spaces to be a field separator, on the other hand, works well.

  • Favor hex over octal. Hex-digit pairs and quads are easier to eyeball-map into bytes and today's 32- and 64-bit words than octal digits of three bits each; also marginally more efficient. This rule needs emphasizing because some older Unix tools such as od(1) violate it; that's a legacy from the instruction field sizes in the machine languages of older PDP minicomputers.

  • For complex records, use a 'stanza' format: multiple lines per record, with a record separator line of %%\n or %\n. The separators make useful visual boundaries for human beings eyeballing the file.

  • In stanza formats, either have one record field per line or use a record format resembling RFC 822 electronic-mail headers, with colon-terminated field-name keywords leading fields. The second choice is appropriate when fields are often either absent or longer than 80 characters, or when records are sparse (e.g., often with empty fields).

  • In stanza formats, support line continuation. When interpreting the file, either discard backslash followed by whitespace or interpret newline followed by whitespace equivalently to a single space, so that a long logical line can be folded into short (easily editable!) physical lines. It's also conventional to ignore trailing whitespace in these formats; this convention protects against common editor bobbles.

  • Either include a version number or design the format as self-describing chunks independent of each other. If there is even the faintest possibility that the format will have to be changed or extended, include a version number so your code can conditionally do the right thing on all versions. Alternatively, design the format as self-describing chunks so that you can add new chunk types without instantly breaking old code.

  • Beware of floating-point round-off problems. Conversion of floating-point numbers from binary to text format and back can lose precision, depending on the quality of the conversion library you are using. If the structure you are marshaling/unmarshaling contains floating point, you should test the conversion in both directions. If it looks like conversion in either direction is subject to roundoff errors, be prepared to dump the floating-point field as raw binary instead, or a string encoding thereof. If you're coding in C or some language that has access to C printf/scanf, the C99 %a specifier may solve this problem.

Unix : Separating Complexity Control from Performance Tuning

First, though, we need to dispose of a few red herrings. Our discussion is not going to be about using concurrency to improve performance. Putting that concern before developing a clean architecture that minimizes global complexity is premature optimization, the root of all evil

A closely related red herring is threads (that is, multiple concurrent processes sharing the same memory-address space). Threading is a performance hack. To avoid a long diversion here, we'll examine threads in more detail at the end of this chapter; the summary is that they do not reduce global complexity but rather increase it, and should therefore be avoided save under dire necessity.

Respecting the Rule of Modularity, on the other hand, is not a red herring; doing so can make your programs—and your life—simpler.

Another important reason for breaking up programs into cooperating processes is for better security. Under Unix, programs that must be run by ordinary users, but must have write access to security-critical system resources, get that access through a feature called the setuid bit. Executable files are the smallest unit of code that can hold a setuid bit; thus, every line of code in a setuid executable must be trusted. (Well-written setuid programs, however, take all necessary privileged actions first and then drop their privileges back to user level for the remainder of their existence.)


Usually a setuid program only needs its privileges for one or a small handful of operations. It is often possible to break up such a program into cooperating processes, a smaller one that needs setuid and a larger one that does not. When we can do this, only the code in the smaller program has to be trusted. It is in significant part because this kind of partitioning and delegation is possible that Unix has a better security track record than its competitors.