udp.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <ip.h>
  4. #include "dat.h"
  5. #include "protos.h"
  6. typedef struct Hdr Hdr;
  7. struct Hdr
  8. {
  9. uchar sport[2]; /* Source port */
  10. uchar dport[2]; /* Destination port */
  11. uchar len[2]; /* data length */
  12. uchar cksum[2]; /* Checksum */
  13. };
  14. enum
  15. {
  16. UDPLEN= 8,
  17. };
  18. enum
  19. {
  20. Os,
  21. Od,
  22. Osd,
  23. Osetport,
  24. };
  25. static Field p_fields[] =
  26. {
  27. {"s", Fnum, Os, "source port", } ,
  28. {"d", Fnum, Od, "dest port", } ,
  29. {"a", Fnum, Osd, "source/dest port", } ,
  30. {"sd", Fnum, Osd, "source/dest port", } ,
  31. {0}
  32. };
  33. #define ANYPORT ~0UL
  34. static Mux p_mux[] =
  35. {
  36. {"dns", 53, },
  37. {"bootp", 67, },
  38. {"ninep", 6346, }, /* tvs */
  39. {"rtp", ANYPORT, },
  40. {"rtcp", ANYPORT, },
  41. {0},
  42. };
  43. /* default next protocol, can be changed by p_filter, reset by p_compile */
  44. static Proto *defproto = &dump;
  45. static void
  46. p_compile(Filter *f)
  47. {
  48. Mux *m;
  49. if(f->op == '='){
  50. compile_cmp(udp.name, f, p_fields);
  51. return;
  52. }
  53. for(m = p_mux; m->name != nil; m++)
  54. if(strcmp(f->s, m->name) == 0){
  55. f->pr = m->pr;
  56. f->ulv = m->val;
  57. f->subop = Osd;
  58. return;
  59. }
  60. sysfatal("unknown udp field or protocol: %s", f->s);
  61. }
  62. static int
  63. p_filter(Filter *f, Msg *m)
  64. {
  65. Hdr *h;
  66. if(m->pe - m->ps < UDPLEN)
  67. return 0;
  68. h = (Hdr*)m->ps;
  69. m->ps += UDPLEN;
  70. switch(f->subop){
  71. case Os:
  72. return NetS(h->sport) == f->ulv;
  73. case Od:
  74. return NetS(h->dport) == f->ulv;
  75. case Osd:
  76. if(f->ulv == ANYPORT){
  77. defproto = f->pr;
  78. return 1;
  79. }
  80. return NetS(h->sport) == f->ulv || NetS(h->dport) == f->ulv;
  81. }
  82. return 0;
  83. }
  84. static int
  85. p_seprint(Msg *m)
  86. {
  87. Hdr *h;
  88. int dport, sport;
  89. if(m->pe - m->ps < UDPLEN)
  90. return -1;
  91. h = (Hdr*)m->ps;
  92. m->ps += UDPLEN;
  93. /* next protocol */
  94. sport = NetS(h->sport);
  95. dport = NetS(h->dport);
  96. demux(p_mux, sport, dport, m, defproto);
  97. defproto = &dump;
  98. m->p = seprint(m->p, m->e, "s=%d d=%d ck=%4.4ux ln=%4d",
  99. NetS(h->sport), dport,
  100. NetS(h->cksum), NetS(h->len));
  101. return 0;
  102. }
  103. Proto udp =
  104. {
  105. "udp",
  106. p_compile,
  107. p_filter,
  108. p_seprint,
  109. p_mux,
  110. "%lud",
  111. p_fields,
  112. defaultframer,
  113. };