1.1.   Файловые системы в Windows XP/2k3. Основные особенности файловой системы NTFS.
1.2.   Имена файлов и папок (основные правила именования и ограничения). Атрибуты файлов и папок.
1.3.   Назначение и особенности каталогов операционной системы, их размещение по умолчанию. Стандартные переменные окружения, соответствующие каталогам.
%ProgramFiles%
%CommonProgramFiles%
%Path%
%SystemDrive% и %SystemRoot%
%TEMP% и %TMP%
%windir%
%windir%\inf
%windir%\Installer
%windir%\Prefetch
%windir%\Security
%windir%\SoftwareDistribution
%windir%\WinSxS
%windir%\system32
%windir%\system32\config
%windir%\system32\dllcache
%windir%\system32\drivers
%windir%\system32\drivers\etc
1.1.   Специальные директории Windows Shell (Windows special folders). Их назначение, стандартные имена и расположение, конфигурирование через windows registry.
1.2.   Профиль пользователя (User profile). Типы профилей. Профили “All Users” и “Default User”. Структура профиля пользователя в файловой системе. Задание пути к профилю и к папке «My Documents»
1.3.   Защита файлов Windows (Windows File Protection).
1.4.   Сетевые папки (shared folders).
1.5.   Команды и утилиты: attrib, dir, copy, xcopy, del, move, rmdir, rd, subst, net share.




NTFS Design Goals and Features

In the following section, we'll look at the requirements that drove the design of NTFS. Then in the subsequent section, we'll examine the advanced features of NTFS.

High-End File System Requirements

From the start, NTFS was designed to include features required of an enterprise-class file system. To minimize data loss in the face of an unexpected system outage or crash, a file system must ensure that the integrity of its metadata is guaranteed at all times; and to protect sensitive data from unauthorized access, a file system must have an integrated security model. Finally, a file system must allow for software-based data redundancy as a low-cost alternative to hardware-redundant solutions for protecting user data. In this section, you'll find out how NTFS implements each of these capabilities.

Recoverability

To address the requirement for reliable data storage and data access, NTFS provides file system recovery based on the concept of an atomic transaction. Atomic transactions are a technique for handling modifications to a database so that system failures don't affect the correctness or integrity of the database. The basic tenet of atomic transactions is that some database operations, called transactions, are all-or-nothing propositions. (A transaction is defined as an I/O operation that alters file system data or changes the volume's directory structure.) The separate disk updates that make up the transaction must be executed atomically—that is, once the transaction begins to execute, all its disk updates must be completed. If a system failure interrupts the transaction, the part that has been completed must be undone, or rolled back. The rollback operation returns the database to a previously known and consistent state, as if the transaction had never occurred.

NTFS uses atomic transactions to implement its file system recovery feature. If a program initiates an I/O operation that alters the structure of an NTFS volume—that is, changes the directory structure, extends a file, allocates space for a new file, and so on—NTFS treats that operation as an atomic transaction. It guarantees that the transaction is either completed or, if the system fails while executing the transaction, rolled back. The details of how NTFS does this are explained in the section "NTFS Recovery Support" later in the chapter.

In addition, NTFS uses redundant storage for vital file system information so that if a sector on the disk goes bad, NTFS can still access the volume's critical file system data. This redundancy of file system data contrasts with the on-disk structures of both the FAT file system and the HPFS file system (OS/2's native file system format), which have single sectors containing critical file system data. On these file systems, if a read error occurs in one of those sectors an entire volume is lost.

Security

Security in NTFS is derived directly from the Windows object model. Files and directories are protected from being accessed by unauthorized users. (For more information on Windows security, see Chapter 8.) An open file is implemented as a file object with a security descriptor stored on disk as a part of the file. Before a process can open a handle to any object, including a file object, the Windows security system verifies that the process has appropriate authorization to do so. The security descriptor, combined with the requirement that a user log on to the system and provide an identifying password, ensures that no process can access a file unless given specific permission to do so by a system administrator or by the file's owner. (For more information about security descriptors, see the section "Security Descriptors and Access Control" in Chapter 8, and for more details about file objects, see the section "File Objects" in Chapter 9.)

Data Redundancy and Fault Tolerance

In addition to recoverability of file system data, some customers require that their own data not be endangered by a power outage or catastrophic disk failure. The NTFS recovery capabilities do ensure that the file system on a volume remains accessible, but they make no guarantees for complete recovery of user files. Protection for applications that can't risk losing file data is provided through data redundancy.

Data redundancy for user files is implemented via the Windows layered driver model (explained in Chapter 9), which provides fault-tolerant disk support. NTFS communicates with a volume manager, which in turn communicates with a hard disk driver to write data to disk. A volume manager can mirror, or duplicate, data from one disk onto another disk so that a redundant copy can always be retrieved. This support is commonly called RAID level 1. Volume managers also allow data to be written in stripes across three or more disks, using the equivalent of one disk to maintain parity information. If the data on one disk is lost or becomes inaccessible, the driver can reconstruct the disk's contents by means of exclusive-OR operations. This support is called RAID level 5. (See Chapter 10 for more information on striped volumes, mirrored volumes, and RAID-5 volumes.)

Advanced Features of NTFS

In addition to NTFS being recoverable, secure, reliable, and efficient for mission-critical systems, it includes the following advanced features that allow it to support a broad range of applications. Some of these features are exposed as APIs for applications to leverage, and others are internal features:

  • Multiple data streams

  • Unicode-based names

  • General indexing facility

  • Dynamic bad-cluster remapping

  • Hard links and junctions

  • Compression and sparse files

  • Change logging

  • Per-user volume quotas

  • Link tracking

  • Encryption

  • POSIX support

  • Defragmentation

  • Read-only support

