オープンソース・ソフトウェアの開発とダウンロード

Subversion リポジトリの参照

Diff of /trunk/1.7.x/ccs-patch/security/ccsecurity/util.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/1.5.x/ccs-patch/fs/ccs_common.c revision 741 by kumaneko, Sat Dec 1 15:14:21 2007 UTC branches/ccs-patch/security/ccsecurity/util.c revision 2922 by kumaneko, Wed Aug 19 04:26:56 2009 UTC
# Line 1  Line 1 
1  /*  /*
2   * fs/ccs_common.c   * security/ccsecurity/util.c
3   *   *
4   * Common functions for SAKURA and TOMOYO.   * Copyright (C) 2005-2009  NTT DATA CORPORATION
5   *   *
6   * Copyright (C) 2005-2007  NTT DATA CORPORATION   * Version: 1.7.0-pre   2009/08/08
  *  
  * Version: 1.5.2-pre   2007/11/29  
7   *   *
8   * This file is applicable to both 2.4.30 and 2.6.11 and later.   * This file is applicable to both 2.4.30 and 2.6.11 and later.
9   * See README.ccs for ChangeLog.   * See README.ccs for ChangeLog.
10   *   *
11   */   */
12    
13  #include <linux/string.h>  #include "internal.h"
 #include <linux/mm.h>  
 #include <linux/utime.h>  
 #include <linux/file.h>  
 #include <linux/module.h>  
 #include <linux/slab.h>  
 #include <asm/uaccess.h>  
 #include <stdarg.h>  
 #include <linux/version.h>  
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
 #include <linux/namei.h>  
 #include <linux/mount.h>  
 static const int lookup_flags = LOOKUP_FOLLOW;  
 #else  
 static const int lookup_flags = LOOKUP_FOLLOW | LOOKUP_POSITIVE;  
 #endif  
 #include <linux/realpath.h>  
 #include <linux/ccs_common.h>  
 #include <linux/ccs_proc.h>  
 #include <linux/tomoyo.h>  
14    
15  #ifdef CONFIG_TOMOYO_MAX_ACCEPT_ENTRY  DEFINE_MUTEX(ccs_policy_lock);
 #define MAX_ACCEPT_ENTRY (CONFIG_TOMOYO_MAX_ACCEPT_ENTRY)  
 #else  
 #define MAX_ACCEPT_ENTRY 2048  
 #endif  
 #ifdef CONFIG_TOMOYO_MAX_GRANT_LOG  
 #define MAX_GRANT_LOG (CONFIG_TOMOYO_MAX_GRANT_LOG)  
 #else  
 #define MAX_GRANT_LOG 1024  
 #endif  
 #ifdef CONFIG_TOMOYO_MAX_REJECT_LOG  
 #define MAX_REJECT_LOG (CONFIG_TOMOYO_MAX_REJECT_LOG)  
 #else  
 #define MAX_REJECT_LOG 1024  
 #endif  
