MEME2

Page 1

What's in a Meme? What is Cryptography? by Mandarino Cryptography is the science of using mathematics to encrypt and decrypt information. Once the information has been encrypted, it can be stored on insecure media or transmitted on an insecure network (like the Internet) so that it cannot be read by anyone except the intended recipient. What is the encryption and decryption process? Encryption is the process in which data (plaintext) is translated into something that appears to be random and meaningless (ciphertext). Decryption is the process in which the ciphertext is converted back to plaintext. What is a cryptographic algorithm? A cryptographic algorithm, or cipher, is a mathematical function used in the encryption and decryption process. A cryptographic algorithm works in combination with a key (a number, word, or phrase) to encrypt and decrypt data. To encrypt, the algorithm mathematically combines the information to be protected with a supplied key. The result of this combination is the encrypted data. To decrypt, the algorithm performs a calculation combining the encrypted data with a supplied key. The result of this combination is the decrypted data. If either the key or the data is modified, the algorithm produces a different result. The goal of every encryption algorithm is to make it as difficult as possible to decrypt the generated ciphertext without using the key. If a really good encryption algorithm is used, then there is no technique significantly better than methodically trying every possible key. Even for a key size of just 40 bits, this works out to 2�40 (just over 1 trillion) possible keys. Differences between symmetric and asymmetric algorithms. Symmetric algorithms encrypt and decrypt with the same key. Main advantages of symmetric algorithms are its security and high speed. Asymmetric algorithms encrypt and decrypt with different keys. Data is encrypted with a public key, and decrypted with a private key. Asymmetric algorithms (also known as public-key algorithms) need at least a 3,000-bit key to achieve the same level of security of a 128-bit symmetric algorithm. Asymmetric algorithms are incredibly slow and it is impractical to use them to


encrypt large amounts of data. Symmetric algorithms are about 1,000 times faster than asymmetric ones. How secure is Encrypt Easy? Encrypt Easy uses these and others strong (symmetric) cryptographic algorithms to protect your information: Blowfish (448-bit key) is a strong and fast algorithm designed by Bruce Schneier, one of the most prestigious cryptographers all over the world. Rijndael (256-bit key) is a high security algorithm created by Joan Daemen and Vincent Rijmen (Belgium). Rijndael is the new Advanced Encryption Standard (AES) chosen by the National Institute of Standards and Technology (NIST). Triple DES (192-bit key) is a strong, well-known, U.S. Government algorithm. TripleDES use the DES algorithm three times with three different keys. Gost (256-bit key) is a cryptographic algorithm from Russia that appears to be the Russian analog to DES. Gost has undergone intensive peer review and is regarded to be secure. CAST (256-bit key) is a rather dependable algorithm with key length up to 64 bits. Developed by C.M. Adams and S.E. Tavares, who offered it at AES competition. Twofish (256-bit key) is algorithm that replaced Blowfish, authored by Bruce Schneier as its predecessor. Considered to be hack-proof (no known incidents of code-cracking). At present, there is no way to break any of these algorithms, unless to try all possible keys. If one billion computers were each searching one billion keys per second, it would take over 10*10�24 years to recover information encrypted with a 168-bit algorithm (the age of the universe is 10*10�9 years). In addition, Encrypt Easy implements mechanisms against modifications in its code. When executed, it verifies the algorithms with the test vectors provided by their designers. The algorithms implemented in Encrypt Easy are Block Ciphers. This means that they encrypt data in block units, rather than a single bit at a time. The algorithms are used in Cipher Block Chaining mode, where the original data is XORed with the previous ciphertext before encryption. On the first encryption, a random-generated 128-bit Initialization Vector is used as the ciphertext. CBC mode ensures that even if the data contains many identical blocks, they will each encrypt to a different ciphertext block. When you enter your passphrase into Encrypt Easy, it is hashed with a Hash algorithm to generate a fingerprint, also known as digest. The one-way Hash function takes variable-length input, in this case your passphrase, and produces a fixed-length output. Also ensures that, if the passphrase is changed -even by just one bit- an entirely different output value is generated. This value is the key actually used by the cipher. That process is repeated using a different Hash function for each encryption algorithm, thus generating four unique keys. Â


Sorry in advance for the long posting... It looks like AES with 256-bit keys are broken. Running the command line: Python test.py aes produces the output at the bottom of this posting. Note that 128-bit keys seem to be working. I was able to reproduce this from an interactive session, as follows: D:\work\Python\pycrypto-1.9a6>python ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Crypto.Cipher import AES >>> key = '1234567890123456' >>> plain = key >>> aes = AES.new(key, AES.MODE_ECB) >>> cipher = aes.encrypt(plain) >>> aes.decrypt(cipher) '1234567890123456' #WORKS WITH 128-BIT KEY >>> >>> key = '12345678901234567890123456789012' >>> len(key) 32 >>> plain = key >>> aes = AES.new(key, AES.MODE_ECB) >>> cipher = aes.encrypt(plain) >>> aes.decrypt(cipher) '\xcde\xf6O\xbd\xea\xe8i\x86\xd21\xfa\xe1\xb2\xec\xfd[u\x06\xfa\x8f%\xf5\xc9 \xb6 \xd5\xf2\x02{\xc9\xa0\xa3' #FAILS WITH 256-BIT KEY >>> I am running Win2K, Python 2.2.2 (ActiveState Build 224), and pyCrypto 1.9a6. I currently do not have access to other platforms to try and reproduce this. I have encountered this with ECB, CBC, and CTR modes. Note: While messing around with this, I tried the following: >>> key = '12345678901234567890123456789012' >>> plain = key >>> aes = AES.new(key, AES.MODE_CBC) >>> cipher = aes.encrypt(plain) >>> aes.decrypt(cipher) '\xa4G\x9aD\xa5}K\x14\xd0\xeaC\xee\x0b\xd4{d7890123456789012'