The following sections provide an overview of these features.

Multiple Data Streams

In NTFS, each unit of information associated with a file—including its name, its owner, its time stamps, its contents, and so on—is implemented as a file attribute (NTFS object attribute). Each attribute consists of a single stream—that is, a simple sequence of bytes. This generic implementation makes it easy to add more attributes (and therefore more streams) to a file.

Because a file's data is "just another attribute" of the file and because new attributes can be added, NTFS files (and file directories) can contain multiple data streams.

An NTFS file has one default data stream, which has no name. An application can create additional, named data streams and access them by referring to their names. To avoid altering the Microsoft Windows I/O APIs, which take a string as a filename argument, the name of the data stream is specified by appending a colon (:) to the filename. Because the colon is a reserved character, it can serve as a separator between the filename and the data stream name, as illustrated in this example:

myfile.dat:stream2

Each stream has a separate allocation size (which defines how much disk space has been reserved for it), actual size (which is how many bytes the caller has used), and valid data length (which is how much of the stream has been initialized). In addition, each stream is given a separate file lock that is used to lock byte ranges and to allow concurrent access.

One component in Windows that uses multiple data streams is the Apple Macintosh file server support that comes with Windows Server. Macintosh systems use two streams per file— one to store data and the other to store resource information, such as the file type and the icon used to represent the file. Because NTFS allows multiple data streams, a Macintosh user can copy an entire Macintosh folder to a Windows server, and another Macintosh user can copy the folder from the server without losing resource information.

Windows Explorer is another application that uses streams. When you right-click on an NTFS file and select Properties, the Summary tab of the resulting dialog box lets you associate information with the file, such as a title, subject, author, and keywords. Windows Explorer stores the information in an alternate stream it adds to the file, named Summary Information.

Other applications can use the multiple data stream feature as well. A backup utility, for example, might use an extra data stream to store backup-specific time stamps on files. Or an archival utility might implement hierarchical storage in which files that are older than a certain date or that haven't been accessed for a specified period of time are moved to tape. The utility could copy the file to tape, set the file's default data stream to 0, and add a data stream that specifies the name and location of the tape on which the file is stored.

EXPERIMENT: Looking at Streams

Most Windows applications aren't designed to work with alternate named streams, but both the echo and more commands are. Thus, a simple way to view streams in action is to create a named stream using echo and then display it using more. The following command sequence creates a file named test with a stream named stream:

C:\>echo hello > test:stream

C:\>more < test:stream

hello

C:\>

If you perform a directory listing, test's file size doesn't reflect the data stored in the alternate stream because NTFS returns the size of only the unnamed data stream for file query operations, including directory listings.

C:\>dir  test

Volume in drive C is WINDOWS

Volume Serial Number is 3991-3040



Directory of C:\



08/01/00 02:37p 0 test

1 File(s) 0 bytes

112,558,080 bytes free

You can determine what files and directories on your system have alternate data streams with the Streams utility from http://www.sysinternals.com:

C:\>streams test



Streams v1.5 - Enumerate alternate NTFS data streams

Copyright (C) 1999-2003 Mark Russinovich

Sysinternals - www.sysinternals.com

C:\Temp\test:

:stream:$DATA 8


Unicode-Based Names

Like Windows as a whole, NTFS is fully Unicode enabled, using Unicode characters to store names of files, directories, and volumes. Unicode, a 16-bit character-coding scheme, allows each character in each of the world's major languages to be uniquely represented, which aids in moving data easily from one country to another. Unicode is an improvement over the traditional representation of international characters—using a double-byte coding scheme that stores some characters in 8 bits and others in 16 bits, a technique that requires loading various code pages to establish the available characters. Because Unicode has a unique representation for each character, it doesn't depend on which code page is loaded. Each directory and filename in a path can be as many as 255 characters long and can contain Unicode characters, embedded spaces, and multiple periods.

General Indexing Facility

The NTFS architecture is structured to allow indexing of file attributes on a disk volume. This structure enables the file system to efficiently locate files that match certain criteria—for example, all the files in a particular directory. The FAT file system indexes filenames but doesn't sort them, making lookups in large directories slow.

Several NTFS features take advantage of general indexing, including consolidated security descriptors, in which the security descriptors of a volume's files and directories are stored in a single internal stream, have duplicates removed, and are indexed using an internal security identifier that NTFS defines. The use of indexing by these features is described in the section "NTFS On-Disk Structure" later in this chapter.

Dynamic Bad-Cluster Remapping

Ordinarily, if a program tries to read data from a bad disk sector, the read operation fails and the data in the allocated cluster becomes inaccessible. If the disk is formatted as a fault-tolerant NTFS volume, however, the Windows fault-tolerant driver dynamically retrieves a good copy of the data that was stored on the bad sector and then sends NTFS a warning that the sector is bad. NTFS allocates a new cluster, replacing the cluster in which the bad sector resides, and copies the data to the new cluster. It flags the bad cluster and no longer uses it. This data recovery and dynamic bad-cluster remapping is an especially useful feature for file servers and fault-tolerant systems or for any application that can't afford to lose data. If the volume manager isn't loaded when a sector goes bad, NTFS still replaces the cluster and doesn't reuse it, but it can't recover the data that was on the bad sector.

Hard Links and Junctions

A hard link allows multiple paths to refer to the same file. (Hard links are not supported on directories.) If you create a hard link named C:\Users\Documents\Spec.doc that refers to the existing file C:\My Documents\Spec.doc, the two paths link to the same on-disk file and you can make changes to the file using either path. Processes can create hard links with the Windows CreateHardLink function or the ln POSIX function.