16    
17  /*************************  VARIABLES  *************************/  /* Has /sbin/init started? */
18    bool ccs_policy_loaded;
19    
20  /* /sbin/init started? */  /* Profile table. Memory is allocated as needed. */
21  int sbin_init_started = 0;  struct ccs_profile *ccs_profile_ptr[CCS_MAX_PROFILES];
22    
23  const char *ccs_log_level = KERN_DEBUG;  /* Utility functions. */
24    
25  static struct {  /**
26          const char *keyword;   * ccs_parse_ulong - Parse an "unsigned long" value.
27          unsigned int current_value;   *
28          const unsigned int max_value;   * @result: Pointer to "unsigned long".
29  } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {   * @str:    Pointer to string to parse.
30          [CCS_PROFILE_COMMENT]            = { "COMMENT",             0, 0 }, /* Reserved for string. */   *
31          [CCS_TOMOYO_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },   * Returns value type on success, 0 otherwise.
32          [CCS_TOMOYO_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },   *
33          [CCS_TOMOYO_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },   * The @src is updated to point the first character after the value
34          [CCS_TOMOYO_MAC_FOR_NETWORK]     = { "MAC_FOR_NETWORK",     0, 3 },   * on success.
35          [CCS_TOMOYO_MAC_FOR_SIGNAL]      = { "MAC_FOR_SIGNAL",      0, 3 },   */
36          [CCS_SAKURA_DENY_CONCEAL_MOUNT]  = { "DENY_CONCEAL_MOUNT",  0, 3 },  u8 ccs_parse_ulong(unsigned long *result, char **str)
37          [CCS_SAKURA_RESTRICT_CHROOT]     = { "RESTRICT_CHROOT",     0, 3 },  {
38          [CCS_SAKURA_RESTRICT_MOUNT]      = { "RESTRICT_MOUNT",      0, 3 },          const char *cp = *str;
39          [CCS_SAKURA_RESTRICT_UNMOUNT]    = { "RESTRICT_UNMOUNT",    0, 3 },          char *ep;
40          [CCS_SAKURA_RESTRICT_PIVOT_ROOT] = { "RESTRICT_PIVOT_ROOT", 0, 3 },          int base = 10;
41          [CCS_SAKURA_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },          if (*cp == '0') {
42          [CCS_TOMOYO_MAX_ACCEPT_ENTRY]    = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },                  char c = *(cp + 1);
43          [CCS_TOMOYO_MAX_GRANT_LOG]       = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },                  if (c == 'x' || c == 'X') {
44          [CCS_TOMOYO_MAX_REJECT_LOG]      = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },                          base = 16;
45          [CCS_TOMOYO_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },                          cp += 2;
46          [CCS_ALLOW_ENFORCE_GRACE]        = { "ALLOW_ENFORCE_GRACE", 0, 1 },                  } else if (c >= '0' && c <= '7') {
47          [CCS_SLEEP_PERIOD]               = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */                          base = 8;
48          [CCS_TOMOYO_ALT_EXEC]            = { "ALT_EXEC",            0, 0 }, /* Reserved for string. */                          cp++;
49  };                  }
50            }
51  struct profile {          *result = simple_strtoul(cp, &ep, base);
52          unsigned int value[CCS_MAX_CONTROL_INDEX];          if (cp == ep)
53          const struct path_info *comment;                  return 0;
54          const struct path_info *alt_exec;          *str = ep;
55  };          switch (base) {
56            case 16:
57  static struct profile *profile_ptr[MAX_PROFILES];                  return CCS_VALUE_TYPE_HEXADECIMAL;
58            case 8:
59  /*************************  UTILITY FUNCTIONS  *************************/                  return CCS_VALUE_TYPE_OCTAL;
60            default:
61                    return CCS_VALUE_TYPE_DECIMAL;
62            }
63    }
64    
65  #ifdef CONFIG_TOMOYO  /**
66  static int __init TOMOYO_Quiet_Setup(char *str)   * ccs_print_ulong - Print an "unsigned long" value.
67     *
68     * @buffer:     Pointer to buffer.
69     * @buffer_len: Size of @buffer.
70     * @value:      An "unsigned long" value.
71     * @type:       Type of @value.
72     *
73     * Returns nothing.
74     */
75    void ccs_print_ulong(char *buffer, const int buffer_len,
76                         const unsigned long value, const u8 type)
77  {  {
78          ccs_control_array[CCS_TOMOYO_VERBOSE].current_value = 0;          if (type == CCS_VALUE_TYPE_DECIMAL)
79          return 0;                  snprintf(buffer, buffer_len, "%lu", value);
80            else if (type == CCS_VALUE_TYPE_OCTAL)
81                    snprintf(buffer, buffer_len, "0%lo", value);
82            else if (type == CCS_VALUE_TYPE_HEXADECIMAL)
83                    snprintf(buffer, buffer_len, "0x%lX", value);
84            else
85                    snprintf(buffer, buffer_len, "type(%u)", type);
86    }
87    
88    bool ccs_parse_name_union(const char *filename, struct ccs_name_union *ptr)
89    {
90            if (!ccs_is_correct_path(filename, 0, 0, 0))
91                    return false;
92            if (filename[0] == '@') {
93                    ptr->group = ccs_get_path_group(filename + 1);
94                    ptr->is_group = true;
95                    return ptr->group != NULL;
96            }
97            ptr->filename = ccs_get_name(filename);
98            ptr->is_group = false;
99            return ptr->filename != NULL;
100    }
101    
102    bool ccs_parse_number_union(char *data, struct ccs_number_union *num)
103    {
104            u8 type;
105            unsigned long v;
106            memset(num, 0, sizeof(*num));
107            if (data[0] == '@') {
108                    if (!ccs_is_correct_path(data, 0, 0, 0))
109                            return false;
110                    num->group = ccs_get_number_group(data + 1);
111                    num->is_group = true;
112                    return num->group != NULL;
113            }
114            type = ccs_parse_ulong(&v, &data);
115            if (!type)
116                    return false;
117            num->values[0] = v;
118            num->min_type = type;
119            if (!*data) {
120                    num->values[1] = v;
121                    num->max_type = type;
122                    return true;
123            }
124            if (*data++ != '-')
125                    return false;
126            type = ccs_parse_ulong(&v, &data);
127            if (!type || *data)
128                    return false;
129            num->values[1] = v;
130            num->max_type = type;
131            return true;
132  }  }
133    
134  __setup("TOMOYO_QUIET", TOMOYO_Quiet_Setup);  /**
135  #endif   * ccs_is_byte_range - Check whether the string isa \ooo style octal value.
136     *
137     * @str: Pointer to the string.
138     *
139     * Returns true if @str is a \ooo style octal value, false otherwise.
140     */
141    static inline bool ccs_is_byte_range(const char *str)
142    {
143            return *str >= '0' && *str++ <= '3' &&
144                    *str >= '0' && *str++ <= '7' &&
145                    *str >= '0' && *str <= '7';
146    }
147    
148  /* Am I root? */  /**
149  static int isRoot(void)   * ccs_is_decimal - Check whether the character is a decimal character.
150     *
151     * @c: The character to check.
152     *
153     * Returns true if @c is a decimal character, false otherwise.
154     */
155    static inline bool ccs_is_decimal(const char c)
156  {  {
157          return !current->uid && !current->euid;          return c >= '0' && c <= '9';
158  }  }
159    
160  /*  /**
161   * Format string.   * ccs_is_hexadecimal - Check whether the character is a hexadecimal character.
162     *
163     * @c: The character to check.
164     *
165     * Returns true if @c is a hexadecimal character, false otherwise.
166     */
167    static inline bool ccs_is_hexadecimal(const char c)
168    {
169            return (c >= '0' && c <= '9') ||
170                    (c >= 'A' && c <= 'F') ||
171                    (c >= 'a' && c <= 'f');
172    }
173    
174    /**
175     * ccs_is_alphabet_char - Check whether the character is an alphabet.
176     *
177     * @c: The character to check.
178     *
179     * Returns true if @c is an alphabet character, false otherwise.
180     */
181    static inline bool ccs_is_alphabet_char(const char c)
182    {
183            return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
184    }
185    
186    /**
187     * ccs_make_byte - Make byte value from three octal characters.
188     *
189     * @c1: The first character.
190     * @c2: The second character.
191     * @c3: The third character.
192     *
193     * Returns byte value.
194     */
195    static inline u8 ccs_make_byte(const u8 c1, const u8 c2, const u8 c3)
196    {
197            return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
198    }
199    
200    /**
201     * ccs_str_starts - Check whether the given string starts with the given keyword.
202     *
203     * @src:  Pointer to pointer to the string.
204     * @find: Pointer to the keyword.
205     *
206     * Returns true if @src starts with @find, false otherwise.
207     *
208     * The @src is updated to point the first character after the @find
209     * if @src starts with @find.
210     */
211    bool ccs_str_starts(char **src, const char *find)
212    {
213            const int len = strlen(find);
214            char *tmp = *src;
215            if (strncmp(tmp, find, len))
216                    return false;
217            tmp += len;
218            *src = tmp;
219            return true;
220    }
221    
222    /**
223     * ccs_normalize_line - Format string.
224     *
225     * @buffer: The line to normalize.
226     *
227   * Leading and trailing whitespaces are removed.   * Leading and trailing whitespaces are removed.
228   * Multiple whitespaces are packed into single space.   * Multiple whitespaces are packed into single space.
229     *
230     * Returns nothing.
231   */   */
232  static void NormalizeLine(unsigned char *buffer)  void ccs_normalize_line(unsigned char *buffer)
233  {  {
234          unsigned char *sp = buffer, *dp = buffer;          unsigned char *sp = buffer;
235          int first = 1;          unsigned char *dp = buffer;
236          while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;          bool first = true;
237            while (*sp && (*sp <= ' ' || *sp >= 127))
238                    sp++;
239          while (*sp) {          while (*sp) {
240                  if (!first) *dp++ = ' ';                  if (!first)
241                  first = 0;                          *dp++ = ' ';
242                  while (*sp > ' ' && *sp < 127) *dp++ = *sp++;                  first = false;
243                  while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;                  while (*sp > ' ' && *sp < 127)
244                            *dp++ = *sp++;
245                    while (*sp && (*sp <= ' ' || *sp >= 127))
246                            sp++;
247          }          }
248          *dp = '\0';          *dp = '\0';
249  }  }
250    
251  /*  /**
252   *  Check whether the given filename follows the naming rules.   * ccs_tokenize - Tokenize string.
253   *  Returns nonzero if follows, zero otherwise.   *
254     * @buffer: The line to tokenize.
255     * @w:      Pointer to "char *".
256     * @size:   Sizeof @w .
257     *
258     * Returns true on success, false otherwise.
259     */
260    bool ccs_tokenize(char *buffer, char *w[], size_t size)
261    {
262            int count = size / sizeof(char *);
263            int i;
264            for (i = 0; i < count; i++)
265                    w[i] = "";
266            for (i = 0; i < count; i++) {
267                    char *cp = strchr(buffer, ' ');
268                    if (cp)
269                            *cp = '\0';
270                    w[i] = buffer;
271                    if (!cp)
272                            break;
273                    buffer = cp + 1;
274            }
275            return i < count || !*buffer;
276    }
277    
278    /**
279     * ccs_is_correct_path - Validate a pathname.
280     * @filename:     The pathname to check.
281     * @start_type:   Should the pathname start with '/'?
282     *                1 = must / -1 = must not / 0 = don't care
283     * @pattern_type: Can the pathname contain a wildcard?
284     *                1 = must / -1 = must not / 0 = don't care
285     * @end_type:     Should the pathname end with '/'?
286     *                1 = must / -1 = must not / 0 = don't care
287     *
288     * Check whether the given filename follows the naming rules.
289     * Returns true if @filename follows the naming rules, false otherwise.
290   */   */
291  bool IsCorrectPath(const char *filename, const int start_type, const int pattern_type, const int end_type, const char *function)  bool ccs_is_correct_path(const char *filename, const s8 start_type,
292                             const s8 pattern_type, const s8 end_type)
293  {  {
294          int contains_pattern = 0;          bool contains_pattern = false;
295          char c, d, e;          unsigned char c;
296            unsigned char d;
297            unsigned char e;
298          const char *original_filename = filename;          const char *original_filename = filename;
299          if (!filename) goto out;          if (!filename)
300                    goto out;
301          c = *filename;          c = *filename;
302          if (start_type == 1) { /* Must start with '/' */          if (start_type == 1) { /* Must start with '/' */
303                  if (c != '/') goto out;                  if (c != '/')
304                            goto out;
305          } else if (start_type == -1) { /* Must not start with '/' */          } else if (start_type == -1) { /* Must not start with '/' */
306                  if (c == '/') goto out;                  if (c == '/')
307                            goto out;
308          }          }
309          if (c) c = * (strchr(filename, '\0') - 1);          if (c)
310                    c = *(filename + strlen(filename) - 1);
311          if (end_type == 1) { /* Must end with '/' */          if (end_type == 1) { /* Must end with '/' */
312                  if (c != '/') goto out;                  if (c != '/')
313                            goto out;
314          } else if (end_type == -1) { /* Must not end with '/' */          } else if (end_type == -1) { /* Must not end with '/' */
315                  if (c == '/') goto out;                  if (c == '/')
316                            goto out;
317          }          }
318          while ((c = *filename++) != '\0') {          while (1) {
319                    c = *filename++;
320                    if (!c)
321                            break;
322                  if (c == '\\') {                  if (c == '\\') {
323                          switch ((c = *filename++)) {                          c = *filename++;
324                            switch (c) {
325                          case '\\':  /* "\\" */                          case '\\':  /* "\\" */
326                                  continue;                                  continue;
327                          case '$':   /* "\$" */                          case '$':   /* "\$" */
# Line 164  bool IsCorrectPath(const char *filename, Line 334  bool IsCorrectPath(const char *filename,
334                          case 'a':   /* "\a" */                          case 'a':   /* "\a" */
335                          case 'A':   /* "\A" */                          case 'A':   /* "\A" */
336                          case '-':   /* "\-" */                          case '-':   /* "\-" */
337                                  if (pattern_type == -1) break; /* Must not contain pattern */                                  if (pattern_type == -1)
338                                  contains_pattern = 1;                                          break; /* Must not contain pattern */
339                                    contains_pattern = true;
340                                  continue;                                  continue;
341                          case '0':   /* "\ooo" */                          case '0':   /* "\ooo" */
342                          case '1':                          case '1':
343                          case '2':                          case '2':
344                          case '3':                          case '3':
345                                  if ((d = *filename++) >= '0' && d <= '7' && (e = *filename++) >= '0' && e <= '7') {                                  d = *filename++;
346                                          const unsigned char f =                                  if (d < '0' || d > '7')
347                                                  (((unsigned char) (c - '0')) << 6) +                                          break;
348                                                  (((unsigned char) (d - '0')) << 3) +                                  e = *filename++;
349                                                  (((unsigned char) (e - '0')));                                  if (e < '0' || e > '7')
350                                          if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                          break;
351                                  }                                  c = ccs_make_byte(c, d, e);
352                                    if (c && (c <= ' ' || c >= 127))
353                                            continue; /* pattern is not \000 */
354                          }                          }
355                          goto out;                          goto out;
356                  } else if (c <= ' ' || c >= 127) {                  } else if (c <= ' ' || c >= 127) {
# Line 185  bool IsCorrectPath(const char *filename, Line 358  bool IsCorrectPath(const char *filename,
358                  }                  }
359          }          }
360          if (pattern_type == 1) { /* Must contain pattern */          if (pattern_type == 1) { /* Must contain pattern */
361                  if (!contains_pattern) goto out;                  if (!contains_pattern)
362                            goto out;
363          }          }
364          return 1;          return true;
365   out:   out:
366          printk(KERN_DEBUG "%s: Invalid pathname '%s'\n", function, original_filename);          printk(KERN_DEBUG "Invalid pathname '%s'\n", original_filename);
367          return 0;          return false;
368  }  }
369    
370  /*  /**
371   *  Check whether the given domainname follows the naming rules.   * ccs_is_correct_domain - Check whether the given domainname follows the naming rules.
372   *  Returns nonzero if follows, zero otherwise.   * @domainname:   The domainname to check.
373     *
374     * Returns true if @domainname follows the naming rules, false otherwise.
375   */   */
376  bool IsCorrectDomain(const unsigned char *domainname, const char *function)  bool ccs_is_correct_domain(const unsigned char *domainname)
377  {  {
378          unsigned char c, d, e;          unsigned char c;
379            unsigned char d;
380            unsigned char e;
381          const char *org_domainname = domainname;          const char *org_domainname = domainname;
382          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN)) goto out;          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN))
383                    goto out;
384          domainname += ROOT_NAME_LEN;          domainname += ROOT_NAME_LEN;
385          if (!*domainname) return 1;          if (!*domainname)
386                    return true;
387          do {          do {
388                  if (*domainname++ != ' ') goto out;                  if (*domainname++ != ' ')
389                  if (*domainname++ != '/') goto out;                          goto out;
390                  while ((c = *domainname) != '\0' && c != ' ') {                  if (*domainname++ != '/')
391                            goto out;
392                    while (1) {
393                            c = *domainname;
394                            if (!c || c == ' ')
395                                    break;
396                          domainname++;                          domainname++;
397                          if (c == '\\') {                          if (c == '\\') {
398                                  switch ((c = *domainname++)) {                                  c = *domainname++;
399                                    switch ((c)) {
400                                  case '\\':  /* "\\" */                                  case '\\':  /* "\\" */
401                                          continue;                                          continue;
402                                  case '0':   /* "\ooo" */                                  case '0':   /* "\ooo" */
403                                  case '1':                                  case '1':
404                                  case '2':                                  case '2':
405                                  case '3':                                  case '3':
406                                          if ((d = *domainname++) >= '0' && d <= '7' && (e = *domainname++) >= '0' && e <= '7') {                                          d = *domainname++;
407                                                  const unsigned char f =                                          if (d < '0' || d > '7')
408                                                          (((unsigned char) (c - '0')) << 6) +                                                  break;
409                                                          (((unsigned char) (d - '0')) << 3) +                                          e = *domainname++;
410                                                          (((unsigned char) (e - '0')));                                          if (e < '0' || e > '7')
411                                                  if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                                  break;
412                                          }                                          c = ccs_make_byte(c, d, e);
413                                            if (c && (c <= ' ' || c >= 127))
414                                                    /* pattern is not \000 */
415                                                    continue;
416                                  }                                  }
417                                  goto out;                                  goto out;
418                          } else if (c < ' ' || c >= 127) {                          } else if (c < ' ' || c >= 127) {
# Line 231  bool IsCorrectDomain(const unsigned char Line 420  bool IsCorrectDomain(const unsigned char
420                          }                          }
421                  }                  }
422          } while (*domainname);          } while (*domainname);
423          return 1;          return true;
424   out:   out:
425          printk(KERN_DEBUG "%s: Invalid domainname '%s'\n", function, org_domainname);          printk(KERN_DEBUG "Invalid domainname '%s'\n", org_domainname);
426          return 0;          return false;
427  }  }
428    
429  bool IsDomainDef(const unsigned char *buffer)  /**
430     * ccs_is_domain_def - Check whether the given token can be a domainname.
431     *
432     * @buffer: The token to check.
433     *
434     * Returns true if @buffer possibly be a domainname, false otherwise.
435     */
436    bool ccs_is_domain_def(const unsigned char *buffer)
437  {  {
438          /* while (*buffer && (*buffer <= ' ' || *buffer >= 127)) buffer++; */          return !strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN);
         return strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN) == 0;  
