Add network emulation feature.
[sim/o1-interface.git] / ntsimulator / ntsim-ng / utils / network_emulation.c
1 /*************************************************************************
2 *
3 * Copyright 2020 highstreet technologies GmbH and others
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 ***************************************************************************/
17
18 #define _GNU_SOURCE
19
20 #include "network_emulation.h"
21 #include "log_utils.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <assert.h>
25
26 int network_emulation_init(void) {
27     system("tc qdisc add dev eth0 root netem limit "NETWORK_EMULATION_DEFAULT_LIMIT" delay 0ms > /dev/null");
28     return NTS_ERR_OK;
29 }
30
31 int network_emulation_update(const network_emultation_settings_t *s) {
32     assert(s);
33
34     char command[512];
35     if(s->delay.time && s->delay.jitter) {
36         sprintf(command, "tc qdisc change dev eth0 root netem limit %d delay %dms %dms %d%% distribution %s loss random %d%% corrupt %d%% %d%% duplicate %d%% %d%% reorder %d%% %d%% rate %dkbit > /dev/null", s->limit, s->delay.time, s->delay.jitter, s->delay.correlation, s->delay.distribution, s->loss, s->corruption.percentage, s->corruption.correlation, s->duplication.percentage, s->duplication.correlation, s->reordering.percentage, s->reordering.correlation, s->rate);
37     }
38     else {
39         sprintf(command, "tc qdisc change dev eth0 root netem limit %d delay %dms %dms %d%% loss random %d%% corrupt %d%% %d%% duplicate %d%% %d%% reorder %d%% %d%% rate %dkbit > /dev/null", s->limit, s->delay.time, s->delay.jitter, s->delay.correlation, s->loss, s->corruption.percentage, s->corruption.correlation, s->duplication.percentage, s->duplication.correlation, s->reordering.percentage, s->reordering.correlation, s->rate);
40     }
41     log_add_verbose(2, "chaning netem: %s\n", command);
42     int rc = system(command);
43     return rc;
44 }