In addition to hard links, NTFS supports another type of redirection called junctions. Junctions, also called symbolic links, allow a directory to redirect file or directory pathname translation to an alternate directory. For example, if the path C:\Drivers is a junction that redirects to C:\Windows\System32\Drivers, an application reading C:\Drivers\Ntfs.sys actually reads C:\Windows\System\Drivers\Ntfs.sys. Junctions are a useful way to lift directories that are deep in a directory tree to a more convenient depth without disturbing the original tree's structure or contents. The example just cited lifts the drivers directory to the volume's root directory, reducing the directory depth of Ntfs.sys from three levels to one when Ntfs.sys is accessed through the junction. You can't use junctions to link to remote directories—only to directories on local volumes.

Junctions are based on an NTFS mechanism called reparse points. (Reparse points are discussed further in the section "Reparse Points" later in this chapter.) A reparse point is a file or directory that has a block of data called reparse data associated with it. Reparse data is userdefined data about the file or directory, such as its state or location, that can be read from the reparse point by the application that created the data, a file system filter driver, or the I/O manager. When NTFS encounters a reparse point during a file or directory lookup, it returns a reparse status code, which signals file system filter drivers that are attached to the volume, and the I/O manager, to examine the reparse data. Each reparse point type has a unique reparse tag. The reparse tag allows the component responsible for interpreting the reparse point's reparse data to recognize the reparse point without having to check the reparse data. A reparse tag owner, either a file system filter driver or the I/O manager, can choose one of the following options when it recognizes reparse data:

  • The reparse tag owner can manipulate the pathname specified in the file I/O operation that crosses the reparse point and let the I/O operation reissue with the altered pathname. Junctions take this approach to redirect a directory lookup, for example.

  • The reparse tag owner can remove the reparse point from the file, alter the file in some way, and then reissue the file I/O operation. The Windows Hierarchical Storage Management (HSM) system uses reparse points in this way. HSM archives files by moving their contents to tape, leaving reparse points in their place. When a process accesses a file that has been archived, the HSM filter driver (\Windows\System32\Drivers\Rsfilter.sys) removes the reparse point from the file, reads the file's data from the archival media, and reissues the access. Thus, the retrieval of the offline data is transparent to a process accessing an archived file.

There are no Windows functions for creating reparse points. Instead, processes must use the FSCTL_SET_REPARSE_POINT file system control code with the Windows DeviceIoControl function. A process can query a reparse point's contents with the FSCTL_GET_REPARSE_ POINT file system control code. The FILE_ATTRIBUTE_REPARSE_POINT flag is set in a reparse point's file attributes, so applications can check for reparse points by using the Windows GetFileAttributes function.

EXPERIMENT: Creating a Junction

Windows doesn't include any tools for creating junctions, but you can create a junction with either the Junction tool from http://www.sysinternals.com (which includes source code) or the Windows resource kits tool Linkd. The Linkd tool also lets you view the definition of existing junctions, and Junction lets you view information about junctions and other reparse point tags.


Compression and Sparse Files

NTFS supports compression of file data. Because NTFS performs compression and decompression procedures transparently, applications don't have to be modified to take advantage of this feature. Directories can also be compressed, which means that any files subsequently created in the directory are compressed.

Applications compress and decompress files by passing DeviceIoControl the FSCTL_SET_ COMPRESSION file system control code. They query the compression state of a file or directory with the FSCTL_GET_COMPRESSION file system control code. A file or directory that is compressed has the FILE_ATTRIBUTE_COMPRESSED flag set in its attributes, so applications can also determine a file or directory's compression state with GetFileAttributes.

A second type of compression is known as sparse files. If a file is marked as sparse, NTFS doesn't allocate space on a volume for portions of the file that an application designates as empty. NTFS returns 0-filled buffers when an application reads from empty areas of a sparse file. This type of compression can be useful for client/server applications that implement circular-buffer logging, in which the server records information to a file and clients asynchronously read the information. Because the information that the server writes isn't needed after a client has read it, there's no need to store the information in the file. By making such a file sparse, the client can specify the portions of the file it reads as empty, freeing up space on the volume. The server can continue to append new information to the file, without fear that the file will grow to consume all available space on the volume.

As for compressed files, NTFS manages sparse files transparently. Applications specify a file's sparseness state by passing the FSCTL_SET_SPARSE file system control code to DeviceIoControl. To set a range of a file to empty, applications use the FSCTL_SET_ZERO_DATA code, and they can ask NTFS for a description of what parts of a file are sparse by using the control code FSCTL_QUERY_ALLOCATED_RANGES. One application of sparse files is the NTFS change journal, described next.

Change Logging

Many types of applications need to monitor volumes for file and directory changes. For example, an automatic backup program might perform an initial full backup and then incremental backups based on file changes. An obvious way for an application to monitor a volume for changes is for it to scan the volume, recording the state of files and directories, and on a subsequent scan detect differences. This process can adversely affect system performance, however, especially on computers with thousands or tens of thousands of files.

An alternate approach is for an application to register a directory notification by using the FindFirstChangeNotification or ReadDirectoryChangesW Windows functions. As an input parameter, the application specifies the name of a directory it wants to monitor, and the function returns whenever the contents of the directory changes. Although this approach is more efficient than volume scanning, it requires the application to be running at all times. Using these functions can also require an application to scan directories because FindFirstChangeNotification doesn't indicate what changed—just that something in the directory has changed. An application can pass a buffer to ReadDirectoryChangesW that the FSD fills in with change records. If the buffer overflows, however, the application must be prepared to fall back on scanning the directory.

