ILD

Linux批量添加路由
作者:HerbertYuan 邮箱:yuanjp89@163.com
发布时间:2017-8-28 站点:Inside Linux Development

出发点,VPN应用场景下,让国内IP走非VPN连接。


1 使用方法

可以使用内置中国数据库,也可以使用数据库文件。数据库文件的格式为文本文件,每一行是一个网段,网段的格式为net/prefix。如1.2.3.0/24。使用命令如下:

1
2
batchroute add :china via 192.168.0.1 dev eth0
batchroute del :china

:china表示内置的数据库,其它,则不是数据库文件的路径。


2 代码

代码的核心是netlink和内核交互,操作路由条目。使用sendmsg/recvmsg接口发送和接收消息。直接展示代码吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#include <stdio.h>
#include <errno.h>
#include <string.h>     
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <net/if.h> 
#include <arpa/inet.h>
 
static int g_sequence = 0;
 
static unsigned long chinaip[] = 
{
    16785427, 16846868, 16850963, 16912404, 16916499, 
    16924690, 16973840, 17043476, 17047571, 17055762,
     
    // ...
    // omit, down winroute to get the china ip database
    // url http://insidelinuxdev.net/article/a012ux.html
};
 
void usage()
{
    fprintf(stderr, "batchroute {add | del} db [via nexthop] [dev ifname]\n");
    fprintf(stderr, "\tdb is a text file, each line hold a \n");
    fprintf(stderr, "\tnet/prefix (e.g. 10.0.0.0/8) to be added or deleted\n");
    exit(1);
}
 