439  }  }
440    
441  struct domain_info *FindDomain(const char *domainname0)  /**
442     * ccs_find_domain - Find a domain by the given name.
443     *
444     * @domainname: The domainname to find.
445     *
446     * Returns pointer to "struct ccs_domain_info" if found, NULL otherwise.
447     *
448     * Caller holds ccs_read_lock().
449     */
450    struct ccs_domain_info *ccs_find_domain(const char *domainname)
451  {  {
452          struct domain_info *domain;          struct ccs_domain_info *domain;
453          struct path_info domainname;          struct ccs_path_info name;
454          domainname.name = domainname0;          ccs_assert_read_lock();
455          fill_path_info(&domainname);          name.name = domainname;
456          list1_for_each_entry(domain, &domain_list, list) {          ccs_fill_path_info(&name);
457                  if (!domain->is_deleted && !pathcmp(&domainname, domain->domainname)) return domain;          list_for_each_entry_rcu(domain, &ccs_domain_list, list) {
458                    if (!domain->is_deleted &&
459                        !ccs_pathcmp(&name, domain->domainname))
460                            return domain;
461          }          }
462          return NULL;          return NULL;
463  }  }
464    
465  static int PathDepth(const char *pathname)  /**
466     * ccs_path_depth - Evaluate the number of '/' in a string.
467     *
468     * @pathname: The string to evaluate.
469     *
470     * Returns path depth of the string.
471     *
472     * I score 2 for each of the '/' in the @pathname
473     * and score 1 if the @pathname ends with '/'.
474     */
475    static int ccs_path_depth(const char *pathname)
476  {  {
477          int i = 0;          int i = 0;
478          if (pathname) {          if (pathname) {
479                  char *ep = strchr(pathname, '\0');                  const char *ep = pathname + strlen(pathname);
480                  if (pathname < ep--) {                  if (pathname < ep--) {
481                          if (*ep != '/') i++;                          if (*ep != '/')
482                          while (pathname <= ep) if (*ep-- == '/') i += 2;                                  i++;
483                            while (pathname <= ep)
484                                    if (*ep-- == '/')
485                                            i += 2;
486                  }                  }
487          }          }
488          return i;          return i;
489  }  }
490    
491  static int const_part_length(const char *filename)  /**
492     * ccs_const_part_length - Evaluate the initial length without a pattern in a token.
493     *
494     * @filename: The string to evaluate.
495     *
496     * Returns the initial length without a pattern in @filename.
497     */
498    static int ccs_const_part_length(const char *filename)
499  {  {
500            char c;
501          int len = 0;          int len = 0;
502          if (filename) {          if (!filename)
503                  char c;                  return 0;
504                  while ((c = *filename++) != '\0') {          while (1) {
505                          if (c != '\\') { len++; continue; }                  c = *filename++;
506                          switch (c = *filename++) {                  if (!c)
                         case '\\':  /* "\\" */  
                                 len += 2; continue;  
                         case '0':   /* "\ooo" */  
                         case '1':  
                         case '2':  
                         case '3':  
                                 if ((c = *filename++) >= '0' && c <= '7' && (c = *filename++) >= '0' && c <= '7') { len += 4; continue; }  
                         }  
507                          break;                          break;
508                    if (c != '\\') {
509                            len++;
510                            continue;
511                    }
512                    c = *filename++;
513                    switch (c) {
514                    case '\\':  /* "\\" */
515                            len += 2;
516                            continue;
517                    case '0':   /* "\ooo" */
518                    case '1':
519                    case '2':
520                    case '3':
521                            c = *filename++;
522                            if (c < '0' || c > '7')
523                                    break;
524                            c = *filename++;
525                            if (c < '0' || c > '7')
526                                    break;
527                            len += 4;
528                            continue;
529                  }                  }
530                    break;
531          }          }
532          return len;          return len;
533  }  }
534    
535  void fill_path_info(struct path_info *ptr)  /**
536     * ccs_fill_path_info - Fill in "struct ccs_path_info" members.
537     *
538     * @ptr: Pointer to "struct ccs_path_info" to fill in.
539     *
540     * The caller sets "struct ccs_path_info"->name.
541     */
542    void ccs_fill_path_info(struct ccs_path_info *ptr)
543  {  {
544          const char *name = ptr->name;          const char *name = ptr->name;
545          const int len = strlen(name);          const int len = strlen(name);
546          ptr->total_len = len;          ptr->total_len = len;
547          ptr->const_len = const_part_length(name);          ptr->const_len = ccs_const_part_length(name);
548          ptr->is_dir = len && (name[len - 1] == '/');          ptr->is_dir = len && (name[len - 1] == '/');
549          ptr->is_patterned = (ptr->const_len < len);          ptr->is_patterned = (ptr->const_len < len);
550          ptr->hash = full_name_hash(name, len);          ptr->hash = full_name_hash(name, len);
551          ptr->depth = PathDepth(name);          ptr->depth = ccs_path_depth(name);
552  }  }
553    
554  static int FileMatchesToPattern2(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
555     * ccs_file_matches_pattern2 - Pattern matching without '/' character
556     * and "\-" pattern.
557     *
558     * @filename:     The start of string to check.
559     * @filename_end: The end of string to check.
560     * @pattern:      The start of pattern to compare.
561     * @pattern_end:  The end of pattern to compare.
562     *
563     * Returns true if @filename matches @pattern, false otherwise.
564     */
565    static bool ccs_file_matches_pattern2(const char *filename,
566                                          const char *filename_end,
567                                          const char *pattern,
568                                          const char *pattern_end)
569  {  {
570          while (filename < filename_end && pattern < pattern_end) {          while (filename < filename_end && pattern < pattern_end) {
571                    char c;
572                  if (*pattern != '\\') {                  if (*pattern != '\\') {
573                          if (*filename++ != *pattern++) return 0;                          if (*filename++ != *pattern++)
574                  } else {                                  return false;
575                          char c = *filename;                          continue;
576                          pattern++;                  }
577                          switch (*pattern) {                  c = *filename;
578                          case '?':                  pattern++;
579                                  if (c == '/') {                  switch (*pattern) {
580                                          return 0;                          int i;
581                                  } else if (c == '\\') {                          int j;
582                                          if ((c = filename[1]) == '\\') {                  case '?':
583                                                  filename++; /* safe because filename is \\ */                          if (c == '/') {
584                                          } else if (c >= '0' && c <= '3' && (c = filename[2]) >= '0' && c <= '7' && (c = filename[3]) >= '0' && c <= '7') {                                  return false;
585                                                  filename += 3; /* safe because filename is \ooo */                          } else if (c == '\\') {
586                                          } else {                                  if (filename[1] == '\\')
587                                                  return 0;                                          filename++;
588                                          }                                  else if (ccs_is_byte_range(filename + 1))
589                                  }                                          filename += 3;
590                                  break;                                  else
591                          case '\\':                                          return false;
592                                  if (c != '\\') return 0;                          }
593                                  if (*++filename != '\\') return 0; /* safe because *filename != '\0' */                          break;
594                                  break;                  case '\\':
595                          case '+':                          if (c != '\\')
596                                  if (c < '0' || c > '9') return 0;                                  return false;
597                                  break;                          if (*++filename != '\\')
598                          case 'x':                                  return false;
599                                  if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))) return 0;                          break;
600                                  break;                  case '+':
601                          case 'a':                          if (!ccs_is_decimal(c))
602                                  if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) return 0;                                  return false;
603                            break;
604                    case 'x':
605                            if (!ccs_is_hexadecimal(c))
606                                    return false;
607                            break;
608                    case 'a':
609                            if (!ccs_is_alphabet_char(c))
610                                    return false;
611                            break;
612                    case '0':
613                    case '1':
614                    case '2':
615                    case '3':
616                            if (c == '\\' && ccs_is_byte_range(filename + 1)
617                                && strncmp(filename + 1, pattern, 3) == 0) {
618                                    filename += 3;
619                                    pattern += 2;
620                                  break;                                  break;
621                          case '0':                          }
622                          case '1':                          return false; /* Not matched. */
623                          case '2':                  case '*':
624                          case '3':                  case '@':
625                                  if (c == '\\' && (c = filename[1]) >= '0' && c <= '3' && c == *pattern                          for (i = 0; i <= filename_end - filename; i++) {
626                                          && (c = filename[2]) >= '0' && c <= '7' && c == pattern[1]                                  if (ccs_file_matches_pattern2(filename + i,
627                                          && (c = filename[3]) >= '0' && c <= '7' && c == pattern[2]) {                                                                filename_end,
628                                          filename += 3; /* safe because filename is \ooo */                                                                pattern + 1,
629                                          pattern += 2; /* safe because pattern is \ooo  */                                                                pattern_end))
630                                            return true;
631                                    c = filename[i];
632                                    if (c == '.' && *pattern == '@')
633                                          break;                                          break;
634                                  }                                  if (c != '\\')
635                                  return 0; /* Not matched. */                                          continue;
636                          case '*':                                  if (filename[i + 1] == '\\')
637                          case '@':                                          i++;
638                                  {                                  else if (ccs_is_byte_range(filename + i + 1))
639                                          int i;                                          i += 3;
640                                          for (i = 0; i <= filename_end - filename; i++) {                                  else
641                                                  if (FileMatchesToPattern2(filename + i, filename_end, pattern + 1, pattern_end)) return 1;                                          break; /* Bad pattern. */
642                                                  if ((c = filename[i]) == '.' && *pattern == '@') break;                          }
643                                                  if (c == '\\') {                          return false; /* Not matched. */
644                                                          if ((c = filename[i + 1]) == '\\') {                  default:
645                                                                  i++; /* safe because filename is \\ */                          j = 0;
646                                                          } else if (c >= '0' && c <= '3' && (c = filename[i + 2]) >= '0' && c <= '7' && (c = filename[i + 3]) >= '0' && c <= '7') {                          c = *pattern;
647                                                                  i += 3; /* safe because filename is \ooo */                          if (c == '$') {
648                                                          } else {                                  while (ccs_is_decimal(filename[j]))
649                                                                  break; /* Bad pattern. */                                          j++;
650                                                          }                          } else if (c == 'X') {
651                                                  }                                  while (ccs_is_hexadecimal(filename[j]))
652                                          }                                          j++;
653                                          return 0; /* Not matched. */                          } else if (c == 'A') {
654                                  }                                  while (ccs_is_alphabet_char(filename[j]))
655                          default:                                          j++;
656                                  {                          }
657                                          int i, j = 0;                          for (i = 1; i <= j; i++) {
658                                          if ((c = *pattern) == '$') {                                  if (ccs_file_matches_pattern2(filename + i,
659                                                  while ((c = filename[j]) >= '0' && c <= '9') j++;                                                                filename_end,
660                                          } else if (c == 'X') {                                                                pattern + 1,
661                                                  while (((c = filename[j]) >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) j++;                                                                pattern_end))
662                                          } else if (c == 'A') {                                          return true;
                                                 while (((c = filename[j]) >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) j++;  
                                         }  
                                         for (i = 1; i <= j; i++) {  
                                                 if (FileMatchesToPattern2(filename + i, filename_end, pattern + 1, pattern_end)) return 1;  
                                         }  
                                 }  
                                 return 0; /* Not matched or bad pattern. */  
663                          }                          }
664                          filename++; /* safe because *filename != '\0' */                          return false; /* Not matched or bad pattern. */
                         pattern++; /* safe because *pattern != '\0' */  
665                  }                  }
666                    filename++;
667                    pattern++;
668          }          }
669          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;          while (*pattern == '\\' &&
670          return (filename == filename_end && pattern == pattern_end);                 (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
671                    pattern += 2;
672            return filename == filename_end && pattern == pattern_end;
673  }  }
674    
675  static int FileMatchesToPattern(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
676     * ccs_file_matches_pattern - Pattern matching without without '/' character.
677     *
678     * @filename:     The start of string to check.
679     * @filename_end: The end of string to check.
680     * @pattern:      The start of pattern to compare.
681     * @pattern_end:  The end of pattern to compare.
682     *
683     * Returns true if @filename matches @pattern, false otherwise.
684     */
685    static bool ccs_file_matches_pattern(const char *filename,
686                                         const char *filename_end,
687                                         const char *pattern,
688                                         const char *pattern_end)
689  {  {
690          const char *pattern_start = pattern;          const char *pattern_start = pattern;
691          int first = 1;          bool first = true;
692          int result;          bool result;
693          while (pattern < pattern_end - 1) {          while (pattern < pattern_end - 1) {
694                  if (*pattern++ != '\\' || *pattern++ != '-') continue;                  /* Split at "\-" pattern. */
695                  result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern - 2);                  if (*pattern++ != '\\' || *pattern++ != '-')
696                  if (first) result = !result;                          continue;
697                  if (result) return 0;                  result = ccs_file_matches_pattern2(filename, filename_end,
698                  first = 0;                                                     pattern_start, pattern - 2);
699                    if (first)
700                            result = !result;
701                    if (result)
702                            return false;
703                    first = false;
704                  pattern_start = pattern;                  pattern_start = pattern;
705          }          }
706          result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern_end);          result = ccs_file_matches_pattern2(filename, filename_end,
707                                               pattern_start, pattern_end);
708          return first ? result : !result;          return first ? result : !result;
709  }  }
710    
711  /*  /**
712   *  Check whether the given pathname matches to the given pattern.   * ccs_path_matches_pattern - Check whether the given filename matches the given pattern.
713   *  Returns nonzero if matches, zero otherwise.   * @filename: The filename to check.
714     * @pattern:  The pattern to compare.
715   *   *
716   *  The following patterns are available.   * Returns true if matches, false otherwise.
717   *    \\     \ itself.   *
718   *    \ooo   Octal representation of a byte.   * The following patterns are available.
719   *    \*     More than or equals to 0 character other than '/'.   *   \\     \ itself.
720   *    \@     More than or equals to 0 character other than '/' or '.'.   *   \ooo   Octal representation of a byte.
721   *    \?     1 byte character other than '/'.   *   \*     More than or equals to 0 character other than '/'.
722   *    \$     More than or equals to 1 decimal digit.   *   \@     More than or equals to 0 character other than '/' or '.'.
723   *    \+     1 decimal digit.   *   \?     1 byte character other than '/'.
724   *    \X     More than or equals to 1 hexadecimal digit.   *   \$     More than or equals to 1 decimal digit.
725   *    \x     1 hexadecimal digit.   *   \+     1 decimal digit.
726   *    \A     More than or equals to 1 alphabet character.   *   \X     More than or equals to 1 hexadecimal digit.
727   *    \a     1 alphabet character.   *   \x     1 hexadecimal digit.
728   *    \-     Subtraction operator.   *   \A     More than or equals to 1 alphabet character.
729   */   *   \a     1 alphabet character.
730     *   \-     Subtraction operator.
731  int PathMatchesToPattern(const struct path_info *pathname0, const struct path_info *pattern0)   */
732  {  bool ccs_path_matches_pattern(const struct ccs_path_info *filename,
733          /* if (!pathname || !pattern) return 0; */                                const struct ccs_path_info *pattern)
734          const char *pathname = pathname0->name, *pattern = pattern0->name;  {
735          const int len = pattern0->const_len;          /*
736          if (!pattern0->is_patterned) return !pathcmp(pathname0, pattern0);            if (!filename || !pattern)
737          if (pathname0->depth != pattern0->depth) return 0;            return false;
738          if (strncmp(pathname, pattern, len)) return 0;          */
739          pathname += len; pattern += len;          const char *f = filename->name;
740          while (*pathname && *pattern) {          const char *p = pattern->name;
741                  const char *pathname_delimiter = strchr(pathname, '/'), *pattern_delimiter = strchr(pattern, '/');          const int len = pattern->const_len;
742                  if (!pathname_delimiter) pathname_delimiter = strchr(pathname, '\0');          /* If @pattern doesn't contain pattern, I can use strcmp(). */
743                  if (!pattern_delimiter) pattern_delimiter = strchr(pattern, '\0');          if (!pattern->is_patterned)
744                  if (!FileMatchesToPattern(pathname, pathname_delimiter, pattern, pattern_delimiter)) return 0;                  return !ccs_pathcmp(filename, pattern);
745                  pathname = *pathname_delimiter ? pathname_delimiter + 1 : pathname_delimiter;          /* Don't compare if the number of '/' differs. */
746                  pattern = *pattern_delimiter ? pattern_delimiter + 1 : pattern_delimiter;          if (filename->depth != pattern->depth)
747          }                  return false;
748          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;          /* Compare the initial length without patterns. */
749          return (!*pathname && !*pattern);          if (strncmp(f, p, len))
750  }                  return false;
751            f += len;
752  /*          p += len;
753   *  Transactional printf() to struct io_buffer structure.          /* Main loop. Compare each directory component. */
754   *  snprintf() will truncate, but io_printf() won't.          while (*f && *p) {
755   *  Returns zero on success, nonzero otherwise.                  const char *f_delimiter = strchr(f, '/');
756   */                  const char *p_delimiter = strchr(p, '/');
757  int io_printf(struct io_buffer *head, const char *fmt, ...)                  if (!f_delimiter)
758  {                          f_delimiter = f + strlen(f);
759          va_list args;                  if (!p_delimiter)
760          int len, pos = head->read_avail, size = head->readbuf_size - pos;                          p_delimiter = p + strlen(p);
761          if (size <= 0) return -ENOMEM;                  if (!ccs_file_matches_pattern(f, f_delimiter, p, p_delimiter))
762          va_start(args, fmt);                          return false;
763          len = vsnprintf(head->read_buf + pos, size, fmt, args);                  f = f_delimiter;
764          va_end(args);                  if (*f)
765          if (pos + len >= head->readbuf_size) return -ENOMEM;                          f++;
766          head->read_avail += len;                  p = p_delimiter;
767          return 0;                  if (*p)
768                            p++;
769            }
770            /* Ignore trailing "\*" and "\@" in @pattern. */
771            while (*p == '\\' &&
772                   (*(p + 1) == '*' || *(p + 1) == '@'))
773                    p += 2;
774            return !*f && !*p;
775  }  }
776    
777  /*  /**
778   * Get realpath() of current process.   * ccs_get_exe - Get ccs_realpath() of current process.
779   * This function uses ccs_alloc(), so caller must ccs_free() if this function didn't return NULL.   *
780     * Returns the ccs_realpath() of current process on success, NULL otherwise.
781     *
782     * This function uses kzalloc(), so the caller must kfree()
783     * if this function didn't return NULL.
784   */   */
785  const char *GetEXE(void)  const char *ccs_get_exe(void)
786  {  {
787          struct mm_struct *mm = current->mm;          struct mm_struct *mm = current->mm;
788          struct vm_area_struct *vma;          struct vm_area_struct *vma;
789          const char *cp = NULL;          const char *cp = NULL;
790          if (!mm) return NULL;          if (!mm)
791                    return NULL;
792          down_read(&mm->mmap_sem);          down_read(&mm->mmap_sem);
793          for (vma = mm->mmap; vma; vma = vma->vm_next) {          for (vma = mm->mmap; vma; vma = vma->vm_next) {
794                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
795                          cp = realpath_from_dentry(vma->vm_file->f_dentry, vma->vm_file->f_vfsmnt);  #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
796                            struct path path = { vma->vm_file->f_vfsmnt,
797                                                 vma->vm_file->f_dentry };
798                            cp = ccs_realpath_from_path(&path);
799    #else
800                            cp = ccs_realpath_from_path(&vma->vm_file->f_path);
801    #endif
802                          break;                          break;
803                  }                  }
804          }          }
# Line 488  const char *GetEXE(void) Line 806  const char *GetEXE(void)
806          return cp;          return cp;
807  }  }
808    
809  const char *GetMSG(const bool is_enforce)  /**
810  {   * ccs_get_msg - Get warning message.
811          if (is_enforce) return "ERROR"; else return "WARNING";   *
812  }   * @is_enforce: Is it enforcing mode?
813     *
814  const char *GetAltExec(void)   * Returns "ERROR" or "WARNING".
815  {   */
816          const u8 profile = current->domain_info->profile;  const char *ccs_get_msg(const bool is_enforce)
         const struct path_info *alt_exec = profile_ptr[profile] ? profile_ptr[profile]->alt_exec : NULL;  
         return alt_exec ? alt_exec->name : NULL;  
 }  
   
 /*************************  DOMAIN POLICY HANDLER  *************************/  
   
 /* Check whether the given access control is enabled. */  
 unsigned int CheckCCSFlags(const unsigned int index)  
 {  
         const u8 profile = current->domain_info->profile;  
         return sbin_init_started && index < CCS_MAX_CONTROL_INDEX  
 #if MAX_PROFILES != 256  
                 && profile < MAX_PROFILES  
 #endif  
                 && profile_ptr[profile] ? profile_ptr[profile]->value[index] : 0;  
 }  
 EXPORT_SYMBOL(CheckCCSFlags);  
   
 bool TomoyoVerboseMode(void)  
 {  
         return CheckCCSFlags(CCS_TOMOYO_VERBOSE) != 0;  
 }  
   
 /* Check whether the given access control is enforce mode. */  
 bool CheckCCSEnforce(const unsigned int index)  
 {  
         return CheckCCSFlags(index) == 3;  
 }  
 EXPORT_SYMBOL(CheckCCSEnforce);  
   
 bool CheckDomainQuota(struct domain_info * const domain)  
 {  
         unsigned int count = 0;  
         struct acl_info *ptr;  
         if (!domain) return 1;  
         list1_for_each_entry(ptr, &domain->acl_info_list, list) {  
                 if (!ptr->is_deleted) count++;  
         }  
         if (count < CheckCCSFlags(CCS_TOMOYO_MAX_ACCEPT_ENTRY)) return 1;  
         if (!domain->quota_warned) {  
                 domain->quota_warned = 1;  
                 printk("TOMOYO-WARNING: Domain '%s' has so many ACLs to hold. Stopped learning mode.\n", domain->domainname->name);  
         }  
         return 0;  
 }  
   
 /* Check whether the given access control is learning mode. */  
 bool CheckCCSAccept(const unsigned int index, struct domain_info * const domain)  
