parse.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. for(i=0; i<cb->nf; i++){
  68. if(i > 0)
  69. p = seprint(p, e, " ");
  70. p = seprint(p, e, "%q", cb->f[i]);
  71. }
  72. strcpy(p, "\"");
  73. respond(r, err);
  74. }
  75. /*
  76. * Look up entry in table
  77. */
  78. Cmdtab*
  79. lookupcmd(Cmdbuf *cb, Cmdtab *ctab, int nctab)
  80. {
  81. int i;
  82. Cmdtab *ct;
  83. if(cb->nf == 0){
  84. werrstr("empty control message");
  85. return nil;
  86. }
  87. for(ct = ctab, i=0; i<nctab; i++, ct++){
  88. if(strcmp(ct->cmd, "*") !=0) /* wildcard always matches */
  89. if(strcmp(ct->cmd, cb->f[0]) != 0)
  90. continue;
  91. if(ct->narg != 0 && ct->narg != cb->nf){
  92. werrstr("bad # args to command");
  93. return nil;
  94. }
  95. return ct;
  96. }
  97. werrstr("unknown control message");
  98. return nil;
  99. }