parse.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <fcall.h>
  4. #include <thread.h>
  5. #include <9p.h>
  6. /*
  7. * Generous estimate of number of fields, including terminal nil pointer
  8. */
  9. static int
  10. ncmdfield(char *p, int n)
  11. {
  12. int white, nwhite;
  13. char *ep;
  14. int nf;
  15. if(p == nil)
  16. return 1;
  17. nf = 0;
  18. ep = p+n;
  19. white = 1; /* first text will start field */
  20. while(p < ep){
  21. nwhite = (strchr(" \t\r\n", *p++ & 0xFF) != 0); /* UTF is irrelevant */
  22. if(white && !nwhite) /* beginning of field */
  23. nf++;
  24. white = nwhite;
  25. }
  26. return nf+1; /* +1 for nil */
  27. }
  28. /*
  29. * parse a command written to a device
  30. */
  31. Cmdbuf*
  32. parsecmd(char *p, int n)
  33. {
  34. Cmdbuf *cb;
  35. int nf;
  36. char *sp;
  37. nf = ncmdfield(p, n);
  38. /* allocate Cmdbuf plus string pointers plus copy of string including \0 */
  39. sp = emalloc9p(sizeof(*cb) + nf * sizeof(char*) + n + 1);
  40. cb = (Cmdbuf*)sp;
  41. cb->f = (char**)(&cb[1]);
  42. cb->buf = (char*)(&cb->f[nf]);
  43. memmove(cb->buf, p, n);
  44. /* dump new line and null terminate */
  45. if(n > 0 && cb->buf[n-1] == '\n')
  46. n--;
  47. cb->buf[n] = '\0';
  48. cb->nf = tokenize(cb->buf, cb->f, nf-1);
  49. cb->f[cb->nf] = nil;
  50. return cb;
  51. }
  52. /*
  53. * Reconstruct original message, for error diagnostic
  54. */
  55. void
  56. respondcmderror(Req *r, Cmdbuf *cb, char *fmt, ...)
  57. {
  58. int i;
  59. va_list arg;
  60. char *p, *e;
  61. char err[ERRMAX];
  62. e = err+ERRMAX-10;
  63. va_start(arg, fmt);
  64. p = vseprint(err, e, fmt, arg);
  65. va_end(arg);
  66. p = seprint(p, e, ": \"");
  67. quotefmtinstall(); /* just in case */
  68. for(i=0; i<cb->nf; i++){
  69. if(i > 0)
  70. p = seprint(p, e, " ");
  71. p = seprint(p, e, "%q", cb->f[i]);
  72. }
  73. strcpy(p, "\"");
  74. respond(r, err);
  75. }
  76. /*
  77. * Look up entry in table
  78. */
  79. Cmdtab*
  80. lookupcmd(Cmdbuf *cb, Cmdtab *ctab, int nctab)
  81. {
  82. int i;
  83. Cmdtab *ct;
  84. if(cb->nf == 0){
  85. werrstr("empty control message");
  86. return nil;
  87. }
  88. for(ct = ctab, i=0; i<nctab; i++, ct++){
  89. if(strcmp(ct->cmd, "*") !=0) /* wildcard always matches */
  90. if(strcmp(ct->cmd, cb->f[0]) != 0)
  91. continue;
  92. if(ct->narg != 0 && ct->narg != cb->nf){
  93. werrstr("bad # args to command");
  94. return nil;
  95. }
  96. return ct;
  97. }
  98. werrstr("unknown control message");
  99. return nil;
  100. }