817  {  {
818          if (CheckCCSFlags(index) != 1) return 0;          if (is_enforce)
819          return CheckDomainQuota(domain);                  return "ERROR";
820            else
821                    return "WARNING";
822  }  }
 EXPORT_SYMBOL(CheckCCSAccept);  
823    
824  static struct profile *FindOrAssignNewProfile(const unsigned int profile)  /**
825  {   * ccs_can_sleep - Check whether it is permitted to do operations that may sleep.
826          static DEFINE_MUTEX(profile_lock);   *
827          struct profile *ptr = NULL;   * Returns true if it is permitted to do operations that may sleep,
828          mutex_lock(&profile_lock);   * false otherwise.
829          if (profile < MAX_PROFILES && (ptr = profile_ptr[profile]) == NULL) {   *
830                  if ((ptr = alloc_element(sizeof(*ptr))) != NULL) {   * TOMOYO Linux supports interactive enforcement that lets processes
831                          int i;   * wait for the administrator's decision.
832                          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) ptr->value[i] = ccs_control_array[i].current_value;   * All hooks but the one for ccs_may_autobind() are inserted where
833                          mb(); /* Avoid out-of-order execution. */   * it is permitted to do operations that may sleep.
834                          profile_ptr[profile] = ptr;   * Thus, this warning should not happen.
835                  }   */
836          }  bool ccs_can_sleep(void)
         mutex_unlock(&profile_lock);  
         return ptr;  
 }  
   
 /* #define ALT_EXEC */  
   
 static int SetProfile(struct io_buffer *head)  
