lookup_serv.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <sys/socket.h>
  2. #include <netinet/in.h>
  3. #include <netdb.h>
  4. #include <ctype.h>
  5. #include <string.h>
  6. #include <fcntl.h>
  7. #include "lookup.h"
  8. #include "stdio_impl.h"
  9. int __lookup_serv(struct service buf[static MAXSERVS], const char *name, int proto, int flags)
  10. {
  11. char line[128];
  12. int cnt = 0;
  13. char *p, *z = "";
  14. unsigned long port = 0;
  15. if (name) {
  16. if (!*name) return EAI_SERVICE;
  17. port = strtoul(name, &z, 10);
  18. }
  19. if (!*z) {
  20. if (port > 65535) return EAI_SERVICE;
  21. if (proto != IPPROTO_UDP) {
  22. buf[cnt].port = port;
  23. buf[cnt++].proto = IPPROTO_TCP;
  24. }
  25. if (proto != IPPROTO_TCP) {
  26. buf[cnt].port = port;
  27. buf[cnt++].proto = IPPROTO_UDP;
  28. }
  29. return cnt;
  30. }
  31. if (flags & AI_NUMERICSERV) return EAI_SERVICE;
  32. size_t l = strlen(name);
  33. unsigned char _buf[1032];
  34. FILE _f, *f = __fopen_rb_ca("/etc/services", &_f, _buf, sizeof _buf);
  35. if (!f) return EAI_SERVICE;
  36. while (fgets(line, sizeof line, f) && cnt < MAXSERVS) {
  37. if ((p=strchr(line, '#'))) *p++='\n', *p=0;
  38. /* Find service name */
  39. for(p=line; (p=strstr(p, name)); p++) {
  40. if (p>line && !isspace(p[-1])) continue;
  41. if (p[l] && !isspace(p[l])) continue;
  42. break;
  43. }
  44. if (!p) continue;
  45. /* Skip past canonical name at beginning of line */
  46. for (p=line; *p && !isspace(*p); p++);
  47. port = strtoul(p, &z, 10);
  48. if (port > 65535 || z==p) continue;
  49. if (!strncmp(z, "/udp", 4)) {
  50. if (proto == IPPROTO_TCP) continue;
  51. buf[cnt].port = port;
  52. buf[cnt++].proto = IPPROTO_UDP;
  53. }
  54. if (!strncmp(z, "/tcp", 4)) {
  55. if (proto == IPPROTO_UDP) continue;
  56. buf[cnt].port = port;
  57. buf[cnt++].proto = IPPROTO_TCP;
  58. }
  59. }
  60. __fclose_ca(f);
  61. return cnt > 0 ? cnt : EAI_SERVICE;
  62. }