The last 16 bytes are decrypted properly for CBC mode. Perhaps this is a clue to what the issue may be. I also submitted this as a bug on the SourceForge pyCrypto project area. Test output: Stream Ciphers: =============== Block Ciphers: ============== AES:  ECB mode: 12799.9359134 K/sec  CFB mode: 576.576878755 K/sec  CBC mode: 12800.012207 K/sec  PGP mode: 12800.012207 K/sec  OFB mode: 12799.9359134 K/sec  CTR mode: 3657.14634487 K/sec  Testing IV handling  Verifying against test suite... ***ERROR: AES failed on entry ('000102030405060708090A0B0C0D0E0F1011121314151617', '00112233445566778899AABBCCDDEEFF', 'DDA97CA4864CDFE06EAF70A0EC0D7191') 0xb9 0xc4 0x5 0x95 0xa7 0x9 0xa3 0x5b 0x5b 0x84 0xce 0x59 0x7e 0xa4 0x47 0xe4 ***ERROR: AES failed on entry ('000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F', '00112233445566778899AABBCCDDEEFF', '8EA2B7CA516745BFEAFC49904B496089') 0xc7 0x52 0xa6 0x96 0x5f 0x80 0xfe 0xc 0xe7 0xcb 0x52 0xd9 0x8b 0x4 0x7a 0xb ***ERROR: AES encrypt failed on entry (2, '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', '4f021db243bc633d7178183a9fa071e8b4d9ada9ad7dedf4e5e738763f69145a571b242 012f b7ae07fa9baac3df102e008b0e27988598881d920a9e64f5615cd', {'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0xc 0xb2 0xb7 0x9b 0x16 0x6e 0x7b 0x6e 0x2e 0x28 0xc0 0x89 0x2f 0x9c 0xae 0x84 0x5b 0x9c 0xd8 0xc6 0x4b 0xe6 0x57 0x53 0x73 0x3e 0x9f 0x89 0x30 0xf 0xc3 0x28 0x52 0x1f 0x3e 0x95 0xfc 0x16 0x32 0x7f 0x1d 0x50 0x14 0x4d 0xd2


0x5c 0xff 0xc0 0x29 0x2d 0x44 0x36 0xa0 0xfc 0x5c 0x5a 0x5d 0x9c 0xca 0xf2 0x7c 0x91 0x47 0xbd ***ERROR:Â AES encrypt failed on entry (2, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'f58c4c04d6e5f1ba779eabfb5f7bfbd69cfc4e967edb808d679f777bc6702c7d39f23369a9 d 9bacfa530e26304231461b2eb05e2c39be9fcda6c19078c6a9d1b', {'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x4 0x8b 0x96 0x39 0x2a 0x9 0x84 0xb5 0xe5 0x9b 0x4b 0xfc 0xbe 0x7b 0x3a 0xc2 0xc8 0x5d 0xe9 0xce 0xbd 0xb9 0x64 0x33 0xf2 0xcb 0xad 0x19 0x75 0x9c 0xeb 0x69 0x78 0x8a 0x9e 0x28 0x60 0x47 0xe0 0x1b 0xb8 0x4b 0x42 0x32 0xce 0x9 0x5c 0x42 0x82 0x3f 0x18 0x62 0x69 0x7e 0xa7 0xfd 0x35 0xe0 0x4 0x5c 0xd 0x64 0xc2 0xeb ***ERROR:Â AES encrypt failed on entry (5, '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'cdc80d6fddf18cab34c25909c99a4174fcc28b8d4c63837c09e81700c11004018d9a9aea c0f 6596f559c6d4daf59a5f26d9f200857ca6c3e9cac524bd9acc92a', {'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x69 0x3e 0x6f 0x73 0x37 0x32 0x6f 0x97 0x7a 0x9e 0x68 0xf1 0x17 0x65 0x1 0x68 0x83 0xf0 0x1f 0x2 0x2b 0x16 0xc2 0x30 0x56 0x84 0x37 0x51 0x6d 0x2a 0x44 0x27 0x59 0xda 0x80 0x3a 0x25 0xc1 0x62 0xc6 0xeb 0x64 0xf6 0x36 0x61 0x8d 0xa 0xfa 0x79 0xd3 0x95 0x3a 0x61 0x2a 0x31 0x12 0x4f 0xe8 0x99 0xba 0x49 0xd6 0x41 0xd3 ***ERROR:Â AES encrypt failed on entry (5, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'dc7e84bfda79164b7ecd8486985d38604febdc6740d20b3ac88f6ad82a4fb08d71ab47a0 86e 86eedf39d1c5bba97c4080126141d67f37be8538f5a8be740e484', {'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x61 0xe4 0xfc 0xdd 0x2e 0x77 0x59 0xd4 0xdd 0x30 0xad 0x16 0xd9 0x43 0x7c 0x89 0x10 0xbc 0xe8 0x13 0xd5 0x2f 0x9d 0x3d 0x3e 0x3c 0x68 0xfc 0x31 0xec 0x76 0x3 0xb4 0xde 0xe8 0xec 0x7b 0x9c 0xa 0x8f 0x8 0x63 0x7f 0x26 0x94 0x87 0xcd 0x3d 0x3f 0xb9 0xa9 0xd0 0xe4 0xe2 0xfd 0x58 0xf2 0x45 0xe9 0x3d 0xf1 0x5d 0x35 0xbe ***ERROR:Â AES decrypt failed on entry (5, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4',


'6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'dc7e84bfda79164b7ecd8486985d38604febdc6740d20b3ac88f6ad82a4fb08d71ab47a0 86e 86eedf39d1c5bba97c4080126141d67f37be8538f5a8be740e484', {'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x26 0x7b 0x45 0xd6 0x25 0xd 0xea 0x5f 0xc9 0x5b 0xc3 0xba 0xa6 0x3c 0x39 0xc4 0x7d 0xdb 0x8f 0x7e 0x37 0xbb 0x74 0xac 0x1b 0xd9 0x11 0x7 0xc9 0x73 0x7d 0x3c 0x1d 0xda 0xe 0xd5 0xc 0xd5 0xb3 0xa1 0x4d 0xed 0x3c 0xea 0x37 0x7a 0x83 0x2d 0x35 0xd4 0xcd 0xd0 0xd9 0x3 0x86 0x28 0x35 0x37 0x1f 0x9e 0x39 0x33 0x70 0xd4 ***ERROR:Â AES encrypt failed on entry (6, '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', '1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e941e36b26bd 1e bc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050', {'counter': <testdata.ctr instance at 0x0085CDC8>}) 0xd1 0x4 0x92 0x72 0xf4 0x34 0x9b 0xae 0xa5 0x4d 0xa2 0x3c 0x5c 0x79 0x8a 0xc6 0x24 0x1b 0x95 0x96 0x83 0x7c 0x47 0x9f 0x6b 0xe8 0x83 0xe7 0x7f 0xe7 0x68 0x19 0xbd 0x4e 0x26 0x9a 0x96 0x24 0x38 0x2f 0xb8 0x75 0x73 0xdd 0x43 0x6e 0xc9 0x25 0xd7 0x97 0xa4 0x58 0x9e 0x5e 0x22 0x94 0x2d 0x7c 0x9b 0xb9 0xc 0xa9 0xe5 0x26 ***ERROR:Â AES encrypt failed on entry (6, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', '601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c52b0930da a23 de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6', {'counter': <testdata.ctr instance at 0x0085CF68>}) 0xf5 0x39 0xb9 0x28 0x97 0x20 0x83 0x52 0x6b 0x8c 0xd2 0x19 0xd5 0x1f 0xde 0x92 0x3f 0x7a 0xd 0xb4 0xec 0xa7 0x31 0x5 0x4a 0x46 0xe3 0xf 0x9e 0xf1 0x57 0x82 0xc0 0xcd 0x17 0x45 0x46 0x14 0x3f 0xcb 0x8b 0x17 0xce 0xab 0x11 0x35 0xe 0xa 0xfd 0x40 0x84 0x54 0xc8 0x82 0xf6 0x8b 0xea 0x78 0x48 0x86 0x2d 0x58 0xbb 0x81 ***ERROR:Â AES decrypt failed on entry (6, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', '601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c52b0930da


a23 de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6', {'counter': <testdata.ctr instance at 0x0085CF68>}) 0x8e 0xe 0xe4 0xe8 0xe3 0xae 0xcf 0xad 0xbb 0xa 0xbf 0x37 0x7b 0xdf 0xb2 0x33 0x4b 0xc 0xd1 0x7b 0x2b 0x53 0x7f 0x1d 0x3c 0xc5 0x7d 0x96 0x91 0xb5 0x9d 0xd6 0x51 0xbf 0x17 0xb 0x5c 0x1 0x73 0x3 0x57 0xc6 0x94 0x2f 0x73 0x70 0x8b 0x7e 0x94 0x17 0x8 0x8b 0x2c 0x6e 0x97 0x13 0xde 0xd7 0x6d 0x42 0x66 0xa7 0x1e 0xfb ***ERROR:Â AES encrypt failed on entry (3, '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b', '6bc1bee22e409f96e93d7e117393172aae2d', 'cda2521ef0a905ca44cd057cbf0d47a0678a', {'segment_size': 8, 'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x69 0x44 0xaf 0x9b 0x8b 0xeb 0xa0 0xc6 0x82 0x97 0x6d 0xe1 0x22 0x2e 0x62 0x35 0xb4 0xc1 ***ERROR:Â AES encrypt failed on entry (3, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d', 'dc1f1a8520a64db55fcc8ac554844e889700', {'segment_size': 8, 'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x2c 0x74 0x93 0x11 0x15 0x24 0xd4 0xcb 0x34 0xba 0x65 0x6b 0x40 0x4e 0x12 0xc9 0x7 0x11 ***ERROR:Â AES encrypt failed on entry (3, '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'cdc80d6fddf18cab34c25909c99a417467ce7f7f81173621961a2b70171d3d7a2e1e8a1d d59 b88b1c8e60fed1efac4c9c05f9f9ca9834fa042ae8fba584b09ff', {'segment_size': 128, 'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x69 0x3e 0x6f 0x73 0x37 0x32 0x6f 0x97 0x7a 0x9e 0x68 0xf1 0x17 0x65 0x1 0x68 0x5e 0xa9 0x6d 0xe6 0xef 0x56 0xe2 0x1 0xba 0x29 0x58 0x6c 0x80 0xab 0x13 0x42 0x78 0xe8 0xe6 0xb 0x3f 0x33 0x5e 0xdc 0x0 0xf 0x7b 0x31 0x42 0x12 0xe5 0x67 0xc1 0xb4 0x9c 0x9d 0x16 0xb9 0x65 0xb2 0xe8 0x4d 0x1d 0x67 0x9c 0xa8 0x94 0xe7 ***ERROR:Â AES encrypt failed on entry (3, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'dc7e84bfda79164b7ecd8486985d386039ffed143b28b1c832113c6331e5407bdf101324 15e 54b92a13ed0a8267ae2f975a385741ab9cef82031623d55b1e471', {'segment_size': 128, 'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x61 0xe4 0xfc 0xdd 0x2e 0x77 0x59 0xd4 0xdd 0x30 0xad 0x16 0xd9 0x43 0x7c


0x89 0x6e 0x93 0x9f 0x3d 0xa2 0x1 0x8b 0x1a 0xc9 0xd9 0x3f 0x47 0xcd 0xd4 0x3a 0x28 0x7b 0x4 0x41 0x4b 0xc3 0x23 0xd9 0x4c 0xb1 0x15 0x67 0x64 0x76 0xb9 0xa9 0xa4 0x2b 0xe9 0xc3 0x1b 0x4a 0xe1 0x6c 0x70 0x42 0xed 0x4a 0xd5 0x52 0xd7 0x12 0xf6 ***ERROR:Â AES decrypt failed on entry (3, '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4', '6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c4 6a35 ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710', 'dc7e84bfda79164b7ecd8486985d386039ffed143b28b1c832113c6331e5407bdf101324 15e 54b92a13ed0a8267ae2f975a385741ab9cef82031623d55b1e471', {'segment_size': 128, 'IV': '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'}) 0x26 0x7b 0x45 0xd6 0x25 0xd 0xea 0x5f 0xc9 0x5b 0xc3 0xba 0xa6 0x3c 0x39 0xc4 0xc1 0xd9 0x59 0x50 0x18 0xbe 0x20 0xbe 0xcc 0x25 0x76 0xc8 0x12 0xb2 0xd4 0x2b 0x8a 0xfc 0xbc 0xb 0x3c 0xb8 0x7 0xba 0x8e 0xea 0xc6 0xc4 0xe0 0x3d 0xee 0x13 0x43 0xb2 0x88 0x17 0x4f 0x7f 0xb7 0x5b 0x85 0xbc 0xc8 0xd4 0x19 0xb6 0x23 0xbf 1. Use directional antennae to avoid excessive spreading of the signal. Signals can emanate many hundreds of feet! 2. Change the default password on the access point (AP). As most freeware scanning software can quickly suss out the default password it is vital that the password is changed. 3. Always use wired equivalent privacy (WEP). While WEP is not automatically secure it does at very least act as a barrier. 4. Ensure the WLAN is on a separate network or firewalled interface. Treat the WLAN as a semi-untrusted network. 5. Install a personal firewall on all systems using WiFi (The wireless protocol). Many new laptops are being shipped with inbuilt WiFi cards which means your system may be remotely accessible without the protection of firewall. 6. Perform regular external WLAN audits with a scanning tool. Check for the introduction of unauthorised APs to the network. 7. Perform regular internal WLAN audits. Additionally, check for the introduction of unauthorised wireless cards and APs that maybe used for illegal file sharing. 8. Administration of wireless networks is important! Administration should be conducted via secure encrypted sessions. Make sure you are using SSL (secure socket layer) and VPN authenticated sessions that protect the administrator password when doing this.


9. Maintain audit logs of who is using the WLAN. Audit them regularly to identify unauthorised access and internal abuse of the network. 10. Assess the information passing over the wireless networks. Consider the sensitivity and lifetime of data passing over the wireless network. Is it covered by the Data Protection Act? And remember - wireless networks should always be treated as public networks! Mr. Mandarino


MEME I was careful to encode mime stuff with carriage return/line feed as C1341. I was careful to check for buffer overrun and consequent security holes when calling sprintf to substitute a caller supplied string into a fixed length buffer. <image src="http:/cgi-bin/pushprog/~rima/tc/gifs?1+10+ +.gif+2500000+image/gif+1.gif+image/gif"> The pieces are: http:/cgi-bin/pushprog /~rima/tc/gifs ? 1 + 10 .gif 2500000 image/gif 1.gif image/gif

Run the pushprog cgi program on the current machine. Directory: /~rima/tc/gifs Start of command line arguments. Starting: 1 (with 1st frame) Space (occurs between arguments) (Will be left out from now on.) Ending: 10 (Display through 10th frame) Prefix: none Suffix: .gif (Files are named N.gif, N is frame #) Delay: 2.5 seconds between frames FrameMType: image/gif (Frames are gif images) Final: 1.gif (Redisplay /~rima/tc/gifs/1.gif as last frame) FinalMType: image/gif (Last frame is a gif too.)

Bugs: We could allow the "../" substring in Prefix, Suffix, and Final, so long as we check that we don't back up past DOCUMENT_ROOT. Relies on the server to deliver the frames in a timely manner. Apparently, this does not always happen. The trouble seems to be that the server waits for some buffer to fill. Perhaps this can be avoided in the NCSA HTTPD server by compiling it with CGI_SSI_HACK defined. Does something weird when outputting a file containing the MULTIPART_DELIMITER string.


Doesn't check for error on munmap call due to lack of documented return code. Failure on write of mime multipart header or delimiter may not produce a clean error message. The error messages don't do squat when used in a <img src="..."> type html clause because the browser is expecting a image and I'm returning ascii text (although with the correct mime type.) */ #include <fcntl.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> /* Forward function declarations. */ void send_frame(int fvar, char * mime_type) ; void frame_error(char * mesg) ; void legal_path(char * path, char * argname) ; void server_error(char * mesg) ; void delay_till_alarm(int microseconds) ; void alarm_handler(int signal) ; /* The largest string we can handle. */ #define MULTIPART_DELIMITER "--ThisRandomString" #define CONTENT_TYPE "Content-type: %s\r\n\r\n" /* blank line follows header */ #define MAX_SSIZE 500 char error_mesg[MAX_SSIZE] ; char buf[MAX_SSIZE] ; int buf_len ; /* number of chars in previous */ char rep_multipart_delimiter[sizeof(MULTIPART_DELIMITER) + 10] ; int rmd_len ; /* number of chars in previous */ char final_multipart_delimiter[sizeof(MULTIPART_DELIMITER) + 10] ; int fmd_len ; /* number of chars in previous */ int alarm_received = 1 ; /* A boolean, used in the timer system. */ /* Initialize so there's no pause before the first frame. */ int main(int argc, char ** argv) { #define ARGS_EXPECTED 9


char * directory ; int starting ; int ending ; char * prefix ; char * suffix ; int delay ; char * frame_mtype ; char * final ; char * final_mtype ; char filepath[MAX_SSIZE] ; struct itimerval timerval ; FILE * stdout_stream ; int step ; int display_frames ; int frame_no ; int fd ; char * final_path ; int directory_size ; char * filepath_format = "%s/%s%d%s" ; #define MIME_HEADER "Content-type: multipart/x-mixedreplace;boundary=ThisRandomString\r\n" /* Initialize globals. */ rmd_len = sprintf(rep_multipart_delimiter, "\r\n%s\r\n", MULTIPART_DELIMITER) ; fmd_len = sprintf(final_multipart_delimiter, "\r\n%s--\r\n", MULTIPART_DELIMITER) ; /* Get all the arguments. */ if ((directory = getenv("PATH_TRANSLATED")) == NULL) server_error("No PATH_TRANSLATED.") ; directory_size = strlen(directory) ; if (argc != ARGS_EXPECTED) { sprintf(error_mesg, "Wrong number of arguments to cgi program. \ Expected %d, got: %d", ARGS_EXPECTED, argc) ; server_error(error_mesg) ; } starting = atoi(argv[1]) ; ending = atoi(argv[2]) ;


prefix = argv[3] ; suffix = argv[4] ; delay = atoi(argv[5]) ; frame_mtype = argv[6] ; final = argv[7] ; final_mtype = argv[8] ; /* Check the arguments. */ /* The supplied paths cannot reference "../" */ legal_path(prefix, "Prefix") ; legal_path(suffix, "Suffix") ; legal_path(final, "Final") ; /* See that the supplied prefix and suffix won't overflow our buffers. */ if (strlen(filepath_format) + directory_size + strlen(prefix) + 10 + /* for decimal representation of frame_no */ strlen(suffix) > sizeof(filepath) - 1 /* for trailing \0 */ ) server_error("The filepath variable has overrun it's storage because the prefix and suffix are too long.") ; /* Check the length of the mime content type. (For send_frame.) */ if (strlen(CONTENT_TYPE) - 2 + /* for the %s */ strlen(frame_mtype) > sizeof(buf) - 1 /* for trailing \0 */ ) server_error("Buffer overrun, mime content type too long") ; /* See that the timer is not being used. */ if (getitimer(ITIMER_REAL, &timerval) || timerval.it_value.tv_sec || timerval.it_value.tv_usec) server_error("Real time timer already in use.") ; /* Get a stream pointer for stdout so we can flush it. */ stdout_stream = fdopen(STDOUT_FILENO, "a" ) ; if (stdout_stream == NULL) server_error("Unable to associate a stream with stdout.") ; if (strlen(final) != 0) { /* Make the Final argument relative to PATH_TRANSLATED, instead of cgi-bin. Construct the full pathname. (final_path) */ int final_path_size ;


int final_offset ; /* Allocate memory for the full pathname. */ final_path_size = directory_size + strlen(final) ; if (directory[directory_size] == '/') final_path_size += 1 ; final_path = (char *) malloc(final_path_size + 1) ; /* Construct full pathname. */ strcpy(final_path, directory) ; final_offset = directory_size ; if (directory[directory_size] != '/') { /* We need to add a / to delimit the end of the PATH_TRANSLATED. */ final_path[directory_size] = '/' ; final_offset += 1 ; } strcpy(final_path + final_offset, final) ; } /* Output the mime multipart header. */ if (write(STDOUT_FILENO, MIME_HEADER, strlen(MIME_HEADER)) == -1) /* This may produce trash if the header is partially output. */ server_error("Cannot output mime multipart header.") ; /* Start the frame display process with a multipart delimiter. */ if (write(STDOUT_FILENO, rep_multipart_delimiter, rmd_len) == -1) frame_error("Cannot write multipart delimiter") ; /* Go through each frame, displaying it. */ display_frames = abs(ending - starting) + 1 ; if ( starting <= ending ) step = 1 ; else step = -1 ; frame_no = starting ; while(1) { /* Open the file. */ sprintf(filepath, filepath_format, directory, prefix, frame_no, suffix ) ; fd = open(filepath, O_RDONLY) ; if (fd == -1) { sprintf(error_mesg, "Unable to open the graphic file for frame: %d", frame_no ) ;


frame_error(error_mesg) ; } /* Wait for the alarm, the reset it. */ delay_till_alarm (delay) ; /* Output the file. */ send_frame(fd, frame_mtype) ; /* Close the file. */ if (close(fd) == -1) { sprintf(error_mesg, "Unable to close the graphic file for frame: %d", frame_no ); frame_error(error_mesg) ; } /* Loop exit test. */ if (display_frames <= 1) break ; /* Output the mime-multipart delimiter to finish the frame. */ if (write(STDOUT_FILENO, rep_multipart_delimiter, rmd_len) == -1) frame_error("Cannot write multipart delimiter") ; /* Make sure that the output is sent. */ if (fflush(stdout_stream)) frame_error("Cannot flush stdout.") ; /* Prepare for next iteration. */ --display_frames ; frame_no = frame_no + step ; }; if (strlen(final) != 0) { /* There is a final frame. */ /* Output the mime-multipart delimiter to finish the previous frame. */ if (write(STDOUT_FILENO, rep_multipart_delimiter, rmd_len) == -1) frame_error("Cannot write multipart delimiter") ; /* Open the last frame. */ fd = open(final_path, O_RDONLY) ; if (fd == -1) frame_error("Unable to open the final frame.") ;


/* Clean up after what we did to setup the final frame. */ free(final_path) ; /* Wait for the alarm, then reset it. */ delay_till_alarm(delay) ; /* Output the last frame. */ send_frame(fd, final_mtype) ; } /* Finish frame outputting entirely. */ if (write(STDOUT_FILENO, final_multipart_delimiter, fmd_len) == -1) server_error("Cannot write final multipart delimiter.") ; /* Make sure that the output is sent. */ if (fflush(stdout_stream)) frame_error("Cannot flush stdout.") ; /* Cleanup The following is cleaned up by the OS when we exit. Close the file holding the final frame. Turn off real time timer. Reset signal handler to the default value. */ exit(EXIT_SUCCESS) ; }; void send_frame(int fvar, char * frame_mtype) { /* Sends a frame from the disk, the disk file is memory mapped. Input: fvar The file variable for the file. frame_mtype The mime type/subtype of the frame. */ struct stat file_status ; caddr_t memory_map ; /* Memory map the file. */ if (fstat(fvar, &file_status)) frame_error("send_frame: fstat called failed.") ; memory_map = mmap(NULL, file_status.st_size, PROT_READ,


MAP_PRIVATE | MAP_FILE, fvar, 0) ; if (memory_map == (caddr_t) -1) frame_error("send_frame: mmap call failed.") ; /* Build a mime content type header in the buf global. */ buf_len = sprintf(buf, CONTENT_TYPE, frame_mtype) ; /* Output the content type of the frame. */ if (write(STDOUT_FILENO, buf, buf_len) == -1) { /* Cannot call frame error because we may have already sent the content type. */ write(STDOUT_FILENO, final_multipart_delimiter, fmd_len) ; exit(-1) ; } /* Output the contents of the file. */ if(write(STDOUT_FILENO, (char *) memory_map, file_status.st_size) == -1) { /* Can't call frame error because we have already sent out the Mime content type. Just finish sending the frame and stop with an error exit. */ write(STDOUT_FILENO, final_multipart_delimiter, fmd_len) ; exit(-1) ; } munmap(memory_map, file_status.st_size) ; return ; }; void legal_path(char * path, char * argname) { /* Check to be sure that the path does not contain anything that would back it out of SERVER_ROOT. Right now this just checks for a ../ substring. */ if (strstr(path, "../") != NULL) { char * error_string ; error_string = "The '%s' argument's value (%s) contains the illegal '../' substring" ; if (strlen(error_string) - 2 - 2 + strlen(argname) + strlen(path) > sizeof(error_mesg) 1) /* The error message is too big. */ sprintf(error_mesg, "The '%s' argument's value contains the illegal '../' substring.", argname) ; else


sprintf(error_mesg, error_string, argname, path) ; server_error(error_mesg) ; } return ; }; void frame_error(char * mesg) { /* Handle a fatal error while outputting frames. */ printf("Content_type: text/html\r\n\r\n") ; printf("<h1>Animation Server Error</h1>") ; printf("This server encountered an error while attempting to display frames:") ; printf("%s", mesg) ; printf(final_multipart_delimiter) ; exit(-1) ; } void server_error(char * mesg) { /* Output a message and stop. */ printf("Content-type: text/html\r\n\r\n"); printf("<h1>Animation Server Error</h1>"); printf("This server encountered an error:<p>"); printf("%s", mesg); exit(-1); } void delay_till_alarm(int waitfor) { /* Wait until the alarm has gone off. Then reset it to go off in waitfor microseconds. Input: waitfor The number of micro seconds to wait before the alarm should go off again. */ static struct itimerval timer_control = { { /* it_interval */ 0, /* tv_sec */ 0}, /* tv_usec */ { /* it_value */ 0, /* tv_sec */ 0}} ; /* tv_usec */ static struct sigaction handler_control = { &alarm_handler, /* sa_handler */


0, /* sa_mask */ SA_NOMASK & SA_RESTART & SA_ONESHOT} ; /* sa_flags */ /* sa_restorer */ if (waitfor == 0) return ; if (! alarm_received) pause() ; /* The alarm has gone off, turn it back on. */ timer_control.it_value.tv_usec = waitfor ; if(setitimer(ITIMER_REAL, &timer_control, NULL)) frame_error("delay_till_alarm: failed called to setitimer.") ; /* Establish a handler for the alarm. */ if (sigaction(SIGALRM, &handler_control, NULL )) frame_error("delay_till_alarm: failed call to sigaction.") ; alarm_received = 0 ; return ; } void alarm_handler(int signal) { /* Remember whether the alarm went off. */ alarm_received = 1 ; return ;} A>Mandarino 10/2010 The Lifecycle of Meme

Meme have a life-cycle similar to parasites. During the transmission phase of the meme it is encoded in a vector, such as a spoken message, text, image, email, observed behaviour or slab of stone. When a potential host decodes the meme (reads the text, hears the message) the meme may become active and infects the person, who becomes a new host (the infection phase). At some point the meme is encoded in a suitable vector (not necessarily the same medium it was originally decoded from) and can be spread to infect new hosts. [For a complete model of the proposed Meme Cycle by A. Mandarino revieuw it @ issuu.com or National Library


File Transfer Protocol (FTP)


by Mr. Mandarino 5/5/5 File Transfer Protocol (FTP) FTP is a standard protocol with STD Number 9. Its status is recommended. It is described in RFC 959 - File Transfer Protocol (FTP). Copying files from one machine to another is one of the most frequently used operations. The data transfer between client and server can be in either direction. The client may send a file to the server machine. It may also request a file from this server. To access remote files, the user must identify himself to the server. At this point the server is responsible for authenticating the client before it allows the file transfer. From an FTP user's point of view, the link is connection-oriented. In other words, it is necessary to have both hosts up and running TCP/IP to establish a file transfer. Overview of FTP FTP uses TCP as a transport protocol to provide reliable end-to-end connections. Two connections are used: the first is for login and follows the TELNET protocol and the second is for managing the data transfer. As it is necessary to log into the remote host, the user must have a user name and a password to access files and directories. The user who initiates the connection assumes the client function, while the server function is provided by the remote host. On both sides of the link the FTP application is built with a protocol interpreter (PI), a data transfer process (DTP), and a user interface. The user interface communicates with the protocol interpreter, which is in charge of the control connection. This protocol interpreter has to communicate the necessary information to its own file system. On the opposite side of the link, the protocol interpreter, besides its function of responding to the TELNET protocol, has to initiate the data connection. During the file transfer, the data management is performed by DTPs. After a user's request is completed, the server's PI has to close the control connection. 4.4.2 FTP Operations When using FTP, the user will perform some or all of the following operations: • Connect to a remote host • Select a directory •

List files available for transfer

Define the transfer mode

Copy files to or from the remote host

Disconnect from the remote host

4.4.2.1 Connect to the Remote Host


To execute a file transfer, the user begins by logging into the remote host. This is the primary method of handling the security. The user must have a user ID and password for the remote host, unless using Anonymous FTP which is described in Anonymous FTP. There are three commands which are used: Open Selects the remote host and initiates the login session User Identifies the remote user ID Pass Authenticates the user Site Sends information to the foreign host that is used to provide services specific to that host 4.4.2.2 Select a Directory When the control link is established, the user may use the cd (change directory) subcommand to select a remote directory to work with. Obviously, user can only access directories for which the remote user ID has the appropriate authorization. The user may select a local directory with the lcd (local change directory) command. The syntax of theses commands depends upon the operating system in use. 4.4.2.3 List Files Available for Transfer This is done using the dir or ls subcommands. 4.4.2.4 Specifying the Transfer Mode Transferring data between dissimilar systems often requires transformations of the data as part of the transfer process. The user has to decide on two aspects of the data handling: • The way the bits will be moved from one place to another. • The different representations of data upon the system's architecture. This is controlled using two subcommands: Mode Specifies whether the file is to be treated as having a record structure in a byte stream format. Block Logical record boundaries of the file are preserved. Stream The file is treated as a byte stream. This is the default, and provides more efficient transfer but may not produce the desired results when working with a record-based file system. Type


Specifies the character sets used for the data. ASCII Indicates that both hosts are ASCII-based, or that if one is ASCII-based and the other is EBCDIC-based, that ASCII-EBCDIC translation should be performed. EBCDIC Indicates that both hosts use an EBCDIC data representation. Image Indicates that data is to be treated as contiguous bits packed in 8-bit bytes. Because these subcommands do not cover all possible differences between systems, the SITE subcommand is available to issue implementation-dependent commands. 4.4.2.5 Copy Files Get Copies a file from the remote host to the local host. Put Copies a file from the local host to the remote host. 4.4.2.6 End the Transfer Session Quit Disconnects from the remote host and terminates FTP. Some implementations use the BYE subcommand. Close Disconnects from the remote host but leaves the FTP client running. An open command may be issued to work with a new host. 4.4.3 Reply Codes In order to manage these operations, the client and server conduct a dialog using the TELNET convention. The client issues commands, and the server responds with reply codes. The responses also include comments for the benefit of the user, but the client program uses only the codes. Reply codes are three digits long, with the first digit being the most significant. Table: FTP Reply Codes - The second and third digits provide more details about the response. Example For each user command, shown like this, the FTP server responds with a message beginning with a 3-digit reply code, shown like this: FTP foreignhost 220 service ready USERNAME cms01


331 user name okay PASSWORD xyxyx 230 user logged in TYPE Image 200 command okay 4.4.4 FTP Scenario A LAN user has to transfer a file from his workstation to a system running VM. The file has to be transferred from his disk to the minidisk 191 owned by the CMS's user cms01. There is no Resource Access Control Facility (RACF) installed. The symbolic name corresponding to an Internet address is host01.itsc.raleigh.ibm.com. FTP Scenario 4.4.5 A Sample FTP Session [C:\SAMPLES]ftp host01.itsc.raleigh.ibm.com Connected to host01.itsc.raleigh.ibm.com. 220 host01 FTP server (Version 4.1 Sat Nov 23 12:52:09 CST 1991) ready. Name (rs60002): cms01 331 Password required for cms01. Password: xxxxxx 230 User cms01 logged in. ftp> put file01.tst file01.tst 200 PORT command successful. 150 Opening data connection for file01.tst (1252 bytes). 226 Transfer complete. local: file01.tst remote: file01.tst 1285 bytes received in 0.062 seconds (20 Kbytes/s) ftp> close 221 Goodbye. ftp> quit Figure: A Sample FTP Session - Transfer a file to a remote host 4.4.5.1 Anonymous FTP Many TCP/IP sites implement what is known as anonymous FTP, which means that these sites allow public access to some file directories. The remote user only needs to use the login name anonymous and password guest or some other common password conventions, for example the user's Internet E-mail ID. The password convention used on a system is explained to the user during the login process.


4.4.6 Implementations 4.4.6.1 VM TCP/IP for VM is implemented with server and client functions of FTP. This implementation provides you with most of the capabilities useful for file transfer. Please refer to IBM TCP/IP Version 2 Release 3 for VM: User's Guide for a list of the subcommands that may be used. The file transfer process can be automated using the EXEC interface which allows you to read the FTP subcommands from a file (using the FILEDEF command) or from the program stack. By default, the results of your FTP dialog are printed on your terminal. A file may be defined as the output device for the FTP dialog using the FILEDEF command, in which case the dialog output is placed in the file rather than typed on the console. Please refer to the IBM TCP/IP Version 2 Release 3 for VM: User's Guide for more information about the EXEC interface. While in an FTP session you can issue CMS commands on your local (client) VM system. The Resource Access Control Facility (RACF) allows FTP servers to act as surrogates for other user IDs. This means that the FTP server can access those disks available to that user ID (the one entered during the logon procedure). Please refer to IBM TCP/IP Version 2 Release 3 for VM: Planning and Customization for more information about RACF considerations. 4.4.6.2 MVS TCP/IP for MVS is implemented with both server and client functions of FTP. This implementation provides you with most of the capabilities useful for file transfer. Please refer to IBM TCP/IP Version 3 Release 1 for MVS: User's Guide for a list of the subcommands that may be used. There are two FTP servers available in MVS: • The old Pascal-based FTP server (module FTPSERVE) • The new C-based FTP server (module EZAFTSRV), which is recommended The C FTP Server provides an FTP server specifically designed for MVS TCP/IP. In addition to providing all the functions found in the Pascal-based FTP server (except RDW), C FTP Server uses native MVS file interfaces; has a structured design; takes advantage of MP support, reducing the need for multiple servers; improves the RAS characteristics for FTP server; adds struct-r support; provides delete/catalog options if file transfer fails. The C FTP Server is available in an MVS/ESA environment only. The C FTP Server will be the basis for future enhancements of the FTP server. No enhancements are planned for the Pascal server in further releases. SQL Query to DB2 MVS FTP also supports the DATABASE 2 (DB2) SQL query function. Only the SELECT DML operation is supported. That is, other DML (INSERT, UPDATE or DELETE) and


DDL operations are not supported. The SQL query may be submitted to a DB2 subsystem at either the local or the remote site, as illustrated below: 1. put (submit) a local file containing an SQL query to any DB2 subsystem at the remote MVS FTP server and get (retrieve) the SQL query results in a file from the remote MVS FTP server 2. put a local file containing an SQL query to any DB2 subsystem at the local MVS FTP client; upon completion of the query operation, the local MVS FTP client will transfer the SQL query output file to the remote FTP server The site and locsite FTP subcommands are used to switch the filetype to sql and to identify the name of the DB2 subsystem. Please refer to IBM TCP/IP Version 3 Release 1 for MVS: User's Guide for the syntax of these FTP subcommands. An FTP installation may also have the flexibility of defining the following user security exits: Check IP and PORT Addresses, Check USER and PASSWORD, Check the Command, and Check use of JES. The FTP server also provides user accounting and control information using the MVS SMF (System Management Facility) records. For example, client identity, IP addresses, used commands and failed logon attempts can be recorded. IBM TCP/IP for MVS uses SMF record type 118 for all SMF records. The file transfer process can be automated using the EXEC interface that allows you to read the FTP subcommands from a disk (ALLOC DA(FTPIN) DD(INPUT) SHR REU) or from a program stack (QUEUE command). As the default, the results of your FTP dialog are printed on your terminal. If a disk file is defined as the output device (ALLOC DA(FTPOUT) DD(OUTPUT) SHR REU ), the dialog results go into the file. Please refer to the IBM TCP/IP Version 3 Release 1 for MVS: User's Guide for more information about the EXEC interface. You can also run FTP as a batch job, but you must supply the JCL and submit it as a job with TSO job submission facility. While in an FTP session you can issue TSO commands on your local (client) MVS system. Job Submission via JES The MVS FTP server allows you to interface with MVS Job Entry System (JES). First an FTP session must be established between the client and the FTP MVS server (The SET FILETYPE=JES command activates the JES interface). The FTP server provides four functions in its JES interface: 1. Submit a job. The JCL is created on the client and sent to the MVS server using FTP. 2. Display the status of all the user's jobs. 3. Receive the spool output of the job (JCL messages and SYSOUT). Automatic return of JES output to the FTP client is possible. 4. Delete a job. Please refer to IBM TCP/IP Version 3 Release 1 for MVS: Customization and Administration Guide for more information about the JES interface.


Special SITE parameters for transferring files between two MVS systems •

Data Compression as defined in RFC 959 Data is transmitted in a compressed format.

Checkpoint and Restart as defined in RFC 959

Both the block and the compressed transfer mode supports checkpoint/restart. When checkpointing is used, the sending side inserts checkpoint markers into the data being transmitted. Now assume that your connection breaks down in the middle of the transfer of a large file. All you have to do now is to start the FTP client again, reconnect to the server, reestablish your mode and type settings, and issue the restart command. 4.4.6.3 OS/400 Both the FTP client and server functions are supported in OS/400. FTP supports the following functions: • Creating libraries, files, and members using the OS/400 FTP server subcommands. Since the FTP protocol limits remote FTP server subcommand names to 4 characters or less, the OS/400 FTP server supports abbreviated AS/400 CL commands. For example, CRTL is the abbreviated subcommand for CRTLIB • •

Using ASCII and EBCDIC mapping tables for AS/400 servers and FTP clients to map incoming and outgoing data. Running FTP unattended in batch mode by using either a REXX EXEC or a CL program.

Submitting and accepting remote CL commands.

Transferring binary files without changes.

Sending document files in EBCDIC format or translating them to ASCII (the default format).

Converting double-byte character set (DBCS) data from AS/400 EBCDIC code pages to and from internet ASCII code pages.

Sending or receiving physical files, source files, logical files, save files, hierarchical file system files (HFS), including Client Access/400 files and document library object (DLO) files.

Sending or receiving files greater than 16 million bytes.


The FTP client can be started with the FTP or the STRCPFTP command. OS/400 files must be specified in the following format (otherwise, the default may not be the name you expect or want): {Libraryname/}Filename.membername 4.4.6.4 AIX/6000 AIX/6000 provides a full implementation of FTP. It supports the standard set of subcommands with the addition of NLIST, RSTATUS, RHELP, SIZE and SYSTEM. Both the client and server functions are supported, via the ftp and the ftpd programs, respectively. The ftpd server (also known as a daemon) is a subserver controlled by the inetd subsystem (also known as the super daemon). The $HOME/.netrc file can be used to specify automatic login information for the user ID and password to use at the foreign host. Since this file is not encrypted, the automatic login feature is not available when your AIX system has been configured with the securetcpip command. The rcp command and the rshd server (daemon) can be used to transfer files between AIX systems. They provide two additional features: copying file attributes and copying recursively subdirectory files. Since rcp and rshd do not provide a secure environment for transferring files, they are disabled by running the securetcpip command. The securetcpip command is used to enable additional security environments by disabling commands that are not trusted. For more information about the securetcpip command, please refer to AIX Version 3.2 for RISC System/6000 Communication Concepts and Procedures. 4.4.6.5 AIX/ESA Both the FTP client and server functions are provided in AIX/ESA. In addition, the rcp command may also be used, if your local system is listed in the /etc/hosts.equiv file on the remote system; or, your system and your user name are listed in the .rhosts file in your home directory on the remote system. Note: Any copy operation is subject to the AIX/ESA security features in effect. For more details, please refer to AIX/ESA Security Features User's Guide. 4.4.6.6 OS/2 TCP/IP for OS/2 implements both the client and server functions of FTP. Two files are used by the FTP to enable or automate various functions. These files are: • TRUSERS - Used by the FTP server to define access authorization to users on the foreign host. You can assign user IDs, passwords, and authority (read or write) on a directory basis. Here is an example of a TRUSERS file: user: mandarino:


• • • • • •

d:\ wr: d:\tmp

Where:

user: meme matt wr^: c:\etc

o

mandarino is the user ID

o

adm is his password

o

rd: d:\ allows ADM to read any file whose access path begins with d:\.

o

wr: d:\tmp allows ADM to write into any file whose access path begins with d:\tmp.

o

meme is the user ID

o

matt is her password

o

wr^: c:\etc gives Meme access to read or write to any file except those whose access path begin with c:\etc.

NETRC - Used by FTP clients as a source for user ID and password values and macros (the init macro is the one that executes when the session is established).

Here is an example of NETRC file: machine fsc5 login debulois password xxxxxx macdef init pwd macdef go lcd c:\work binary hash put meme.meme matt.matt machine reso login debulois password yyyyyyy macdef init pwd When the command FTP fsc5 is issued the following sequence takes place: 1. The NETRC file is read from the line machine fsc5 2. The password and user ID are transmitted to the server 3. The init macro is executed (that is, the pwd FTP subcommand is executed) and control is returned to the keyboard 4. The go macro can be executed under the FTP command prompt.


The FTP -n fsc5 command allows you to log on to the host named fsc5 without reading the NETRC file. These two files can be hidden by the File Manager and their location can be customized. A Presentation Manager FTP client application is also provided (FTPPM). The FTP server can be initiated by the INETD super server or by the ftpd command. The High Performance File System (HPFS) is supported. TCP/IP for OS/2 also includes an API that allows applications to have a client interface for file transfer. Applications written to this interface can communicate with multiple FTP servers at the same time (256 connections maximum). The interface also allows thirdparty proxy transfers between pairs of FTP servers. In addition to the FTP specific API calls, a ping() call is included to allow the application to determine whether the remote host is alive before attempting FTP transfers. The programs may be compiled and linked using the IBM C-Set/2 32-bit compiler or alternatively, the Microsoft C Compiler Version 6.0A. The REXX FTP Application Program Interface (API) package, which is provided in the TCP/IP V2.0 for OS/2 Base Kit, provides access to the OS/2 TCP/IP FTP APIs. The REXX FTP API function names are similar to the FTP subcommands. 4.4.6.7 DOS TCP/IP for DOS implements both the client and server functions of FTP. In particular, a DOS-based FTP server and client are provided as well as a Windows-based FTP client. The FTP server function is implemented as a dedicated, foreground process and can support multiple concurrent FTP client sessions. It supports DOS wild card characters for multiple file transfers. Its security function is similar to that of the OS/2 implementation of a trusted users file named TRUSERS. Once in the FTP command shell (ftp>) you can (basic FTP subcommands not included): • Enter DOS command with the ! subcommand • Reserve space on the host to accommodate the file to be transferred with the allocate subcommand •

Transfer a single file from a host and append it to a file on your PC with the getappend subcommand

Read the FTP subcommands from a file on your PC with the take subcommand

Inform the FTP server that your byte-size is eight bits with the tenex subcommand

A file transfer from TCP/IP for DOS can be automated using a command file with the ftp -f command_file command. TCP/IP for DOS also includes an API which allows applications to have a client interface for file transfer. Applications written to this interface can communicate with multiple FTP servers at the same time (256 connections maximum). The interface also allows third-party proxy transfers between pairs of FTP servers. In addition to the FTP


specific API calls, a ping() call is included to allow the application to determine whether the remote host is alive before attempting FTP transfers. Sincerely, Mr. Mandarino, Instructor

Introduction to objects, images, and applets by ADM 02/08 HTML's multimedia features allow authors to include images, applets (programs that are automatically downloaded and run on the user's machine), video clips, and other HTML documents in their pages. For example, to include a PNG image in a document, authors may write: <BODY> <P>Here's a closeup of the Grand Canyon: <OBJECT data="canyon.png" type="image/png"> This is a <EM>closeup</EM> of the Grand Canyon. </OBJECT> </BODY> Previous versions of HTML allowed authors to include images (via IMG) and applets (via APPLET). These elements have several limitations: They fail to solve the more general problem of how to include new and future media


types. The APPLET element only works with Java-based applets. This element is deprecated in favor of OBJECT. They pose accessibility problems. To address these issues, HTML 4 introduces the OBJECT element, which offers an allpurpose solution to generic object inclusion. The OBJECT element allows HTML authors to specify everything required by an object for its presentation by a user agent: source code, initial values, and run-time data. In this specification, the term "object" is used to describe the things that people want to place in HTML documents; other commonly used terms for these things are: applets, plug-ins, media handlers, etc. The new OBJECT element thus subsumes some of the tasks carried out by existing elements. Consider the following chart of functionalities: Type of inclusion Specific element Generic element Image IMG OBJECT Applet APPLET (Deprecated.) OBJECT Another HTML document IFRAME OBJECT The chart indicates that each type of inclusion has a specific and a general solution. The generic OBJECT element will serve as the solution for implementing future media types. To include images, authors may use the OBJECT element or the IMG element. To include applets, authors should use the OBJECT element as the APPLET element is deprecated. To include one HTML document in another, authors may use either the new IFRAME element or the OBJECT element. In both cases, the embedded document remains independent of the main document. Visual user agents may present the embedded document in a distinct window within the main document. Please consult the notes on embedded documents for a comparison of OBJECT and IFRAME for document inclusion. Images and other included objects may have hyperlinks associated with them, both through the standard linking mechanisms, but also via image maps. An image map specifies active geometric regions of an included object and assigns a link to each region. When activated, these links may cause a document to be retrieved, may run a program on the server, etc. In the following sections, we discuss the various mechanisms available to authors for multimedia inclusions and creating image maps for those inclusions. 13.2 Including an image: the IMG element


<!-- To avoid problems with text-only UAs as well as to make image content understandable and navigable to users of non-visual UAs, you need to provide a description with ALT, and avoid server-side image maps --> <!ELEMENT IMG - O EMPTY -- Embedded image --> <!ATTLIST IMG %attrs; -- %coreattrs, %i18n, %events -src %URI; #REQUIRED -- URI of image to embed -alt %Text; #REQUIRED -- short description -longdesc %URI; #IMPLIED -- link to long description (complements alt) -name CDATA #IMPLIED -- name of image for scripting -height %Length; #IMPLIED -- override height -width %Length; #IMPLIED -- override width -usemap %URI; #IMPLIED -- use client-side image map -ismap (ismap) #IMPLIED -- use server-side image map -> Start tag: required, End tag: forbidden Attribute definitions src = uri [CT] This attribute specifies the location of the image resource. Examples of widely recognized image formats include GIF, JPEG, and PNG. longdesc = uri [CT] This attribute specifies a link to a long description of the image. This description should supplement the short description provided using the alt attribute. When the image has an associated image map, this attribute should provide information about the image map's contents. This is particularly important for server-side image maps. Since an IMG element may be within the content of an A element, the user agent's mechanism in the user interface for accessing the "longdesc" resource of the former must be different than the mechanism for accessing the href resource of the latter. name = cdata [CI] This attribute names the element so that it may be referred to from style sheets or scripts. Note. This attribute has been included for backwards compatibility. Applications should use the id attribute to identify elements. Attributes defined elsewhere id, class (document-wide identifiers) alt (alternate text) lang (language information), dir (text direction) title (element title) style (inline style information) onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup (intrinsic events) ismap, usemap (client side image maps)


align, width, height, border, hspace, vspace (visual presentation of objects, images, and applets) The IMG element embeds an image in the current document at the location of the element's definition. The IMG element has no content; it is usually replaced inline by the image designated by the src attribute, the exception being for left or right-aligned images that are "floated" out of line. In an earlier example, we defined a link to a family photo. Here, we insert the photo directly into the current document: <BODY> <P>I just returned from vacation! Here's a photo of my family at the lake: <IMG alt="A photo of my family at the lake."> </BODY> This inclusion may also be achieved with the OBJECT element as follows: <BODY> <P>I just returned from vacation! Here's a photo of my family at the lake: <OBJECT data=http://www.somecompany.com/People/Ian/vacation/family.png type="image/png"> A photo of my family at the lake. </OBJECT> </BODY> The alt attribute specifies alternate text that is rendered when the image cannot be displayed (see below for information on how to specify alternate text ). User agents must render alternate text when they cannot support images, they cannot support a certain image type or when they are configured not to display images. The following example shows how the longdesc attribute can be used to link to a richer description: <BODY> <P> <IMG src="sitemap.gif" alt="HP Labs Site Map" longdesc="sitemap.html"> </BODY> The alt attribute provides a short description of the image. This should be sufficient to allow users to decide whether they want to follow the link given by the longdesc attribute to the longer description, here "sitemap.html". Please consult the section on the visual presentation of objects, images, and applets for information about image size, alignment, and borders. 13.3 Generic inclusion: the OBJECT element


<!ELEMENT OBJECT - - (PARAM | %flow;)* -- generic embedded object --> <!ATTLIST OBJECT %attrs; -- %coreattrs, %i18n, %events -declare (declare) #IMPLIED -- declare but don't instantiate flag -classid %URI; #IMPLIED -- identifies an implementation -codebase %URI; #IMPLIED -- base URI for classid, data, archive-data %URI; #IMPLIED -- reference to object's data -type %ContentType; #IMPLIED -- content type for data -codetype %ContentType; #IMPLIED -- content type for code -archive CDATA #IMPLIED -- space-separated list of URIs -standby %Text; #IMPLIED -- message to show while loading -height %Length; #IMPLIED -- override height -width %Length; #IMPLIED -- override width -usemap %URI; #IMPLIED -- use client-side image map -name CDATA #IMPLIED -- submit as part of form -tabindex NUMBER #IMPLIED -- position in tabbing order -> Start tag: required, End tag: required Attribute definitions classid = uri [CT] This attribute may be used to specify the location of an object's implementation via a URI. It may be used together with, or as an alternative to the data attribute, depending on the type of object involved. codebase = uri [CT] This attribute specifies the base path used to resolve relative URIs specified by the classid, data, and archive attributes. When absent, its default value is the base URI of the current document. codetype = content-type [CI] This attribute specifies the content type of data expected when downloading the object specified by classid. This attribute is optional but recommended when classid is specified since it allows the user agent to avoid loading information for unsupported content types. When absent, it defaults to the value of the type attribute. data = uri [CT] This attribute may be used to specify the location of the object's data, for instance image data for objects defining images, or more generally, a serialized form of an object which can be used to recreate it. If given as a relative URI, it should be interpreted relative to the codebase attribute. type = content-type [CI] This attribute specifies the content type for the data specified by data. This attribute is optional but recommended when data is specified since it allows the user agent to avoid loading information for unsupported content types. If the value of this attribute differs


from the HTTP Content-Type returned by the server when the object is retrieved, the HTTP Content-Type takes precedence. archive = uri-list [CT] This attribute may be used to specify a space-separated list of URIs for archives containing resources relevant to the object, which may include the resources specified by the classid and data attributes. Preloading archives will generally result in reduced load times for objects. Archives specified as relative URIs should be interpreted relative to the codebase attribute. declare [CI] When present, this boolean attribute makes the current OBJECT definition a declaration only. The object must be instantiated by a subsequent OBJECT definition referring to this declaration. standby = text [CS] This attribute specifies a message that a user agent may render while loading the object's implementation and data. Attributes defined elsewhere id, class (document-wide identifiers) lang (language information), dir (text direction) title (element title) style (inline style information) onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup (intrinsic events) tabindex (tabbing navigation) usemap (client side image maps) name (form submission) align, width, height, border, hspace, vspace (visual presentation of objects, images, and applets) Most user agents have built-in mechanisms for rendering common data types such as text, GIF images, colors, fonts, and a handful of graphic elements. To render data types they don't support natively, user agents generally run external applications. The OBJECT element allows authors to control whether data should be rendered externally or by some program, specified by the author, that renders the data within the user agent. In the most general case, an author may need to specify three types of information: The implementation of the included object. For instance, if the included object is a clock applet, the author must indicate the location of the applet's executable code. The data to be rendered. For instance, if the included object is a program that renders font data, the author must indicate the location of that data. Additional values required by the object at run-time. For example, some applets may require initial values for parameters. The OBJECT element allows authors to specify all three types of data, but authors may not have to specify all three at once. For example, some objects may not require data (e.g., a self-contained applet that performs a small animation). Others may not require


run-time initialization. Still others may not require additional implementation information, i.e., the user agent itself may already know how to render that type of data (e.g., GIF images). Authors specify an object's implementation and the location of the data to be rendered via the OBJECT element. To specify run-time values, however, authors use the PARAM element, which is discussed in the section on object initialization. The OBJECT element may also appear in the content of the HEAD element. Since user agents generally do not render elements in the HEAD, authors should ensure that any OBJECT elements in the HEAD do not specify content that may be rendered. Please consult the section on sharing frame data for an example of including the OBJECT element in the HEAD element. Please consult the section on form controls for information about OBJECT elements in forms. This document does not specify the behavior of OBJECT elements that use both the classid attribute to identify an implementation and the data attribute to specify data for that implementation. In order to ensure portability, authors should use the PARAM element to tell implementations where to retrieve additional data. 13.3.1 Rules for rendering objects A user agent must interpret an OBJECT element according to the following precedence rules: The user agent must first try to render the object. It should not render the element's contents, but it must examine them in case the element contains any direct children that are PARAM elements (see object initialization) or MAP elements (see client-side image maps). If the user agent is not able to render the object for whatever reason (configured not to, lack of resources, wrong architecture, etc.), it must try to render its contents. Authors should not include content in OBJECT elements that appear in the HEAD element. In the following example, we insert an analog clock applet in a document via the OBJECT element. The applet, written in the Python language, requires no additional data or run-time values. The classid attribute specifies the location of the applet: <P><OBJECT classid=http://www.miamachina.it/analogclock.py> </OBJECT> Note that the clock will be rendered as soon as the user agent interprets this OBJECT declaration. It is possible to delay rendering of an object by first declaring the object (described below).


Authors should complete this declaration by including alternate text as the contents of OBJECT in case the user agent cannot render the clock. <P><OBJECT classid=An animated clock. </OBJECT> One significant consequence of the OBJECT element's design is that it offers a mechanism for specifying alternate object renderings; each embedded OBJECT declaration may specify alternate content types. If a user agent cannot render the outermost OBJECT, it tries to render the contents, which may be another OBJECT element, etc. In the following example, we embed several OBJECT declarations to illustrate how alternate renderings work. A user agent will attempt to render the first OBJECT element it can, in the following order: (1) an Earth applet written in the Python language, (2) an MPEG animation of the Earth, (3) a GIF image of the Earth, (4) alternate text. <P> <!-- First, try the Python applet --> <OBJECT title="The Earth as seen from space" classid=" <!-- Else, try the MPEG video --> <OBJECT data="TheEarth.mpeg" type="application/mpeg"> <!-- Else, try the GIF image --> <OBJECT data="TheEarth.gif" type="image/gif"> <!-- Else render the text --> The <STRONG>Earth</STRONG> as seen from space. </OBJECT> </OBJECT> </OBJECT> The outermost declaration specifies an applet that requires no data or initial values. The second declaration specifies an MPEG animation and, since it does not define the location of an implementation to handle MPEG, relies on the user agent to handle the animation. We also set the type attribute so that a user agent that knows it cannot render MPEG will not bother to retrieve "TheEarth.mpeg" from the network. The third declaration specifies the location of a GIF file and furnishes alternate text in case all other mechanisms fail. Inline vs. external data. Data to be rendered may be supplied in two ways: inline and from an external resource. While the former method will generally lead to faster rendering, it is not convenient when rendering large quantities of data. Here's an example that illustrates how inline data may be fed to an OBJECT: <P> <OBJECT id="clock1" classid="clsid:663C8FEF-1EF9-11CF-A3DB-080036F12502"


data="data:application/x-oleobject;base64, ...base64 data..."> A clock. </OBJECT> Please consult the section on the visual presentation of objects, images, and applets for information about object size, alignment, and borders. 13.3.2 Object initialization: the PARAM element <!ELEMENT PARAM - O EMPTY -- named property value --> <!ATTLIST PARAM id ID #IMPLIED -- document-wide unique id -name CDATA #REQUIRED -- property name -value CDATA #IMPLIED -- property value -valuetype (DATA|REF|OBJECT) DATA -- How to interpret value -type %ContentType; #IMPLIED -- content type for value when valuetype=ref -> Start tag: required, End tag: forbidden Attribute definitions name = cdata This attribute defines the name of a run-time parameter, assumed to be known by the inserted object. Whether the property name is case-sensitive depends on the specific object implementation. value = cdata This attribute specifies the value of a run-time parameter specified by name. Property values have no meaning to HTML; their meaning is determined by the object in question. valuetype = data|ref|object [CI] This attribute specifies the type of the value attribute. Possible values: data: This is default value for the attribute. It means that the value specified by value will be evaluated and passed to the object's implementation as a string. ref: The value specified by value is a URI that designates a resource where run-time values are stored. This allows support tools to identify URIs given as parameters. The URI must be passed to the object as is, i.e., unresolved. object: The value specified by value is an identifier that refers to an OBJECT declaration in the same document. The identifier must be the value of the id attribute set for the declared OBJECT element. type = content-type [CI] This attribute specifies the content type of the resource designated by the value attribute only in the case where valuetype is set to "ref". This attribute thus specifies for the user agent, the type of values that will be found at the URI designated by value. Attributes defined elsewhere


id (document-wide identifiers) PARAM elements specify a set of values that may be required by an object at run-time. Any number of PARAM elements may appear in the content of an OBJECT or APPLET element, in any order, but must be placed at the start of the content of the enclosing OBJECT or APPLET element. The syntax of names and values is assumed to be understood by the object's implementation. This document does not specify how user agents should retrieve name/value pairs nor how they should interpret parameter names that appear twice. We return to the clock example to illustrate the use of PARAM: suppose that the applet is able to handle two run-time parameters that define its initial height and width. We can set the initial dimensions to 40x40 pixels with two PARAM elements. <P><OBJECT classid=""> <PARAM name="height" value="40" valuetype="data"> <PARAM name="width" value="40" valuetype="data"> This user agent cannot render Python applications. </OBJECT> In the following example, run-time data for the object's "Init_values" parameter is specified as an external resource (a GIF file). The value of the valuetype attribute is thus set to "ref" and the value is a URI designating the resource. <P><OBJECT classid="" standby="Loading Elvis..."> <PARAM name="Init_values" value="./images/elvis.gif"> valuetype="ref"> </OBJECT> Note that we have also set the standby attribute so that the user agent may display a message while the rendering mechanism loads. When an OBJECT element is rendered, user agents must search the content for only those PARAM elements that are direct children and "feed" them to the OBJECT. Thus, in the following example, if "obj1" is rendered, "param1" applies to "obj1" (and not "obj2"). If "obj1" is not rendered and "obj2" is, "param1" is ignored, and "param2" applies to "obj2". If neither OBJECT is rendered, neither PARAM applies. <P> <OBJECT id="obj1"> <PARAM name="param1"> <OBJECT id="obj2"> <PARAM name="param2"> </OBJECT>


</OBJECT> 13.3.3 Global naming schemes for objects The location of an object's implementation is given by a URI. As we discussed in the introduction to URIs, the first segment of an absolute URI specifies the naming scheme used to transfer the data designated by the URI. For HTML documents, this scheme is frequently "http". Some applets might employ other naming schemes. For instance, when specifying a Java applet, authors may use URIs that begin with "java" and for ActiveX applets, authors may use "clsid". In the following example, we insert a Java applet into an HTML document. <P><OBJECT classid="java:program.start"> </OBJECT> By setting the codetype attribute, a user agent can decide whether to retrieve the Java application based on its ability to do so. <OBJECT codetype="application/java-archive" classid="java:program.start"> </OBJECT> Some rendering schemes require additional information to identify their implementation and must be told where to find that information. Authors may give path information to the object's implementation via the codebase attribute. <OBJECT codetype="application/java-archive" classid="java:program.start"> codebase="/" </OBJECT> The following example specifies (with the classid attribute) an ActiveX object via a URI that begins with the naming scheme "clsid". The data attribute locates the data to render (another clock). <P><OBJECT classid="clsid:663C8FEF-1EF9-11CF-A3DB-080036F12502" data=" This application is not supported. </OBJECT> 13.3.4 Object declarations and instantiations The preceding examples have only illustrated isolated object definitions. When a document is to contain more than one instance of the same object, it is possible to separate the declaration of the object from its instantiations. Doing so has several advantages: Data may be retrieved from the network by the user agent one time (during the declaration) and reused for each instantiation. It is possible to instantiate an object from a location other than the object's declaration, for example, from a link.


It is possible to specify objects as run-time data for other objects. To declare an object so that it is not executed when read by the user agent, set the boolean declare attribute in the OBJECT element. At the same time, authors must identify the declaration by setting the id attribute in the OBJECT element to a unique value. Later instantiations of the object will refer to this identifier. A declared OBJECT must appear in a document before the first instance of that OBJECT. An object defined with the declare attribute is instantiated every time an element that refers to that object requires it to be rendered (e.g., a link that refers to it is activated, an object that refers to it is activated, etc.). In the following example, we declare an OBJECT and cause it to be instantiated by referring to it from a link. Thus, the object can be activated by clicking on some highlighted text, for example. <P><OBJECT declare id="earth.declaration" data="TheEarth.mpeg" type="application/mpeg"> The <STRONG>Earth</STRONG> as seen from space. </OBJECT> ...later in the document... <P>A neat <A href="#earth.declaration"> animation of The Earth!</A> The following example illustrates how to specify run-time values that are other objects. In this example, we send text (a poem, in fact) to a hypothetical mechanism for viewing poems. The object recognizes a run-time parameter named "font" (say, for rendering the poem text in a certain font). The value for this parameter is itself an object that inserts (but does not render) the font object. The relationship between the font object and the poem viewer object is achieved by (1) assigning the id "tribune" to the font object declaration and (2) referring to it from the PARAM element of the poem viewer object (with valuetype and value). <P><OBJECT declare id="tribune" type="application/x-webfont" data="tribune.gif"> </OBJECT> ...view the poem in KublaKhan.txt here... <P><OBJECT classid="" data="KublaKhan.txt"> <PARAM name="font" valuetype="object" value="#tribune"> <P>You're missing a really cool poem viewer ... </OBJECT> User agents that don't support the declare attribute must render the contents of the


OBJECT declaration. 13.4 Including an applet: the APPLET element APPLET is deprecated (with all its attributes) in favor of OBJECT. See the Transitional DTD for the formal definition. Attribute definitions codebase = uri [CT] This attribute specifies the base URI for the applet. If this attribute is not specified, then it defaults the same base URI as for the current document. Values for this attribute may only refer to subdirectories of the directory containing the current document. Note. While the restriction on subdirectories is a departure from common practice and the HTML 3.2 specification, the HTML Working Group has chosen to leave the restriction in this version of the specification for security reasons. code = cdata [CS] This attribute specifies either the name of the class file that contains the applet's compiled applet subclass or the path to get the class, including the class file itself. It is interpreted with respect to the applet's codebase. One of code or object must be present. name = cdata [CS] This attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other. archive = uri-list [CT] This attribute specifies a comma-separated list of URIs for archives containing classes and other resources that will be "preloaded". The classes are loaded using an instance of an AppletClassLoader with the given codebase. Relative URIs for archives are interpreted with respect to the applet's codebase. Preloading resources can significantly improve the performance of applets. object = cdata [CS] This attribute names a resource containing a serialized representation of an applet's state. It is interpreted relative to the applet's codebase. The serialized data contains the applet's class name but not the implementation. The class name is used to retrieve the implementation from a class file or archive. When the applet is "deserialized" the start() method is invoked but not the init() method. Attributes valid when the original object was serialized are not restored. Any attributes passed to this APPLET instance will be available to the applet. Authors should use this feature with extreme caution. An applet should be stopped before it is serialized. Either code or object must be present. If both code and object are given, it is an error if they provide different class names. width = length [CI] This attribute specifies the initial width of the applet's display area (excluding any windows or dialogs that the applet creates).


height = length [CI] This attribute specifies the initial height of the applet's display area (excluding any windows or dialogs that the applet creates). Attributes defined elsewhere id, class (document-wide identifiers) title (element title) style (inline style information) alt (alternate text) align, hspace, vspace (visual presentation of objects, images, and applets) This element, supported by all Java-enabled browsers, allows designers to embed a Java applet in an HTML document. It has been deprecated in favor of the OBJECT element. The content of the APPLET acts as alternate information for user agents that don't support this element or are currently configured not to support applets. User agents must ignore the content otherwise. DEPRECATED EXAMPLE: In the following example, the APPLET element includes a Java applet in the document. Since no codebase is supplied, the applet is assumed to be in the same directory as the current document. <APPLET code="Bubbles.class" width="500" height="500"> Java applet that draws animated bubbles. </APPLET> This example may be rewritten with OBJECT as follows: <P><OBJECT codetype="application/java" classid="java:Bubbles.class" width="500" height="500"> Java applet that draws animated bubbles. </OBJECT> Initial values may be supplied to the applet via the PARAM element. DEPRECATED EXAMPLE: The following sample Java applet: <APPLET code="AudioItem" width="15" height="15"> <PARAM name="snd" value="Hello.au|Welcome.au"> Java applet that plays a welcoming sound. </APPLET> may be rewritten as follows with OBJECT: <OBJECT codetype="application/java" classid="AudioItem"


width="15" height="15"> <PARAM name="snd" value="Hello.au|Welcome.au"> Java applet that plays a welcoming sound. </OBJECT> 13.5 Notes on embedded documents Sometimes, rather than linking to a document, an author may want to embed it directly into a primary HTML document. Authors may use either the IFRAME element or the OBJECT element for this purpose, but the elements differ in some ways. Not only do the two elements have different content models, the IFRAME element may be a target frame (see the section on specifying target frame information for details) and may be "selected" by a user agent as the focus for printing, viewing HTML source, etc. User agents may render selected frames elements in ways that distinguish them from unselected frames (e.g., by drawing a border around the selected frame). An embedded document is entirely independent of the document in which it is embedded. For instance, relative URIs within the embedded document resolve according to the base URI of the embedded document, not that of the main document. An embedded document is only rendered within another document (e.g., in a subwindow); it remains otherwise independent. For instance, the following line embeds the contents of embed_me.html at the location where the OBJECT definition occurs. ...text before... <OBJECT data="embed_me.html"> Warning: embed_me.html could not be embedded. </OBJECT> ...text after... Recall that the contents of OBJECT must only be rendered if the file specified by the data attribute cannot be loaded. The behavior of a user agent in cases where a file includes itself is not defined. 13.6 Image maps Image maps allow authors to specify regions of an image or object and assign a specific action to each region (e.g., retrieve a document, run a program, etc.) When the region is activated by the user, the action is executed. An image map is created by associating an object with a specification of sensitive geometric areas on the object. There are two types of image maps: Client-side. When a user activates a region of a client-side image map with a mouse, the pixel coordinates are interpreted by the user agent. The user agent selects a link that was specified for the activated region and follows it.


Server-side. When a user activates a region of a server-side image map with a mouse, the pixel coordinates of the click are sent to the server-side agent specified by the href attribute of the A element. The server-side agent interprets the coordinates and performs some action. Client-side image maps are preferred over server-side image maps for at least two reasons: they are accessible to people browsing with non-graphical user agents and they offer immediate feedback as to whether or not the pointer is over an active region. 13.6.1 Client-side image maps: the MAP and AREA elements <!ELEMENT MAP - - ((%block;) | AREA)+ -- client-side image map --> <!ATTLIST MAP %attrs; -- %coreattrs, %i18n, %events -name CDATA #REQUIRED -- for reference by usemap -> Start tag: required, End tag: required <!ELEMENT AREA - O EMPTY -- client-side image map area --> <!ATTLIST AREA %attrs; -- %coreattrs, %i18n, %events -shape %Shape; rect -- controls interpretation of coords -coords %Coords; #IMPLIED -- comma-separated list of lengths -href %URI; #IMPLIED -- URI for linked resource -nohref (nohref) #IMPLIED -- this region has no action -alt %Text; #REQUIRED -- short description -tabindex NUMBER #IMPLIED -- position in tabbing order -accesskey %Character; #IMPLIED -- accessibility key character -onfocus %Script; #IMPLIED -- the element got the focus -onblur %Script; #IMPLIED -- the element lost the focus -> Start tag: required, End tag: forbidden MAP attribute definitions name = cdata [CI] This attribute assigns a name to the image map defined by a MAP element. AREA attribute definitions shape = default|rect|circle|poly [CI] This attribute specifies the shape of a region. Possible values: default: Specifies the entire region. rect: Define a rectangular region. circle: Define a circular region. poly: Define a polygonal region.


coords = coordinates [CN] This attribute specifies the position and shape on the screen. The number and order of values depends on the shape being defined. Possible combinations: rect: left-x, top-y, right-x, bottom-y. circle: center-x, center-y, radius. Note. When the radius value is a percentage value, user agents should calculate the final radius value based on the associated object's width and height. The radius should be the smaller value of the two. poly: x1, y1, x2, y2, ..., xN, yN. The first x and y coordinate pair and the last should be the same to close the polygon. When these coordinate values are not the same, user agents should infer an additional coordinate pair to close the polygon. Coordinates are relative to the top, left corner of the object. All values are lengths. All values are separated by commas. nohref [CI] When set, this boolean attribute specifies that a region has no associated link. Attribute to associate an image map with an element usemap = uri [CT] This attribute associates an image map with an element. The image map is defined by a MAP element. The value of usemap must match the value of the name attribute of the associated MAP element. Attributes defined elsewhere id, class (document-wide identifiers) lang (language information), dir (text direction) title (element title) style (inline style information) name (submitting objects with forms) alt (alternate text) href (anchor reference) target (frame target information) tabindex (tabbing navigation) accesskey (access keys) shape (image maps) onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup, onfocus, onblur (intrinsic events) The MAP element specifies a client-side image map (or other navigation mechanism) that may be associated with another elements (IMG, OBJECT, or INPUT). An image map is associated with an element via the element's usemap attribute. The MAP element may be used without an associated image for general navigation mechanisms. The presence of the usemap attribute for an OBJECT implies that the object being included is an image. Furthermore, when the OBJECT element has an associated client-side image map, user agents may implement user interaction with the OBJECT solely in terms of the client-side image map. This allows user agents (such as an audio browser or robot) to interact with the OBJECT without having to process it; the user agent may even elect not to retrieve (or process) the object. When an OBJECT has an


associated image map, authors should not expect that the object will be retrieved or processed by every user agent. The MAP element content model allows authors to combine the following: One or more AREA elements. These elements have no content but specify the geometric regions of the image map and the link associated with each region. Note that user agents do not generally render AREA elements. Therefore, authors must provide alternate text for each AREA with the alt attribute (see below for information on how to specify alternate text). Block-level content. This content should include A elements that specify the geometric regions of the image map and the link associated with each region. Note that the user agent should render block-level content of a MAP element. Authors should use this method to create more accessible documents. When a MAP element contains mixed content (both AREA elements and block-level content), user agents must ignore the AREA elements. Authors should specify an image maps's geometry completely with AREA elements, or completely with A elements, or completely with both if content is mixed. Authors may wish to mix content so that older user agents will handle map geometries specified by AREA elements and new user agents will take advantage of richer block content. If two or more defined regions overlap, the region-defining element that appears earliest in the document takes precedence (i.e., responds to user input). User agents and authors should offer textual alternates to graphical image maps for cases when graphics are not available or the user cannot access them. For example, user agents may use alt text to create textual links in place of a graphical image map. Such links may be activated in a variety of ways (keyboard, voice activation, etc.). Note. MAP is not backwards compatible with HTML 2.0 user agents. Client-side image map examples In the following example, we create a client-side image map for the OBJECT element. We do not want to render the image map's contents when the OBJECT is rendered, so we "hide" the MAP element within the OBJECT element's content. Consequently, the MAP element's contents will only be rendered if the OBJECT cannot be rendered. <HTML> <HEAD> <TITLE>The cool site!</TITLE> </HEAD> <BODY> <P><OBJECT data="navbar1.gif" type="image/gif" usemap="#map1"> <MAP name="map1">


<P>Navigate the site: <A href="guide.html" shape="rect" coords="0,0,118,28">Access Guide</a> | <A href="shortcut.html" shape="rect" coords="118,0,184,28">Go</A> | <A href="search.html" shape="circle" coords="184,200,60">Search</A> | <A href="top10.html" shape="poly" coords="276,0,276,28,100,200,50,50,276,0">Top Ten</A> </MAP> </OBJECT> </BODY> </HTML> We may want to render the image map's contents even when a user agent can render the OBJECT. For instance, we may want to associate an image map with an OBJECT element and include a text navigation bar at the bottom of the page. To do so, we define the MAP element outside the OBJECT: <HTML> <HEAD> <TITLE>The cool site!</TITLE> </HEAD> <BODY> <P><OBJECT data="navbar1.gif" type="image/gif" usemap="#map1"> </OBJECT> ...the rest of the page here... <MAP name="map1"> <P>Navigate the site: <A href="guide.html" shape="rect" coords="0,0,118,28">Access Guide</a> | <A href="shortcut.html" shape="rect" coords="118,0,184,28">Go</A> | <A href="search.html" shape="circle" coords="184,200,60">Search</A> | <A href="top10.html" shape="poly" coords="276,0,276,28,100,200,50,50,276,0">Top Ten</A> </MAP> </BODY> </HTML> In the following example, we create a similar image map, this time using the AREA element. Note the use of alt text: <P><OBJECT data="navbar1.gif" type="image/gif" usemap="#map1"> <P>This is a navigation bar. </OBJECT> <MAP name="map1"> <AREA href="guide.html" alt="Access Guide" shape="rect"


coords="0,0,118,28"> <AREA href="search.html" alt="Search" shape="rect" coords="184,0,276,28"> <AREA href="shortcut.html" alt="Go" shape="circle" coords="184,200,60"> <AREA href="top10.html" alt="Top Ten" shape="poly" coords="276,0,276,28,100,200,50,50,276,0"> </MAP> Here is a similar version using the IMG element instead of OBJECT (with the same MAP declaration): <P><IMG src="navbar1.gif" usemap="#map1" alt="navigation bar"> The following example illustrates how image maps may be shared. Nested OBJECT elements are useful for providing fallbacks in case a user agent doesn't support certain formats. For example: <P> <OBJECT data="navbar.png" type="image/png"> <OBJECT data="navbar.gif" type="image/gif"> text describing the image... </OBJECT> </OBJECT> If the user agent doesn't support the PNG format, it tries to render the GIF image. If it doesn't support GIF (e.g., it's a speech-based user agent), it defaults to the text description provided as the content of the inner OBJECT element. When OBJECT elements are nested this way, authors may share image maps among them: <P> <OBJECT data="navbar.png" type="image/png" usemap="#map1"> <OBJECT data="navbar.gif" type="image/gif" usemap="#map1"> <MAP name="map1"> <P>Navigate the site: <A href="guide.html" shape="rect" coords="0,0,118,28">Access Guide</a> | <A href="shortcut.html" shape="rect" coords="118,0,184,28">Go</A> | <A href="search.html" shape="circle" coords="184,200,60">Search</A> | <A href="top10.html" shape="poly" coords="276,0,276,28,100,200,50,50,276,0">Top Ten</A> </MAP> </OBJECT>


</OBJECT> The following example illustrates how anchors may be specified to create inactive zones within an image map. The first anchor specifies a small circular region with no associated link. The second anchor specifies a larger circular region with the same center coordinates. Combined, the two form a ring whose center is inactive and whose rim is active. The order of the anchor definitions is important, since the smaller circle must override the larger circle. <MAP name="map1"> <P> <A shape="circle" coords="100,200,50">I'm inactive.</A> <A href="outer-ring-link.html" shape="circle" coords="100,200,250">I'm active.</A> </MAP> Similarly, the nohref attribute for the AREA element declares that geometric region has no associated link. 13.6.2 Server-side image maps Server-side image maps may be interesting in cases where the image map is too complicated for a client-side image map. It is only possible to define a server-side image map for the IMG and INPUT elements. In the case of IMG, the IMG must be inside an A element and the boolean attribute ismap ([CI]) must be set. In the case of INPUT, the INPUT must be of type "image". When the user activates the link by clicking on the image, the screen coordinates are sent directly to the server where the document resides. Screen coordinates are expressed as screen pixel values relative to the image. For normative information about the definition of a pixel and how to scale it, please consult [CSS1]. In the following example, the active region defines a server-side link. Thus, a click anywhere on the image will cause the click's coordinates to be sent to the server. <P><A href=" <IMG src="game.gif" ismap alt="target"></A> The location clicked is passed to the server as follows. The user agent derives a new URI from the URI specified by the href attribute of the A element, by appending `?' followed by the x and y coordinates, separated by a comma. The link is then followed using the new URI. For instance, in the given example, if the user clicks at the location x=10, y=27 ". User agents that do not offer the user a means to select specific coordinates (e.g., nongraphical user agents that rely on keyboard input, speech-based user agents, etc.) should send the coordinates "0,0" to the server when the link is activated. 13.7 Visual presentation of images, objects, and applets


All IMG and OBJECT attributes that concern visual alignment and presentation have been deprecated in favor of style sheets. 13.7.1 Width and height Attribute definitions width = length [CN] Image and object width override. height = length [CN] Image and object height override. When specified, the width and height attributes tell user agents to override the natural image or object size in favor of these values. When the object is an image, it is scaled. User agents should do their best to scale an object or image to match the width and height specified by the author. Note that lengths expressed as percentages are based on the horizontal or vertical space currently available, not on the natural size of the image, object, or applet. The height and width attributes give user agents an idea of the size of an image or object so that they may reserve space for it and continue rendering the document while waiting for the image data. 13.7.2 White space around images and objects Attribute definitions hspace = pixels [CN] Deprecated. This attribute specifies the amount of white space to be inserted to the left and right of an IMG, APPLET, or OBJECT. The default value is not specified, but is generally a small, non-zero length. vspace = pixels [CN] Deprecated. This attribute specifies the amount of white space to be inserted above and below an IMG, APPLET, or OBJECT. The default value is not specified, but is generally a small, non-zero length. 13.7.3 Borders An image or object may be surrounded by a border (e.g., when a border is specified by the user or when the image is the content of an A element). Attribute definitions border = pixels [CN] Deprecated. This attribute specifies the width of an IMG or OBJECT border, in pixels. The default value for this attribute depends on the user agent. 13.7.4 Alignment


Attribute definitions align = bottom|middle|top|left|right Deprecated. This attribute specifies the position of an IMG, OBJECT, or APPLET with respect to its context. The following values for align concern the object's position with respect to surrounding text: bottom: means that the bottom of the object should be vertically aligned with the current baseline. This is the default value. middle: means that the center of the object should be vertically aligned with the current baseline. top: means that the top of the object should be vertically aligned with the top of the current text line. Two other values, left and right, cause the image to float to the current left or right margin. They are discussed in the section on floating objects. Differing interpretations of align. User agents vary in their interpretation of the align attribute. Some only take into account what has occurred on the text line prior to the element, some take into account the text on both sides of the element. 13.8 How to specify alternate text Attribute definitions alt = text [CS] For user agents that cannot display images, forms, or applets, this attribute specifies alternate text. The language of the alternate text is specified by the lang attribute. Several non-textual elements (IMG, AREA, APPLET, and INPUT) let authors specify alternate text to serve as content when the element cannot be rendered normally. Specifying alternate text assists users without graphic display terminals, users whose browsers don't support forms, visually impaired users, those who use speech synthesizers, those who have configured their graphical user agents not to display images, etc. The alt attribute must be specified for the IMG and AREA elements. It is optional for the INPUT and APPLET elements. While alternate text may be very helpful, it must be handled with care. Authors should observe the following guidelines: Do not specify irrelevant alternate text when including images intended to format a page, for instance, alt="red ball" would be inappropriate for an image that adds a red ball for decorating a heading or paragraph. In such cases, the alternate text should be the empty string (""). Authors are in any case advised to avoid using images to format


pages; style sheets should be used instead. Do not specify meaningless alternate text (e.g., "dummy text"). Not only will this frustrate users, it will slow down user agents that must convert text to speech or braille output. Implementors should consult the section on accessibility for information about how to handle cases of omitted alternate text. :) Mr. Mandarino

ASP.Net

In this section we will touch base on one of important concepts in ASP. Net. For ASP.NET FAQ's - ParT I (I) Do session use cookies? Twist:- How can we make session to not to use cookies ? Left to the user, you will enjoy to find this answer. (I) How can we force all the validation control to run? Page.Validate (B) How can we check if all the validation control are valid and proper? Using the Page.IsValid () property you can check whether all the validation are done. (A) If client side validation is enabled in your Web page, does that mean server side code is not run. When client side validation is enabled server emit's JavaScript code for the custom validators. However, note that does not mean that server side checks on custom validators do not execute. It does this redundant check two times, as some of the validators do not support client side scripting.


(A)Which JavaScript file is referenced for validating the validators at the client side? WebUIValidation.js JavaScript file installed at "aspnet_client" root IIS directory is used to validate the validation controls at the client side (B)How to disable client side script in validators? Set 'EnableClientScript' to false. (A)How can I show the entire validation error message in a message box on the client side? In validation summary set "ShowMessageBox" to true. (B)You find that one of your validations is very complicated and does not fit in any of the validators, what will you do? Best is to go for CustomValidators. Below is a sample code for a custom validator, which checks that a textbox should not have zero value <asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="Number not divisible by Zero" ControlToValidate="txtNumber" OnServerValidate="ServerValidate" ClientValidationFunction="CheckZero" /><br> Input: <asp:TextBox id="txtNumber" runat="server" /> <script language="javascript"> <!--function CheckZero(source, args) { int val = parseInt(args.Value, 10); if (value==0) { args. IsValid = false; } } // --> </script> (I)What exactly happens when ASPX page is requested from a browser? Note: - Here the interviewer is expecting complete flow of how an ASPX page is processed with respect to IIS and ASP.NET engine.


Following are the steps which occur when we request a ASPX page :The browser sends the request to the webserver. Let us assume that the webserver at the other end is IIS. Once IIS receives the request he looks on which engine can serve this request.When we mean engine means the DLL who can parse this page or compile and send a response back to browser. Which request to map to is decided by file extension of the page requested. Depending on file extension following are some mapping • •

.aspx, for ASP.NET Web pages, .aspx, for ASP.NET Web

pages, •

.asmx, for ASP.NET Web services,

.config, for ASP.NET configuration files,

.ashx, for custom ASP.NET HTTP handlers,

.rem, for remoting resources

You can also configure the extension mapping to which engine can route by using the IIS engine.


following screen shows some IIS mappings Example an ASP page will be sent to old classic ASP.DLL to compile. While .ASPX pages will be routed to ASP.NET engine for compilation. •

As this book mainly will target ASP.NET we will look in to how ASP.NET pages that is ASPX pages generation sequence occurs. Once IIS passes the request to ASP.NET engine page has to go through two section HTTP module section and HTTP handler section. Both these section have there own work to be done in order that the page is properly compiled and sent to the IIS. HTTP modules inspect the incoming request and depending on that, they can change the internal workflow of the request. HTTP handler actually compiles the page and generates output. If you see your machine.config file you will see following section of HTTP modules <httpModules> <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" /> <add name="Session" type="System.Web.SessionState.SessionStateModule" /> <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" /> <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" /> <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" /> <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" /> <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />


<add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </httpModules> The above mapping will show which Namespace handles which functionality. Example FormsAthuentication is handled by "System. Web. Security.FormsAuthenticationModule". If you look at the web.config, section HTTP module is where authentication and authorization happens. Ok now the HTTP handler is where the actual compilation takes place and the output is generated. Following is a paste from HTTP handler section of WEB.CONFIG file. <httpHandlers> <add verb="*" path="*.vjsproj" type="System.Web.HttpForbiddenHandler" /> <add verb="*" path="*.java" type="System.Web.HttpForbiddenHandler" /> <add verb="*" path="*.jsl" type="System.Web.HttpForbiddenHandler" /> <add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler" /> <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" /> <add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" /> ... </httpHandlers> •

Depending on the File extension handler decides which Namespace will generate the output. Example all .ASPX extension files will be compiled by System.Web.UI.PageHandlerFactory Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then to the browser.


IIS flow from various sections. (B) How can we kill a user session? Session abandon (I) How do you upload a file in ASP.NET? I will leave this to the readers ... Just a hint we have to use System.Web.HttpPostedFile class. (I) How do I send email message from ASP.NET? ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail class. Just a small homework creates a Asp.NET project and send a email at shiv_koirala@yahoo.com. Do not Spam.


(A) What are different IIS isolation levels? IIS has three level of isolation:LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects every one.

LOW IIS process scenario Medium (Pooled):- In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running


Medium pooled scenario High (Isolated):-In high isolated scenario every process is running is there own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.

High isolation scenario (A)ASP used STA threading model, what is the threading model used for ASP.NET. ASP.NET uses MTA threading model. (A)What is the use of <%@ page aspcompat=true %> attribute?


This attribute works like a compatibility option. As mentioned before ASP worked in STA model and ASP.NET works in MTA model, but what if your ASP.NET application is using a VB COM component. In order that VB COM runs properly in ASP.NET threading model, we have to set attribute. After defining the ASPCOMPAT directive attribute ASP.NET pages runs in STA model thus building the compatibility between ASP.NET and old COM components that does not support MTA model. (B) Explain the differences between Server-side and Client-side code? Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is executed on the browser. (I)Can you explain Forms authentication in detail? In old ASP if you where said to create a login page and do authentication you have to do hell lot of custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see in detail what form authentication is. Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then Forms authentication mechanism sends the user to the login page. Following are the steps, which defines steps for Forms authentication:•

Configure Web.config file with forms authentication. As shown below in the config file you can see we have give the cookie name and loginurl page. <configuration> <system.web> <!-- Other settings omitted. --> <authentication mode="Forms"> <forms name="logincookies" loginUrl="login.aspx" protection="All" timeout="30" path="/" /> </authentication> </system.web> </configuration>

Remove anonymous access to the IIS web application, following are changes done to web.config file. <configuration> <system.web>


<!-- Other settings omitted. --> <authorization> <deny users="?" /> </authorization> </system.web> </configuration> •

Create the login page, which will accept user information. You will have create your login page that is the Login.aspx, which will actually take the user data.

Finally a small coding in the login button. Let us assume that the login page has two textboxes TX name and txtapssword. Also, import System.Web.Security and put the following code in login button of the page. If Page.IsValid Then If FormsAuthentication.Authenticate(txtName.Text, txtPassword.Text) Then FormsAuthentication.RedirectFromLoginPage(txtName.Text, False) Else lblStatus.Text = "Error not proper user" End If End If

(A)How do I sign out in forms authentication? FormsAuthentication.Signout () (A)If cookies are not enabled at browser end does form Authentication work? No, it does not work. (A)How to use a checkbox in a data grid? Twist: - How can I track event in checkbox, which is one of the columns of a data grid? Note: - This is normally asked when the interviewer want to see that have you really worked practically on a project. Following are the steps to be done:In ASPX page you have to add Item template tag in data grid. <ItemTemplate> <asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True"


OnCheckedChanged="Check_Clicked"></asp:CheckBox> </ItemTemplate> If you look at the Item template, we have "OnCheckChanged" event. This "OnCheckChanged" event has "Check Clicked" subroutine is actually in behind code. Note this method, which is in behind code, should either be "protected" or "public" Following below is the subroutine, which defines the method Protected Sub Check Clicked (By Val sender As Object, By Val e As EventArgs) 'Do something End Sub The above steps should be defined in short to the interviewer, which will give a quick feeling of your practical experience with ASP.NET' (I)What are the steps to create a windows service in VB.NET? Windows Services are long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted. Following are the steps to create a service:Create a project of type "Windows Service".


Create project for Windows Service If you see, the class created it is automatically inheriting from "System.ServiceProcess.ServiceBase". You can override the following events provided by service and write your custom code. All the three main events can be used that is Start, stop and continue. protected override void OnStart(string[] args) { } protected override void OnStop() { } protected override void OnContinue() { } Now to install the service you need to do run the install util exe. InstallUtil <Project Path>\BIN\MyNewService.exe (A) What is the difference between "Web farms" and "Web garden"? "Web farms" are used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic, which decides


which web server from the farm, handles the request. For instance, we have two servers "Server1" and "Server2" which have the same configuration and content. Therefore, there is a special switch, which stands in between these two servers and the users and routes the request accordingly.


Web Farm in action Above figure explains in detail how web farm work. You can see there is a router in between which takes a request and sees which one of the server is least loaded and forwards the request to that server. Therefore, for request1 it route is server1, for request2 it routes server2, for request3 it routes to server3 and final request4 is routed to server4. So you can see because we have web farm at place server1 and server2 are loaded with two request each rather than one server loading to full. One more advantage of using this kind of architecture is if one of the servers goes down we can still run with the other server thus having 24x7 uptime. The routing logic can be a number of different options:•

Round robin: Each node gets a request sent to it "in turn". Therefore, server1 gets a request, then server2 again, then server1, then server2 again. As shown in the above figure. Least Active: Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes. Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be "equal" in performance. If one performs better than the other, then send more requests there rather than which is moving slowly?

Before we try to understand what a web garden is let's try to understand how IIS handles processes. All requests to IIS are routed to "aspnet_wp.exe" for IIS 5.0 and "w3wp.exe" for IIS 6.0. In normal case i.e. with out web garden, we have one worker process instance ("aspnet_wp.exe" / "w3wp.exe") across all requests. This one instance of worker process uses the CPU processor as directed by the operating system.


with out Web Garden However, when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. You can see in the below diagram we have different worker process instances created which run on different CPU's.


With Web Garden In short, we can define a model in which multiple processes run on multiple CPUs in a single server machine are termed as Web garden. (A) How do we configure "Web Garden"? "Web garden" can be configured by using process model settings in "machine.config" or "Web.config" file. The configuration section is named <process Model> and is shown in the following example. The process model is enabled by default (enable="true"). Below is the snippet from config file. <process Model enable="true" timeout="infinite" idle Timeout="infinite" shutdown Timeout="0:00:05" requestLimit="infinite" requestQueueLimit="5000" memoryLimit="80" webGarden="false" cpuMask="12" userName="" password="" logLevel="errors" clientConnectedCheck="0:00:05" />


From the above process model section for web garden, we are concerned with only two attributes "web garden" and "cpuMask". Web Garden: - Controls CPU affinity. True indicates that processes should be affinities to the corresponding CPU. The default is False. CpuMask:- Specifies which processors on a multiprocessor server are eligible to run ASP.NET processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET threads. ASP.NET launches one worker process for each eligible CPU. If web Garden is set to false, cpuMask is ignored and only one worker process will run regardless of the number of processors in the machine. If web Garden is set to true, ASP.NET launches one worker process for each CPU that corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff. Below are detail steps of how to implement web garden • •

Click Start and then click Run. Type calc.exe and then click OK.

Go to View menu, click Scientific.

Go to View menu, click Binary.

Use zero and one to specify the processors ASP.NET can or cannot use. Use one for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100.

On the View menu, click Decimal. Note the decimal number.

Open the Web.config or machine.config file in a text editor such as Notepad. The Web.config file is located in the folder where the application is saved.

In the Web.config file, add the process Model configuration element under the System. Web element. Before adding <process Model> to Web.config file, the user has to make sure that the allow Definition attribute in the <process Model> section of the Web.config file is set to everywhere.

Add and then set the web Garden attribute of the process Model element to True.

Add and then set the cpuMask attribute of the process Model element to the result that is determined in your calculation. Do not preface the number with zerox because the result of the calculation is a decimal number.

The following example demonstrates the process Model element that is configured to enable only the first two processors of a four-processor computer.


<processModel enable="true" webGarden="true" cpuMask="12" /> Save the Web.config file. The ASP.NET application automatically restarts and uses only the specified processors. (B) What is the main difference between Grid layout and Flow Layout? Grid Layout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, Flow Layout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers. If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in Flow layout, you can see more of using HTML table to position elements, which is compatible with wide range of browsers. (I) What's the difference between trace and debug in ASP.NET? Debug and trace enables you to monitor the application for errors and exception with out VS.NET IDE. In Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the part of the executable they run on the same thread where the code runs and they do not given you the exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will see a debug file also as shown in figure 'Debug Mode'.

Debug mode Trace works in both debug as well as release mode. The main advantage of using trace over debug is to do performance analysis which can not be done by debug. Trace runs on a different thread thus it does not impact the main code thread. Note: - There is also a fundamental difference in thinking when we want to use trace and when want to debug. Tracing is a process about getting information regarding program's execution. On the other hand debugging is about finding errors in the code.


(A) How do you enable tracing in on an ASP.NET page? To enable tracing on an ASP.NET page we need to put the 'trace' attribute to true on the page attribute as shown in figure 'Tracing in Action' ( Its numbered as 1 in the figure). In the behind code we can use the trace object to put tracing like one we have shown on the page load numbered as (4). We have used the 'trace.write' to display our tracing. You can also see the trace data which is circled. 2 and 3 show the actual data. You can see how trace shows in details the tracing information for a page with events and time period for execution. If you make the 'trace' as false you will only see the actual display i.e. 'This is the actual data'. So you can enable and disable trace with out actually compiling and uploading new DLL's on production environment.


Tracing in Action The above sample enables tracing only at page level. To enable tracing on application level we need to modify the 'web.config' file and put the 'trace' tag with 'enabled=true'. <trace enabled="true" requestLimit="10" pageOutput="false" localOnly="true" /> (B) Which namespace is needed to implement debug and trace ? Debug and trace class belongs to 'System.Diagnostic' namespace. (A) Can you explain the concept of trace listener? 'Tracelistener' are objects that get tracing information from the trace class and they output the data to some medium. For instance you can see from the figure 'TraceListener' how it listens to the trace object and outputs the same to UI, File or a windows event log. There are three different types of 'tracelistener' first is the 'defaulttracelistener' (this outputs the data to UI), second is 'textwritertracelistener' (this outputs to a file) and the final one is 'Eventlogtracelistener' which outputs the same to a windows event log.


TraceListener Below is a code snippet for 'textwritertracelistener' and 'eventlogtracelistener'. Using 'textwritertracelistener' we have forwarded the trace's to 'ErrorLog.txt' file and in the second snippet we have used the 'Eventlogtracelistener' to forward the trace's to windows event log.

Tracelistener in action (I) What are trace switches? Trace switches helps us to control and govern the tracing behavior of a project. There are two types of trace switches 'BooleanSwitch' and 'TraceSwitch'. BooleanSwitch, as the name says, is a kind of on/off switch which can be either enabled (true) or disabled (false).


Trace switches 'TraceSwitch' on the other hand offers more options rather than simple true/false like 'BooleanSwitch'. Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a switch to a particular level, it includes all levels from the indicated level down. For example, if you set a TraceSwitch's Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to TraceLevel.Warning, will be taken in to account. Below are the various levels in 'TraceSwitch' object. Off a Outputs no messages to Trace Listeners Error a Outputs only error messages to Trace Listeners Warning a Outputs error and warning messages to Trace Listeners Info a Outputs informational, warning and error messages to Trace Listeners Verbose a Outputs all messages to Trace Listeners TraceSwitch objSwitch = new TraceSwitch("TraceWarningandError", "Error in trace") ; objSwitch.Level = TraceLevel.Warning.


Sincerely Mandarino


XHTML™ 1.0 The Extensible HyperText Markup Language A Reformulation of HTML 4 in XML 1.0 Please refer to the errata for this document, which may include some normative corrections. See also translations. This document is also available in these non-normative formats: Multi-part XHTML file, PostScript version, PDF version, ZIP archive, and Gzip'd TAR archive. Abstract This specification defines the Second Edition of XHTML 1.0, a reformulation of HTML 4 as an XML 1.0 application, and three DTDs corresponding to the ones defined by HTML 4. The semantics of the elements and their attributes are defined in the W3C Recommendation for HTML 4. These semantics provide the foundation for future extensibility of XHTML. Compatibility with existing HTML user agents is possible by following a small set of guidelines. Status of this document This section describes the status of this document at the time of its publication. Other documents may supersede this document. The latest status of this document series is maintained at the W3C. This document is the second edition of the XHTML 1.0 specification incorporating the errata changes as of 1 August 2002. Changes between this version and the previous Recommendation are illustrated in a diff-marked version. This second edition is not a new version of XHTML 1.0 (first published 26 January 2000). The changes in this document reflect corrections applied as a result of comments submitted by the community and as a result of ongoing work within the HTML Working Group. There are no substantive changes in this document - only the integration of various errata. This document has been produced as part of the W3C HTML Activity. The goals of the HTML Working Group (members only) are discussed in the HTML Working Group charter.


At the time of publication, the working group believed there were zero patent disclosures relevant to this specification. A current list of patent disclosures relevant to this specification may be found on the Working Group's patent disclosure page. A list of current W3C Recommendations and other technical documents can be found at Quick Table of Contents 1. What is XHTML? 2. Definitions 3. Normative Definition of XHTML 1.0 4. Differences with HTML 4 5. Compatibility Issues A. DTDs B. Element Prohibitions C. HTML Compatibility Guidelines D. Acknowledgements E. References Full Table of Contents 1. What is XHTML? 1.1. What is HTML 4? 1.2. What is XML? 1.3. Why the need for XHTML? 2. Definitions 2.1. Terminology 2.2. General Terms 3. Normative Definition of XHTML 1.0 3.1. Document Conformance 3.1.1. Strictly Conforming Documents 3.1.2. Using XHTML with other namespaces 3.2. User Agent Conformance 4. Differences with HTML 4 4.1. Documents must be well-formed 4.2. Element and attribute names must be in lower case 4.3. For non-empty elements, end tags are required 4.4. Attribute values must always be quoted 4.5. Attribute Minimization 4.6. Empty Elements 4.7. White Space handling in attribute values 4.8. Script and Style elements 4.9. SGML exclusions 4.10. The elements with 'id' and 'name' attributes 4.11. Attributes with pre-defined value sets


4.12. Entity references as hex values 5. Compatibility Issues 5.1. Internet Media Type A. DTDs A.1. Document Type Definitions A.1.1. XHTML-1.0-Strict A.1.2. XHTML-1.0-Transitional A.1.3. XHTML-1.0-Frameset A.2. Entity Sets A.2.1. Latin-1 characters A.2.2. Special characters A.2.3. Symbols B. Element Prohibitions C. HTML Compatibility Guidelines C.1. Processing Instructions and the XML Declaration C.2. Empty Elements C.3. Element Minimization and Empty Element Content C.4. Embedded Style Sheets and Scripts C.5. Line Breaks within Attribute Values C.6. Isindex C.7. The lang and xml:lang Attributes C.8. Fragment Identifiers C.9. Character Encoding C.10. Boolean Attributes C.11. Document Object Model and XHTML C.12. Using Ampersands in Attribute Values (and Elsewhere) C.13. Cascading Style Sheets (CSS) and XHTML C.14. Referencing Style Elements when serving as XML C.15. White Space Characters in HTML vs. XML C.16. The Named Character Reference ' D. Acknowledgements E. References 1. What is XHTML? This section is informative. XHTML is a family of current and future document types and modules that reproduce, subset, and extend HTML 4 [HTML4]. XHTML family document types are XML based, and ultimately are designed to work in conjunction with XML-based user agents. The details of this family and its evolution are discussed in more detail in [XHTMLMOD]. XHTML 1.0 (this specification) is the first document type in the XHTML family. It is a reformulation of the three HTML 4 document types as applications of XML 1.0 [XML]. It is intended to be used as a language for content that is both XML-conforming and, if some simple guidelines are followed, operates in HTML 4 conforming user agents. Developers who migrate their content to XHTML 1.0 will realize the following benefits:


XHTML documents are XML conforming. As such, they are readily viewed, edited, and validated with standard XML tools. XHTML documents can be written to operate as well or better than they did before in existing HTML 4-conforming user agents as well as in new, XHTML 1.0 conforming user agents. XHTML documents can utilize applications (e.g. scripts and applets) that rely upon either the HTML Document Object Model or the XML Document Object Model [DOM]. As the XHTML family evolves, documents conforming to XHTML 1.0 will be more likely to interoperate within and among various XHTML environments. The XHTML family is the next step in the evolution of the Internet. By migrating to XHTML today, content developers can enter the XML world with all of its attendant benefits, while still remaining confident in their content's backward and future compatibility. 1.1. What is HTML 4? HTML 4 [HTML4] is an SGML (Standard Generalized Markup Language) application conforming to International Standard ISO 8879, and is widely regarded as the standard publishing language of the World Wide Web. SGML is a language for describing markup languages, particularly those used in electronic document exchange, document management, and document publishing. HTML is an example of a language defined in SGML. SGML has been around since the middle 1980's and has remained quite stable. Much of this stability stems from the fact that the language is both feature-rich and flexible. This flexibility, however, comes at a price, and that price is a level of complexity that has inhibited its adoption in a diversity of environments, including the World Wide Web. HTML, as originally conceived, was to be a language for the exchange of scientific and other technical documents, suitable for use by non-document specialists. HTML addressed the problem of SGML complexity by specifying a small set of structural and semantic tags suitable for authoring relatively simple documents. In addition to simplifying the document structure, HTML added support for hypertext. Multimedia capabilities were added later. In a remarkably short space of time, HTML became wildly popular and rapidly outgrew its original purpose. Since HTML's inception, there has been rapid invention of new elements for use within HTML (as a standard) and for adapting HTML to vertical, highly specialized, markets. This plethora of new elements has led to interoperability problems for documents across different platforms. 1.2. What is XML? XML™ is the shorthand name for Extensible Markup Language [XML].


XML was conceived as a means of regaining the power and flexibility of SGML without most of its complexity. Although a restricted form of SGML, XML nonetheless preserves most of SGML's power and richness, and yet still retains all of SGML's commonly used features. While retaining these beneficial features, XML removes many of the more complex features of SGML that make the authoring and design of suitable software both difficult and costly. 1.3. Why the need for XHTML? The benefits of migrating to XHTML 1.0 are described above. Some of the benefits of migrating to XHTML in general are: Document developers and user agent designers are constantly discovering new ways to express their ideas through new markup. In XML, it is relatively easy to introduce new elements or additional element attributes. The XHTML family is designed to accommodate these extensions through XHTML modules and techniques for developing new XHTML-conforming modules (described in the XHTML Modularization specification). These modules will permit the combination of existing and new feature sets when developing content and when designing new user agents. Alternate ways of accessing the Internet are constantly being introduced. The XHTML family is designed with general user agent interoperability in mind. Through a new user agent and document profiling mechanism, servers, proxies, and user agents will be able to perform best effort content transformation. Ultimately, it will be possible to develop XHTML-conforming content that is usable by any XHTML-conforming user agent. 2. Definitions This section is normative. 2.1. Terminology The following terms are used in this specification. These terms extend the definitions in [RFC2119] in ways based upon similar definitions in ISO/IEC 9945-1:1990 [POSIX.1]: May With respect to implementations, the word "may" is to be interpreted as an optional feature that is not required in this specification but can be provided. With respect to Document Conformance, the word "may" means that the optional feature must not be used. The term "optional" has the same definition as "may". Must In this specification, the word "must" is to be interpreted as a mandatory requirement on the implementation or on Strictly Conforming XHTML Documents, depending upon the context. The term "shall" has the same definition as "must". Optional


See "May". Reserved A value or behavior is unspecified, but it is not allowed to be used by Conforming Documents nor to be supported by Conforming User Agents. Shall See "Must". Should With respect to implementations, the word "should" is to be interpreted as an implementation recommendation, but not a requirement. With respect to documents, the word "should" is to be interpreted as recommended programming practice for documents and a requirement for Strictly Conforming XHTML Documents. Supported Certain facilities in this specification are optional. If a facility is supported, it behaves as specified by this specification. Unspecified When a value or behavior is unspecified, the specification defines no portability requirements for a facility on an implementation even when faced with a document that uses the facility. A document that requires specific behavior in such an instance, rather than tolerating any behavior when using that facility, is not a Strictly Conforming XHTML Document. 2.2. General Terms Attribute An attribute is a parameter to an element declared in the DTD. An attribute's type and value range, including a possible default value, are defined in the DTD. DTD A DTD, or document type definition, is a collection of XML markup declarations that, as a collection, defines the legal structure, elements, and attributes that are available for use in a document that complies to the DTD. Document A document is a stream of data that, after being combined with any other streams it references, is structured such that it holds information contained within elements that are organized as defined in the associated DTD. See Document Conformance for more information. Element An element is a document structuring unit declared in the DTD. The element's content model is defined in the DTD, and additional semantics may be defined in the prose description of the element. Facilities Facilities are elements, attributes, and the semantics associated with those elements and attributes. Implementation See User Agent. Parsing Parsing is the act whereby a document is scanned, and the information contained within the document is filtered into the context of the elements in which the information is


structured. Rendering Rendering is the act whereby the information in a document is presented. This presentation is done in the form most appropriate to the environment (e.g. aurally, visually, in print). User Agent A user agent is a system that processes XHTML documents in accordance with this specification. See User Agent Conformance for more information. Validation Validation is a process whereby documents are verified against the associated DTD, ensuring that the structure, use of elements, and use of attributes are consistent with the definitions in the DTD. Well-formed A document is well-formed when it is structured according to the rules defined in Section 2.1 of the XML 1.0 Recommendation [XML]. 3. Normative Definition of XHTML 1.0 This section is normative. 3.1. Document Conformance This version of XHTML provides a definition of strictly conforming XHTML 1.0 documents, which are restricted to elements and attributes from the XML and XHTML 1.0 namespaces. See Section 3.1.2 for information on using XHTML with other namespaces, for instance, to include metadata expressed in RDF within XHTML documents. 3.1.1. Strictly Conforming Documents A Strictly Conforming XHTML Document is an XML document that requires only the facilities described as mandatory in this specification. Such a document must meet all of the following criteria: It must conform to the constraints expressed in one of the three DTDs found in DTDs and in Appendix B. The root element of the document must be html. The root element of the document must contain an xmlns declaration for the XHTML namespace [XMLNS]. The namespace for XHTML is defined to be. An example root element might look like: <html xmlns= xml:lang="en" lang="en"> There must be a DOCTYPE declaration in the document prior to the root element. The public identifier included in the DOCTYPE declaration must reference one of the three


DTDs found in DTDs using the respective Formal Public Identifier. The system identifier may be changed to reflect local system conventions. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" The DTD subset must not be used to override any parameter entities in the DTD. An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" <html xmlns <head> <title>Virtual Library</title> </head> <body> <p>Moved to <a href="example.org</a>.</p> </body> </html> 3.1.2. Using XHTML with other namespaces The XHTML namespace may be used with other XML namespaces as per [XMLNS], although such documents are not strictly conforming XHTML 1.0 documents as defined above. Work by W3C is addressing ways to specify conformance for documents involving multiple namespaces. For an example, see [XHTML+MathML]. The following example shows the way in which XHTML 1.0 could be used in conjunction with the MathML Recommendation: <html xmlns= xml:lang="en" lang="en"> <head> <title>A Math Example</title> </head> <body> <p>The following is MathML markup:</p> <math xmlns=" <apply> <log/> <logbase>


<cn> 3 </cn> </logbase> <ci> x </ci> </apply> </math> </body> </html> The following example shows the way in which XHTML 1.0 markup could be incorporated into another XML namespace: <?xml version="1.0" encoding="UTF-8"?> <!-- initially, the default namespace is "books" --> <book xmlns='urn:loc.gov:books' xmlns:isbn='urn:ISBN:0-395-36341-6' xml:lang="en" lang="en"> <title>Cheaper by the Dozen</title> <isbn:number>1568491379</isbn:number> <notes> <!-- make HTML the default namespace for a hypertext commentary --> <p xmlns=' This is also available < </p> </notes> </book> 3.2. User Agent Conformance A conforming user agent must meet all of the following criteria: In order to be consistent with the XML 1.0 Recommendation [XML], the user agent must parse and evaluate an XHTML document for well-formedness. If the user agent claims to be a validating user agent, it must also validate documents against their referenced DTDs according to [XML]. When the user agent claims to support facilities defined within this specification or required by this specification through normative reference, it must do so in ways consistent with the facilities' definition. When a user agent processes an XHTML document as generic XML, it shall only recognize attributes of type ID (i.e. the id attribute on most XHTML elements) as fragment identifiers. If a user agent encounters an element it does not recognize, it must process the element's content. If a user agent encounters an attribute it does not recognize, it must ignore the entire attribute specification (i.e., the attribute and its value). If a user agent encounters an attribute value it does not recognize, it must use the default attribute value. If it encounters an entity reference (other than one of the entities defined in this recommendation or in the XML recommendation) for which the user agent has processed no declaration (which could happen if the declaration is in the external


subset which the user agent hasn't read), the entity reference should be processed as the characters (starting with the ampersand and ending with the semi-colon) that make up the entity reference. When processing content, user agents that encounter characters or character entity references that are recognized but not renderable may substitute another rendering that gives the same meaning, or must display the document in such a way that it is obvious to the user that normal rendering has not taken place. White space is handled according to the following rules. The following characters are defined in [XML] white space characters: SPACE ( ) HORIZONTAL TABULATION (	) CARRIAGE RETURN (
) LINE FEED (
) The XML processor normalizes different systems' line end codes into one single LINE FEED character, that is passed up to the application. The user agent must use the definition from CSS for processing whitespace characters [CSS2]. Note that the CSS2 recommendation does not explicitly address the issue of whitespace handling in non-Latin character sets. This will be addressed in a future version of CSS, at which time this reference will be updated. Note that in order to produce a Canonical XHTML document, the rules above must be applied and the rules in [XMLC14N] must also be applied to the document. 4. Differences with HTML 4 This section is informative. Due to the fact that XHTML is an XML application, certain practices that were perfectly legal in SGML-based HTML 4 [HTML4] must be changed. 4.1. Documents must be well-formed Well-formedness is a new concept introduced by [XML]. Essentially this means that all elements must either have closing tags or be written in a special form (as described below), and that all the elements must nest properly. Although overlapping is illegal in SGML, it is widely tolerated in existing browsers. CORRECT: nested elements. <p>here is an emphasized <em>paragraph</em>.</p> INCORRECT: overlapping elements


<p>here is an emphasized <em>paragraph.</p></em> 4.2. Element and attribute names must be in lower case XHTML documents must use lower case for all HTML element and attribute names. This difference is necessary because XML is case-sensitive e.g. <li> and <LI> are different tags. 4.3. For non-empty elements, end tags are required In SGML-based HTML 4 certain elements were permitted to omit the end tag; with the elements that followed implying closure. XML does not allow end tags to be omitted. All elements other than those declared in the DTD as EMPTY must have an end tag. Elements that are declared in the DTD as EMPTY can have an end tag or can use empty element shorthand (see Empty Elements). CORRECT: terminated elements <p>here is a paragraph.</p><p>here is another paragraph.</p> INCORRECT: unterminated elements <p>here is a paragraph.<p>here is another paragraph. 4.4. Attribute values must always be quoted All attribute values must be quoted, even those which appear to be numeric. CORRECT: quoted attribute values <td rowspan="3"> INCORRECT: unquoted attribute values <td rowspan=3> 4.5. Attribute Minimization XML does not support attribute minimization. Attribute-value pairs must be written in full. Attribute names such as compact and checked cannot occur in elements without their value being specified. CORRECT: unminimized attributes <dl compact="compact">


INCORRECT: minimized attributes <dl compact> 4.6. Empty Elements Empty elements must either have an end tag or the start tag must end with />. For instance, <br/> or <hr></hr>. See HTML Compatibility Guidelines for information on ways to ensure this is backward compatible with HTML 4 user agents. CORRECT: terminated empty elements <br/><hr/> INCORRECT: unterminated empty elements <br><hr> 4.7. White Space handling in attribute values When user agents process attributes, they do so according to Section 3.3.3 of [XML]: Strip leading and trailing white space. Map sequences of one or more white space characters (including line breaks) to a single inter-word space. 4.8. Script and Style elements In XHTML, the script and style elements are declared as having #PCDATA content. As a result, < and & will be treated as the start of markup, and entities such as < and & will be recognized as entity references by the XML processor to < and & respectively. Wrapping the content of the script or style element within a CDATA marked section avoids the expansion of these entities. <script type="text/javascript"> <![CDATA[ ... unescaped script content ... ]]> </script> CDATA sections are recognized by the XML processor and appear as nodes in the Document Object Model, see Section 1.3 of the DOM Level 1 Recommendation [DOM]. An alternative is to use external script and style documents. 4.9. SGML exclusions


SGML gives the writer of a DTD the ability to exclude specific elements from being contained within an element. Such prohibitions (called "exclusions") are not possible in XML. For example, the HTML 4 Strict DTD forbids the nesting of an 'a' element within another 'a' element to any descendant depth. It is not possible to spell out such prohibitions in XML. Even though these prohibitions cannot be defined in the DTD, certain elements should not be nested. A summary of such elements and the elements that should not be nested in them is found in the normative Element Prohibitions. 4.10. The elements with 'id' and 'name' attributes HTML 4 defined the name attribute for the elements a, applet, form, frame, iframe, img, and map. HTML 4 also introduced the id attribute. Both of these attributes are designed to be used as fragment identifiers. In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html. Note that in XHTML 1.0, the name attribute of these elements is formally deprecated, and will be removed in a subsequent version of XHTML. 4.11. Attributes with pre-defined value sets HTML 4 and XHTML both have some attributes that have pre-defined and limited sets of values (e.g. the type attribute of the input element). In SGML and XML, these are called enumerated attributes. Under HTML 4, the interpretation of these values was case-insensitive, so a value of TEXT was equivalent to a value of text. Under XML, the interpretation of these values is case-sensitive, and in XHTML 1 all of these values are defined in lower-case. 4.12. Entity references as hex values SGML and XML both permit references to characters by using hexadecimal values. In SGML these references could be made using either &#Xnn; or &#xnn;. In XML documents, you must use the lower-case version (i.e. &#xnn;) 5. Compatibility Issues This section is normative.


Although there is no requirement for XHTML 1.0 documents to be compatible with existing user agents, in practice this is easy to accomplish. Guidelines for creating compatible documents can be found in Appendix C. 5.1. Internet Media Type XHTML Documents which follow the guidelines set forth in Appendix C, "HTML Compatibility Guidelines" may be labeled with the Internet Media Type "text/html" [RFC2854], as they are compatible with most HTML browsers. Those documents, and any other document conforming to this specification, may also be labeled with the Internet Media Type "application/xhtml+xml" as defined in [RFC3236]. For further information on using media types with XHTML, see the informative note [XHTMLMIME]. A. DTDs This appendix is normative. These DTDs and entity sets form a normative part of this specification. The complete set of DTD files together with an XML declaration and SGML Open Catalog is included in the zip file and the gzip'd tar file for this specification. Users looking for local copies of the DTDs to work with should download and use those archives rather than using the specific DTDs referenced below. A.1. Document Type Definitions These DTDs approximate the HTML 4 DTDs. The W3C recommends that you use the authoritative versions of these DTDs at their defined SYSTEM identifiers when validating content. If you need to use these DTDs locally you should download one of the archives of this version. For completeness, the normative versions of the DTDs are included here: A.1.1. XHTML-1.0-Strict The file DTD/xhtml1-strict.dtd is a normative part of this specification. The annotated contents of this file are available in this separate section for completeness. A.1.2. XHTML-1.0-Transitional The file DTD/xhtml1-transitional.dtd is a normative part of this specification. The annotated contents of this file are available in this separate section for completeness. A.1.3. XHTML-1.0-Frameset The file DTD/xhtml1-frameset.dtd is a normative part of this specification. The annotated contents of this file are available in this separate section for completeness.


A.2. Entity Sets The XHTML entity sets are the same as for HTML 4, but have been modified to be valid XML 1.0 entity declarations. Note the entity for the Euro currency sign (€ or € or €) is defined as part of the special characters. A.2.1. Latin-1 characters The file DTD/xhtml-lat1.ent is a normative part of this specification. The annotated contents of this file are available in this separate section for completeness. A.2.2. Special characters The file DTD/xhtml-special.ent is a normative part of this specification. The annotated contents of this file are available in this separate section for completeness. A.2.3. Symbols The file DTD/xhtml-symbol.ent is a normative part of this specification. The annotated contents of this file are available in this separate section for completeness. B. Element Prohibitions This appendix is normative. The following elements have prohibitions on which elements they can contain (see SGML Exclusions). This prohibition applies to all depths of nesting, i.e. it contains all the descendant elements. a must not contain other a elements. pre must not contain the img, object, big, small, sub, or sup elements. button must not contain the input, select, textarea, label, button, form, fieldset, iframe or isindex elements. label must not contain other label elements. form must not contain other form elements. C. HTML Compatibility Guidelines This appendix is informative. This appendix summarizes design guidelines for authors who wish their XHTML documents to render on existing HTML user agents. Note that this recommendation


does not define how HTML conforming user agents should process HTML documents. Nor does it define the meaning of the Internet Media Type text/html. For these definitions, see [HTML4] and [RFC2854] respectively. C.1. Processing Instructions and the XML Declaration Be aware that processing instructions are rendered on some user agents. Also, some user agents interpret the XML declaration to mean that the document is unrecognized XML rather than HTML, and therefore may not render the document as expected. For compatibility with these types of legacy browsers, you may want to avoid using processing instructions and XML declarations. Remember, however, that when the XML declaration is not included in a document, the document can only use the default character encodings UTF-8 or UTF-16. C.2. Empty Elements Include a space before the trailing / and > of empty elements, e.g. <br />, <hr /> and <img src="karen.jpg" alt="Karen" />. Also, use the minimized tag syntax for empty elements, e.g. <br />, as the alternative syntax <br></br> allowed by XML gives uncertain results in many existing user agents. C.3. Element Minimization and Empty Element Content Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />). C.4. Embedded Style Sheets and Scripts Use external style sheets if your style sheet uses < or & or ]]> or --. Use external scripts if your script uses < or & or ]]> or --. Note that XML parsers are permitted to silently remove the contents of comments. Therefore, the historical practice of "hiding" scripts and style sheets within "comments" to make the documents backward compatible is likely to not work as expected in XML-based user agents. C.5. Line Breaks within Attribute Values Avoid line breaks and multiple white space characters within attribute values. These are handled inconsistently by user agents. C.6. Isindex Don't include more than one isindex element in the document head. The isindex element is deprecated in favor of the input element. C.7. The lang and xml:lang Attributes


Use both the lang and xml:lang attributes when specifying the language of an element. The value of the xml:lang attribute takes precedence. C.8. Fragment Identifiers In XML, URI-references [RFC2396] that end with fragment identifiers of the form "#foo" do not refer to elements with an attribute name="foo"; rather, they refer to elements with an attribute defined to be of type ID, e.g., the id attribute in HTML 4. Many existing HTML clients don't support the use of ID-type attributes in this way, so identical values may be supplied for both of these attributes to ensure maximum forward and backward compatibility (e.g., <a id="foo" name="foo">...</a>). Further, since the set of legal values for attributes of type ID is much smaller than for those of type CDATA, the type of the name attribute has been changed to NMTOKEN. This attribute is constrained such that it can only have the same values as type ID, or as the Name production in XML 1.0 Section 2.3, production 5. Unfortunately, this constraint cannot be expressed in the XHTML 1.0 DTDs. Because of this change, care must be taken when converting existing HTML documents. The values of these attributes must be unique within the document, valid, and any references to these fragment identifiers (both internal and external) must be updated should the values be changed during conversion. Note that the collection of legal values in XML 1.0 Section 2.3, production 5 is much larger than that permitted to be used in the ID and NAME types defined in HTML 4. When defining fragment identifiers to be backward-compatible, only strings matching the pattern [A-Za-z][A-Za-z0-9:_.-]* should be used. See Section 6.2 of [HTML4] for more information. Finally, note that XHTML 1.0 has deprecated the name attribute of the a, applet, form, frame, iframe, img, and map elements, and it will be removed from XHTML in subsequent versions. C.9. Character Encoding Historically, the character encoding of an HTML document is either specified by a web server via the charset parameter of the HTTP Content-Type header, or via a meta element in the document itself. In an XML document, the character encoding of the document is specified on the XML declaration (e.g., <?xml version="1.0" encoding="EUC-JP"?>). In order to portably present documents with specific character encodings, the best approach is to ensure that the web server provides the correct headers. If this is not possible, a document that wants to set its character encoding explicitly must include both the XML declaration an encoding declaration and a meta http-equiv statement (e.g., <meta http-equiv="Content-type" content="text/html; charset=EUC-JP" />). In XHTML-conforming user agents, the value of the encoding declaration of the XML declaration takes precedence.


Note: be aware that if a document must include the character encoding declaration in a meta http-equiv statement, that document may always be interpreted by HTTP servers and/or user agents as being of the internet media type defined in that statement. If a document is to be served as multiple media types, the HTTP server must be used to set the encoding of the document. C.10. Boolean Attributes Some HTML user agents are unable to interpret boolean attributes when these appear in their full (non-minimized) form, as required by XML 1.0. Note this problem doesn't affect user agents compliant with HTML 4. The following attributes are involved: compact, nowrap, ismap, declare, noshade, checked, disabled, readonly, multiple, selected, noresize, defer. C.11. Document Object Model and XHTML The Document Object Model level 1 Recommendation [DOM] defines document object model interfaces for XML and HTML 4. The HTML 4 document object model specifies that HTML element and attribute names are returned in upper-case. The XML document object model specifies that element and attribute names are returned in the case they are specified. In XHTML 1.0, elements and attributes are specified in lower-case. This apparent difference can be addressed in two ways: User agents that access XHTML documents served as Internet media type text/html via the DOM can use the HTML DOM, and can rely upon element and attribute names being returned in upper-case from those interfaces. User agents that access XHTML documents served as Internet media types text/xml, application/xml, or application/xhtml+xml can also use the XML DOM. Elements and attributes will be returned in lower-case. Also, some XHTML elements may or may not appear in the object tree because they are optional in the content model (e.g. the tbody element within table). This occurs because in HTML 4 some elements were permitted to be minimized such that their start and end tags are both omitted (an SGML feature). This is not possible in XML. Rather than require document authors to insert extraneous elements, XHTML has made the elements optional. User agents need to adapt to this accordingly. For further information on this topic, see [DOM2] C.12. Using Ampersands in Attribute Values (and Elsewhere) In both SGML and XML, the ampersand character ("&") declares the beginning of an entity reference (e.g., ® for the registered trademark symbol "®"). Unfortunately, many HTML user agents have silently ignored incorrect usage of the ampersand character in HTML documents - treating ampersands that do not look like entity references as literal ampersands. XML-based user agents will not tolerate this incorrect usage, and any document that uses an ampersand incorrectly will not be "valid", and consequently will not conform to this specification. In order to ensure that documents are compatible with historical HTML user agents and XML-based user agents,


ampersands used in a document that are to be treated as literal characters must be expressed themselves as an entity reference (e.g. "&"). For example, when the href attribute of the a element refers to a CGI script that takes parameters, it must be expressed as recommended: C.13. Cascading Style Sheets (CSS) and XHTML The Cascading Style Sheets level 2 Recommendation [CSS2] defines style properties which are applied to the parse tree of the HTML or XML documents. Differences in parsing will produce different visual or aural results, depending on the selectors used. The following hints will reduce this effect for documents which are served without modification as both media types: CSS style sheets for XHTML should use lower case element and attribute names. In tables, the tbody element will be inferred by the parser of an HTML user agent, but not by the parser of an XML user agent. Therefore you should always explicitly add a tbody element if it is referred to in a CSS selector. Within the XHTML namespace, user agents are expected to recognize the "id" attribute as an attribute of type ID. Therefore, style sheets should be able to continue using the shorthand "#" selector syntax even if the user agent does not read the DTD. Within the XHTML namespace, user agents are expected to recognize the "class" attribute. Therefore, style sheets should be able to continue using the shorthand "." selector syntax. CSS defines different conformance rules for HTML and XML documents; be aware that the HTML rules apply to XHTML documents delivered as HTML and the XML rules apply to XHTML documents delivered as XML. C.14. Referencing Style Elements when serving as XML In HTML 4 and XHTML, the style element can be used to define document-internal style rules. In XML, an XML stylesheet declaration is used to define style rules. In order to be compatible with this convention, style elements should have their fragment identifier set using the id attribute, and an XML stylesheet declaration should reference this fragment. For example: <?xml-stylesheet href="type="text/css"?> <?xml-stylesheet href="#internalStyle" type="text/css"?> <!DOCTYPE html <head> <title>An internal stylesheet example</title> <style type="text/css" id="internalStyle"> code { color: green; font-family: monospace; font-weight: bold; }


</style> </head> <body> <p> This is text that uses our <code>internal stylesheet</code>. </p> </body> </html> C.15. White Space Characters in HTML vs. XML Some characters that are legal in HTML documents, are illegal in XML document. For example, in HTML, the Formfeed character (U+000C) is treated as white space, in XHTML, due to XML's definition of characters, it is illegal. C.16. The Named Character Reference ' The named character reference ' (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use ' instead of ' to work as expected in HTML 4 user agents. :) Mr. Mandarino


Copyright 1996, Meme. The Text of this program may be freely distributed so long as this copyright notice is included in it's entirety and any changes from the original text of the program are clearly noted. The inclusion of a diff between the original and the modified version with the distribution satisfies this requirement. This program may be freely used by non profit organizations and individuals personal use, all others are licensed to use this program upon payment of $10 U.S. to: Meme 907 North Hazard Avenue Los Angeles Ca. 90063 The user assumes all liability and risk associated with the use of this program. -----------------------------<end of copyright notice>---------------Comments and corrections may be addressed to the author A. Mandarino, <adm@meme.com>. C cgi program to display animation. Arguments: The first is an environment variable, the remainder are supplied on the command line separated by plus signs. All arguments must be supplied. Directory The frames are in. As supplied by the caller is appended to the path of the called cgi program in the invoking URL. This path is translated by the server in the same way it translates all paths in URLs,


so usually this will be relative to the DocumentRoot HTTPD server configuration parameter although ~ may be able to be used to reference relative to a user's home directory. Referenced in this code through the PATH_TRANSLATED environment variable, which supplies relative to the default directory of the cgi process. Starting Frame number. Ending Frame number. Prefix Which appears before the frame number in each filename. May not contain the ../ sequence of characters. Suffix Which appears after the frame number in each filename. May not contain the ../ sequence of characters. Delay After display of each frame, In microseconds. The actual accuracy of this is the same as that of the setitimer(2) signal. At the time of this writing it is accurate to 10 milliseconds. At least this long of an interval will occur between the output of the beginning of each frame. FrameMType Mime type/subtype of the frames. Final Path to final frame (relative to Directory argument.) Must be a relative pathname (no leading /.) Null string when there is no final frame. May not contain the ../ sequence of characters. FinalMType Mime type/subtype of the final frame. Uses server push. Errors result in termination of the animation and generation of a message. I was careful to encode mime stuff with carriage return/line feed as per RFC1341. I was careful to check for buffer overrun and consequent security holes when calling sprintf to substitute a caller supplied string into a fixed length buffer. Example: <image src="http:/cgi-bin/pushprog/~rima/tc/gifs?1+10+ +.gif+2500000+image/gif+1.gif+image/gif"> The pieces are:


http:/cgi-bin/pushprog /~rima/tc/gifs ? 1 + 10

.gif

2500000 image/gif 1.gif

image/gif

Run the pushprog cgi program on the current machine. Directory: /~rima/tc/gifs Start of command line arguments. Starting: 1 (with 1st frame) Space (occurs between arguments) (Will be left out from now on.) Ending: 10 (Display through 10th frame) Prefix: none Suffix: .gif (Files are named N.gif, N is frame #) Delay: 2.5 seconds between frames FrameMType: image/gif (Frames are gif images) Final: 1.gif (Redisplay /~rima/tc/gifs/1.gif as last frame) FinalMType: image/gif (Last frame is a gif too.) Bugs:

We could allow the "../" substring in Prefix, Suffix, and Final, so long as we check that we don't back up past DOCUMENT_ROOT. Relies on the server to deliver the frames in a timely manner. Apparently, this does not always happen. The trouble seems to be that the server waits for some buffer to fill. Perhaps this can be avoided in the NCSA HTTPD server by compiling it with CGI_SSI_HACK defined. Does something weird when outputting a file containing the MULTIPART_DELIMITER string. Doesn't check for error on munmap call due to lack of documented return code. Failure on write of mime multipart header or delimiter may not produce a clean error message. The error messages don't do squat when used in a <img src="..."> type html clause because the browser is expecting a image and I'm returning ascii text (although with the correct mime type.) */


#include <fcntl.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> /* Forward function declarations. */ void send_frame(int fvar, char * mime_type) ; void frame_error(char * mesg) ; void legal_path(char * path, char * argname) ; void server_error(char * mesg) ; void delay_till_alarm(int microseconds) ; void alarm_handler(int signal) ; /* The largest string we can handle. */ #define MULTIPART_DELIMITER "--ThisRandomString" #define CONTENT_TYPE "Content-type: %s\r\n\r\n" /* blank line follows header */ #define MAX_SSIZE 500 char error_mesg[MAX_SSIZE] ; char buf[MAX_SSIZE] ; int buf_len ; /* number of chars in previous */ char rep_multipart_delimiter[sizeof(MULTIPART_DELIMITER) + 10] ; int rmd_len ; /* number of chars in previous */ char final_multipart_delimiter[sizeof(MULTIPART_DELIMITER) + 10] ; int fmd_len ; /* number of chars in previous */ int alarm_received = 1 ; /* A boolean, used in the timer system. */ /* Initialize so there's no pause before the first frame. */ int main(int argc, char ** argv) { #define ARGS_EXPECTED 9 char * directory ; int starting ; int ending ; char * prefix ;


char * suffix ; int delay ; char * frame_mtype ; char * final ; char * final_mtype ; char filepath[MAX_SSIZE] ; struct itimerval timerval ; FILE * stdout_stream ; int step ; int display_frames ; int frame_no ; int fd ; char * final_path ; int directory_size ; char * filepath_format = "%s/%s%d%s" ; #define MIME_HEADER "Content-type: multipart/x-mixedreplace;boundary=ThisRandomString\r\n" /* Initialize globals. */ rmd_len = sprintf(rep_multipart_delimiter, "\r\n%s\r\n", MULTIPART_DELIMITER) ; fmd_len = sprintf(final_multipart_delimiter, "\r\n%s--\r\n", MULTIPART_DELIMITER) ; /* Get all the arguments. */ if ((directory = getenv("PATH_TRANSLATED")) == NULL) server_error("No PATH_TRANSLATED.") ; directory_size = strlen(directory) ; if (argc != ARGS_EXPECTED) { sprintf(error_mesg, "Wrong number of arguments to cgi program. \ Expected %d, got: %d", ARGS_EXPECTED, argc) ; server_error(error_mesg) ; } starting = atoi(argv[1]) ;


ending = atoi(argv[2]) ; prefix = argv[3] ; suffix = argv[4] ; delay = atoi(argv[5]) ; frame_mtype = argv[6] ; final = argv[7] ; final_mtype = argv[8] ; /* Check the arguments. */ /* The supplied paths cannot reference "../" */ legal_path(prefix, "Prefix") ; legal_path(suffix, "Suffix") ; legal_path(final, "Final") ; /* See that the supplied prefix and suffix won't overflow our buffers. */ if (strlen(filepath_format) + directory_size + strlen(prefix) + 10 + /* for decimal representation of frame_no */ strlen(suffix) > sizeof(filepath) - 1 /* for trailing \0 */ ) server_error("The filepath variable has overrun it's storage because the prefix and suffix are too long.") ; /* Check the length of the mime content type. (For send_frame.) */ if (strlen(CONTENT_TYPE) - 2 + /* for the %s */ strlen(frame_mtype) > sizeof(buf) - 1 /* for trailing \0 */ ) server_error("Buffer overrun, mime content type too long") ;

/* See that the timer is not being used. */ if (getitimer(ITIMER_REAL, &timerval) || timerval.it_value.tv_sec || timerval.it_value.tv_usec) server_error("Real time timer already in use.") ; /* Get a stream pointer for stdout so we can flush it. */ stdout_stream = fdopen(STDOUT_FILENO, "a" ) ; if (stdout_stream == NULL)


server_error("Unable to associate a stream with stdout.") ; if (strlen(final) != 0) { /* Make the Final argument relative to PATH_TRANSLATED, instead of cgi-bin. Construct the full pathname. (final_path) */ int final_path_size ; int final_offset ; /* Allocate memory for the full pathname. */ final_path_size = directory_size + strlen(final) ; if (directory[directory_size] == '/') final_path_size += 1 ; final_path = (char *) malloc(final_path_size + 1) ; /* Construct full pathname. */ strcpy(final_path, directory) ; final_offset = directory_size ; if (directory[directory_size] != '/') { /* We need to add a / to delimit the end of the PATH_TRANSLATED. */ final_path[directory_size] = '/' ; final_offset += 1 ; } strcpy(final_path + final_offset, final) ; } /* Output the mime multipart header. */ if (write(STDOUT_FILENO, MIME_HEADER, strlen(MIME_HEADER)) == -1) /* This may produce trash if the header is partially output. */ server_error("Cannot output mime multipart header.") ; /* Start the frame display process with a multipart delimiter. */ if (write(STDOUT_FILENO, rep_multipart_delimiter, rmd_len) == -1) frame_error("Cannot write multipart delimiter") ; /* Go through each frame, displaying it. */ display_frames = abs(ending - starting) + 1 ; if ( starting <= ending ) step = 1 ; else step = -1 ;


frame_no = starting ; while(1) { /* Open the file. */ sprintf(filepath, filepath_format, directory, prefix, frame_no, suffix ) ; fd = open(filepath, O_RDONLY) ; if (fd == -1) { sprintf(error_mesg, "Unable to open the graphic file for frame: %d", frame_no ) ; frame_error(error_mesg) ; } /* Wait for the alarm, the reset it. */ delay_till_alarm (delay) ; /* Output the file. */ send_frame(fd, frame_mtype) ; /* Close the file. */ if (close(fd) == -1) { sprintf(error_mesg, "Unable to close the graphic file for frame: %d", frame_no ); frame_error(error_mesg) ; } /* Loop exit test. */ if (display_frames <= 1) break ; /* Output the mime-multipart delimiter to finish the frame. */ if (write(STDOUT_FILENO, rep_multipart_delimiter, rmd_len) == -1) frame_error("Cannot write multipart delimiter") ; /* Make sure that the output is sent. */ if (fflush(stdout_stream)) frame_error("Cannot flush stdout.") ; /* Prepare for next iteration. */


--display_frames ; frame_no = frame_no + step ; }; if (strlen(final) != 0) { /* There is a final frame. */ /* Output the mime-multipart delimiter to finish the previous frame. */ if (write(STDOUT_FILENO, rep_multipart_delimiter, rmd_len) == -1) frame_error("Cannot write multipart delimiter") ; /* Open the last frame. */ fd = open(final_path, O_RDONLY) ; if (fd == -1) frame_error("Unable to open the final frame.") ; /* Clean up after what we did to setup the final frame. */ free(final_path) ; /* Wait for the alarm, then reset it. */ delay_till_alarm(delay) ; /* Output the last frame. */ send_frame(fd, final_mtype) ; } /* Finish frame outputting entirely. */ if (write(STDOUT_FILENO, final_multipart_delimiter, fmd_len) == -1) server_error("Cannot write final multipart delimiter.") ; /* Make sure that the output is sent. */ if (fflush(stdout_stream)) frame_error("Cannot flush stdout.") ; /* Cleanup The following is cleaned up by the OS when we exit. Close the file holding the final frame. Turn off real time timer. Reset signal handler to the default value. */


exit(EXIT_SUCCESS) ; }; void send_frame(int fvar, char * frame_mtype) { /* Sends a frame from the disk, the disk file is memory mapped. Input: fvar The file variable for the file. frame_mtype The mime type/subtype of the frame. */ struct stat file_status ; caddr_t memory_map ; /* Memory map the file. */ if (fstat(fvar, &file_status)) frame_error("send_frame: fstat called failed.") ; memory_map = mmap(NULL, file_status.st_size, PROT_READ, MAP_PRIVATE | MAP_FILE, fvar, 0) ; if (memory_map == (caddr_t) -1) frame_error("send_frame: mmap call failed.") ; /* Build a mime content type header in the buf global. */ buf_len = sprintf(buf, CONTENT_TYPE, frame_mtype) ; /* Output the content type of the frame. */ if (write(STDOUT_FILENO, buf, buf_len) == -1) { /* Cannot call frame error because we may have already sent the content type. */ write(STDOUT_FILENO, final_multipart_delimiter, fmd_len) ; exit(-1) ; } /* Output the contents of the file. */ if(write(STDOUT_FILENO, (char *) memory_map, file_status.st_size) == -1) { /* Can't call frame error because we have already sent out the


Mime content type. Just finish sending the frame and stop with an error exit. */ write(STDOUT_FILENO, final_multipart_delimiter, fmd_len) ; exit(-1) ; } munmap(memory_map, file_status.st_size) ; return ; }; void legal_path(char * path, char * argname) { /* Check to be sure that the path does not contain anything that would back it out of SERVER_ROOT. Right now this just checks for a ../ substring. */ if (strstr(path, "../") != NULL) { char * error_string ; error_string = "The '%s' argument's value (%s) contains the illegal '../' substring" ; if (strlen(error_string) - 2 - 2 + strlen(argname) + strlen(path) > sizeof(error_mesg) 1) /* The error message is too big. */ sprintf(error_mesg, "The '%s' argument's value contains the illegal '../' substring.", argname) ; else sprintf(error_mesg, error_string, argname, path) ; server_error(error_mesg) ; } return ; };

void frame_error(char * mesg) { /* Handle a fatal error while outputting frames. */ printf("Content_type: text/html\r\n\r\n") ; printf("<h1>Animation Server Error</h1>") ;


printf("This server encountered an error while attempting to display frames:") ; printf("%s", mesg) ; printf(final_multipart_delimiter) ; exit(-1) ; } void server_error(char * mesg) { /* Output a message and stop. */ printf("Content-type: text/html\r\n\r\n"); printf("<h1>Animation Server Error</h1>"); printf("This server encountered an error:<p>"); printf("%s", mesg); exit(-1); } void delay_till_alarm(int waitfor) { /* Wait until the alarm has gone off. Then reset it to go off in waitfor microseconds. Input: waitfor The number of micro seconds to wait before the alarm should go off again. */ static struct itimerval timer_control = { { /* it_interval */ 0, /* tv_sec */ 0}, /* tv_usec */ { /* it_value */ 0, /* tv_sec */ 0}} ; /* tv_usec */ static struct sigaction handler_control = { &alarm_handler, /* sa_handler */ 0, /* sa_mask */ SA_NOMASK & SA_RESTART & SA_ONESHOT} ; /* sa_flags */ /* sa_restorer */ if (waitfor == 0) return ;


if (! alarm_received) pause() ; /* The alarm has gone off, turn it back on. */ timer_control.it_value.tv_usec = waitfor ; if(setitimer(ITIMER_REAL, &timer_control, NULL)) frame_error("delay_till_alarm: failed called to setitimer.") ; /* Establish a handler for the alarm. */ if (sigaction(SIGALRM, &handler_control, NULL )) frame_error("delay_till_alarm: failed call to sigaction.") ; alarm_received = 0 ; return ; } void alarm_handler(int signal) { /* Remember whether the alarm went off. */ alarm_received = 1 ; return ; }


A. Mandarino adm@cyberdude.com


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.