Debian Codegraph @

listings/chapter-11/processes.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <assert.h>
8 #include <dirent.h>
9 #include <fcntl.h>
10 #include <grp.h>
11 #include <pwd.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <sys/uio.h>
18 #include <unistd.h>
19
20 #include "server.h"
21
22 /* Set *UID and *GID to the owning user ID and group ID, respectively,
23 of process PID. Return zero on success, non-zero on failure. */
24
25 static int get_uid_gid (pid_t pid, uid_t* uid, gid_t* gid)
26 {
27 char dir_name[64];
28 struct stat dir_info;
29 int rval;
30
31 /* Generate the name of the process's directory in /proc. */
32 snprintf (dir_name, sizeof (dir_name), "/proc/%d", (int) pid);
33 /* Obtain information about the directory. */
34 rval = stat (dir_name, &dir_info);
35 if (rval != 0)
36 /* Couldn't find it; perhaps this process no longer exists. */
37 return 1;
38 /* Make sure it's a directory; anything else is unexpected. */
39 assert (S_ISDIR (dir_info.st_mode));
40
41 /* Extract the IDs we want. */
42 *uid = dir_info.st_uid;
43 *gid = dir_info.st_gid;
44 return 0;
45 }
46
47 /* Return the name of user UID. The return value is a buffer which the
48 caller must allocate with free. UID must be a valid user ID. */
49
50 static char* get_user_name (uid_t uid)
51 {
52 struct passwd* entry;
53
54 entry = getpwuid (uid);
55 if (entry == NULL)
56 system_error ("getpwuid");
57 return xstrdup (entry->pw_name);
58 }
59
60 /* Return the name of group GID. The return value is a buffer which the
61 caller must allocate with free. GID must be a valid group ID. */
62
63 static char* get_group_name (gid_t gid)
64 {
65 struct group* entry;
66
67 entry = getgrgid (gid);
68 if (entry == NULL)
69 system_error ("getgrgid");
70 return xstrdup (entry->gr_name);
71 }
72
73 /* Return the name of the program running in process PID, or NULL on
74 error. The return value is a newly-allocated buffer which the caller
75 must deallocate with free. */
76
77 static char* get_program_name (pid_t pid)
78 {
79 char file_name[64];
80 char status_info[256];
81 int fd;
82 int rval;
83 char* open_paren;
84 char* close_paren;
85 char* result;
86
87 /* Generate the name of the "stat" file in the process's /proc
88 directory, and open it. */
89 snprintf (file_name, sizeof (file_name), "/proc/%d/stat", (int) pid);
90 fd = open (file_name, O_RDONLY);
91 if (fd == -1)
92 /* Couldn't open the stat file for this process. Perhaps the
93 process no longer exists. */
94 return NULL;
95 /* Read the contents. */
96 rval = read (fd, status_info, sizeof (status_info) - 1);
97 close (fd);
98 if (rval <= 0)
99 /* Couldn't read, for some reason; bail. */
100 return NULL;
101 /* NUL-terminate the file contents. */
102 status_info[rval] = '\0';
103
104 /* The program name is the second element of the file contents, and is
105 surrounded by parentheses. Find the positions of the parentheses
106 in the file contents. */
107 open_paren = strchr (status_info, '(');
108 close_paren = strchr (status_info, ')');
109 if (open_paren == NULL
110 || close_paren == NULL
111 || close_paren < open_paren)
112 /* Couldn't find them; bail. */
113 return NULL;
114 /* Allocate memory for the result. */
115 result = (char*) xmalloc (close_paren - open_paren);
116 /* Copy the program name into the result. */
117 strncpy (result, open_paren + 1, close_paren - open_paren - 1);
118 /* strncpy doesn't NUL-terminate the result, so do it here. */
119 result[close_paren - open_paren - 1] = '\0';
120 /* All done. */
121 return result;
122 }
123
124 /* Return the resident set size (RSS), in kilobytes, of process PID.
125 Return -1 on failure. */
126
127 static int get_rss (pid_t pid)
128 {
129 char file_name[64];
130 int fd;
131 char mem_info[128];
132 int rval;
133 int rss;
134
135 /* Generate the name of the process's "statm" entry in its /proc
136 directory. */
137 snprintf (file_name, sizeof (file_name), "/proc/%d/statm", (int) pid);
138 /* Open it. */
139 fd = open (file_name, O_RDONLY);
140 if (fd == -1)
141 /* Couldn't open it; perhaps this process no longer exists. */
142 return -1;
143 /* Read the file's contents. */
144 rval = read (fd, mem_info, sizeof (mem_info) - 1);
145 close (fd);
146 if (rval <= 0)
147 /* Couldn't read the contents; bail. */
148 return -1;
149 /* NUL-terminate the contents. */
150 mem_info[rval] = '\0';
151 /* Extract the RSS. It's the second item. */
152 rval = sscanf (mem_info, "%*d %d", &rss);
153 if (rval != 1)
154 /* The contents of statm are formatted in a way we don't understand. */
155 return -1;
156
157 /* The values in statm are in units of the system's page size.
158 Convert the RSS to kilobytes. */
159 return rss * getpagesize () / 1024;
160 }
161
162 /* Generate an HTML table row for process PID. The return value is a
163 pointer to a buffer which the caller must deallocate with free, or
164 NULL if an error occurs. */
165
166 static char* format_process_info (pid_t pid)
167 {
168 int rval;
169 uid_t uid;
170 gid_t gid;
171 char* user_name;
172 char* group_name;
173 int rss;
174 char* program_name;
175 size_t result_length;
176 char* result;
177
178 /* Obtain the process's user and group IDs. */
179 rval = get_uid_gid (pid, &uid, &gid);
180 if (rval != 0)
181 return NULL;
182 /* Obtain the process's RSS. */
183 rss = get_rss (pid);
184 if (rss == -1)
185 return NULL;
186 /* Obtain the process's program name. */
187 program_name = get_program_name (pid);
188 if (program_name == NULL)
189 return NULL;
190 /* Convert user and group IDs to corresponding names. */
191 user_name = get_user_name (uid);
192 group_name = get_group_name (gid);
193
194 /* Compute the length of the string we'll need to hold the result, and
195 allocate memory to hold it. */
196 result_length = strlen (program_name)
197 + strlen (user_name) + strlen (group_name) + 128;
198 result = (char*) xmalloc (result_length);
199 /* Format the result. */
200 snprintf (result, result_length,
201 "<tr><td align=\"right\">%d</td><td><tt>%s</tt></td><td>%s</td>"
202 "<td>%s</td><td align=\"right\">%d</td></tr>\n",
203 (int) pid, program_name, user_name, group_name, rss);
204 /* Clean up. */
205 free (program_name);
206 free (user_name);
207 free (group_name);
208 /* All done. */
209 return result;
210 }
211
212 /* HTML source for the start of the process listing page. */
213
214 static char* page_start =
215 "<html>\n"
216 " <body>\n"
217 " <table cellpadding=\"4\" cellspacing=\"0\" border=\"1\">\n"
218 " <thead>\n"
219 " <tr>\n"
220 " <th>PID</th>\n"
221 " <th>Program</th>\n"
222 " <th>User</th>\n"
223 " <th>Group</th>\n"
224 " <th>RSS&nbsp;(KB)</th>\n"
225 " </tr>\n"
226 " </thead>\n"
227 " <tbody>\n";
228
229 /* HTML source for the end of the process listing page. */
230
231 static char* page_end =
232 " </tbody>\n"
233 " </table>\n"
234 " </body>\n"
235 "</html>\n";
236
237 void module_generate (int fd)
238 {
239 size_t i;
240 DIR* proc_listing;
241
242 /* Set up an iovec array. We'll fill this with buffers that'll be
243 part of our output, growing it dynamically as necessary. */
244
245 /* The number of elements in the array that we've used. */
246 size_t vec_length = 0;
247 /* The allocated size of the array. */
248 size_t vec_size = 16;
249 /* The array of iovcec elemens. */
250 struct iovec* vec =
251 (struct iovec*) xmalloc (vec_size * sizeof (struct iovec));
252
253 /* The first buffer is the HTML source for the start of the page. */
254 vec[vec_length].iov_base = page_start;
255 vec[vec_length].iov_len = strlen (page_start);
256 ++vec_length;
257
258 /* Start a directory listing for /proc. */
259 proc_listing = opendir ("/proc");
260 if (proc_listing == NULL)
261 system_error ("opendir");
262
263 /* Loop over directory entries in /proc. */
264 while (1) {
265 struct dirent* proc_entry;
266 const char* name;
267 pid_t pid;
268 char* process_info;
269
270 /* Get the next entry in /proc. */
271 proc_entry = readdir (proc_listing);
272 if (proc_entry == NULL)
273 /* We've hit the end of the listing. */
274 break;
275
276 /* If this entry is not composed purely of digits, it's not a
277 process directory, so skip it. */
278 name = proc_entry->d_name;
279 if (strspn (name, "0123456789") != strlen (name))
280 continue;
281 /* The name of the entry is the process ID. */
282 pid = (pid_t) atoi (name);
283 /* Generate HTML for a table row describing this process. */
284 process_info = format_process_info (pid);
285 if (process_info == NULL)
286 /* Something went wrong. The process may have vanished while we
287 were looking at it. Use a placeholder row instead. */
288 process_info = "<tr><td colspan=\"5\">ERROR</td></tr>";
289
290 /* Make sure the iovec array is long enough to hold this buffer
291 (plus one more, since we'll add an extra element when we're done
292 listing processes). If not, grow it to twice its current size. */
293 if (vec_length == vec_size - 1) {
294 vec_size *= 2;
295 vec = xrealloc (vec, vec_size * sizeof (struct iovec));
296 }
297 /* Store this buffer as the next element of the array. */
298 vec[vec_length].iov_base = process_info;
299 vec[vec_length].iov_len = strlen (process_info);
300 ++vec_length;
301 }
302
303 /* End the directory listing operation. */
304 closedir (proc_listing);
305
306 /* Add one last buffer with HTML that ends the page. */
307 vec[vec_length].iov_base = page_end;
308 vec[vec_length].iov_len = strlen (page_end);
309 ++vec_length;
310
311 /* Output the entire page to the client file descriptor all at once. */
312 writev (fd, vec, vec_length);
313
314 /* Deallocate the buffers we created. The first and last are static,
315 and should not be deallocated. */
316 for (i = 1; i < vec_length - 1; ++i)
317 free (vec[i].iov_base);
318 /* Deallocate the iovec array. */
319 free (vec);
320 }