]> Pileus Git - ~andy/fetchmail/blob - servport.c
Attempt merging from 6.3.24.
[~andy/fetchmail] / servport.c
1 /** \file servport.c Resolve service name to port number.
2  * \author Matthias Andree
3  * \date 2005 - 2006
4  *
5  * Copyright (C) 2005 by Matthias Andree
6  * For license terms, see the file COPYING in this directory.
7  */
8 #include "fetchmail.h"
9 #include "getaddrinfo.h"
10 #include "gettext.h"
11
12 #include <errno.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/types.h>
16 #include <netdb.h>
17 #include <netinet/in.h>
18 #include <arpa/inet.h>
19 #include <sys/socket.h>
20
21 int servport(const char *service) {
22     int port, e;
23     unsigned long u;
24     char *end;
25
26     if (service == 0)
27         return -1;
28
29     /*
30      * Check if the service is a number. If so, convert it.
31      * If it isn't a number, call getservbyname to resolve it.
32      */
33     errno = 0;
34     u = strtoul(service, &end, 10);
35     if (errno || end[strspn(end, POSIX_space)] != '\0') {
36         struct addrinfo hints, *res;
37
38         /* hardcode kpop to port 1109 as per fetchmail(1)
39          * manual page, it's not a IANA registered service */
40         if (strcmp(service, "kpop") == 0)
41             return 1109;
42
43         memset(&hints, 0, sizeof hints);
44         hints.ai_family = AF_UNSPEC;
45         hints.ai_socktype = SOCK_STREAM;
46         hints.ai_protocol = IPPROTO_TCP;
47         e = fm_getaddrinfo(NULL, service, &hints, &res);
48         if (e) {
49             report(stderr, GT_("getaddrinfo(NULL, \"%s\") error: %s\n"),
50                     service, gai_strerror(e));
51             goto err;
52         } else {
53             switch(res->ai_addr->sa_family) {
54                 case AF_INET:
55                     port = ntohs(((struct sockaddr_in *)res->ai_addr)->sin_port);
56                 break;
57 #ifdef AF_INET6
58                 case AF_INET6:
59                     port = ntohs(((struct sockaddr_in6 *)res->ai_addr)->sin6_port);
60                 break;
61 #endif
62                 default:
63                     fm_freeaddrinfo(res);
64                     goto err;
65             }
66             fm_freeaddrinfo(res);
67         }
68     } else {
69         if (u == 0 || u > 65535)
70             goto err;
71         port = u;
72     }
73
74     return port;
75 err:
76     report(stderr, GT_("Cannot resolve service %s to port number.\n"), service);
77     report(stderr, GT_("Please specify the service as decimal port number.\n"));
78     return -1;
79 }
80 /* end of servport.c */