chmod.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include <u.h>
  2. #include <libc.h>
  3. #define U(x) (x<<6)
  4. #define G(x) (x<<3)
  5. #define O(x) (x)
  6. #define A(x) (U(x)|G(x)|O(x))
  7. #define DMRWE (DMREAD|DMWRITE|DMEXEC)
  8. int parsemode(char *, ulong *, ulong *);
  9. void
  10. main(int argc, char *argv[])
  11. {
  12. int i;
  13. Dir *dir, ndir;
  14. ulong mode, mask;
  15. char *p;
  16. if(argc < 3){
  17. fprint(2, "usage: chmod 0777 file ... or chmod [who]op[rwxalt] file ...\n");
  18. exits("usage");
  19. }
  20. mode = strtol(argv[1], &p, 8);
  21. if(*p == 0)
  22. mask = A(DMRWE);
  23. else if(!parsemode(argv[1], &mask, &mode)){
  24. fprint(2, "chmod: bad mode: %s\n", argv[1]);
  25. exits("mode");
  26. }
  27. nulldir(&ndir);
  28. for(i=2; i<argc; i++){
  29. dir = dirstat(argv[i]);
  30. if(dir == nil){
  31. fprint(2, "chmod: can't stat %s: %r\n", argv[i]);
  32. continue;
  33. }
  34. ndir.mode = (dir->mode & ~mask) | (mode & mask);
  35. free(dir);
  36. if(dirwstat(argv[i], &ndir)==-1){
  37. fprint(2, "chmod: can't wstat %s: %r\n", argv[i]);
  38. continue;
  39. }
  40. }
  41. exits(0);
  42. }
  43. int
  44. parsemode(char *spec, ulong *pmask, ulong *pmode)
  45. {
  46. ulong mode, mask;
  47. int done, op;
  48. char *s;
  49. s = spec;
  50. mask = DMAPPEND | DMEXCL | DMTMP;
  51. for(done=0; !done; ){
  52. switch(*s){
  53. case 'u':
  54. mask |= U(DMRWE); break;
  55. case 'g':
  56. mask |= G(DMRWE); break;
  57. case 'o':
  58. mask |= O(DMRWE); break;
  59. case 'a':
  60. mask |= A(DMRWE); break;
  61. case 0:
  62. return 0;
  63. default:
  64. done = 1;
  65. }
  66. if(!done)
  67. s++;
  68. }
  69. if(s == spec)
  70. mask |= A(DMRWE);
  71. op = *s++;
  72. if(op != '+' && op != '-' && op != '=')
  73. return 0;
  74. mode = 0;
  75. for(; *s ; s++){
  76. switch(*s){
  77. case 'r':
  78. mode |= A(DMREAD); break;
  79. case 'w':
  80. mode |= A(DMWRITE); break;
  81. case 'x':
  82. mode |= A(DMEXEC); break;
  83. case 'a':
  84. mode |= DMAPPEND; break;
  85. case 'l':
  86. mode |= DMEXCL; break;
  87. case 't':
  88. mode |= DMTMP; break;
  89. default:
  90. return 0;
  91. }
  92. }
  93. if(*s != 0)
  94. return 0;
  95. if(op == '+' || op == '-')
  96. mask &= mode;
  97. if(op == '-')
  98. mode = ~mode;
  99. *pmask = mask;
  100. *pmode = mode;
  101. return 1;
  102. }