We are a communications fee system. I just entered the company, the manager let me see these source code, the way, add comments! Depressed, I haven't used it before! The compilation platform is: C Builder6.
-------------------------------------------------- -------------------------------------------------- ----------------------------
The following is a document
design manual
1. introduction
1.1 Writing
Analyze the functionality to be implemented, the required input and output items, make macro designs for the realization of the system;
1.2 background
a. System monitoring and management
b. Designer: // Designer Developer: // Developer User: Science // User: 1.3 Definition
[List the definitions of the specimen used in this document and the original phrase of the foreign letter group word. ]
1.4 Reference
[List the relevant references. ]
2. Overall design
2.1 demand regulations
[Describe the functional performance requirements for the main input and output items of the system. include]
2.1.1 System function
1, Service Monitoring Center (server)
(1) Service registration, service status monitoring
(2) Write the status of the service to the database and provide the client's query request;
(3) Surveillance and query of service real-time status information, provide real-time monitoring information to the client;
(4) Management and control services;
(5) Send a alarm information to the alarm center;
2, system resource monitor (server)
(1) Hardware system resource monitoring;
(2) Real-time interaction with the log service;
(3) Receive the alarm information to the client (or send a text message to the skilled person);
3, the alarm center (server)
(1) Receive the alarm information sent by the monitoring center while sending a text message to the client (or the technician);
(2) Write the alarm information into the database;
(3) The alarm is automatically released;
4, information query (client)
(1) Query of system hardware resources;
(2) System hardware resource history query;
(3) Query of each service status;
(4) Query of system service status;
(5) System business status history query;
2.1.2 System Performance
1, accuracy
Provides data that can accurately react system, service, and health status;
2, time characteristic requirements
In real time, monitor the system, the operating state of the service, and even if it is fed back to the client;
The client-side scheduling request to the system can respond;
3, reliability
4, flexibility
2.1.3 Input and output requirements
2.1.4 Data management capability requirements
2.1.5 Troubleshooting Requirements
2.1.6 Other special requirements
2.2 Operation Environment
1, mainly running on the Windows 2000 system;
2, need to consider porting to the Linux, UNIX system, so less C Builder components during the encoding process;
2.2.1 Equipment
[List the hard devices required to run the software. Description of the new device and its specialized functions. ]
2.2.2 Support Software
[List support software, including the operating system, compile (or assembly) program to be used, test support software, etc. ] 2.2.3 interface
[Describe the interface, data communication protocol, etc. between the system with other systems, etc.]
2.2.4 Control
[Description Method and Control Signal of the Run of the System and describe the source of these control signals. ]
2.3 Basic design concepts and process flows
[Describe the basic design concepts and processing flows of the system, try to use the form of the chart. ]
2.4 structure
[Give the overall block diagram of the system structure (including software, hardware structure block diagram), indicating the division of each module of the system, and the identifier and function of each system module should be described, and the control and being controlled between each module is given. Control relationship. ]
2.5 Relationship between functional requirements and system modules
This article uses a matrix to illustrate the allocation relationship between the functional needs of each function. ]
[System Module 1] [System Module 2] [...] [System Module M] [Features Demand 1] √
[Functional Demand 2]
√
[┇]
[Functional Demand N]
√
√
2.6 manual processing process
[Describe the artificial processing process that has to be included during the operation of the system. ]
2.7 Issues I have not resolved
[Description of the designer thinks that the designer believes that the designer must solve before the system is completed. ]
3. Interface design
3.1 User Interface
[Description will provide commands to users and their syntax structure, and corresponding answer information. ]
[Description provides the definition of the hardware control panel that is provided to the user. ]
3.2 External interface
[Description The arrangement of all interfaces of the system with the outside world includes interface between software and hardware, interface relationship between the system and the support system. ]
3.3 Internal interface
[Describe the arrangement of the interface between the various system elements within the system. ]
4. Run design
4.1 Operation module combination
[Describe the combination of various running modules caused by the application of different external operations, indicating that the internal modules of each run will mean the support software of each run. ]
4.2 Running Control
[Description Method and operation steps of each outside operation. ]
4.3 Running time
[Description Each run module combination will occupy the time of various resources. ]
5. System data structure design
[Do not involve software design, not included]
5.1 Type of logical structure design
[Given the name, identifier of each data structure used by the software in this system, each data item, record, text, and the identification, definition, length, and hierarchical or form between them. Relationship. ]
5.2 Points of physical structure design
[Given the storage requirements, access methods, access units, access, design considerations, and confidential conditions for each data item in each of the data structures used in this system. ]
5.3 Relationship between data structure and procedures
Describe the correspondence between the various data structures and the various programs accessing these data structures. ]
[Program 1] [Program 2] [...] [Program M] [Data Structure 1] √
[Data Structure 2] √ √
Bamboo
[Data Structure N]
√
√
6. System error processing design
6.1 error message
[Methods of the system output information in the form of each possible error or failure are in the form of the system output information. ]
6.2 Remedy
[Illustrate the variables that may be taken after the failure. include:]
a. Backup Technology [Requirening Techniques Preparing Used, the original system data is established and initiated when the original system data is lost, for example, periodically record the disk information to the tape is a backup technology for disk media. . ]
b. Equipment Technology [Reference Techniques Preparing Using the Adoption System, Use another system or method of another efficiency to obtain certain parts of the desired result, such as an automated system's marking technology can be manual manual operation and data recording. ]
c. Recovery and Reacture Technology [Description Recovery Restart Technology, so that the software will be executed from the fault point to the method of re-running the software from the beginning. ]
6.3 System maintenance design
[Description For the convenience of system maintenance, the arrangements made in the program internal design include specifically arranged inspection and maintenance of the system in the program. ]
Database design manual
1 Introduction
1.1 Writing
1. Provide background database implementation for system implementation; DBMS
2. Support and reference for the data requirements of the system code; Coding Staff1.2 background
a. [The name of the database to be developed and the name of the software system that uses this database;]
b. [List the task of this project, developers, users. ]
1.3 definition
[List the definitions of the specimen used in this document and the original phrase of the foreign letter group word. ]
1.4 Reference
[List the relevant references. ]
2. External design
1.1 status of the identifier
[Contact, detailed instructions for unique code, name, or identifier of the database, additional descriptive information is also given. If the database is still in the experiment, it is still used in the test or temporarily used, then this feature and its effective time range. ]
2.2 Using its program
[List all applications to use or access this database, give each name and version number for each of these applications. ]
2.3 agreed
[Statement a programmer or a system analyst to the establishment of the label, identifying the apparatus, identify the appointment. ]
2.4 Specialized guidance
[To prepare the generation of this database, engage in testing of this database, maintenance staff offering specialized guidance. ]
2.5 Support Software
[Brief introduction to support software directly related to this database. Note the name, version number of these software, the main features of the version number. List the title, number and source of these technical files for these support software]
3. Structural design
3.1 Concept Structure Design
[Description This database will reflect the original data of entities, attributes, and the relationship between the real world, including each data item, record, system, and file identifier, definition, type, metrics, and value domain. Establish each user view of this database. ]
3.2 Logical Structure Design
[Description of the original data is decomposed, the database global logical structure is reorganized after the merger. ]
3.3 Physical Structure Design
[Establish system programmer view. ]
4. Design
4.1 Data Dictionary Design
[Various items involved in database design generally have to establish data dictionaries to illustrate their identifiers, synonymous names and related information. ]
4.2 Safety Confidential Design
[Describe in the design of the database, how to distinguish between different visits, different access types, and different data objects, the database security confidential design considerations obtained separately. ]
CD-BCS Monitoring Service API Function Description
1. PRC_GettelnetInfo ();
Purpose: Get business server Telnet port output information
Implementation: Get the output information of the Socket port, send it to the front desk in the form of NMS message parameters
Remarks:
After the client starts the request, as long as it does not actively disconnect the request, the output parameters will continue to send to the client.
2. Getcpuinfo (), used to get the current CPU utilization rate
Objective: Get the current CPU utilization rate of the system
Implementation:, call the ntquerysysteminformation () function to get the current CPU time, calculate the CPU utilization; this part is implemented in the program has added a clear annotation, no more details,
If you have any questions, you can refer to MSDN;
3. GetMemoryInfo (TBCSMEMORYINFO & MEMINFO) Gets the current memory information of the system
Objective: To obtain information about the memory (physical memory and virtual memory) of the current system, if the memory utilization is required, you can calculate it.
Implementation: Call the GlobalMemoryStatus (& Memory) function Get the current memory information of the system,
Returns: Structure TBCSMemoryInfo defines in Unit3.h
If you have any questions, you can refer to MSDN;
4. GetDiskinfo (TBCSDiskinfo * DiskInfo) Gets this machine disk information
OBJECTIVE: To obtain local disk information (logical disk name, total capacity, used space, unused space), can be calculated if disk utilization is required; implementation:
1) Call getProcAddress () load the dynamic connection library and return the output function address
2) Call the getLogicalDriveStringsTrings () function Get the logical disk name
3) Call the PgetDiskFreespaceEx () function Get the specified logic disk space information
If you have any questions, you can refer to MSDN;
5. GetServiceList (tbcsservicelist * & service) gets the list of local service
Objective: To list the specified server (herein refer to this machine) system service list, return to the number of services
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null or when the PServer point to the empty string, it means this machine; return to the management database handle.
2) Call the enumserviceSstatusex () function enumeration service list and obtain basic information;
3) Call the SCHSERVICE () function to get the specified service handle;
4) Call QueryServiceConfig2 () Get, specify the description of the service;
Specifically realize the reference code, if you have any questions, you can refer to MSDN;
6. GetServiceProperty (TBCSServiceProperty & ServiceProperty, String ServiceName) Gets the properties of the specified service
Objective: Get all kinds of information for designated services
Realization: Every step in the code is detailed, no longer repeated;
7. GetProcessList (TBCSProcessInfo & ProcessInfo, int ProcessID) Gets a list of processes
Objective: Get the specified process
achieve:
1) Call the getProcAddress () function Define a function ntquerySystemInformation (); to call the ntquerySystemInformation () function in the ntdll.dll library;
2) Call the custom function ntquerySysteminformation () Get processes, return to structural arrays;
3) Enumeration Process list (including process brief message);
For more information on process information, see AccessList List Example GetProcessList See attachment;
8. GetNetInfo (TBCSNetInfo & NetInfo) Getting Network Information
Objective: Get the network information of this unit
(Simulation Enter: NetStat -a -n Display Network Information in DOS Tips)
achieve:
Reference: "Monitoring Network Traffic" and "Network Information Example API.txt" and Code Note
9. InstallService (String ServiceName, String DisplayName, String Path) Installation Service Purpose: Implement Service Installation
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null, or when the PServer point to the empty string, point to the local service management database; the access method is SC_Manager_create_service; return to the management database handle.
2) Call the CreateService () function creation service and add to the service management database;
10. UninstallService (String ServiceName) Uninstall Service
Purpose: To achieve service uninstallation
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null, or when the PServer point to the empty string, point to the local service management database; the access method is SC_Manager_create_service; return to the management database handle.
2) Call the OpenService () function to get the service handle;
3) Call the ControlService () service to uninstall the service;
11. StartupService (String ServiceName) boot service
Purpose: To achieve service startup
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null, or when the PServer point to the empty string, point to the local service management database; the access method is SC_Manager_create_service; return to the management database handle.
2) Call the OpenService () function to get the service handle;
3) Call the queryServiceStatus () function to get the service status;
4) Call the startService () function to start the service;
12. StopService (String ServiceName) Stop service
Purpose: To achieve service stop
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null, or when the PServer point to the empty string, point to the local service management database; the access method is SC_Manager_create_service; return to the management database handle.
2) Call the OpenService () function to get the service handle;
3) Call the queryServiceStatus () function to get the service status;
4) Call the startService () function stops the service;
13. Pauseservice (String ServiceName) Suspension Service
Objective: To achieve service suspension
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null, or when the PServer point to the empty string, point to the local service management database; the access method is SC_Manager_create_service; return to the management database handle.
2) Call the OpenService () function to get the service handle;
3) Call the queryServiceStatus () function to get the service status;
4) Call the startService () function to suspend the service;
14. ContinueService (String ServiceName) Restore Services
Purpose: Restore the service to start state
achieve:
1) Call the OpenScManager () function, establish a connection to the specified machine service management database, when the PServer is null, or when the PServer point to the empty string, point to the local service management database; the access method is SC_Manager_create_service; return to the management database handle.
2) Call the OpenService () function to get the service handle;
3) Call the queryServiceStatus () function to get the service status;
4) Call the startService () function to restore this service as the startup state;
15. Closepeocess (int processid) termination process
Purpose: Terminate the designated process
achieve:
Call the OpenProcess () function Get the specified process handle; call the TerminateProcess () function to override the process;
16. RestartServer () Restart the server
Purpose: Restart the server
achieve:
To use the "User32.dll" library. First call the openprocessToken () function to get the current process token, then call the LookUpprivileGeValue () function to increase the permissions to make Shutdown permissions. SHUTDOWM is available when you function AdjustTokenPrivileges (). Finally call the exitWindowSex () function restart system.
Declaration and definition of TSOCKInfo class:
17. Get Socket Resources Use Information
Reference: Comments in the "Relevance Process and Port" and Code
System monitoring and management
First, classification
Network resources: including monitoring, release, management, network traffic monitoring, management, monitoring, management
Basic resources: including hard drive, memory, operating system monitoring, management, system process management
Application: Operational Status Monitoring, Management of Application System
Second, realize
The implementation of network resources and basic resources already has a prototype, continues to improve according to the original approach, and needs to take into account the current system structure.
Application Monitoring and Management: Add Monitoring Center, Monitor, Alarm, and Adaptive Modification to Existing Services in an existing system structure
The functions that the monitoring center needs to be completed include: status monitoring of other services, records data on data, history of history, query, real-time data query, system real-time resource management. The monitoring center can configure one or more according to actual needs. The functions that the monitor needs to be completed include: this hardware system resource is monitored, interacting with the log service for real-time data records. The monitor is located on all hardware nodes of the system, at least one of each node
The features that the alarm need to be completed include: alarm information sent by the monitoring center, alarm information registration, and the alarm information is released. You can use different alarm methods such as software, SMS, etc. The alarm can configure one or more according to actual needs.
Other Adaptive Modifications: Keepalive Messages Send.
Front desk must be implemented: system network resources, real-time monitoring and scheduling, history query, real-time state monitoring and scheduling of basic resources.
Third, the environment
Development, test environment:
Windows2000 Server Oracle8.1.7 and Oracle 9.0 and Sybase11.5 BCB6.0 XML4.0
However, it is possible to consider that the system is ported to UNIX: Try to use the BCB, VCL-specific controls and class, as much as possible with standard C .
Fourth, the message definition
4.1 Monitoring Center needs to process messages
l Service Registration: Other services registered to the monitoring center and send initial information for the monitoring center for use
l System Service Application Message: The message of other BCSS service processing is sent to the surveillance service while sending it to the boundary gateway. The monitoring service is statistically, and the error message is real-time monitoring, and the difference between other messages.
l Link Monitoring Message: Other BCSS services Send link maintenance to the monitoring center and Keepalive message, the purpose is: the status of each business service is detected by the monitoring center.
l System Service Status query: The front desk is initiated, query the current system, the running status of each service, the monitoring front desk can set the operation status of each part of the current system, if real-time information is required, you need to send it directly to the monitor , Return directly by the monitor, otherwise read the nearest information from the database
l Alarm information query: initiated by the front desk, query the alarm information within a given time
l System Resource Inquiry: Surrected by the front desk, query the resource status of each node of the current system, the monitoring front desk can set the resource status of each node, if needed, if you need real-time information, you need to send it directly to the monitor, directly from the monitor Return, otherwise reads the most recent information from the database
l Historical record: initiated by the foreground, query the service status of the system within a given time range, system resource status
l Alarm information registration: initiated by the monitoring center, send alarm information to the alarm
l The alarm information is released: initiated by the monitoring center, send alarm to the alarm to release information
l System resource scheduling: initiated by the front desk according to the return information of the system resource query, to stop a service, restart a machine, modify some system parameters, etc., the operation is implemented while implementing the database first .
4.2 Monitor needs to handle messages
The monitor is responsible for acquiring local resource conditions, interacting with the log service to record real-time status, the message you need to send is a message to write a write database sent by the log service; the real-time information required by the monitoring center, including real-time resources (network, hardware, etc. Information 4.3 Alarms need to process messages
l Alarm information registration: initiated by the monitoring center, send alarm information to the alarm
l The alarm information is released: initiated by the monitoring center, send alarm to the alarm to release information
V. Database needs new tables and stored procedures
5.1 table structure
l System Node Summary Information Table: Describe the summary information of each node of the system, such as: CPU, memory, hard disk, operating system
l System Structure Information Table: Describe profile information of system software, such as: service number, listening port, listening address, debug port, debug address, service description, etc.
l System Business Status Table: Storage System The service status information of the system, such as service number, processing of service, success, failure, currently processed business information, current failure information, time, receipt, and send bytes Number
l System Business Status History: Storage System Business Status History
l System Resource Status: The resource status information of each node on the day, such as: IP address, time, memory information, hard disk information, Socket connection, etc., wherein memory information includes: available memory, virtual memory, etc., hard drives include: logic The number of disks, disk capacity, available disk capacity, etc.
l System Network Status Table: Describe the number of network connections of each node and each connection information table, such as: time, local IP, peer IP, local port, peer port, connection status, etc.
l System resource status historical table
l System network status historical table
l Alarm Information Form: Store information and status of the alarm, including: type, alarm information, sending status, whether it is released, etc.
l System Scheduling History Table: Storage System Scheduling Operation History
5.2 Storage Process
l System Service Scan: Used to Scan the alarm information in the system database, if there is information that requires alarm, the number of the alarm information and the alarm message are returned, and the alarm service sends a warning message if No, return 0. If the monitoring center calls the process fails, the time interval is repeatedly called, and the database failure is considered to fail for 3 consecutive times.
l Other stored processes mainly include: querying business status, resource status, business history, resource history, system scheduling operation record, etc.
Six, program structure descriptions and precautions
Take similar to the previous service structure, but the monitoring center is different in that the array of all BCSS corresponding state descriptions is required, which is a structural array or an object array, a BCSS corresponding to the object, which needs to be described. The state variable described is included:
Service status (by Keepalive Message Maintenance), business information (including business number, number of success, failure, continuous failure, current prompt information, current failure information, sending bytes, number of bytes, etc.)
This object writes the cumulative data of the previous day before business every day, then clears, disconnects all connections, re-maintained by BCSS; the monitoring center needs to establish a connection with the database, as the server needs to establish a connection to all monitors Need to establish a connection with the alarm, you need to establish a connection monitor with all BCSS to establish a connection with the log service, you need to establish a connection with the monitoring center.
The alarm acts as a different database connection to the client style and needs to establish a connection with the monitoring center.
-------------------------------------------------- -------------------------------------------------- -------------------------- // Project.cpp
#include
#include
#pragma HDRSTOP
#define Application Svcmgr :: Application
Useform ("Unit1.cpp", BCSInfocollect); / * TService: file type * /
Useform ("Unit2.cpp", DM); / * TDATAMODULE: FILE TYPE * /
/ / -------------------------------------------------------------------------------------------- ---------------------------
WinApi Winmain (Hinstance, Hinstance, LPSTR, INT)
{
Try
{
Application-> Initialize ();
Application-> title = "bcsinfocollect";
Application-> Createform (__ classid (tbcsinfocollect), & bcsinfocollect;
Application-> Createform (__ClassID (TDM), & DM);
Application-> Run ();
}
Catch (Exception & Exception)
{
SYSUTILS :: ShowException (& Exception, System :: Exceptaddr ());
}
Catch (...)
{
Try
{
Throw Exception ("");
}
Catch (Exception & Exception)
{
SYSUTILS :: ShowException (& Exception, System :: Exceptaddr ());
}
}
Return 0;
}
-------------------------------------------------- -------------------------------------------------- -------------------
//Unit1.cpp
/ / -------------------------------------------------------------------------------------------- ---------------------------
#include "unit1.h"
/ / -------------------------------------------------------------------------------------------- ---------------------------
#pragma package (smart_init)
#pragma resource "* .dfm"
TtelnetConsole * console = null; TNMsInterfaceForserver NMSServer;
TBCSInfocollect * bcsinfocollect;
/ / -------------------------------------------------------------------------------------------- ---------------------------
__fastcall tbcsinfocolect :: TbCsinfocollect (tcomponent * Owner)
: TSERVICE (OWNER)
{
}
TServiceController __fastcall tbcsinfocolect :: GetServiceController (void)
{
Return (TServiceController) ServiceController;
}
Void __stdcall serviceController (unsigned ctrlcode)
{
BCSINFOCOLLECT-> Controller (Ctrlcode);
}
/ / -------------------------------------------------------------------------------------------- ---------------------------
Void __fastcall tbcsinfocolect :: ServiceExecute (TService * Sender)
{
TreginiFile * Pini = New Treginifile ("NICESoft // BCS // ServerGuardian");
Int executeContinueflag = 0;
While (! terminated)
{
Try
{
IF (ExecuteContinueflag> 20 && Pini)
{
Pini-> WriteInteger (Name, "ActiveFlag", 10);
ExecuteContinueflag = 0;
}
ExecuteContinueflag ;
}
Catch (...)
{
}
Sleep (50);
ServiceThread-> ProcessRequests (False);
Nmsserver.execute ();
}
}
Void TBCSINFOCOLLECT :: Debuginfo (String Info)
{
Console-> Print (INFO "/ R / N");
LOG2 ("801 ::" info, "bcs.log");
}
/ / -------------------------------------------------------------------------------------------- ---------------------------
Void __fastcall tbcsinfocolect :: ServicesTART (TService * Sender, Bool & Started)
{
BTRY
INT port = 10006, SRVID = 801;
Coinitialize (NULL);
IF (nmsserver.flag () { LTRY Nmsserver.oncommevent = onserveraccept; Port = Globalinfo.regini-> Readinteger (app, "listening port", 10006); // Value from registry SRVID = Globalinfo.regini-> Readinteger (App, Services Number ", 801); LTRY For (int i = 0; i // nmsserver.fclient [i] .SetautoCompress (true); LTRY NMSSERVER.FCLIENT [I] .ongeetnms = OnGetServerClient1Message; // Server Receive NMS response event NMSServer.fclient [i] .oncommevent = onclientevent; LTRY } NMSServer.ServiceId (SRVID); Try { NMSSERVER.SETADDRESS ("", (word) port); // Setting up connection Debuginfo ("preted start" string (port)); LTRY Nmsserver.initialize (); Started = true; // Initialization Service DebugInfo ("Service Start"); } Catch (Exception & E) { Started = false; DebugInfo ("Service Startup Failure:" E.Message); } } Else { Nmsserver.final (); Started = false; } ETRY } / / -------------------------------------------------------------------------------------------- --------------------------- Void TBCSINFOCOLLECT :: OnServeraccept (TNMsinterfaceForperConnecttion * Sendder, TNMScommeventcode Eventcode) { Try { if (Eventcode == CEACCEPT) { } Else if (eventcode == CEDISCONNECT) { } } Catch (...) {} } Void Tbcsinfocollect :: oncliente (TNMsinterfaceForperConnecttion * Sender, TNMScommeventcode Eventcode) { Try { if (Eventcode == CEDISCONNECT) { } Else { } } Catch (...) {} } Void TBCSINFOCOLLECT :: ONGETSERVERCLIENT1MESSAGE (TNMSinterfaceforperConnection * Sender, TNetMessage & NMS) { Try { Debuginfo ("from:" sender-> getRemoteAddress () "Receive NMS ID:" String (nms.MESSAGEID)); // if (sender-> pftag! = Null) { DM-> ExecuteNMS (NMS, * Sender); } } Catch (...) {} } Void __fastcall tbcsinfocolect :: ServiceStop (TService * Sender, Bool & stopped) { Couninitialize (); } / / -------------------------------------------------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --- //Unit2.cpp / / -------------------------------------------------------------------------------------------- --------------------------- #include #pragma HDRSTOP #include "unit2.h" #include "unit1.h" #include "unit3.h" #define __service_used__ Extern ttelnetconsole * console; / / -------------------------------------------------------------------------------------------- --------------------------- #pragma package (smart_init) #pragma resource "* .dfm" #include TDM * DM; Extern tgetinfo * getSerinfo; Tbcsdiskinfo service; / / -------------------------------------------------------------------------------------------- --------------------------- __fastcall tdm :: TDM (Tcomponent * Owner) : TDATAMODULE (OWNER) { } / / -------------------------------------------------------------------------------------------- --------------------------- INT TDM :: Executenms (TNMSINTERFACEFORPERCONNECTTION & Sender) { Try { ReceiveNMs.MessageType = (ReceiveNMs.MessageType & 0xFFF9) | 0x4; Switch (ReceiveNMs.MessageID) { Case NMS_Login: PRC_Login (ReceiveNMs, Sender); Break; Case NMS_GetInitialInfo: PRC_INITIALIZE (ReceiveNMs, Sender); Break; Case NMS_GettelnetInfo: PRC_GettelnetInfo (ReceiveNMs, Sender); Break; Case NMS_InitialInfo: PRC_INITIALIZE ((ReceiveNMs, Sender); Break; Case NMS_GetServiceList: PRC_GetServiceList (ReceiveNMs, Sender); Break; Case NMS_GetsystemInfo: PRC_GETSYSTEMINFO (ReceiveNMs, Sender); Break; Case NMS_GETPROCESSINFO: PRC_GETPROCESSINFO (ReceiveNMs, Sender); Break; Case NMS_GetNetInfo: PRC_GetNetInfo (ReceiveNMs, Sender); Break; Case NMS_ServiceControlInfo: PRC_ServiceCtrl (ReceiveNMs, Sender); Break; Case NMS_OPERATE: PRC_OPERATE (ReceiveNMs, Sender); Break; DEFAULT: Break; } Return 0; } Catch (Exception & E) { INT ERR_CODE = 9999; String Err_msg = E.MESSAGE; TVARIABLE TMPJGJ (Para_Result_code); TMPJGJ = Err_code; ReceiveNMs.Parameters << Tmpjgj; Tmpjgj.resetas (Para_Result_MSG); IF (err_msg == "") Err_msg = "Unfained exception information!"; Tmpjgj = err_msg; ReceiveNMs.Parameters << Tmpjgj; Sender << receivemp; Return 1; } } Void TDM :: Prc_login (TNMSinterfaceForperConnecttion & Sender) { Try { INT RET_CODE = 0; String RET_MSG = "" TVARIABLE TMPVAR; ReceiveNMs.MessageId = 1000; ReceiveNMs.Modelid = 1020; String gh = receivenms.Parameters [para_staff_id] .sstring (); IF (GH. Trim ()! = "") { Int retcode = 0; IF (retcode == 0) { RET_CODE = 0; ReceiveNMs.MessageId = 1000; RET_MSG = String ("Hello,") GH ", welcome to BCS service management and monitoring system ./n login time:" tdatetime :: currentdatetime (). FormatString ("YYYY / MM / DD HH: NN: SS "); } Else { RET_CODE = 100; RET_MSG = "Login failed"; } } Else { RET_CODE = 1001; RET_MSG = "Please enter the job number below"; } TMPVAR.RESETAS (Para_Result_code); TMPVAR = RET_CODE; ReceiveNMs.Parameters << TMPVAR; IF (RET_MSG.LENGTH ()) { TMPVAR.RESETAS (Para_Result_MSG); TMPVAR = RET_MSG; ReceiveNMs.Parameters << TMPVAR; } Sender << receivemp; } Catch (Exception & E) { INT ERR_CODE = 9999; String Err_msg = E.MESSAGE; TVARIABLE TMPVAR (Para_Result_code); TMPVAR = Err_code; ReceiveNMs.Parameters << TMPVAR; TMPVAR.RESETAS (Para_Result_MSG); IF (err_msg == "") Err_msg = "Unesented exception information!"; TMPVAR = Err_MSG; ReceiveNMs.Parameters << TMPVAR; Sender << receivemp; } Void TDM :: Prc_initialize (TNMsinterface & ReceiveNMS, TNMsinterfaceForperConnecttion & Sender) { } Void TDM :: PRC_GettelnetInfo (TNMSINTERFACEFORPERCONNECTTION & Sender) { TVARIABLE TMPVAR; // string status = receivempinms.parameters [para_linkstate_in] .sstring (); String Serverip = receivempenms.Parameters [Para_Destaddr_in] .sstring (); INT ServerPort = receivempinMs.Parameters [Para_Destport_in] .asinteger (); Clientsocket1-> address = serverIP; Clientsocket1-> port = serverport; // for (int i = 0; i <2; i ) // { IF (! Clientsocket1-> Active) { Clientsocket1-> Active = true; } IF (clientsocket1-> socket-> receiveLength ()) { String telnetInfo = clientsocket1-> socket-> receivetext (); TMPVAR.RESETAS (Para_Gettelnet_info); TMPVAR = TelnetInfo; ReceiveNMs.Parameters << TMPVAR; } Sender << receivemp; // can be judged, if the reception does not pass back "STOP" information, then the I -, continue loop } } / / -------------------------------------------------------------------------------------------- --------------------------- Void TDM :: PRC_GETSYSTEMINFO (TNMSINTERFACEFORPERCONNECTTION & Sender) { } / / -------------------------------------------------------------------------------------------- --------------------------- Void TDM :: Prc_getServiceList (TNMSinterfaceForperConnecttion & Sender) { } / / -------------------------------------------------------------------------------------------- --------------------------- Void TDM :: PRC_GETPROCESSINFO (TNMSINTERFACEFORPERCONNECTTION & Sender) { } / / -------------------------------------------------------------------------------------------- --------------------------- Void TDM :: Prc_getNetinfo (TNMSINTERFACEFORPERCONNECTITY & SENDER) { } / / -------------------------------------------------------------------------------------------- --------------------------- Void TDM :: Prc_ServiceCtrl (TNMSINTERFACEFORPERCONNECTTION & Sender) { String serviceName = receiveMs.Parameters [service_para_name] .sstring (); INT ctrl = receivempinMs.Parameters [service_para_ctrl] .asinteger (); Switch (ctrl) { Case Service_Start Contrl.startServicea (ServiceName); Break; Case Service_Stop Contrl.contrlService (Str, Service_Control_Stop); Break; Case service_pause Contrl.ControlService (Str, Service_Control_Pause); Break; Case Service_Continue Contrl.contrlService (Str, Service_Control_Continue); Break; DEFAULT: Break; } / / -------------------------------------------------------------------------------------------- --------------------------- Void TDM :: PRC_OPERATE (TNMSINTERFACEFORPERCONNECTTION & Sender) { } -------------------------------------------------- -------------------------------------------------- ------------------------- //Unit3.cpp / / -------------------------------------------------------------------------------------------- --------------------------- #pragma HDRSTOP #include "unit3.h" #include } Tgetinfo :: ~ tgetinfo () {} // ------------------------------------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------- #define systembasicinformation 0 # define systemperformanceinformation 2 # define systemtimeinformation 3 # define li2double (x) ((x) ((x) .highpart) * 4.294967296e9 ((x) .lowpart)) typedef struct {DWORD dwUnknown1; ULONG uKeMaximumIncrement; ULONG uPageSize; ULONG uMmNumberOfPhysicalPages; ULONG uMmLowestPhysicalPage; ULONG uMmHighestPhysicalPage; ULONG uAllocationGranularity; PVOID pLowestUserAddress; PVOID pMmHighestUserAddress; ULONG uKeActiveProcessors; BYTE bKeNumberProcessors; BYTE bUnknown2; WORD wUnknown3;} SYSTEM_BASIC_INFORMATION; Typedef struct {large_integer liidletime; dWord dwspare [76];} system_performance_information; typedef struct {LARGE_INTEGER liKeBootTime; LARGE_INTEGER liKeSystemTime; LARGE_INTEGER liExpTimeZoneBias; ULONG uCurrentTimeZoneId; DWORD dwReserved;} SYSTEM_TIME_INFORMATION; typedef LONG (WINAPI * PROCNTQSI) (UINT, PVOID, ULONG, PULONG); PROCNTQSI NtQuerySystemInformation; // cpu utilization system double TGetInfo: : GetCPUInfo () {SYSTEM_PERFORMANCE_INFORMATION sysPerfInfo; SYSTEM_TIME_INFORMATION SysTimeInfo; SYSTEM_BASIC_INFORMATION SysBaseInfo; double dbIdleTime; double dbSystemTime; LONG status; static LARGE_INTEGER liOldIdleTime = {0,0}; static LARGE_INTEGER liOldSystemTime = {0,0}; NtQuerySystemInformation = (PROCNTQSI) GetProcAddress (GetModuleHandle ( "ntdll"), "NtQuerySystemInformation"); if return S_FALSE (NtQuerySystemInformation!); // number of processors in the system to obtain status = NtQuerySystemInformation (SystemBasicInformation, & SysBaseInfo, sizeof (SysBaseInfo), NULL) ; If (status! = No_error) return s_false; // Get new system time status = ntQuerySystemation, & systimeinfo, sizeof (systimeinfo), 0); if (status! = No_error) Return S_FALSE; // get a new CPU idle time status = NtQuerySystemInformation (SystemPerformanceInformation, & SysPerfInfo, sizeof (SysPerfInfo), NULL); if (! Status = NO_ERROR) return S_FALSE; // if the first call is skipped if (liOldIdleTime.QuadPart =! 0) {// current value = latest value - old value dbIdleTime = Li2Double (SysPerfInfo.liIdleTime) - Li2Double (liOldIdleTime); dbSystemTime = Li2Double (SysTimeInfo.liKeSystemTime) - Li2Double (liOldSystemTime); // current CPU idle time idle time = / System Time DBIDletime = DBIDLETIME / DBSYSTEMTIME; // Current CPU Utilization% = 100 - (Current CPU Free Time * 100) / Processor DBIDLETIME = 100.0 - DBIDletime * 100.0 / (Double) SysbaseInfo.bkenumberProcessors 0.5;} / / Storage new CPU idle and system time lioldidletime = sysperfinfo.liidletime; lioldsystemtime = systemtime; Return dbidletime;} void TGetInfo :: GetMemoryInfo (TBCSMemoryInfo & memInfo) {MEMORYSTATUS memory; memory.dwLength = sizeof (memory); // initialize GlobalMemoryStatus (& memory); memInfo.MemTotalPhys = memory.dwTotalPhys / 1024/1024; memInfo.MemAvailPhys = memory.dwAvailPhys / 1024; memInfo.MemTotalVirtual = memory.dwTotalVirtual / 1024/1024; memInfo.MemAvailVirtual = memory.dwAvailVirtual / 1024;} int TGetInfo :: GetDiskInfo (TBCSDiskInfo * diskInfo) {int Count = 0; typedef BOOL (WINAPI * PGETDISKFREESPACEEX) (LPCSTR , PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER); pGETDISKFREESPACEEX pGetDiskFreeSpaceEx; __int64 i64FreeBytesToCaller, i64TotalTypes, i64FreeBytes; pGetDiskFreeSpaceEx = (pGETDISKFREESPACEEX) GetProcAddress (GetModuleHandle ( "kernel32.dll"), "GetDiskFreeSpaceEx"); if (pGetDiskFreeSpaceEx) {char str [100]; INT N = getLogicalDrivestrings (100, str); for (int i = 0; i Diskinfo = Diskinfo i; diskinfo [i] -> disksize = i64totaltypes; diskinfo [i] -> diskFreespace = i64freebytes; count ;} } Return count;} // Get a list of services void TGetInfo :: GetServiceList (TBCSServiceList * serviceList) {SC_HANDLE hSC; char * pServer = NULL; ENUM_SERVICE_STATUS_PROCESS scstat [100]; DWORD BytesNeed = 0, ServiceReturned = 0, ResumeHandle = 0, ret, i = 0; CHAR * STAT [] = {"", "Stop", "Starting", "Starning", "Continue Pending", "Pause Pending", "Pause"}; HSC = OpenScManager (PServer, Services_Active_Database, SC_Manager_Connect | SC_MANAGER_ENUMERATE_SERVICE); do // begin the enumeration service {ret = EnumServicesStatusEx (hSC, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_STATE_ALL, (LPBYTE) scstat, sizeof (scstat), & BytesNeed, & ServiceReturned, & ResumeHandle, // attention to this parameter, the first call This function should be 0 null); for (int i = 0; i long (__stdcall * NtQuerySystemInformation) (DWORD, PVOID, DWORD, DWORD); static __int64 LastTotalProcessCPUUsage = 0; static __int64 LastCurrentProcessCPUUsage = 0; int CurrentDelta; int TotalDelta; __int64 TotalProcessCPUUsage = 0; __int64 CurrentProcessCPUUsage = 0; pProcInfo = (PVOID) ( new byte [dwInfoSize]); NtQuerySystemInformation = (long (__ stdcall *) (DWORD, PVOID, DWORD, DWORD)) GetProcAddress (GetModuleHandle ( "ntdll.dll"), "NtQuerySystemInformation"); NtQuerySystemInformation (5, pProcInfo, dwInfoSize, 0 ); pProcessInfo = (PPROCESSINFO) pProcInfo; do {TotalProcessCPUUsage = (__int64) pProcessInfo-> KernelTime.QuadPart (__int64) pProcessInfo-> UserTime.QuadPart; if (pProcessInfo-> dwProcessID == processID) // GetCurrentProcessId () takes the current process id {dwWorkingSet = pProcessInfo-> dwWorkingSet; CurrentProcessCPUUsage = (__int64) pProcessInfo-> KernelTime.QuadPart (__int64) pProcessInfo-> UserTime.QuadPart; strcpy (processInfo.ProcessName, String (pProcessInfo-> ProcessName.Buffer). C_STR ());} if (pprocessinfo-> dwoffset == 0) {Break;} PPROCESSINFO = (PPROCESSINFO) ((Byte *) PPROCESSINFO PPROCESSINFO-> dwoffset;} While (TRUE); TotalDelta = TotalProcesscpuusage - LasttotalProcessCPUusage; CurrentDelta = CURRENTPROCPUUSAGE - LastCurrentProcessCPUusage; if (TotalDelta = 0!) {processInfo.ProcessID = pProcessInfo-> dwProcessID; // strcpy (processInfo.ProcessName, String (pProcessInfo-> ProcessName.Buffer) .c_str ()); // Note processInfo.CpuPercent = 100 * ( CurrentDelta / TotalDelta); processInfo.ProcessMemory = dwWorkingSet / 1024;} LastTotalProcessCPUUsage = TotalProcessCPUUsage; LastCurrentProcessCPUUsage = CurrentProcessCPUUsage; delete [] pProcInfo;} // Get Network Information Void Tgetinfo :: GetNetInfo (TBCSNetInfo & NetInfo) {Hinstance Hinst = :: loadLibrary ("iPhlpapi.dll"); DWORD NumberOfInterfaces; typedef DWORD (__stdcall * pGetNumberOfInterfaces) (DWORD *); typedef DWORD (__stdcall * pGetInterfaceInfo) (PIP_INTERFACE_INFO, unsigned long *); typedef DWORD (__stdcall * pGetTcpTable) (PMIB_TCPTABLE, unsigned long *, bool); typedef DWORD ( __stdcall * pgetifentry) (PMIB_IFROW); pGetNumberOfInterfaces pf1 = (pGetNumberOfInterfaces) :: GetProcAddress (hInst, "GetNumberOfInterfaces"); if (pf1) {if (pf1 (& NumberOfInterfaces) == NO_ERROR) {NetInfo.NumInterfaces = NumberOfInterfaces;}} PIP_INTERFACE_INFO pInterfaceInfo = (PIP_INTERFACE_INFO) malloc (sizeof (PIP_INTERFACE_INFO)); unsigned long InfoSize = sizeof (PIP_INTERFACE_INFO); pGetInterfaceInfo pf2 = (pGetInterfaceInfo) :: (hInst GetProcAddress, "GetInterfaceInfo"); if (pf2) {if (pf2 (pInterfaceInfo, & InfoSize)! = NO_ERROR) {pInterfaceInfo = (PIP_INTERFACE_INFO) Realloc (PinterfaceInfo, Infosize); if (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2 (PF2) {Netinfo.numadpaters = PinterfaceInfo-> Numadapters; For (int i = 0; i String ((tcptable.table [i] .dwremoteaddr) >> (j * 8)) & 0xff);}} localport = ((tcPtable.Table [i] .dwlocalport & 0xff00) >> 8) | ((tcptable.table) i] .dwLocalPort & 0xff) << 8); Constate = tcptable.table [i] .dwState; if (Constate == MIB_TCP_STATE_LISTEN) Remoteport = 0; else Remoteport = ((tcptable.table [i] .dwRemotePort & 0xff00) >> 8) ((tcptable.table [i] .dwremoteport & 0xff) << 8); strcpy (NetInfo.Links [i] .localaddr, localip.c_str ()); // Local address Netinfo.links [i] .localport = localport; // Local port STRCPY (NetInfo.links [i] .Remoteaddr ()); // Remote address Netinfo.links [i] .remoteport = Remoteport; // Remote port NetInfo.links [i] .constate = connection; / / connection state}} else {String lpMsgBuf; if (FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, rtn, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language lpMsgBuf.c_str (), 0, NULL)) {ShowMessage (lpMsgBuf );}}} PgetifeNTry PF3 = (PgetiFentry) :: getProcaddress (Hinst, "getifents "); if (pf3) {IF (PF3 (& iFrow) == NO_ERROR) {if (ifrow.dewtype == 6 || ifrow.dwtype == 23) {mibifrow.dwindex = PinterfaceInfo-> Adapter [i]. Index; if (pf3 (& mibifrow) == NO_ERROR) {NetInfo.InterFaceIndex = mibifrow.dwIndex; strcpy (NetInfo.InterFaceName, String (mibifrow.wszName) .c_str ()); strcpy (NetInfo.InterFaceDescr, mibifrow.bDescr); Netinfo.interfacetype = mibifrow.dwtype; NetInfo.InterFaceSpeed = mibifrow.dwSpeed; NetInfo.InterFaceMTU = mibifrow.dwMtu; strcpy (NetInfo.InterFacePhysAddr, mibifrow.bPhysAddr); NetInfo.InterFaceAdminStatus = mibifrow.dwAdminStatus; NetInfo.InterFaceOperStatus = mibifrow.dwOperStatus; NetInfo.InterFaceInByte = mibifrow.dwInOctets ; NetInfo.InterFaceInUcastPkts = mibifrow.dwInUcastPkts; NetInfo.InterFaceInNUcastPkts = mibifrow.dwInNUcastPkts; NetInfo.InterFaceInDiscards = mibifrow.dwInDiscards; NetInfo.InterFaceInErrors = mibifrow.dwInErrors; NetInfo.InterFaceInUnKnownPro = mibifrow.dwInUnknownProtos; NetInfo.InterFaceOutBytes = mibifrow.dwOutOctets; NetInfo .Interfaceoutucastpkts = mibifrow.dwoutucastpkts; NetInfo.InterFaceOutNUcastPkts = mibifrow.dwOutNUcastPkts; NetInfo.InterFaceOutDiscards = mibifrow.dwOutDiscards; NetInfo.InterFaceOutErrors = mibifrow.dwOutErrors; NetInfo.InterFaceOutQLen = mibifrow.dwOutQLen; NetInfo.InterFaceLastChange = mibifrow.dwLastChange;}} } }}}} Free (pInterfaceInfo); :: FreeLibrary (hInst);} // Installation void TGetInfo :: InstallService (String serviceName, String displayName, String path) {SC_HANDLE scm; SC_HANDLE svc; scm = OpenSCManager (NULL, NULL , SC_MANAGER_CREATE_SERVICE); if (! scm = NULL) {svc = CreateService (scm, serviceName.c_str (), displayName.c_str (), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, // automatically SERVICE_ERROR_IGNORE, path.c_str (), / / Service program path NULL, NULL, NULL, NULL, NULL); if (SVC! = Null) ClosESERVICEHANDLE (SVC); ClosESERVICEHANDE (SCM);}} // Uninstall Service Void TgetInfo :: UninstallService (String ServiceName) {SC_HANDLE SCM ; SC_HANDLE svc; SERVICE_STATUS ServiceStatus; scm = OpenSCManager (NULL, NULL, SC_MANAGER_CONNECT); if (scm = NULL!) {svc = OpenService (scm, serviceName.c_str (), SERVICE_ALL_ACCESS); if (! svc = NULL) {QueryServiceStatus (SVC, & ServiceStatus); if (serviceStatus.dwcurrentState == Service_Runni NG) // before deletion, stop this Service ControlService (svc, SERVICE_CONTROL_STOP, & ServiceStatus);. DeleteService (svc); CloseServiceHandle (svc); // delete the Service, the best and then call CloseServiceHandle} CloseServiceHandle (scm); // Now in order to remove the entry from the database}} // terminate the process void TGetInfo :: ClosePeocess (int processID) {HANDLE psn = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, false, processID); // available GetExitCodeProcess (HANDLE, LPDWORD) obtaining ExitCode IF (PSN && TerminateProcess) {MessageBox (Handle, "successfully ended!", application-> title.c_str (), mb_ok | mb_iconinformation;} else messagebox (handle, "Unable to terminate this process!" , Application-> Title.c_str (), MB_OK | MB_ICONERROR);} // Restart server bool tgetinfo :: restartServer () {htoken; token_privileges tkp; // Get a token for this process. IF (!! "token_adjust_privileges | token_query, & htoken) Return (false); // Get the Luid for the shutdown privilege. Lookuppprivilerage (NULL, SE_SHUTDOWN_NAME, & TKP.PRIVILEGES [0] .luid); // Improve permission Tkp.privilegect = 1; // One privilege to set tkp.privileges [0] .attributes = se_privilege_enabled; // Get the shutdown privilege for this process. AdjustTokenPrivileges (HToken, False, & TKP, 0, (ptoken_privileges) null, 0); // makes SE_SHUTDOWN_NAME's privilege is effective IF (getLastError ()! = error_success) Return False; // Reboot The System and Force All Applications to Close. IF (! EXITWINDOWSEX (EWX_REBOOT | EWX_FORCE, 0)) Return False;} -------------------------------------------------- -------------------------------------------------- -------------------- // Unit4.cpp #pragma HDRSTOP #include "unit4.h" #include } TsockInfo :: ~ TsockInfo () { } // State NTQuerySystemInformation () function typef dword (callback * ntquerysysteminformation) (DWORD, PDWORD, DWORD, PVOID); NTQuerySystemInformation NTQUERYSYSTEMINFORMATION // Judgment the array of Socket type Char SzsockType [6] [6] = {"NUL", "TCP", "UDP", "RAW", "RDM", "SEQ"}; // RaisePrivleges () function is used to elevate privileges bool this process TSockInfo :: RaisePrivleges (HANDLE hToken, char * pPriv) {TOKEN_PRIVILEGES tkp; if (! LookupPrivilegeValue (NULL, pPriv, & tkp.Privileges [0] .Luid)) { printf ( "LookupPrivilegeValue Error:% d / n", GetLastError ()); return false;} tkp.PrivilegeCount = 1; tkp.Privileges [0] .Attributes | = SE_PRIVILEGE_ENABLED; int iRet = AdjustTokenPrivileges (hToken, false, & tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0); if (iRet == NULL) // AdjustTokenPrivileges function fails {printf ( "AdjustTokenPrivileges Error:% d / n", GetLastError ()); return false;} else // AdjustTokenPrivileges call {// successful use GetLastError () return values iRet = GetLastError (); switch (iRet) {case ERROR_NOT_ALL_ASSIGNED: // all privileges unassigned printf ( "AdjustTokenPrivileges ERROR_NOT_ALL_ASSIGNED / n"); return false; case ERROR_SUCCESS: // Successfully assigned all privilege returnes; default: // unknown error Printf ("AdjustTokenPrivileges Unknow Error:% D / N", IRET); Return False;}}}}} // AdjustDacl used to adjust the target process DACLvoid TSockInfo :: AdjustDacl (HANDLE hProcess) {SID world = {SID_REVISION, 1, SECURITY_WORLD_SID_AUTHORITY, 0}; LPTSTR ptstrName = (LPTSTR) & world; EXPLICIT_ACCESS ea = {STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL, SET_ACCESS, NO_INHERITANCE, {0, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER, ptstrName}}; ACL * pdacl = 0; if (SetEntriesInAcl (1, & ea, 0, & pdacl) = ERROR_SUCCESS!) printf ( "SetEntriesInAcl Error:% d", GetLastError () ); IF (setsecurityInfo (HProcess, SE_kernel_Object, DACL_SECURITY_INFORMATION, 0, 0, PDACL, 0)! = Error_Success) Printf ("SetSecurityInfo Error:% D", getLastError ()); LocalFree (PDACL); INT TsockInfo :: MainInfo (TBCSNetState * NetState) {printf ("/ t = * = gport beta1 (shotgun@xici.net) = * = / n / n"); int rt, iCount = 0; Wsadata Wsadata; DWORD __stdcall * gmfne) (Handle HModule HModule, LPTSTR LPFILENAME, DWORD NSIZE); IRET = WSAStartup (MakeWord (1, 1), & WSADATA); IF (IRET) Printf ("WsaStartup Error:% D / N", GetLastError )); HANDLE hCurrentProc = GetCurrentProcess (); HANDLE hToken; if (OpenProcessToken (hCurrentProc, TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, & hToken)) printf (!! "OpenProcessToken Error:% d / n", GetLastError ()); else {if (RaisePrivleges (hToken, SE_DEBUG_NAME)) printf ( "SetPrivleges SE_DEBUG_NAME Error:% d / n", GetLastError ());} if (hToken) CloseHandle (hToken); HMODULE hNtdll = NULL; hNtdll = LoadLibrary ( "ntdll.dll"); if {printf ( "LoadLibrary (NTDLL.DLL) Error:% d / n", GetLastError ()); return false;} (hNtdll!) NtQuerySystemInformation = (NTQUERYSYSTEMINFORMATION) GetProcAddress (hNtdll, "NtQuerySystemInformation"); if {printf ( "GetProcess (NtQuerySystemInformation) Error:% d / n", GetLastError ()); return false;} (NtQuerySystemInformation!) HMODULE hPsapi = LoadLibrary ( "PSAPI"); if (! hPsapi) {printf ( "Can not Load psapi./N "); return 0;} GMFNE = (Handle, HModule, LPTSTR, DWORD) GetProcaddress (HPSAPI," GetModuleFileNameExa); if (! gmfne) {Printf ("Cannot getProcess (GetModuleFileNameExa) Error:% D / N ", getLastError ()); return 0;} DWORD dwNumBytes = MAX_HANDLE_LIST_BUF; PDWORD pdwHandleList = (PDWORD) malloc (dwNumBytes); if (pdwHandleList!) {Printf ( "Malloc for Handle List Error:% d / n", GetLastError ()); return false;} DWORD dwNumBytesRet = 0 ; iRet = (* NtQuerySystemInformation) (NT_HANDLE_LIST, pdwHandleList, dwNumBytes, & dwNumBytesRet); DWORD dwNumEntries; PHANDLEINFO pHandleInfo; if (iRet) {printf ( "NtQuerySystemInformation return% d, Error:% d / n", dwNumBytesRet, GetLastError ()) ;} else {HANDLE hProc; dwNumEntries = pdwHandleList [0]; pHandleInfo = (PHANDLEINFO) (pdwHandleList 1); for (DWORD i = 0; i } Else {sockaddr_in name = {0}; name.sin_family = AF_INET; int namelen = sizeof (sockaddr_in); SOCKET s = (SOCKET) hMyHandle; iRet = getsockname (s, (sockaddr *) & name, & namelen); if (iRet ! = SOCKET_ERROR) {INT SOCKTYPE = 0; int Optlen = 4; char FN [128]; if (iCount! = 0) Form1-> NetState = (tbcsnetState *) Realloc (Form1-> NetState, Sizeof (tbcsnetState) * icount 1)); iRet = getsockopt (s, SOL_SOCKET, SO_TYPE, (char *) & sockType, & optlen); hProc = OpenProcess (PROCESS_ALL_ACCESS, false, pHandleInfo-> dwPid); GMFNE (hProc, NULL, fn, 128); CloseHandle (hProc); Form1-> netstate [icount] .ProcessID = pHandleInfo-> dwPid; Form1-> netstate [icount] .SocketPort = ntohs (name.sin_port); strncpy (Form1-> netstate [icount] .SocketType, szSockType [socktype], 6); strcpy (form1-> netstate [iCount] .processname, fn); iCount ;}}} Phandleinfo ;}}} PDWHANDLELIST; if (hcurrentproc) CloseHandle (HcurrentProc); FreeElibrary (HPSAPI); FreeElibrary (HNTDLL); Return iCount;} ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- --------------------------------------- or more is 5 Unit, how can I ask? Note, try to implement some write details. Thank you!