NTFS provides a third approach that overcomes the drawbacks of the first two: an application can configure the NTFS change journal facility by using the DeviceIoControl function's FSCTL_CREATE_USN_JOURNAL file system control code to have NTFS record information about file and directory changes to an internal file called the change journal. A change journal is usually large enough to virtually guarantee that applications get a chance to process changes without missing any. Applications use the FSCTL_QUERY_USN_JOURNAL file system control to read records from a change journal, and they can specify that the DeviceIoControl function not complete until new records are available.

Per-User Volume Quotas

Systems administrators often need to track or limit user disk space usage on shared storage volumes, so NTFS includes quota-management support. NTFS quota-management support allows for per-user specification of quota enforcement, which is useful for usage tracking and tracking when a user reaches warning and limit thresholds. NTFS can be configured to log an event indicating the occurrence to the system Event Log if a user surpasses his warning limit. Similarly, if a user attempts to use more volume storage then her quota limit permits, NTFS can log an event to the system Event Log and fail the application file I/O that would have caused the quota violation with a "disk full" error code.

NTFS tracks a user's volume usage by relying on the fact that it tags files and directories with the security ID (SID) of the user who created them. (See Chapter 8 for a definition of SIDs.) The logical sizes of files and directories a user owns count against the user's administratordefined quota limit. Thus, a user can't circumvent his or her quota limit by creating an empty sparse file that is larger than the quota would allow and then fill the file with nonzero data. Similarly, whereas a 50-KB file might compress to 10 KB, the full 50 KB is used for quota accounting.

By default, volumes don't have quota tracking enabled. You need to use the Quota tab of a volume's Properties dialog box, shown in Figure 12-18, to enable quotas, to specify default warning and limit thresholds, and to configure the NTFS behavior that occurs when a user hits the warning or limit threshold. The Quota Entries tool, which you can launch from this dialog box, enables an administrator to specify different limits and behavior for each user. Applications that want to interact with NTFS quota management use COM quota interfaces, including IDiskQuotaControl, IDiskQuotaUser, and IDiskQuotaEvents.

 

Figure 12-18. Volume Properties dialog box


Link Tracking

Shell shortcuts allow users to place files in their shell namespace (on their desktop, for example) that link to files located in the file system namespace. The Windows Start menu uses shell shortcuts extensively. Similarly, object linking and embedding (OLE) links allow documents from one application to be transparently embedded in the documents of other applications. The products of the Microsoft Office suite, including PowerPoint, Excel, and Word, use OLE linking.

Although shell and OLE links provide an easy way to connect files with one another and with the shell namespace, they have in the past been difficult to manage. If a user moves the source of a shell or OLE link (a link source is the file or directory to which a link points) in Windows NT 4, Windows 95, or Windows 98, the link will be broken and the system has to rely on heuristics to attempt to locate the link's source. NTFS in Windows includes support for a service application called distributed link-tracking, which maintains the integrity of shell and OLE links when link targets move. Using the NTFS link-tracking support, if a link source located on an NTFS volume moves to any other NTFS volume within the originating volume's domain, the link-tracking service can transparently follow the movement and update the link to reflect the change.