837  {  {
838          char *data = head->write_buf;          static u8 count = 20;
839          unsigned int i, value;          if (likely(!in_interrupt()))
840          char *cp;                  return true;
841          struct profile *profile;          if (count) {
842          if (!isRoot()) return -EPERM;                  count--;
843          i = simple_strtoul(data, &cp, 10);                  printk(KERN_ERR "BUG: sleeping function called "
844          if (data != cp) {                         "from invalid context.\n");
845                  if (*cp != '-') return -EINVAL;                  dump_stack();
                 data= cp + 1;  
         }  
         profile = FindOrAssignNewProfile(i);  
         if (!profile) return -EINVAL;  
         cp = strchr(data, '=');  
         if (!cp) return -EINVAL;  
         *cp = '\0';  
         UpdateCounter(CCS_UPDATES_COUNTER_PROFILE);  
         if (strcmp(data, ccs_control_array[CCS_PROFILE_COMMENT].keyword) == 0) {  
                 profile->comment = SaveName(cp + 1);  
                 return 0;  
         }  
 #ifdef ALT_EXEC  
 #ifdef CONFIG_TOMOYO  
         if (strcmp(data, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword) == 0) {  
                 cp++;  
                 if (*cp && !IsCorrectPath(cp, 1, -1, -1, __FUNCTION__)) cp = "";  
                 profile->alt_exec = SaveName(cp);  
                 return 0;  
         }  
 #endif  
 #endif  
         if (sscanf(cp + 1, "%u", &value) != 1) return -EINVAL;  
 #ifdef CONFIG_TOMOYO  
         if (strncmp(data, KEYWORD_MAC_FOR_CAPABILITY, KEYWORD_MAC_FOR_CAPABILITY_LEN) == 0) {  
                 return SetCapabilityStatus(data + KEYWORD_MAC_FOR_CAPABILITY_LEN, value, i);  
         }  
 #endif  
         for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) {  
                 if (strcmp(data, ccs_control_array[i].keyword)) continue;  
                 if (value > ccs_control_array[i].max_value) value = ccs_control_array[i].max_value;  
                 profile->value[i] = value;  
                 return 0;  
846          }          }
847          return -EINVAL;          return false;
848  }  }
849    
850  static int ReadProfile(struct io_buffer *head)  /**
851     * ccs_flags - Check mode for specified functionality.
852     *
853     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
854     * @index:  The functionality to check mode.
855     *
856     * Returns the mode of specified functionality.
857     */
858    unsigned int ccs_flags(const struct ccs_domain_info *domain,
859                                 const u8 index)
860  {  {
861          if (!head->read_eof) {          u8 profile;
862                  if (!isRoot()) return -EPERM;          if (!domain)
863                  if (!head->read_var2) {                  domain = ccs_current_domain();
864                          int step;          profile = domain->profile;
865                          for (step = head->read_step; step < MAX_PROFILES * CCS_MAX_CONTROL_INDEX; step++) {          return ccs_policy_loaded && index < CCS_MAX_CONTROL_INDEX
866                                  const int i = step / CCS_MAX_CONTROL_INDEX, j = step % CCS_MAX_CONTROL_INDEX;  #if CCS_MAX_PROFILES != 256
867                                  const struct profile *profile = profile_ptr[i];                  && profile < CCS_MAX_PROFILES
                                 head->read_step = step;  
                                 if (!profile) continue;  
                                 switch (j) {  
                                 case -1: /* Dummy */  
 #ifndef CONFIG_SAKURA  
                                 case CCS_SAKURA_DENY_CONCEAL_MOUNT:  
                                 case CCS_SAKURA_RESTRICT_CHROOT:  
                                 case CCS_SAKURA_RESTRICT_MOUNT:  
                                 case CCS_SAKURA_RESTRICT_UNMOUNT:  
                                 case CCS_SAKURA_RESTRICT_PIVOT_ROOT:  
                                 case CCS_SAKURA_RESTRICT_AUTOBIND:  
 #endif  
 #ifndef CONFIG_TOMOYO  
                                 case CCS_TOMOYO_MAC_FOR_FILE:  
                                 case CCS_TOMOYO_MAC_FOR_ARGV0:  
                                 case CCS_TOMOYO_MAC_FOR_ENV:  
                                 case CCS_TOMOYO_MAC_FOR_NETWORK:  
                                 case CCS_TOMOYO_MAC_FOR_SIGNAL:  
                                 case CCS_TOMOYO_MAX_ACCEPT_ENTRY:  
                                 case CCS_TOMOYO_MAX_GRANT_LOG:  
                                 case CCS_TOMOYO_MAX_REJECT_LOG:  
                                 case CCS_TOMOYO_VERBOSE:  
868  #endif  #endif
869  #ifndef ALT_EXEC                  && ccs_profile_ptr[profile] ?
870                                  case CCS_TOMOYO_ALT_EXEC:                  ccs_profile_ptr[profile]->value[index] : 0;
                                 case CCS_SLEEP_PERIOD:  
 #endif  
                                         continue;  
                                 }  
                                 if (j == CCS_PROFILE_COMMENT) {  
                                         if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_PROFILE_COMMENT].keyword, profile->comment ? profile->comment->name : "")) break;  
                                 } else if (j == CCS_TOMOYO_ALT_EXEC) {  
                                         const struct path_info *alt_exec = profile->alt_exec;  
                                         if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword, alt_exec ? alt_exec->name : "")) break;  
                                 } else {  
                                         if (io_printf(head, "%u-%s=%u\n", i, ccs_control_array[j].keyword, profile->value[j])) break;  
                                 }  
                         }  
                         if (step == MAX_PROFILES * CCS_MAX_CONTROL_INDEX) {  
                                 head->read_var2 = (void *) "";  
                                 head->read_step = 0;  
                         }  
                 }  
                 if (head->read_var2) {  
 #ifdef CONFIG_TOMOYO  
                         if (ReadCapabilityStatus(head) == 0)  
 #endif  
                                 head->read_eof = 1;  
                 }  
         }  
         return 0;  
 }  
   
 /*************************  POLICY MANAGER HANDLER  *************************/  
   
 struct policy_manager_entry {  
         struct list1_head list;  
         const struct path_info *manager;  
         bool is_domain;  
         bool is_deleted;  
 };  
   
 static LIST1_HEAD(policy_manager_list);  
   
 static int AddManagerEntry(const char *manager, const bool is_delete)  
 {  
         struct policy_manager_entry *new_entry, *ptr;  
         static DEFINE_MUTEX(lock);  
         const struct path_info *saved_manager;  
         int error = -ENOMEM;  
         bool is_domain = 0;  
         if (!isRoot()) return -EPERM;  
         if (IsDomainDef(manager)) {  
                 if (!IsCorrectDomain(manager, __FUNCTION__)) return -EINVAL;  
                 is_domain = 1;  
         } else {  
                 if (!IsCorrectPath(manager, 1, -1, -1, __FUNCTION__)) return -EINVAL;  
         }  
         if ((saved_manager = SaveName(manager)) == NULL) return -ENOMEM;  
         mutex_lock(&lock);  
         list1_for_each_entry(ptr, &policy_manager_list, list) {  
                 if (ptr->manager == saved_manager) {  
                         ptr->is_deleted = is_delete;  
                         error = 0;  
                         goto out;  
                 }  
         }  
         if (is_delete) {  
                 error = -ENOENT;  
                 goto out;  
         }  
         if ((new_entry = alloc_element(sizeof(*new_entry))) == NULL) goto out;  
         new_entry->manager = saved_manager;  
         new_entry->is_domain = is_domain;  
         list1_add_tail_mb(&new_entry->list, &policy_manager_list);  
         error = 0;  
  out:  
         mutex_unlock(&lock);  
         if (!error) UpdateCounter(CCS_UPDATES_COUNTER_MANAGER);  
         return error;  
871  }  }
872    
873  static int AddManagerPolicy(struct io_buffer *head)  /**
874     * ccs_init_request_info - Initialize "struct ccs_request_info" members.
875     *
876     * @r:      Pointer to "struct ccs_request_info" to initialize.
877     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
878     * @index:  Index number of functionality.
879     *
880     * Returns mode.
881     */
882    int ccs_init_request_info(struct ccs_request_info *r,
883                              struct ccs_domain_info *domain, const u8 index)
884  {  {
885          const char *data = head->write_buf;          memset(r, 0, sizeof(*r));
886          bool is_delete = 0;          if (!domain)
887          if (!isRoot()) return -EPERM;                  domain = ccs_current_domain();
888          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          r->domain = domain;
889                  data += KEYWORD_DELETE_LEN;          r->profile = domain->profile;
890                  is_delete = 1;          r->type = index;
891          }          if (!ccs_policy_loaded || !ccs_profile_ptr[r->profile])
892          return AddManagerEntry(data, is_delete);                  r->mode = 0;
893            else
894                    r->mode = ccs_profile_ptr[r->profile]->mac_mode[index];
895            return r->mode;
896  }  }
897    
898  static int ReadManagerPolicy(struct io_buffer *head)  /**
899     * ccs_verbose_mode - Check whether TOMOYO is verbose mode.
900     *
901     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
902     *
903     * Returns true if domain policy violation warning should be printed to
904     * console.
905     */
906    bool ccs_verbose_mode(const struct ccs_domain_info *domain)
907  {  {
908          struct list1_head *pos;          return ccs_flags(domain, CCS_VERBOSE) != 0;
         if (head->read_eof) return 0;  
         if (!isRoot()) return -EPERM;  
         list1_for_each_cookie(pos, head->read_var2, &policy_manager_list) {  
                 struct policy_manager_entry *ptr;  
                 ptr = list1_entry(pos, struct policy_manager_entry, list);  
                 if (ptr->is_deleted) continue;  
                 if (io_printf(head, "%s\n", ptr->manager->name)) return 0;  
         }  
         head->read_eof = 1;  
         return 0;  
909  }  }
910    
911  /* Check whether the current process is a policy manager. */  /**
912  static int IsPolicyManager(void)   * ccs_domain_quota_ok - Check for domain's quota.
913     *
914     * @r: Pointer to "struct ccs_request_info".
915     *
916     * Returns true if the domain is not exceeded quota, false otherwise.
917     *
918     * Caller holds ccs_read_lock().
919     */
920    bool ccs_domain_quota_ok(struct ccs_request_info *r)
921  {  {
922          struct policy_manager_entry *ptr;          unsigned int count = 0;
923          const char *exe;          struct ccs_domain_info *domain = r->domain;
924          const struct path_info *domainname = current->domain_info->domainname;          struct ccs_acl_info *ptr;
925          bool found = 0;          ccs_assert_read_lock();
926          if (!sbin_init_started) return 1;          if (r->mode != 1)
927          list1_for_each_entry(ptr, &policy_manager_list, list) {                  return false;
928                  if (!ptr->is_deleted && ptr->is_domain && !pathcmp(domainname, ptr->manager)) return 1;          if (!domain)
929          }                  return true;
930          if ((exe = GetEXE()) == NULL) return 0;          list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
931          list1_for_each_entry(ptr, &policy_manager_list, list) {                  if (ptr->is_deleted)
932                  if (!ptr->is_deleted && !ptr->is_domain && !strcmp(exe, ptr->manager->name)) {                          continue;
933                          found = 1;                  switch (ptr->type) {
934                            u16 perm;
935                            u8 i;
936                    case CCS_TYPE_PATH_ACL:
937                            perm = container_of(ptr, struct ccs_path_acl, head)->
938                                    perm;
939                            for (i = 0; i < CCS_MAX_PATH_OPERATION; i++)
940                                    if (perm & (1 << i))
941                                            count++;
942                            if (perm & (1 << CCS_TYPE_READ_WRITE))
943                                    count -= 2;
944                          break;                          break;
945                  }                  case CCS_TYPE_PATH2_ACL:
946          }                          perm = container_of(ptr, struct ccs_path2_acl,
947          if (!found) { /* Reduce error messages. */                                              head)->perm;
948                  static pid_t last_pid = 0;                          for (i = 0; i < CCS_MAX_PATH2_OPERATION; i++)
949                  const pid_t pid = current->pid;                                  if (perm & (1 << i))
950                  if (last_pid != pid) {                                          count++;
                         printk("%s ( %s ) is not permitted to update policies.\n", domainname->name, exe);  
                         last_pid = pid;  
                 }  
         }  
         ccs_free(exe);  
         return found;  
 }  
   
 #ifdef CONFIG_TOMOYO  
   
 /*************************  DOMAIN POLICY HANDLER  *************************/  
   
 static char *FindConditionPart(char *data)  
 {  
         char *cp = strstr(data, " if "), *cp2;  
         if (cp) {  
                 while ((cp2 = strstr(cp + 3, " if ")) != NULL) cp = cp2;  
                 *cp++ = '\0';  
         }  
         return cp;  
 }  
   
 static int AddDomainPolicy(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         struct domain_info *domain = head->write_var1;  
         bool is_delete = 0, is_select = 0, is_undelete = 0;  
         unsigned int profile;  
         const struct condition_list *cond = NULL;  
         char *cp;        
         if (!isRoot()) return -EPERM;  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         } else if (strncmp(data, KEYWORD_SELECT, KEYWORD_SELECT_LEN) == 0) {  
                 data += KEYWORD_SELECT_LEN;  
                 is_select = 1;  
         } else if (strncmp(data, KEYWORD_UNDELETE, KEYWORD_UNDELETE_LEN) == 0) {  
                 data += KEYWORD_UNDELETE_LEN;  
                 is_undelete = 1;  
         }  
         UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);  
         if (IsDomainDef(data)) {  
                 if (is_delete) {  
                         DeleteDomain(data);  
                         domain = NULL;  
                 } else if (is_select) {  
                         domain = FindDomain(data);  
                 } else if (is_undelete) {  
                         domain = UndeleteDomain(data);  
                 } else {  
                         domain = FindOrAssignNewDomain(data, 0);  
                 }  
                 head->write_var1 = domain;  
                 return 0;  
         }  
         if (!domain) return -EINVAL;  
   
         if (sscanf(data, KEYWORD_USE_PROFILE "%u", &profile) == 1 && profile < MAX_PROFILES) {  
                 if (profile_ptr[profile] || !sbin_init_started) domain->profile = (u8) profile;  
                 return 0;  
         }  
         cp = FindConditionPart(data);  
         if (cp && (cond = FindOrAssignNewCondition(cp)) == NULL) return -EINVAL;  
         if (strncmp(data, KEYWORD_ALLOW_CAPABILITY, KEYWORD_ALLOW_CAPABILITY_LEN) == 0) {  
                 return AddCapabilityPolicy(data + KEYWORD_ALLOW_CAPABILITY_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_NETWORK, KEYWORD_ALLOW_NETWORK_LEN) == 0) {  
                 return AddNetworkPolicy(data + KEYWORD_ALLOW_NETWORK_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_SIGNAL, KEYWORD_ALLOW_SIGNAL_LEN) == 0) {  
                 return AddSignalPolicy(data + KEYWORD_ALLOW_SIGNAL_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_ARGV0, KEYWORD_ALLOW_ARGV0_LEN) == 0) {  
                 return AddArgv0Policy(data + KEYWORD_ALLOW_ARGV0_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {  
                 return AddEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, domain, cond, is_delete);  
         } else {  
                 return AddFilePolicy(data, domain, cond, is_delete);  
         }  
         return -EINVAL;  
 }  
   
 static int ReadDomainPolicy(struct io_buffer *head)  
 {  
         struct list1_head *dpos;  
         struct list1_head *apos;  
         if (head->read_eof) return 0;  
         if (head->read_step == 0) {  
                 if (!isRoot()) return -EPERM;  
                 head->read_step = 1;  
         }  
         list1_for_each_cookie(dpos, head->read_var1, &domain_list) {  
                 struct domain_info *domain;  
                 domain = list1_entry(dpos, struct domain_info, list);  
                 if (head->read_step != 1) goto acl_loop;  
                 if (domain->is_deleted) continue;  
                 if (io_printf(head, "%s\n" KEYWORD_USE_PROFILE "%u\n%s\n", domain->domainname->name, domain->profile, domain->quota_warned ? "quota_exceeded\n" : "")) return 0;  
                 head->read_step = 2;  
         acl_loop: ;  
                 if (head->read_step == 3) goto tail_mark;  
                 list1_for_each_cookie(apos, head->read_var2, &domain->acl_info_list) {  
                         struct acl_info *ptr;  
                         int pos;  
                         u8 acl_type;  
                         ptr = list1_entry(apos, struct acl_info, list);  
                         if (ptr->is_deleted) continue;  
                         pos = head->read_avail;  
                         acl_type = ptr->type;  
                         if (acl_type == TYPE_FILE_ACL) {  
                                 struct file_acl_record *ptr2 = container_of(ptr, struct file_acl_record, head);  
                                 const unsigned char b = ptr2->u_is_group;  
                                 if (io_printf(head, "%d %s%s", ptr2->perm,  
                                               b ? "@" : "",  
                                               b ? ptr2->u.group->group_name->name : ptr2->u.filename->name)) goto print_acl_rollback;  
                         } else if (acl_type == TYPE_ARGV0_ACL) {  
                                 struct argv0_acl_record *ptr2 = container_of(ptr, struct argv0_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_ARGV0 "%s %s",  
                                               ptr2->filename->name, ptr2->argv0->name)) goto print_acl_rollback;  
                         } else if (acl_type == TYPE_ENV_ACL) {  
                                 struct env_acl_record *ptr2 = container_of(ptr, struct env_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_ENV "%s", ptr2->env->name)) goto print_acl_rollback;  
                         } else if (acl_type == TYPE_CAPABILITY_ACL) {  
                                 struct capability_acl_record *ptr2 = container_of(ptr, struct capability_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s", capability2keyword(ptr2->capability))) goto print_acl_rollback;  
                         } else if (acl_type == TYPE_IP_NETWORK_ACL) {  
                                 struct ip_network_acl_record *ptr2 = container_of(ptr, struct ip_network_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_NETWORK "%s ", network2keyword(ptr2->operation_type))) goto print_acl_rollback;  
                                 switch (ptr2->record_type) {  
                                 case IP_RECORD_TYPE_ADDRESS_GROUP:  
                                         if (io_printf(head, "@%s", ptr2->u.group->group_name->name)) goto print_acl_rollback;  
                                         break;  
                                 case IP_RECORD_TYPE_IPv4:  
                                         {  
                                                 const u32 min_address = ptr2->u.ipv4.min, max_address = ptr2->u.ipv4.max;  
                                                 if (io_printf(head, "%u.%u.%u.%u", HIPQUAD(min_address))) goto print_acl_rollback;  
                                                 if (min_address != max_address && io_printf(head, "-%u.%u.%u.%u", HIPQUAD(max_address))) goto print_acl_rollback;  
                                         }  
                                         break;  
                                 case IP_RECORD_TYPE_IPv6:  
                                         {  
                                                 char buf[64];  
                                                 const struct in6_addr *min_address = ptr2->u.ipv6.min, *max_address = ptr2->u.ipv6.max;  
                                                 print_ipv6(buf, sizeof(buf), min_address);  
                                                 if (io_printf(head, "%s", buf)) goto print_acl_rollback;  
                                                 if (min_address != max_address) {  
                                                         print_ipv6(buf, sizeof(buf), max_address);  
                                                         if (io_printf(head, "-%s", buf)) goto print_acl_rollback;  
                                                 }  
                                         }  
                                         break;  
                                 }  
                                 {  
                                         const u16 min_port = ptr2->min_port, max_port = ptr2->max_port;  
                                         if (io_printf(head, " %u", min_port)) goto print_acl_rollback;  
                                         if (min_port != max_port && io_printf(head, "-%u", max_port)) goto print_acl_rollback;  
                                 }  
                         } else if (acl_type == TYPE_SIGNAL_ACL) {  
                                 struct signal_acl_record *ptr2 = container_of(ptr, struct signal_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_SIGNAL "%u %s", ptr2->sig, ptr2->domainname->name)) goto print_acl_rollback;  
                         } else {  
                                 const char *keyword = acltype2keyword(acl_type);  
                                 if (!keyword) continue;  
                                 if (acltype2paths(acl_type) == 2) {  
                                         struct double_acl_record *ptr2 = container_of(ptr, struct double_acl_record, head);  
                                         const bool b0 = ptr2->u1_is_group, b1 = ptr2->u2_is_group;  
                                         if (io_printf(head, "allow_%s %s%s %s%s", keyword,  
                                                       b0 ? "@" : "", b0 ? ptr2->u1.group1->group_name->name : ptr2->u1.filename1->name,  
                                                       b1 ? "@" : "", b1 ? ptr2->u2.group2->group_name->name : ptr2->u2.filename2->name)) goto print_acl_rollback;  
                                 } else {  
                                         struct single_acl_record *ptr2 = container_of(ptr, struct single_acl_record, head);  
                                         const bool b = ptr2->u_is_group;  
                                         if (io_printf(head, "allow_%s %s%s", keyword,  
                                                       b ? "@" : "", b ? ptr2->u.group->group_name->name : ptr2->u.filename->name)) goto print_acl_rollback;  
                                 }  
                         }  
                         if (DumpCondition(head, ptr->cond)) {  
                         print_acl_rollback: ;  
                         head->read_avail = pos;  
                         return 0;  
                         }  
                 }  
                 head->read_step = 3;  
         tail_mark: ;  
                 if (io_printf(head, "\n")) return 0;  
                 head->read_step = 1;  
         }  
         head->read_eof = 1;  
         return 0;  
 }  
   
 #endif  
   
 static int UpdateDomainProfile(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         char *cp = strchr(data, ' ');  
         struct domain_info *domain;  
         unsigned int profile;  
         if (!isRoot()) return -EPERM;  
         if (!cp) return -EINVAL;  
         *cp = '\0';  
         domain = FindDomain(cp + 1);  
         profile = simple_strtoul(data, NULL, 10);  
         if (domain && profile < MAX_PROFILES && (profile_ptr[profile] || !sbin_init_started)) domain->profile = (u8) profile;  
         UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);  
         return 0;  
 }  
   
 static int ReadDomainProfile(struct io_buffer *head)  
 {  
         struct list1_head *pos;  
         if (head->read_eof) return 0;  
         if (!isRoot()) return -EPERM;  
         list1_for_each_cookie(pos, head->read_var1, &domain_list) {  
                 struct domain_info *domain;  
                 domain = list1_entry(pos, struct domain_info, list);  
                 if (domain->is_deleted) continue;  
                 if (io_printf(head, "%u %s\n", domain->profile, domain->domainname->name)) return 0;  
         }  
         head->read_eof = 1;  
         return 0;  
 }  
   
 static int WritePID(struct io_buffer *head)  
 {  
         head->read_step = (int) simple_strtoul(head->write_buf, NULL, 10);  
         head->read_eof = 0;  
         return 0;  
 }  
   
 static int ReadPID(struct io_buffer *head)  
 {  
         if (head->read_avail == 0 && !head->read_eof) {  
                 const int pid = head->read_step;  
                 struct task_struct *p;  
                 struct domain_info *domain = NULL;  
                 /***** CRITICAL SECTION START *****/  
                 read_lock(&tasklist_lock);  
                 p = find_task_by_pid(pid);  
                 if (p) domain = p->domain_info;  
                 read_unlock(&tasklist_lock);  
                 /***** CRITICAL SECTION END *****/  
                 if (domain) io_printf(head, "%d %u %s", pid, domain->profile, domain->domainname->name);  
                 head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 /*************************  EXCEPTION POLICY HANDLER  *************************/  
   
 #ifdef CONFIG_TOMOYO  
   
 static int AddExceptionPolicy(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         bool is_delete = 0;  
         if (!isRoot()) return -EPERM;  
         UpdateCounter(CCS_UPDATES_COUNTER_EXCEPTION_POLICY);  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         }  
         if (strncmp(data, KEYWORD_KEEP_DOMAIN, KEYWORD_KEEP_DOMAIN_LEN) == 0) {  
                 return AddDomainKeeperPolicy(data + KEYWORD_KEEP_DOMAIN_LEN, 0, is_delete);  
         } else if (strncmp(data, KEYWORD_NO_KEEP_DOMAIN, KEYWORD_NO_KEEP_DOMAIN_LEN) == 0) {  
                 return AddDomainKeeperPolicy(data + KEYWORD_NO_KEEP_DOMAIN_LEN, 1, is_delete);  
         } else if (strncmp(data, KEYWORD_INITIALIZE_DOMAIN, KEYWORD_INITIALIZE_DOMAIN_LEN) == 0) {  
                 return AddDomainInitializerPolicy(data + KEYWORD_INITIALIZE_DOMAIN_LEN, 0, is_delete);  
         } else if (strncmp(data, KEYWORD_NO_INITIALIZE_DOMAIN, KEYWORD_NO_INITIALIZE_DOMAIN_LEN) == 0) {  
                 return AddDomainInitializerPolicy(data + KEYWORD_NO_INITIALIZE_DOMAIN_LEN, 1, is_delete);  
         } else if (strncmp(data, KEYWORD_ALIAS, KEYWORD_ALIAS_LEN) == 0) {  
                 return AddAliasPolicy(data + KEYWORD_ALIAS_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_AGGREGATOR, KEYWORD_AGGREGATOR_LEN) == 0) {  
                 return AddAggregatorPolicy(data + KEYWORD_AGGREGATOR_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_READ, KEYWORD_ALLOW_READ_LEN) == 0) {  
                 return AddGloballyReadablePolicy(data + KEYWORD_ALLOW_READ_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {  
                 return AddGloballyUsableEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_FILE_PATTERN, KEYWORD_FILE_PATTERN_LEN) == 0) {  
                 return AddPatternPolicy(data + KEYWORD_FILE_PATTERN_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_PATH_GROUP, KEYWORD_PATH_GROUP_LEN) == 0) {  
                 return AddPathGroupPolicy(data + KEYWORD_PATH_GROUP_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_DENY_REWRITE, KEYWORD_DENY_REWRITE_LEN) == 0) {  
                 return AddNoRewritePolicy(data + KEYWORD_DENY_REWRITE_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_ADDRESS_GROUP, KEYWORD_ADDRESS_GROUP_LEN) == 0) {  
                 return AddAddressGroupPolicy(data + KEYWORD_ADDRESS_GROUP_LEN, is_delete);  
         }  
         return -EINVAL;  
 }  
   
 static int ReadExceptionPolicy(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 switch (head->read_step) {  
                 case 0:  
                         if (!isRoot()) return -EPERM;  
                         head->read_var2 = NULL; head->read_step = 1;  
                 case 1:  
                         if (ReadDomainKeeperPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 2;  
                 case 2:  
                         if (ReadGloballyReadablePolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 3;  
                 case 3:  
                         if (ReadGloballyUsableEnvPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 4;  
                 case 4:  
                         if (ReadDomainInitializerPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 5;  
                 case 5:  
                         if (ReadAliasPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 6;  
                 case 6:  
                         if (ReadAggregatorPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 7;  
                 case 7:  
                         if (ReadPatternPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 8;  
                 case 8:  
                         if (ReadNoRewritePolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 9;  
                 case 9:  
                         if (ReadPathGroupPolicy(head)) break;  
                         head->read_var1 = head->read_var2 = NULL; head->read_step = 10;  
                 case 10:  
                         if (ReadAddressGroupPolicy(head)) break;  
                         head->read_eof = 1;  
951                          break;                          break;
952                  default:                  case CCS_TYPE_EXECUTE_HANDLER:
953                          return -EINVAL;                  case CCS_TYPE_DENIED_EXECUTE_HANDLER:
                 }  
         }  
         return 0;  
 }  
   
 #endif  
   
 /*************************  SYSTEM POLICY HANDLER  *************************/  
   
 #ifdef CONFIG_SAKURA  
   
 static int AddSystemPolicy(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         bool is_delete = 0;  
         if (!isRoot()) return -EPERM;  
         UpdateCounter(CCS_UPDATES_COUNTER_SYSTEM_POLICY);  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         }  
         if (strncmp(data, KEYWORD_ALLOW_MOUNT, KEYWORD_ALLOW_MOUNT_LEN) == 0)  
                 return AddMountPolicy(data + KEYWORD_ALLOW_MOUNT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_DENY_UNMOUNT, KEYWORD_DENY_UNMOUNT_LEN) == 0)  
                 return AddNoUmountPolicy(data + KEYWORD_DENY_UNMOUNT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_ALLOW_CHROOT, KEYWORD_ALLOW_CHROOT_LEN) == 0)  
                 return AddChrootPolicy(data + KEYWORD_ALLOW_CHROOT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_ALLOW_PIVOT_ROOT, KEYWORD_ALLOW_PIVOT_ROOT_LEN) == 0)  
                 return AddPivotRootPolicy(data + KEYWORD_ALLOW_PIVOT_ROOT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_DENY_AUTOBIND, KEYWORD_DENY_AUTOBIND_LEN) == 0)  
                 return AddReservedPortPolicy(data + KEYWORD_DENY_AUTOBIND_LEN, is_delete);  
         return -EINVAL;  
 }  
   
 static int ReadSystemPolicy(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 switch (head->read_step) {  
                 case 0:  
                         if (!isRoot()) return -EPERM;  
                         head->read_var2 = NULL; head->read_step = 1;  
                 case 1:  
                         if (ReadMountPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 2;  
                 case 2:  
                         if (ReadNoUmountPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 3;  
                 case 3:  
                         if (ReadChrootPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 4;  
                 case 4:  
                         if (ReadPivotRootPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 5;  
                 case 5:  
                         if (ReadReservedPortPolicy(head)) break;  
                         head->read_eof = 1;  
954                          break;                          break;
955                  default:                  case CCS_TYPE_PATH_NUMBER_ACL:
956                          return -EINVAL;                          perm = container_of(ptr, struct ccs_path_number_acl,
957                  }                                              head)->perm;
958          }                          for (i = 0; i < CCS_MAX_PATH_NUMBER_OPERATION; i++)
959          return 0;                                  if (perm & (1 << i))
960  }                                          count++;
   
 #endif  
   
 /*************************  POLICY LOADER  *************************/  
   
 static int profile_loaded = 0;  
   
 static const char *ccs_loader = NULL;  
   
 static int __init CCS_loader_Setup(char *str)  
 {  
         ccs_loader = str;  
         return 0;  
 }  
   
 __setup("CCS_loader=", CCS_loader_Setup);  
   
 void CCS_LoadPolicy(const char *filename)  
 {  
         if (sbin_init_started) return;  
         /*  
          * Check filename is /sbin/init or /sbin/ccs-start .  
          * /sbin/ccs-start is a dummy filename in case where /sbin/init can't be passed.  
          * You can create /sbin/ccs-start by "ln -s /bin/true /sbin/ccs-start", for  
          * only the pathname is needed to activate Mandatory Access Control.  
          */  
         if (strcmp(filename, "/sbin/init") != 0 && strcmp(filename, "/sbin/ccs-start") != 0) return;  
         /*  
          * Don't activate MAC if the path given by 'CCS_loader=' option doesn't exist.  
          * If initrd.img includes /sbin/init but real-root-dev has not mounted on / yet,  
          * activating MAC will block the system since policies are not loaded yet.  
          * So let do_execve() call this function everytime.  
          */  
         {  
                 struct nameidata nd;  
                 if (!ccs_loader) ccs_loader = "/sbin/ccs-init";  
                 if (path_lookup(ccs_loader, lookup_flags, &nd)) {  
                         printk("Not activating Mandatory Access Control now since %s doesn't exist.\n", ccs_loader);  
                         return;  
                 }  
                 path_release(&nd);  
         }  
         if (!profile_loaded) {  
                 char *argv[2], *envp[3];  
                 printk("Calling %s to load policy. Please wait.\n", ccs_loader);  
                 argv[0] = (char *) ccs_loader;  
                 argv[1] = NULL;  
                 envp[0] = "HOME=/";  
                 envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";  
                 envp[2] = NULL;  
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
                 call_usermodehelper(argv[0], argv, envp, 1);  
 #else  
                 call_usermodehelper(argv[0], argv, envp);  
 #endif  
                 while (!profile_loaded) {  
                         set_current_state(TASK_INTERRUPTIBLE);  
                         schedule_timeout(HZ / 10);  
                 }  
         }  
 #ifdef CONFIG_SAKURA  
         printk("SAKURA: 1.5.2-pre   2007/11/29\n");  
 #endif  
 #ifdef CONFIG_TOMOYO  
         printk("TOMOYO: 1.5.2-pre   2007/11/29\n");  
 #endif  
         //if (!profile_loaded) panic("No profiles loaded. Run policy loader using 'init=' option.\n");  
         printk("Mandatory Access Control activated.\n");  
         sbin_init_started = 1;  
         ccs_log_level = KERN_WARNING;  
         { /* Check all profiles currently assigned to domains are defined. */  
                 struct domain_info *domain;  
                 list1_for_each_entry(domain, &domain_list, list) {  
                         const u8 profile = domain->profile;  
                         if (!profile_ptr[profile]) panic("Profile %u (used by '%s') not defined.\n", profile, domain->domainname->name);  
                 }  
         }  
 }  
   
   
 /*************************  MAC Decision Delayer  *************************/  
   
 static DECLARE_WAIT_QUEUE_HEAD(query_wait);  
   
 static spinlock_t query_lock = SPIN_LOCK_UNLOCKED;  
   
 struct query_entry {  
         struct list_head list;  
         char *query;  
         int query_len;  
         unsigned int serial;  
         int timer;  
         int answer;  
 };  
   
 static LIST_HEAD(query_list);  
 static atomic_t queryd_watcher = ATOMIC_INIT(0);  
   
 int CheckSupervisor(const char *fmt, ...)  
 {  
         va_list args;  
         int error = -EPERM;  
         int pos, len;  
         static unsigned int serial = 0;  
         struct query_entry *query_entry;  
         if (!CheckCCSFlags(CCS_ALLOW_ENFORCE_GRACE) || !atomic_read(&queryd_watcher)) {  
 #ifndef ALT_EXEC  
                 if ((current->tomoyo_flags & CCS_DONT_SLEEP_ON_ENFORCE_ERROR) == 0) {  
                         int i;  
                         for (i = 0; i < CheckCCSFlags(CCS_SLEEP_PERIOD); i++) {  
                                 set_current_state(TASK_INTERRUPTIBLE);  
                                 schedule_timeout(HZ / 10);  
                         }  
                 }  
 #endif  
                 return -EPERM;  
         }  
         va_start(args, fmt);  
         len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 32;  
         va_end(args);  
         if ((query_entry = ccs_alloc(sizeof(*query_entry))) == NULL ||  
                 (query_entry->query = ccs_alloc(len)) == NULL) goto out;  
         INIT_LIST_HEAD(&query_entry->list);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         query_entry->serial = serial++;  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         pos = snprintf(query_entry->query, len - 1, "Q%u\n", query_entry->serial);  
         va_start(args, fmt);  
         vsnprintf(query_entry->query + pos, len - 1 - pos, fmt, args);  
         query_entry->query_len = strlen(query_entry->query) + 1;  
         va_end(args);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_add_tail(&query_entry->list, &query_list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         UpdateCounter(CCS_UPDATES_COUNTER_QUERY);  
         /* Give 10 seconds for supervisor's opinion. */  
         for (query_entry->timer = 0; atomic_read(&queryd_watcher) && CheckCCSFlags(CCS_ALLOW_ENFORCE_GRACE) && query_entry->timer < 100; query_entry->timer++) {  
                 wake_up(&query_wait);  
                 set_current_state(TASK_INTERRUPTIBLE);  
                 schedule_timeout(HZ / 10);  
                 if (query_entry->answer) break;  
         }  
         UpdateCounter(CCS_UPDATES_COUNTER_QUERY);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_del(&query_entry->list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         switch (query_entry->answer) {  
         case 1:  
                 /* Granted by administrator. */  
                 error = 0;  
                 break;  
         case 0:  
                 /* Timed out. */  
                 break;  
         default:  
                 /* Rejected by administrator. */  
                 break;  
         }  
  out: ;  
         if (query_entry) ccs_free(query_entry->query);  
         ccs_free(query_entry);  
         return error;  
 }  
   
 static int PollQuery(struct file *file, poll_table *wait)  
 {  
         int found;  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         found = !list_empty(&query_list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (found) return POLLIN | POLLRDNORM;  
         poll_wait(file, &query_wait, wait);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         found = !list_empty(&query_list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (found) return POLLIN | POLLRDNORM;  
         return 0;  
 }  
   
 static int ReadQuery(struct io_buffer *head)  
 {  
         struct list_head *tmp;  
         int pos = 0, len = 0;  
         char *buf;  
         if (head->read_avail) return 0;  
         if (head->read_buf) {  
                 ccs_free(head->read_buf); head->read_buf = NULL;  
                 head->readbuf_size = 0;  
         }  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_for_each(tmp, &query_list) {  
                 struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                 if (pos++ == head->read_step) {  
                         len = ptr->query_len;  
961                          break;                          break;
962                  }                  case CCS_TYPE_PATH_NUMBER3_ACL:
963          }                          perm = container_of(ptr,
964          spin_unlock(&query_lock);                                              struct ccs_path_number3_acl,
965          /***** CRITICAL SECTION END *****/                                              head)->perm;
966          if (!len) {                          for (i = 0; i < CCS_MAX_PATH_NUMBER3_OPERATION;
967                  head->read_step = 0;                               i++)
968                  return 0;                                  if (perm & (1 << i))
969          }                                          count++;
         if ((buf = ccs_alloc(len)) != NULL) {  
                 pos = 0;  
                 /***** CRITICAL SECTION START *****/  
                 spin_lock(&query_lock);  
                 list_for_each(tmp, &query_list) {  
                         struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                         if (pos++ == head->read_step) {  
                                 /* Some query can be skiipped since query_list can change, but I don't care. */  
                                 if (len == ptr->query_len) memmove(buf, ptr->query, len);  
                                 break;  
                         }  
                 }  
                 spin_unlock(&query_lock);  
                 /***** CRITICAL SECTION END *****/  
                 if (buf[0]) {  
                         head->readbuf_size = head->read_avail = len;  
                         head->read_buf = buf;  
                         head->read_step++;  
                 } else {  
                         ccs_free(buf);  
                 }  
         }  
         return 0;  
 }  
   
 static int WriteAnswer(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         struct list_head *tmp;  
         unsigned int serial, answer;  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_for_each(tmp, &query_list) {  
                 struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                 ptr->timer = 0;  
         }  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (sscanf(data, "A%u=%u", &serial, &answer) != 2) return -EINVAL;  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_for_each(tmp, &query_list) {  
                 struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                 if (ptr->serial != serial) continue;  
                 if (!ptr->answer) ptr->answer = answer;  
                 break;  
         }  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         return 0;  
 }  
   
 /*************************  /proc INTERFACE HANDLER  *************************/  
   
 /* Policy updates counter. */  
 static unsigned int updates_counter[MAX_CCS_UPDATES_COUNTER];  
 static spinlock_t updates_counter_lock = SPIN_LOCK_UNLOCKED;  
   
 void UpdateCounter(const unsigned char index)  
 {  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&updates_counter_lock);  
         if (index < MAX_CCS_UPDATES_COUNTER) updates_counter[index]++;  
         spin_unlock(&updates_counter_lock);  
         /***** CRITICAL SECTION END *****/  
 }  
   
 static int ReadUpdatesCounter(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 unsigned int counter[MAX_CCS_UPDATES_COUNTER];  
                 /***** CRITICAL SECTION START *****/  
                 spin_lock(&updates_counter_lock);  
                 memmove(counter, updates_counter, sizeof(updates_counter));  
                 memset(updates_counter, 0, sizeof(updates_counter));  
                 spin_unlock(&updates_counter_lock);  
                 /***** CRITICAL SECTION END *****/  
                 io_printf(head,  
                                   "/proc/ccs/system_policy:    %10u\n"  
                                   "/proc/ccs/domain_policy:    %10u\n"  
                                   "/proc/ccs/exception_policy: %10u\n"  
                                   "/proc/ccs/profile:          %10u\n"  
                                   "/proc/ccs/query:            %10u\n"  
                                   "/proc/ccs/manager:          %10u\n"  
                                   "/proc/ccs/grant_log:        %10u\n"  
                                   "/proc/ccs/reject_log:       %10u\n",  
                                   counter[CCS_UPDATES_COUNTER_SYSTEM_POLICY],  
                                   counter[CCS_UPDATES_COUNTER_DOMAIN_POLICY],  
                                   counter[CCS_UPDATES_COUNTER_EXCEPTION_POLICY],  
                                   counter[CCS_UPDATES_COUNTER_PROFILE],  
                                   counter[CCS_UPDATES_COUNTER_QUERY],  
                                   counter[CCS_UPDATES_COUNTER_MANAGER],  
                                   counter[CCS_UPDATES_COUNTER_GRANT_LOG],  
                                   counter[CCS_UPDATES_COUNTER_REJECT_LOG]);  
                 head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 static int ReadVersion(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 if (io_printf(head, "1.5.2-pre") == 0) head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 static int ReadMemoryCounter(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 const int shared = GetMemoryUsedForSaveName(), private = GetMemoryUsedForElements(), dynamic = GetMemoryUsedForDynamic();  
                 if (io_printf(head, "Shared:  %10u\nPrivate: %10u\nDynamic: %10u\nTotal:   %10u\n", shared, private, dynamic, shared + private + dynamic) == 0) head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 static int ReadSelfDomain(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 io_printf(head, "%s", current->domain_info->domainname->name);  
                 head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 int CCS_OpenControl(const int type, struct file *file)  
 {  
         struct io_buffer *head = ccs_alloc(sizeof(*head));  
         if (!head) return -ENOMEM;  
         mutex_init(&head->read_sem);  
         mutex_init(&head->write_sem);  
         switch (type) {  
 #ifdef CONFIG_SAKURA  
         case CCS_SYSTEMPOLICY:  
                 head->write = AddSystemPolicy;  
                 head->read = ReadSystemPolicy;  
                 break;  
 #endif  
 #ifdef CONFIG_TOMOYO  
         case CCS_DOMAINPOLICY:  
                 head->write = AddDomainPolicy;  
                 head->read = ReadDomainPolicy;  
                 break;  
         case CCS_EXCEPTIONPOLICY:  
                 head->write = AddExceptionPolicy;  
                 head->read = ReadExceptionPolicy;  
                 break;  
         case CCS_GRANTLOG:  
                 head->poll = PollGrantLog;  
                 head->read = ReadGrantLog;  
                 break;  
         case CCS_REJECTLOG:  
                 head->poll = PollRejectLog;  
                 head->read = ReadRejectLog;  
                 break;  
 #endif  
         case CCS_SELFDOMAIN:  
                 head->read = ReadSelfDomain;  
                 break;  
         case CCS_DOMAIN_STATUS:  
                 head->write = UpdateDomainProfile;  
                 head->read = ReadDomainProfile;  
                 break;  
         case CCS_PROCESS_STATUS:  
                 head->write = WritePID;  
                 head->read = ReadPID;  
                 break;  
         case CCS_VERSION:  
                 head->read = ReadVersion;  
                 head->readbuf_size = 128;  
                 break;  
         case CCS_MEMINFO:  
                 head->read = ReadMemoryCounter;  
                 head->readbuf_size = 128;  
                 break;  
         case CCS_PROFILE:  
                 head->write = SetProfile;  
                 head->read = ReadProfile;  
                 break;  
         case CCS_QUERY:  
                 head->poll = PollQuery;  
                 head->write = WriteAnswer;  
                 head->read = ReadQuery;  
                 break;  
         case CCS_MANAGER:  
                 head->write = AddManagerPolicy;  
                 head->read = ReadManagerPolicy;  
                 break;  
         case CCS_UPDATESCOUNTER:  
                 head->read = ReadUpdatesCounter;  
                 break;  
         }  
         if (type != CCS_GRANTLOG && type != CCS_REJECTLOG && type != CCS_QUERY) {  
                 if (!head->readbuf_size) head->readbuf_size = PAGE_SIZE * 2;  
                 if ((head->read_buf = ccs_alloc(head->readbuf_size)) == NULL) {  
                         ccs_free(head);  
                         return -ENOMEM;  
                 }  
         }  
         if (head->write) {  
                 head->writebuf_size = PAGE_SIZE * 2;  
                 if ((head->write_buf = ccs_alloc(head->writebuf_size)) == NULL) {  
                         ccs_free(head->read_buf);  
                         ccs_free(head);  
                         return -ENOMEM;  
                 }  
         }  
         file->private_data = head;  
         if (type == CCS_SELFDOMAIN) CCS_ReadControl(file, NULL, 0);  
         else if (head->write == WriteAnswer) atomic_inc(&queryd_watcher);  
         return 0;  
 }  
   
 static int CopyToUser(struct io_buffer *head, char __user * buffer, int buffer_len)  
 {  
         int len = head->read_avail;  
         char *cp = head->read_buf;  
         if (len > buffer_len) len = buffer_len;  
         if (len) {  
                 if (copy_to_user(buffer, cp, len)) return -EFAULT;  
                 head->read_avail -= len;  
                 memmove(cp, cp + len, head->read_avail);  
         }  
         return len;  
 }  
   
 int CCS_PollControl(struct file *file, poll_table *wait)  
 {  
         struct io_buffer *head = file->private_data;  
         if (!head->poll) return -ENOSYS;  
         return head->poll(file, wait);  
 }  
   
 int CCS_ReadControl(struct file *file, char __user *buffer, const int buffer_len)  
 {  
         int len = 0;  
         struct io_buffer *head = file->private_data;  
         if (!head->read) return -ENOSYS;  
         if (!access_ok(VERIFY_WRITE, buffer, buffer_len)) return -EFAULT;  
         if (mutex_lock_interruptible(&head->read_sem)) return -EINTR;  
         len = head->read(head);  
         if (len >= 0) len = CopyToUser(head, buffer, buffer_len);  
         mutex_unlock(&head->read_sem);  
         return len;  
 }  
   
 int CCS_WriteControl(struct file *file, const char __user *buffer, const int buffer_len)  
 {  
         struct io_buffer *head = file->private_data;  
         int error = buffer_len;  
         int avail_len = buffer_len;  
         char *cp0 = head->write_buf;  
         if (!head->write) return -ENOSYS;  
         if (!access_ok(VERIFY_READ, buffer, buffer_len)) return -EFAULT;  
         if (!isRoot()) return -EPERM;  
         if (head->write != WritePID && !IsPolicyManager()) {  
                 return -EPERM; /* Forbid updating policies for non manager programs. */  
         }  
         if (mutex_lock_interruptible(&head->write_sem)) return -EINTR;  
         while (avail_len > 0) {  
                 char c;  
                 if (head->write_avail >= head->writebuf_size - 1) {  
                         error = -ENOMEM;  
970                          break;                          break;
971                  } else if (get_user(c, buffer)) {                  case CCS_TYPE_IP_NETWORK_ACL:
972                          error = -EFAULT;                          perm = container_of(ptr, struct ccs_ip_network_acl,
973                                                head)->perm;
974                            for (i = 0; i < CCS_MAX_NETWORK_OPERATION; i++)
975                                    if (perm & (1 << i))
976                                            count++;
977                          break;                          break;
978                    default:
979                            count++;
980                  }                  }
981                  buffer++; avail_len--;          }
982                  cp0[head->write_avail++] = c;          if (count < ccs_flags(domain, CCS_MAX_ACCEPT_ENTRY))
983                  if (c != '\n') continue;                  return true;
984                  cp0[head->write_avail - 1] = '\0';          if (!domain->quota_warned) {
985                  head->write_avail = 0;                  domain->quota_warned = true;
986                  NormalizeLine(cp0);                  printk(KERN_WARNING "WARNING: "
987                  head->write(head);                         "Domain '%s' has so many ACLs to hold. "
988          }                         "Stopped learning mode.\n", domain->domainname->name);
989          mutex_unlock(&head->write_sem);          }
990          return error;          return false;
 }  
   
   
 int CCS_CloseControl(struct file *file)  
 {  
         struct io_buffer *head = file->private_data;  
         if (head->write == WriteAnswer) atomic_dec(&queryd_watcher);  
         else if (head->read == ReadMemoryCounter) profile_loaded = 1;  
         ccs_free(head->read_buf); head->read_buf = NULL;  
         ccs_free(head->write_buf); head->write_buf = NULL;  
         ccs_free(head); head = NULL;  
         file->private_data = NULL;  
         return 0;  
991  }  }

Legend:
Removed from v.741  
changed lines
  Added in v.2922

Back to OSDN">Back to OSDN
ViewVC Help
Powered by ViewVC 1.1.26