int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
          int alen)
{
#define NLMSG_TAIL(nmsg) \
    ((struct rtattr *) (((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
 
    int len = RTA_LENGTH(alen);
    struct rtattr *rta;
 
    if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
        fprintf(stderr,
            "addattr_l ERROR: message exceeded bound of %d\n",
            maxlen);
        return -1;
    }
    rta = NLMSG_TAIL(n);
    rta->rta_type = type;
    rta->rta_len = len;
    memcpy(RTA_DATA(rta), data, alen);
    n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
    return 0;
}
 
int mod_route(int action, int sock, unsigned long dest, int prefix, 
    unsigned long gw, unsigned long ifidex)
{
    int status;
    char buf[32768];
    struct nlmsghdr *h;
    int seq;
    int len, l;
 
    struct {
        struct nlmsghdr        n;
        struct rtmsg       r;
        char            buf[1024];
    } req = {
        .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)),
        .n.nlmsg_seq = ++g_sequence,
        .n.nlmsg_pid = 0,
        .r.rtm_family = AF_INET,
        .r.rtm_table = RT_TABLE_MAIN,
    };
     
    struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
    struct iovec iov = { &req};
    struct msghdr msg = { &nladdr, sizeof(nladdr), &iov, 1, NULL, 0, 0 };
 
    req.r.rtm_dst_len = prefix;
 
    if (action == 0)
    {
        req.n.nlmsg_type = RTM_NEWROUTE,
        req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL,
        req.r.rtm_protocol = RTPROT_STATIC;
        req.r.rtm_scope = RT_SCOPE_UNIVERSE;
        req.r.rtm_type = RTN_UNICAST;
        addattr_l(&req.n, sizeof(req), RTA_DST, &dest, 4);
        addattr_l(&req.n, sizeof(req), RTA_GATEWAY, &gw, 4);
        addattr_l(&req.n, sizeof(req), RTA_OIF, &ifidex, 4);
    }
    else
    {
        req.n.nlmsg_type = RTM_DELROUTE,
        req.n.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK,
        addattr_l(&req.n, sizeof(req), RTA_DST, &dest, 4);
    }
 
    iov.iov_len = req.n.nlmsg_len;
    seq = req.n.nlmsg_seq;
    status = sendmsg(sock, &msg, 0);
    if (status < 0) {
        fprintf(stderr, "sendmsg() for add route entry failed: %s\n",
            strerror(errno));
        return 1;
    }
 
    iov.iov_base = buf;
    iov.iov_len = sizeof(buf);
    status = recvmsg(sock, &msg, 0);
    if (status == -1) {
        fprintf(stderr, "recvmsg() for recv a ack failed: %s\n",
            strerror(errno));
        return 1;
    }
    if (status == 0) {
        fprintf(stderr, "EOF on netlink\n");
        return 1;
    }
 
    h = (struct nlmsghdr *)buf; 
    if (status < sizeof(*h)) {
        fprintf(stderr, "invalid response length %d\n", status);
        return 1;
    }
 
    len = h->nlmsg_len;
    l = len - sizeof(*h);
 
    if (l < 0 || len > status) {
        if (msg.msg_flags & MSG_TRUNC) {
            fprintf(stderr, "Truncated message\n");
            return -1;
        }
        fprintf(stderr, "!!!malformed message: len=%d\n", len);
        return 1;
    }
 
 
    if (nladdr.nl_pid != 0 ||
      /*  h->nlmsg_pid != rtnl->local.nl_pid || */
        h->nlmsg_seq != seq) {
        /* Don't forget to skip that message. */
        fprintf(stderr, "no our msg\n");
        return 1; 
    }
 
    if (h->nlmsg_type == NLMSG_ERROR) {
        struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(h);
 
        if (l < sizeof(struct nlmsgerr)) {
            fprintf(stderr, "ERROR truncated\n");
        else if (!err->error) {
            return 0;
        }
 
        fprintf(stderr, "RTNETLINK answers: %s\n",
            strerror(-err->error));
        errno = -err->error;
        return -1;
    }
 
    fprintf(stderr, "Unexpected reply!!!\n");
    return 1;
}
 
// 8 to mask "255.0.0.0"
static inline unsigned long prefix_to_mask(int num)
{
    int i;
    unsigned long v = 0;
    for ( i = 31; i >= 32-num; i--)
        v |= (1 << i);
    return htonl(v);
}
 
// "1.2.3.0/24"
int parse_DB(char *buf, unsigned long *net, int *prefix)
{
    int ret = 1;
    struct in_addr dest;
    char *sep;
    sep = strchr(buf, '/');
    if (sep == NULL) 
        return 1;
     
    *sep = '\0';
 
    if (0 == inet_aton(buf, &dest))
        goto err;
     
    if (1 != sscanf(sep + 1, "%d", prefix) || *prefix < 0 || *prefix > 32) 
        goto err;
     
    if ( (ntohl(dest.s_addr) & ntohl(prefix_to_mask(*prefix))) != ntohl(dest.s_addr)) 
        goto err;
     
    ret = 0;
    *net = dest.s_addr;
     
err:
    *sep = '/';      
    return ret;
}
 
int batch_route(int action, char *db, char *nexthop, char *ifname)
{
    int ret = 1;
    int sock;
    struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
    unsigned long dest;
    int prefix;
    unsigned int gw;
    int ifindex;
    FILE *f;
    char buf[120];
 
    if (action == 0)
    {
        struct in_addr addr;
        if (nexthop == NULL || ifname == NULL) {
            fprintf(stderr, "nexthop and ifname required\n");
            return 1;
        }
 
        if (0 == inet_aton(nexthop, &addr)) {
            fprintf(stderr, "invalid nexthop: %s\n", nexthop);
            return 1;
        }
 
        gw = addr.s_addr;
 
        ifindex = if_nametoindex(ifname);
        if (ifindex == 0) {
            fprintf(stderr, "invalid ifname: %s\n", ifname);
            return 1;
        }
    }
 
     
    sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
    if (sock == -1) {
        fprintf(stderr, "socket() for NETLINK_ROUTE failed: %s\n",
            strerror(errno));
        return 1;
    }
 
    if (bind(sock, (struct sockaddr *)&nladdr, sizeof(nladdr)) < 0) {
        fprintf(stderr, "bind() for NETLINK_ROUTE failed: %s\n",
            strerror(errno));
        return 1;
    }
 
    if (strcmp(db, ":china") == 0) {
        int i;
        for (i = 0; i < sizeof(chinaip)/sizeof(chinaip[0]); i++) {
            dest = htonl(chinaip[i] & 0xffffff00);
            prefix = chinaip[i] & 0xff;
            if (mod_route(action, sock, dest, prefix, gw, ifindex))
                goto errret;
        }
        goto okret;
    }
 
     
    f = fopen(db, "r");
    if (f == NULL) {
        fprintf(stderr, "can't open db file %s: %s\n", db, strerror(errno));
        goto errret;  
    }
 
    while (fgets(buf, sizeof(buf), f))
    {
        if (parse_DB(buf, &dest, &prefix)) {
            fprintf(stderr, "db line formart error: %s", buf);
            goto errret;
        }
    }
 
    rewind(f);
    while (fgets(buf, sizeof(buf), f))
    {      
        if (parse_DB(buf, &dest, &prefix)) {
            fprintf(stderr, "db line formart error: %s", buf);
            goto errret;
        }
 
        if (mod_route(action, sock, dest, prefix, gw, ifindex))
            goto errret;
    }
 
okret:
    ret = 0;
errret:
    close(sock);
    if (f)
        fclose(f);
 
    return 0;
}
 
int main(int argc, char **argv)
{
    int ret = 1;
    char action = -1;
    char *db = NULL;
    char *nexthop = NULL;
    char *ifname = NULL;
 
    if (argc < 3) {
        fprintf(stderr, "no enough args\n");
        usage();
    }
 
    if (strcmp("add", argv[1]) == 0)
        action = 0;
    else if (strcmp("del", argv[1]) == 0)
        action = 1;
    else {
        fprintf(stderr, "arg 1 should be add or del\n");
        usage();
    }
 
    db = argv[2];
     
    argc -= 3;
    argv += 3;
    while (argc > 0) {
        if (strcmp("via", *argv) == 0) 
            nexthop = argv[1];
        else if (strcmp("dev", *argv) == 0) 
            ifname = argv[1];
        else
            usage();
 
        argc -= 2;
        if (argc < 0) {
            fprintf(stderr, "need parameter for %s\n", argv[0]);
            usage();
        }
        argv += 2;
    }
     
    return batch_route(action, db, nexthop, ifname);
}


学习路由操作,可直接参考iproute2源代码。

Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.