NTFS link-tracking support is based on an optional file attribute known as an object ID. An application can assign an object ID to a file by using the FSCTL_CREATE_OR_GET_OBJECT_ID (which assigns an ID if one isn't already assigned) and FSCTL_SET_OBJECT_ID file system control codes. Object IDs are queried with the FSCTL_CREATE_OR_GET_OBJECT_ID and FSCTL_GET_OBJECT_ID file system control codes. The FSCTL_DELETE_OBJECT_ID file system control code lets applications delete object IDs from files.

Encryption

Corporate users often store sensitive information on their computers. Although data stored on company servers is usually safely protected with proper network security settings and physical access control, data stored on laptops can be exposed when a laptop is lost or stolen. NTFS file permissions don't offer protection because NTFS volumes can be fully accessed without regard to security by using NTFS file-reading software that doesn't require Windows to be running. Furthermore, NTFS file permissions are rendered useless when an alternate Windows installation is used to access files from an administrator account. Recall from Chapter 8 that the administrator account has the take-ownership and backup privileges, both of which allow it to access any secured object by overriding the object's security settings.

NTFS includes a facility called Encrypting File System (EFS), which users can use to encrypt sensitive data. The operation of EFS, as that of file compression, is completely transparent to applications, which means that file data is automatically decrypted when an application running in the account of a user authorized to view the data reads it and is automatically encrypted when an authorized application changes the data.

Note

NTFS doesn't permit the encryption of files located in the system volume's root directory or in the \Windows directory because many files in these locations are required during the boot process and EFS isn't active during the boot process.


EFS relies on cryptographic services supplied by Windows in user mode, so it consists of both a kernel-mode component that tightly integrates with NTFS as well as user-mode DLLs that communicate with the Local Security Authority Subsystem (LSASS) and cryptographic DLLs.

Files that are encrypted can be accessed only by using the private key of an account's EFS private/public key pair, and private keys are locked using an account's password. Thus, EFSencrypted files on lost or stolen laptops can't be accessed using any means (other than a brute-force cryptographic attack) without the password of an account that is authorized to view the data.

Applications can use the EncryptFile and DecryptFile Windows API functions to encrypt and decrypt files, and FileEncryptionStatus to retrieve a file or directory's EFS-related attributes, such as whether the file or directory is encrypted.

POSIX Support

As explained in Chapter 2, one of the mandates for Windows was to fully support the POSIX 1003.1 standard. In the file system area, the POSIX standard requires support for case-sensitive file and directory names, traversal permissions (where security for each directory of a path is used when determining whether a user has access to a file or directory), a "file-changetime" time stamp (which is different than the MS-DOS "time-last-modified" stamp), and hard links (multiple directory entries that point to the same file). NTFS implements each of these features.

Defragmentation

A common myth that many people have held since the introduction of NTFS is that it automatically optimizes file placement on disk so as not to fragment the files. While it does make efforts to keep files contiguous, a volume's files can become fragmented over time, especially when there is limited free space. A file is fragmented if its data occupies discontiguous clusters. For example, Figure 12-19 shows a fragmented file consisting of three fragments. However, like most file systems (including versions of FAT on Windows), NTFS makes no special efforts to keep files contiguous, other than to reserve a region of disk space known as the master file table (MFT) zone for the MFT. (NTFS lets other files allocate from the MFT zone when volume free space runs low.) Keeping an area free for the MFT can help it stay contiguous, but it, too, can become fragmented. (See the section "Master File Table" later in this chapter for more information on MFTs.)

 

Figure 12-19. Fragmented and contiguous files


To facilitate the development of third-party disk defragmentation tools, Windows includes a defragmentation API that such tools can use to move file data so that files occupy contiguous clusters. The API consists of file system controls that let applications obtain a map of a volume's free and in-use clusters (FSCTL_GET_VOLUME_BITMAP), obtain a map of a file's cluster usage (FSCTL_GET_RETRIEVAL_POINTERS), and move a file (FSCTL_MOVE_ FILE).

Windows includes a built-in defragmentation tool that is accessible by using the Disk Defragmenter utility (\Windows\System32\Dfrg.msc). The built-in defragmentation tool has a number of limitations that on Windows 2000 include an inability to be run from the command prompt or to be automatically scheduled. In Windows XP and Windows Server 2003, the defragmenter has a command-line interface, \Windows\System32\Defrag.exe, that you can run interactively or schedule, but that does not produce detailed reports or offer control— such as excluding files or directories—over the defragmentation process. Third-party disk defragmentation products typically offer a richer feature set.

In Windows XP, the defragmentation support in NTFS was rewritten to alleviate restrictions present in Windows 2000. For example, in Windows 2000 the defragmenting support in NTFS relies on the cache manager, which introduces a number of limitations such as the inability to move pieces of a file that cross a 256-KB boundary within the file or to defragment NTFS metadata files (such as the Master File Table). (Note that 256 KB is the size of a cache manager view. See Chapter 11 for more information on the cache manager.) In Windows XP and Windows Server 2003, the only limitations imposed by the defragmentation implementation in NTFS is that paging files and NTFS log files cannot be defragmented.

Read-Only Support

Prior to Windows XP, the NTFS file system driver required that volumes it mounted be on writeable media so that it could reset its transactional log files. The Windows XP and Windows Server 2003 NTFS drivers can mount volumes on read-only media, functionality required by embedded systems that have read-only base file system images.

Previous Section  < Day Day Up >  Next Section



Переменные среды

Среда исполнения программ реализуется в виде набора строковых переменных (пар {имя, значение}). Такая реализация среды принята и в Windows, и в Unix/Linux. Эти строковые переменные называются переменными среды (окружения).

Операционная система задаёт некоторый предопределённый набор таких пар. Например, Windows XP может использовать следующий набор переменных среды:

ALLUSERSPROFILE=C:\Documents and Settings\All Users

CLASSPATH=.;C:\SQLLIB\java\db2java.zip;C:\SQLLIB\java\runtime.zip;C:\SQLLIB\java\sqlj.zip

CommonProgramFiles=C:\Program Files\Common Files

COMPUTERNAME=HOME

ComSpec=C:\WINDOWS\system32\cmd.exe

FARLANG=English

HOMEDRIVE=C:

HOMEPATH=\Documents and Settings\vak

LOGONSERVER=\\HOME

NUMBER_OF_PROCESSORS=1

OS=Windows_NT

Path= C:\Perl\bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\PHP4.3.10\dlls;C:\PHP4.3.10\cli;C:\PHP4.3.10

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

PHPRC=C:\PHP4.3.10

PROCESSOR_ARCHITECTURE=x86

PROCESSOR_IDENTIFIER=x86 Family 15 Model 2 Stepping 9, GenuineIntel

PROCESSOR_LEVEL=15

PROCESSOR_REVISION=0209

ProgramFiles=C:\Program Files

PROMPT=G

SESSIONNAME=Console

SystemDrive=C:

SystemRoot=C:\WINDOWS

TEMP=C:\TEMP

TMP=C:\TEMP

USERDOMAIN=HOME

USERNAME=vak

USERPROFILE=C:\Documents and Settings\vak

windir=C:\WINDOWS

Некоторые из переменных среды в приведённом примере относятся к аппаратуре:

NUMBER_OF_PROCESSORS=1

PROCESSOR_ARCHITECTURE=x86

PROCESSOR_IDENTIFIER=x86 Family 15 Model 2 Stepping 9, GenuineIntel

PROCESSOR_LEVEL=15

PROCESSOR_REVISION=0209

Другие — к описанию компьютера:

COMPUTERNAME=HOME

LOGONSERVER=\\HOME

USERDOMAIN=HOME

Третьи — к самой ОС:

OS=Windows_NT

ALLUSERSPROFILE=C:\Documents and Settings\All Users

CommonProgramFiles=C:\Program Files\Common Files

ProgramFiles=C:\Program Files

SystemDrive=C:

SystemRoot=C:\WINDOWS

windir=C:\WINDOWS

Четвёртые описывают важные места в файловой системе: пути к каталогам, в которых следует разыскивать исполняемые программы и к каталогу, в котором следует создавать временные файлы:

Path= C:\Perl\bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\PHP4.3.10\dlls;C:\PHP4.3.10\cli;C:\PHP4.3.10

TEMP=C:\TEMP

TMP=C:\TEMP

Пятые содержат информацию о пользователе:

USERNAME=vak

USERPROFILE=C:\Documents and Settings\vak

HOMEDRIVE=C:

HOMEPATH=\Documents and Settings\vak

Шестые — о характеристиках интерактивного процесса:

PROMPT=G

SESSIONNAME=Console

ComSpec=C:\WINDOWS\system32\cmd.exe

Некоторые переменные среды относятся к отдельным приложениям, установленным в системе:

CLASSPATH=.;C:\SQLLIB\java\db2java.zip;C:\SQLLIB\java\runtime.zip;C:\SQLLIB\java\sqlj.zip

FARLANG=English

PHPRC=C:\PHP4.3.10

Пользователь может создавать переменные среды непосредственно перед запуском программы. В Windows для этого используется команда set (в окне командной строки):

set logFile=C:\gsBuild.log

Переменные среды исполнения программы используются приложением для адаптации своего поведения к конкретной среде, в которой оно выполняется.



The Windows shell is the main graphical user interface in Microsoft Windows, today hosted by Windows Explorer. The Windows shell includes well-known Windows components such as the Taskbar and the Start menu. The Windows shell is not the same as a "command-line shell" , but the two concepts are related.

The Windows Shell is not to be confused with Windows' window manager (the Desktop Window Manager in Windows Vista and forward or the USER subsystem in previous versions), which displays windows and controls how they look.

Features

[edit] Desktop

The Windows shell desktop is an array of icons, rendered behind all open windows and taking up the space left by the taskbar. The typical icons displayed on the desktop is as follows:

  • Shell folders, usually Documents or the Profile folder, Computer, Network and Recycle Bin. Since Windows XP, by default the only shell folder displayed on the desktop has been the Recycle Bin.
  • Shell launchers, special icons added through a shell extension. Examples include Internet Explorer and older versions of Microsoft Outlook.
  • Common shortcuts, or shortcuts that have been installed to the common desktop, usually by a third-party program.
  • User shortcuts, or shortcuts in the current user's desktop.
  • Desktop files and folders.

Right-clicking on a blank area of the desktop displays a menu which contains, apart from the usual file management and organisation options, links to the Personalisation and Screen Resolution control panels (Display Properties in earlier versions), and gadget configuration.

[edit] Taskbar

The taskbar is divided into three main areas:

  • The Start button, which provides access to the Start menu.
  • A list of open windows, with the active window's button rendered in a depressed fashion.
    • A list of shortcuts to programs for easy access. While previously this had its own area, called the Quick Launch toolbar, it has since been integrated into the list of open programs with the release of Windows 7.
    • Deskbands, which are toolbars provided by other programs for easier access to that program's functions.
  • The notification area, system icons and clock. Notifications display from a speech bubble which pops out from the relevant notification icon, while system icons provide access to commonly accessed functions like volume control and network status.

[edit] Start Menu

The Start menu consists of a dual-paned menu containing links to various programs and areas of the system.

The left pane of the start menu generally contains software-related shortcuts, including:

  • Links to the user's default Internet Browser and Email programs.
  • Pinned start menu items.
  • The user's most frequesntly used programs.
  • The All Programs menu, which cantains sortcuts to programs installed on your computer. Icons can be grouped in submenus called program groups.
  • A Search box, which can search for programs, files and control panel settings, as well as replacing the Run dialog and acting as a a rudimentry folder explorer.

The right pane contains links to folders and settings, including:

  • User account settings, accessed from the square containing the user's profile icon.
  • Shell folders, including the user's Profile, Documents, Pictures, and Music folders, the Games Explorer, and Computer.
  • The Control Panel, as well as the Devices and Printers and Default Programs control panels.
  • The Shut Down button, with a menu allowing the user to select other options.

 

 

Профиль пользователя содержит настройки компьютера для конкретного пользователя, включая личные параметры интерфейса и пользовательской среды.

Профиль создается при первом входе пользователя на компьютер под управлением операционной системы Windows XP, Windows 2000 или Windows NT. Профиль представляет собой ряд параметров и файлов, определяющих пользовательскую среду при входе в систему. В него входят настройки приложений, сетевые подключения и принтеры, настройки мыши, а также оформление и расположения окон. Профили не являются пользовательскими политиками. Даже если Вы не используете групповые политики, у пользователя все равно будет свой профиль.

Можно хранить данные пользователей на жестком диске или настроить перемещение данных вслед за пользователем, обеспечивая доступ к ним на любом компьютере локальной сети. В пользовательские данные входят ярлыки к исполняемым файлам, личные файлы и пользовательские настройки (например, собственный словарь офисного приложения).

В зависимости от методов управления локальной сетью, настройки компьютера могут быть заданы пользователем или системным администратором.

Следующие типы пользовательских профилей доступны в Windows 2003 Server, Windows XP Professional и Windows 2000 Professional.

  • Локальный профиль пользователя. Создается при первом входе пользователя в систему и хранится на локальном жестком диске. Любые изменения, сделанные в локальном пользовательском профиле, относятся только к компьютеру, на котором они были произведены.
  • Перемещаемый профиль пользователя. Копия локального профиля хранится на общем ресурсе сервера. Профиль загружается при каждом входе пользователя на компьютер локальной сети. Все изменения в перемещаемом профиле синхронизируются с копией на сервере по завершении пользовательского сеанса.
  • Обязательный профиль пользователя. ИТ специалисты могут использовать этот тип профиля, чтобы задать определенные пользовательские настройки. Изменения в обязательный профиль пользователя могут вносить лишь системные администраторы. Пользовательские изменения сохраняются только до окончания текущего сеанса.
  • Временный профиль пользователя. Временный профиль используется в тех случаях, когда из-за ошибки не удается загрузить профиль пользователя. По завершении сеанса временный профиль удаляется, и изменения, внесенные в настройки пользователя, не сохраняются.

Примечание. Если Вашей организации требуется управление конфигурациями различных групп пользователей и компьютеров, Вы можете воспользоваться групповыми политиками вместо обязательных профилей.

Преимущества профилей пользователей

 

Пользовательские профили призваны разделить обеспечить независимость данных и настроек для каждого пользователя и локального компьютера. Разделение настроек дает следующие преимущества:

  • «Обезличенный» компьютер. Компьютеры организации можно настроить для хранения настроек на серверных ресурсах. Это существенно упрощает замену компьютера или резервное копирование данных. Если возникнет необходимость в замене компьютера, то достаточно будет просто установить новый. Все пользовательские настройки надежно сохраняются в локальной сети и не привязаны к аппаратной конфигурации. Они будут скопированы при первом же входе пользователя в систему на новом компьютере.
  • Перемещение пользовательских настроек от компьютера к компьютеру избавляет от необходимости настраивать каждый компьютер под себя. При входе в систему на компьютере, поддерживающем перемещаемые профили, пользователь видит свой рабочий стол в точно таком же состоянии, в каком он был при завершении предыдущего сеанса. Внедрение поддержки перемещаемых пользователей позволяет им работать на различных компьютерах сети, сохраняя при этом собственный рабочий стол. Данную функциональность поддерживают как перемещаемый, так и обязательный профили.

Наверх страницы

Структура профиля пользователя

Профиль пользователя составляют:

  • Раздел системного реестра (куст). Реестр представляет собой базу данных общих и личных настроек пользователей. Части реестра могут быть сохранены в файлы, именуемые кустами. Такие кусты можно загрузить в реестр при необходимости. Преимущества этой технологии легли в основу функциональности перемещаемых профилей. Куст пользовательского профиля, по сути, представляет собой файл NTuser.dat, загружающийся в раздел реестра HKEY_CURRENT_USER при входе пользователя в систему. Файл NTuser.dat сохраняет все изменения настроек пользовательской среды, произведенные в течение сеанса. В этом файле сохраняются настройки сетевых подключений, конфигурация элементов панели управления, уникальных для каждого пользователя (например, обои на рабочем столе или настройки мыши), а также настройки приложений. Большинство пользовательских настроек доступно для изменения компонентам операционной системы и сторонним приложениям.
  • Набор папок профиля, хранящийся в файловой системе. Файлы пользовательских настроек хранятся в специально отведенном для этого каталоге. При этом для каждого пользователя создается отдельная папка, которую операционная система и приложения в процессе работы наполняют подпапками и файлами данных пользователя. Такими файлами могут быть ярлыки, иконки рабочего стола, автоматически загружаемые приложения, документы, конфигурационные файлы и т.д.

Вместе эти два компонента и составляют пользовательские настройки, которые можно перемещать от компьютера к компьютеру.

На компьютерах, работающих под управлением Windows NT, профили располагаются в системном каталоге %Systemroot%\profiles (обычно, WINNT\profiles). Однако, начиная с Windows 2000, расположение профилей по умолчанию было изменено. В операционных системах Windows 2003 Server, Windows XP или Windows 2000 профили теперь хранятся в папке %Systemdrive%\Documents and Settings, что позволяет отделить пользовательские настройки от папок и файлов операционной системы.

Примечание. Если Вы производите обновление операционной системы с Windows NT на более новую версию, то расположение профилей остается неизменным (%Systemroot%\profiles),

В Таблице 1 приведены расположения профилей пользователей для каждого из возможных сценариев установки Windows XP.

Таблица 1. Расположение профилей пользователей.

Операционная система Расположение профилей пользователей
«Чистая» установка Windows XP (нет предыдущей ОС) %SYSTEMDRIVE%\Documents and Settings; например, C:\Documents and Settings
Обновление Windows 2000 до Windows XP SYSTEMDRIVE%\Documents and Settings; например, C:\Documents and Settings
Обновление Windows NT 4.0 до Windows XP %SYSTEMROOT%\Profiles; например, C:\WinNT\Profiles
Обновление Windows 98 до Windows XP %SYSTEMDRIVE%\Documents and Settings; например, C:\Documents and Settings

Пользовательские настройки, хранящиеся в реестре

Файл NTuser.dat содержит следующие настройки:

  • Настройки Проводника. Все пользовательские настройки Проводника и сетевых подключений.
  • Настройки панели задач.
  • Настройки принтеров. Все подключения к сетевым принтерам.
  • Панель управления. Все пользовательские настройки панели управления.
  • Стандартные программы. Все пользовательские настройки приложений Windows, многие из которых доступны из меню Пуск – Программы – Стандартные (Калькулятор, Блокнот, Paint, HyperTerminal и другие)
  • Настройки приложений. Многие приложения хранят пользовательские настройки в разделе реестра HKEY_CURRENT_USER. Например, MS Word 2003 хранит там свои настройки панелей инструментов.

Настройки, хранящиеся в папках профиля

Рисунок 1 демонстрирует структуру профиля пользователя:

Рисунок 1. Профиль пользователя.

Каждый пользовательский профиль содержит следующие папки:

  • Application data*. Данные различных приложений. Например, вспомогательный словарь текстового редактора. Производители программного обеспечения определяют, какие данные хранить в этой папке.
  • Cookies. Файлы «cookie» обозревателя Internet Explorer.
  • Local Settings*. Настройки приложений, которые не перемещаются вместе с профилем. Обычно они либо относятся к конкретному компьютеру, либо слишком большой объем данных препятствует их эффективному перемещению.
    • Application data. Данные приложений, относящиеся к конкретному компьютеру.
    • History. Журнал обозревателя Internet Explorer
    • Temp. Временные файлы.
    • Temporary Internet Files. Автономные файлы (кэш) обозревателя Internet Explorer.
  • Nethood*. Ярлыки к элементам сетевого окружения.
  • Printhood*. Ярлыки к принтерам.
  • SendTo. Ярлыки к папкам и приложениям.
  • Главное меню. Ярлыки к программам.
  • Избранное. Избранное (закладки) обозревателя Internet Explorer.
  • Мои документы. Папка по умолчанию для новых документов и файлов пользователя. Приложения должны создаваться таким образом, чтобы они по умолчанию сохраняли свои файлы в этой папке.
  • Мои рисунки. Папка по умолчанию для графических изображений.
  • Моя музыка. Папка по умолчанию для музыкальных файлов.
  • Недавние документы. Ярлыки к недавно использовавшимся документам.
  • Рабочий стол. Элементы рабочего стола, включая файлы и ярлыки.
  • Шаблоны*. Ярлыки к шаблонам.

 

 

 

Защита файлов Windows (англ. Windows File Protection, WFP) — технология, позволяющая запретить программам изменять или удалять наиболее важные системные файлы операционных систем семейства Windows. Защита критически важных системных файлов позволяет избежать ряда серьёзных проблем и сбоев в работе операционной системы и прикладного программного обеспечения, например, DLL hell.

Названия в различных версиях Windows:

Когда Windows File Protection активна, перезапись или удаление незаблокированного системного файла приводит к немедленному восстановлению его оригинальной версии, которая хранится в специальной системной папке. В операционных системах семейства Windows NT это %WINDIR%\system32\Dllcache, в Windows ME — %SYSTEMROOT%\Options\Install.

Все файлы, устанавливаемые операционной системой, защищены от изменения или удаления. Цифровая подпись этих файлов хранится в каталоге %SYSTEMROOT%\system32\catRoot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}. Изменение вышеназванных системных файлов разрешено только немногочисленным специальным компонентам, например, Установщик Windows или Установщик пакетов (англ. Package Installer). В противном случае файл возвращается в исходное состояние без каких-либо запросов или сообщений. Лишь тогда, когда Windows File Protection не удаётся найти требуемый файл самостоятельно, производится поиск в локальной сети, Интернете или выдаётся запрос пользователю с просьбой вставить установочный диск в дисковод.

