@@ -63,7 +63,7 @@ bool Iptables::newChain(std::string chain)
6363}
6464
6565/*
66- * Append rule to chain
66+ * Append rule to the end of the chain
6767 */
6868bool Iptables::append (std::string chain, std::string rule)
6969{
@@ -91,7 +91,7 @@ bool Iptables::append(std::string chain, std::string rule)
9191}
9292
9393/*
94- * Append rules to chain
94+ * Append multiple rules to the end of the chain
9595 */
9696bool Iptables::append (std::string chain, std::vector<std::string>* rules)
9797{
@@ -117,6 +117,61 @@ bool Iptables::append(std::string chain, std::vector<std::string>* rules)
117117 return true ;
118118}
119119
120+ /*
121+ * Insert rule to the chain at specified position
122+ */
123+ bool Iptables::insert (std::string chain, std::string rule, int pos)
124+ {
125+ // Need root access to work with iptables
126+ if (cunistd::getuid () != 0 ) {
127+ throw std::runtime_error (" Error, root access required to work with iptables!" );
128+ }
129+
130+ // Prepare command
131+ std::string cmd = " iptables -I " + chain + " " + std::to_string (pos) + " " + rule;
132+ int response = 0 ;
133+ if (!std::system (NULL )) {
134+ throw std::runtime_error (" Command processor not available." );
135+ }
136+
137+ // Exec command
138+ response = std::system (cmd.c_str ());
139+
140+ // Check response
141+ if (response == 0 ) {
142+ return true ;
143+ } else {
144+ throw std::runtime_error (" Failed to execute iptables, returned code: " + std::to_string (response));
145+ }
146+ }
147+
148+ /*
149+ * Append multiple rules at specified position in chain
150+ */
151+ bool Iptables::insert (std::string chain, std::vector<std::string>* rules, int pos)
152+ {
153+ // Need root access to work with iptables
154+ if (cunistd::getuid () != 0 ) {
155+ throw std::runtime_error (" Error, root access required to work with iptables!" );
156+ }
157+
158+ int response = 0 ;
159+ if (!std::system (NULL )) {
160+ throw std::runtime_error (" Command processor not available." );
161+ }
162+
163+ std::string cmd;
164+ for (std::vector<std::string>::iterator it = rules->begin (); it != rules->end (); ++it) {
165+ cmd = " iptables -I " + chain + " " + std::to_string (pos) + " " + *it;
166+ response = std::system (cmd.c_str ());
167+ if (response != 0 ) {
168+ throw std::runtime_error (" Failed to execute iptables, returned code: " + std::to_string (response));
169+ }
170+ }
171+
172+ return true ;
173+ }
174+
120175/*
121176 * Delete rule from chain
122177 */
0 commit comments