ледующий раздел реестра является основным местом размещения настроек реестра для службы защиты файлов и службы проверки системных файлов Windows:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

Кроме того, настройки могут также храниться в следующем разделе реестра:

HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows NT\Windows File Protection
ри запуске Windows служба защиты файлов Windows синхронизирует (копирует) свои настройки из раздела реестра
HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows NT\Windows File Protection
в раздел реестра
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon
Таким образом, если какое-то из следующих значений входит в раздел
HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows NT\Windows File Protection
, оно будет иметь приоритет над таким же значением из раздела
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon
.

По умолчанию вносить изменения в эти настройки могут только пользователи с правами администратора или полного доступа к системе.

Значения реестра

SFCDisable (REG_DWORD)

0 = включено (по умолчанию)
1 = отключено, при загрузке будет предложено включить
2 = отключено только для следующей загрузки, предложения включить не будет
4 = включено, всплывающие сообщения отключены

Примечание. Для вариантов 1 и 2: Чтобы эти варианты работали, необходимо подключить для них отладчик ядра. Если отладчик ядра не подключен, служба защиты Windows не отключается.

SFCScan (REG_DWORD)

0 = не выполнять сканирование защищенных файлов при загрузке (параметр по умолчанию)
1 = сканировать защищенные файлы при каждой загрузке
2 = сканировать защищенные файлы один раз

SFCQuota (REG_DWORD)

n = размер (в мегабайтах) квоты dllcache (по умолчанию 0xffffffff или примерно 300 МБ)
FFFFFFFF = кэшировать все защищенные системные файлы на локальном жестком диске

SFCDllCacheDir (REG_EXPAND_SZ)

Path = локальный или сетевой путь к папке dllcache (по умолчанию %SystemRoot%\System32)

Примечание. Общие сетевые файлы для каталога dllcache больше не поддерживаются.

SFCShowProgress (REG_DWORD)

0 = индикатор выполнения проверки системных файлов не отображается (по умолчанию)
1 = индикатор выполнения проверки системных файлов отображается

Примечание. Сведения о расположении файлов-источников Windows 2000 хранятся в реестре и могут быть изменены таким образом, чтобы указывать на букву_диска для тома, содержащего папку I386 с файлами установки. Можно также изменить значение SourcePath таким образом, чтобы оно указывало не на сетевой диск, а на путь в формате UNC.

Значение SourcePath расположено в следующем разделе системного реестра:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Setup
Пример:

Если каталог I386 находится по адресу C:\I386, значение будет равно C:\.

Если каталог I386 находится по адресу \\Servera\w2kflat\I386, значение будет равно \\Servera\W2KFlat.

После перезагрузки компьютера служба защиты файлов Windows и служба проверки системных файлов используют новый путь к источнику вместо того, чтобы предлагать вставить установочный компакт-диск Windows 2000.
Бесплатный хостинг uCoz