-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.c
More file actions
2068 lines (1669 loc) · 75.8 KB
/
Copy pathcontroller.c
File metadata and controls
2068 lines (1669 loc) · 75.8 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* sudo mn --controller=remote,ip=IP,port=6653 --switch=ovsk,protocols=OpenFlow10
*/
/*
* From my understanding of OpenFlow, here is how the conrtoller works
* 1. The controller listens for incoming connections from switches
* - A socket is created for TCP connections.
* - The socket is bound to a port and listens for incoming connections.
* - All indexes in the switch array have a mutex locked placed on them for later.
* - A thread is created to handle incoming connections by running the accept_handler.
*
* 2. The accept_handler function is called when a new connection is accepted by the listener thread.
* - The function locks the switch array and finds a free slot to store the switch information.
* - Once locked, finds a free slot in the switch array to store the switch information.
* - The switch socket is stored in the switch array and a new thread is created run switch_handler.
* - The switch array is unlocked.
* - If the maximum number of switches is reached, the connection is rejected.
* - Each new thread handles communication between the controller and the switch.
*
* 3. In the switch handler, the thread begins the OpenFlow handshake.
* - Thread sends a HELLO message to the switch with send_hello.
* - The switch handler thread waits for incoming messages from the switch.
* - The thread processes incoming messages with handle_switch_message.
* - The switch handler thread sends an ECHO_REQUEST to the switch every 5 seconds.
* - The switch handler thread waits for an ECHO_REPLY from the switch.
*
* 4. The handle_switch_message function processes incoming OpenFlow messages.
* - The function verifies the message length.
* - The function processes the message based on the message type.
* - handle_hello updates the switch version and sends a features request.
* - handle_echo_request sends an ECHO_REPLY back to the switch.
* - handle_echo_reply updates the last_echo_reply time.
* - handle_features_reply updates switch features and port information.
* - handle_packet_in logs packet information.
* - handle_port_status logs port status changes.
*
* 5. The send_openflow_msg function sends OpenFlow messages to the switch.
* - The function locks the switch mutex.
* - The function sends the message to the switch socket.
* - The function unlocks the switch mutex.
*
* 6. The send_hello function sends a HELLO message to the switch.
* - The function creates a HELLO message and sends it to the switch.
*
* 7. The send_features_request function sends a FEATURES_REQUEST to the switch.
* - The function creates a FEATURES_REQUEST message and sends it to the switch.
*
* 8. The send_echo_request function sends an ECHO_REQUEST to the switch.
* - The function creates an ECHO_REQUEST message and sends it to the switch.
*/
#include "headers/smartalloc.h"
#include "headers/checksum.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <pthread.h>
#include <inttypes.h>
#include <stdarg.h>
#include <netinet/tcp.h>
#include <stdbool.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include </usr/include/igraph/igraph.h>
#include "headers/uthash.h"
#if defined(__linux__)
#include <endian.h>
#elif defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#define be64toh(x) OSSwapBigToHostInt64(x)
#endif
#include "headers/controller.h"
#include "headers/openflow.h"
#define MAX_PORTS_PER_SWITCH 256
#define DEF_PORT 6653
/* ------------------------------------------------------ GLOBAL --------------------------------------------------- */
/* global variables */
struct switch_info switches[MAX_SWITCHES];
pthread_mutex_t switches_lock = PTHREAD_MUTEX_INITIALIZER;
int server_socket;
volatile int running = 1; /* for controller clean up and running */
struct network_topology topology;
#define MESSAGE_QUEUE_TIMEOUT 5 /* 5 seconds timeout for queued messages */
/* ---------------------------------------------------- FLOW TABLE ------------------------------------------------- */
/* add a new flow entry */
bool add_flow_entry(struct switch_info *sw, uint64_t dpid, uint16_t in_port, uint8_t *dst_mac, uint16_t out_port) {
log_msg(sw, "DEBUG: Adding new flow to switch flow table with dpid %016" PRIx64 " in_port %u dst_mac %02x:%02x:%02x:%02x:%02x:%02x out_port %u\n",
dpid, in_port, dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5], out_port);
//log_msg(sw, "MUTEX: Locking flow table\n");
pthread_mutex_lock(&sw->flow_table_lock);
/* first check if the flow already exists */
for (int i = 0; i < sw->num_flows; i++) {
if (sw->flow_table[i].active &&
sw->flow_table[i].switch_dpid == dpid &&
sw->flow_table[i].in_port == in_port &&
memcmp(sw->flow_table[i].dst_mac, dst_mac, MAC_ADDR_LEN) == 0 &&
sw->flow_table[i].out_port == out_port) {
/* flow exists, update timestamp */
sw->flow_table[i].install_time = time(NULL);
log_msg(sw, "DEBUG: Flow already exists, updating timestamp\n");
pthread_mutex_unlock(&sw->flow_table_lock);
// log_msg(sw, "MUTEX: Unlocked flow table\n");
return false; /* flow wasn't newly added */
}
}
/* check if we have room for a new flow */
if (sw->num_flows >= MAX_FLOWS) {
log_msg(NULL, "ERROR: Flow table full, cannot add new flow\n");
pthread_mutex_unlock(&sw->flow_table_lock);
// log_msg(sw, "MUTEX: Unlocked flow table\n");
return false;
}
/* add new flow */
sw->flow_table[sw->num_flows].switch_dpid = dpid;
sw->flow_table[sw->num_flows].in_port = in_port;
memcpy(sw->flow_table[sw->num_flows].dst_mac, dst_mac, MAC_ADDR_LEN);
sw->flow_table[sw->num_flows].out_port = out_port;
sw->flow_table[sw->num_flows].install_time = time(NULL);
sw->flow_table[sw->num_flows].active = true;
sw->num_flows++;
log_msg(sw, "DEBUG: Added new flow to switch flow table\n");
pthread_mutex_unlock(&sw->flow_table_lock);
// log_msg(sw, "MUTEX: Unlocked flow table\n");
return true; /* new flow was added */
}
/* check if a flow exists */
bool flow_exists(struct switch_info * sw, uint64_t dpid, uint16_t in_port, uint8_t *dst_mac, uint16_t out_port) {
bool exists = false;
// log_msg(sw, "MUTEX: Locking flow table\n");
pthread_mutex_lock(&sw->flow_table_lock);
for (int i = 0; i < sw->num_flows; i++) {
if (sw->flow_table[i].active &&
sw->flow_table[i].switch_dpid == dpid &&
sw->flow_table[i].in_port == in_port &&
memcmp(sw->flow_table[i].dst_mac, dst_mac, MAC_ADDR_LEN) == 0 &&
sw->flow_table[i].out_port == out_port) {
exists = true;
break;
}
}
/* exit with existance of flow */
pthread_mutex_unlock(&sw->flow_table_lock);
// log_msg(sw, "MUTEX: Unlocked flow table\n");
return exists;
}
/* -------------------------------------------------- PORT VALIDATION ---------------------------------------------- */
/* check if a port number is valid */
bool is_valid_port(uint16_t port_no) {
/* Check that it's a valid physical port or special port */
if (port_no < OFPP_MAX) {
return true;
}
/* check if it's a valid special port */
switch (port_no) {
case OFPP_IN_PORT:
case OFPP_TABLE:
case OFPP_NORMAL:
case OFPP_FLOOD:
case OFPP_ALL:
case OFPP_CONTROLLER:
case OFPP_LOCAL:
return true;
default:
return false;
}
}
/*
* Determines if a port is a trunk port by checking if it's part of any link
* between switches in the topology.
*/
bool is_trunk_port(struct switch_info * sw, uint64_t dpid, uint16_t port_no) {
/* a port is a trunk port if it appears in any edge in the topology graph */
// log_msg(sw, "MUTEX: Locking topology\n");
pthread_mutex_lock(&topology.lock);
for (igraph_integer_t i = 0; i < igraph_ecount(&topology.graph); i++) {
uint64_t src_dpid = (uint64_t)EAN(&topology.graph, "src_dpid", i);
uint64_t dst_dpid = (uint64_t)EAN(&topology.graph, "dst_dpid", i);
uint16_t src_port = (uint16_t)EAN(&topology.graph, "src_port", i);
uint16_t dst_port = (uint16_t)EAN(&topology.graph, "dst_port", i);
/* if this port is used in this edge, it's a trunk port */
if ((src_dpid == dpid && src_port == port_no) ||
(dst_dpid == dpid && dst_port == port_no)) {
pthread_mutex_unlock(&topology.lock);
// log_msg(sw, "MUTEX: Unlocked topology\n");
return true;
}
}
pthread_mutex_unlock(&topology.lock);
// log_msg(sw, "MUTEX: Unlocked topology\n");
return false;
}
/* ---------------------------------------------------- MAC TABLE -------------------------------------------------- */
/* lock for the MAC table */
struct mac_entry *mac_table = NULL;
pthread_mutex_t mac_table_lock = PTHREAD_MUTEX_INITIALIZER;
/* add or update an entry */
void add_or_update_mac(struct switch_info *sw, uint8_t *mac, uint64_t dpid, uint16_t port_no, bool is_infrastructure) {
/* first determine if this port is a trunk port */
bool is_trunk = is_trunk_port(sw, dpid, port_no);
log_msg(sw, "DEBUG: Adding or updating MAC %02x:%02x:%02x:%02x:%02x:%02x from switch %016" PRIx64 " port %d (is_trunk=%d, is_infrastructure=%d)\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], dpid, port_no, is_trunk, is_infrastructure);
pthread_mutex_lock(&mac_table_lock);
struct mac_entry *entry;
/* look up existing entry */
HASH_FIND(hh, mac_table, mac, MAC_ADDR_LEN, entry);
/* no existing entry - always add new entry regardless of trunk status */
if (entry == NULL) {
entry = malloc(sizeof(struct mac_entry));
if (!entry) {
log_msg(sw, "ERROR: Failed to allocate memory for MAC entry\n");
pthread_mutex_unlock(&mac_table_lock);
return;
}
memcpy(entry->mac, mac, MAC_ADDR_LEN);
entry->switch_dpid = dpid;
entry->port_no = port_no;
entry->last_seen = time(NULL);
entry->is_trunk = is_trunk;
entry->is_infrastructure = is_infrastructure;
HASH_ADD(hh, mac_table, mac, MAC_ADDR_LEN, entry);
log_msg(sw, "DEBUG: Added new MAC %02x:%02x:%02x:%02x:%02x:%02x to table for switch %016" PRIx64 " port %d (is_trunk=%d, is_infrastructure=%d)\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], dpid, port_no, is_trunk, is_infrastructure);
}
/* existing entry - need to decide whether to update */
else {
bool should_update = false;
/* never update infrastructure entries with non-infrastructure entries */
if (entry->is_infrastructure && !is_infrastructure) {
log_msg(sw, "DEBUG: Not updating - existing entry is infrastructure, new is not\n");
}
/* for infrastructure entries, always update with newer infrastructure info */
else if (is_infrastructure) {
should_update = true;
log_msg(sw, "DEBUG: Updating with new infrastructure info\n");
}
/* Ffor non-infrastructure entries, use the existing trunk port logic */
else {
/* new info is from non-trunk port (direct connection) */
if (!is_trunk) {
/* Always prefer direct connections */
should_update = true;
log_msg(sw, "DEBUG: Updating MAC with direct connection (old is_trunk=%d, new is_trunk=%d)\n",
entry->is_trunk, is_trunk);
}
/* new info is from trunk port, existing entry is from trunk port */
else if (entry->is_trunk) {
/* update if the existing trunk entry is old or if trunk port has changed */
time_t current_time = time(NULL);
if ((current_time - entry->last_seen > 5) ||
(entry->switch_dpid != dpid || entry->port_no != port_no)) {
should_update = true;
log_msg(sw, "DEBUG: Updating trunk info with newer trunk info (old port=%d, new port=%d)\n",
entry->port_no, port_no);
} else {
log_msg(sw, "DEBUG: Not updating - recent trunk info exists and hasn't changed\n");
}
}
/* new info is from trunk port, existing entry is from non-trunk port */
else {
/* never overwrite direct connection with trunk info */
log_msg(sw, "DEBUG: Not updating - existing direct connection preferred over trunk info\n");
}
}
/* update the entry if our logic determined we should */
if (should_update) {
log_msg(sw, "DEBUG: Updating MAC %02x:%02x:%02x:%02x:%02x:%02x from switch %016" PRIx64 " port %d to switch %016" PRIx64 " port %d\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
entry->switch_dpid, entry->port_no, dpid, port_no);
entry->switch_dpid = dpid;
entry->port_no = port_no;
entry->last_seen = time(NULL);
entry->is_trunk = is_trunk;
/* only update the infrastructure flag if we're explicitly setting it to true */
if (is_infrastructure) {
entry->is_infrastructure = true;
}
}
}
pthread_mutex_unlock(&mac_table_lock);
}
/* find an entry */
struct mac_entry *find_mac(uint8_t *mac) {
// printf("MUTEX: Locking MAC table\n");
pthread_mutex_lock(&mac_table_lock);
struct mac_entry *entry;
HASH_FIND(hh, mac_table, mac, MAC_ADDR_LEN, entry);
printf("DEBUG: MAC lookup for %02x:%02x:%02x:%02x:%02x:%02x: %s\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
entry ? "Found" : "Not found");
if (entry) {
printf("DEBUG: MAC %02x:%02x:%02x:%02x:%02x:%02x is on switch %016" PRIx64 " port %d\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
entry->switch_dpid, entry->port_no);
}
pthread_mutex_unlock(&mac_table_lock);
// printf("MUTEX: Unlocked MAC table\n");
return entry;
}
/* fnction to clean up the MAC table */
void cleanup_mac_table() {
struct mac_entry *current, *tmp;
pthread_mutex_lock(&mac_table_lock);
HASH_ITER(hh, mac_table, current, tmp) {
HASH_DEL(mac_table, current);
free(current);
}
pthread_mutex_unlock(&mac_table_lock);
}
/* remove MAC entries older than MAC_ENTRY_TIMEOUT seconds */
void prune_mac_table() {
struct mac_entry *current, *tmp;
time_t current_time = time(NULL);
pthread_mutex_lock(&mac_table_lock);
HASH_ITER(hh, mac_table, current, tmp) {
/* Skip infrastructure entries which are permanent */
if (!current->is_infrastructure &&
(current_time - current->last_seen > MAC_ENTRY_TIMEOUT)) {
HASH_DEL(mac_table, current);
free(current);
}
}
pthread_mutex_unlock(&mac_table_lock);
}
/* ---------------------------------------------------- HELPERS ---------------------------------------------------- */
/* signal handler */
void signal_handler(int signum) {
printf("\nShutdown signal received, cleaning up...\n");
running = 0;
}
/* thread-safe logging function */
void log_msg(struct switch_info * sw, const char *format, ...) {
va_list args;
va_start(args, format);
pthread_mutex_lock(&switches_lock);
/* get current time with microsecond precision */
struct timeval tv;
gettimeofday(&tv, NULL);
struct tm *tm_info = localtime(&tv.tv_sec);
/* print timestamp in HH:MM:SS.microseconds format */
printf("[%02d:%02d:%02d.%06ld] ",
tm_info->tm_hour,
tm_info->tm_min,
tm_info->tm_sec,
(long)tv.tv_usec);
if (sw) {
printf("> Switch %016" PRIx64 ": ", sw->datapath_id);
}
vprintf(format, args);
fflush(stdout);
pthread_mutex_unlock(&switches_lock);
va_end(args);
}
/* clean up function for threads and and switches*/
void cleanup_switch(struct switch_info *sw) {
/* remove from topology first */
handle_switch_disconnect(sw);
printf("Cleaning up switch %016" PRIx64 " from topology\n", sw->datapath_id);
pthread_mutex_lock(&sw->lock);
if (sw->active) {
sw->active = 0;
close(sw->socket);
/* free port information */
if (sw->ports) {
free(sw->ports);
sw->ports = NULL;
}
sw->num_ports = 0;
sw->hello_received = 0;
sw->features_received = 0;
}
pthread_mutex_unlock(&sw->lock);
/* Ccean up message queue */
pthread_mutex_lock(&sw->queue_lock);
struct pending_message *current = sw->outgoing_queue;
while (current) {
struct pending_message *next = current->next;
free(current->data);
free(current);
current = next;
}
sw->outgoing_queue = NULL;
pthread_mutex_unlock(&sw->queue_lock);
pthread_mutex_destroy(&sw->queue_lock);
/* clean up flow table - properly free all entries */
pthread_mutex_lock(&sw->flow_table_lock);
/* no need to free individual entries since we're freeing the whole table */
free(sw->flow_table);
sw->flow_table = NULL;
sw->num_flows = 0;
pthread_mutex_unlock(&sw->flow_table_lock);
pthread_mutex_destroy(&sw->flow_table_lock);
/* remove this switch's MAC entries */
remove_switch_mac_entries(sw->datapath_id);
}
/* function to remove MAC entries for a specific switch */
void remove_switch_mac_entries(uint64_t dpid) {
struct mac_entry *current, *tmp;
pthread_mutex_lock(&mac_table_lock);
HASH_ITER(hh, mac_table, current, tmp) {
if (current->switch_dpid == dpid) {
HASH_DEL(mac_table, current);
free(current);
}
}
pthread_mutex_unlock(&mac_table_lock);
}
/* ------------------------------------------------------ MAIN ----------------------------------------------------- */
/* main controller function */
int main(int argc, char *argv[]) {
int port = DEF_PORT;
/* handle command line args for port number */
if (argc > 1) {
port = atoi(argv[1]);
}
/* set up signal handling */
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
printf("OpenFlow Controller starting on port %d...\n", port);
/* initialize controller */
init_controller(port);
/* Add periodic maintenance tasks */
time_t last_maintenance = time(NULL);
/* Main loop - wait for shutdown signal or perform maintenance */
while (running) {
time_t now = time(NULL);
/* Perform maintenance every 60 seconds */
if (now - last_maintenance > 60) {
prune_mac_table();
last_maintenance = now;
}
sleep(1);
}
/* Cleanup threads and switches */
int i;
for (i = 0; i < MAX_SWITCHES; i++) {
if (switches[i].active) {
switches[i].active = 0;
close(switches[i].socket);
cleanup_switch(&switches[i]);
}
pthread_mutex_destroy(&switches[i].lock);
}
/* Clean global topology structure */
cleanup_topology();
/* Clean up MAC table */
cleanup_mac_table();
/* Close server socket */
close(server_socket);
/* Destroy global mutex */
pthread_mutex_destroy(&switches_lock);
pthread_mutex_destroy(&mac_table_lock);
return 0;
}
/* initialize controller */
void init_controller(int port) {
printf("Initializing controller\n");
struct sockaddr_in addr;
int i, opt = 1;
/* initialize switch array which will handle info about connected switches */
/* each will have a thread lock for thread safety */
for (i = 0; i < MAX_SWITCHES; i++) {
memset(&switches[i], 0, sizeof(struct switch_info));
pthread_mutex_init(&switches[i].lock, NULL);
/* initialize flow table */
struct flow_entry *flow_table = malloc(MAX_FLOWS * sizeof(struct flow_entry));
memset(flow_table, 0, MAX_FLOWS * sizeof(struct flow_entry));
switches[i].flow_table = flow_table;
pthread_mutex_init(&switches[i].flow_table_lock, NULL);
/* initialize queue lock */
pthread_mutex_init(&switches[i].queue_lock, NULL);
}
/* GLOBAL VARIABLE create a tcp server socket, SOCK_STREAM = TCP */
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
perror("Failed to create socket");
exit(1);
}
printf("Controller socket created\n");
/* set socket options */
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
/* bind to port */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY; /* listen on all interfaces */
addr.sin_port = htons(port); /* default openflow port */
/* associate the socket descriptor we got with the address/port */
if (bind(server_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("Failed to bind");
exit(1);
}
printf("Socket bound successfully to port %d\n", port);
/* listen for connections */
if (listen(server_socket, 5) < 0) {
perror("Failed to listen");
exit(1);
}
/* create the global topology so new sitches can call its functions */
init_topology();
/* create lock for mac table */
pthread_mutex_init(&mac_table_lock, NULL);
printf("MAC table lock initialized\n");
/* start accept thread, creates a thread that listens for new connections
* the handler will create new threads for each new connection
* pass no args to handler */
pthread_t accept_thread;
if (pthread_create(&accept_thread, NULL, accept_handler, NULL) != 0) {
perror("Failed to create accept thread");
exit(1);
}
printf("Controller initialized\n");
}
/* accept incoming switch connections, spawns new threads for each connection */
void *accept_handler(void *arg) {
struct sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
while (running) {
/* accept new connection from the socket created in init_controller */
int client = accept(server_socket, (struct sockaddr *)&addr, &addr_len);
/* set socket to non-blocking */
int flags = fcntl(client, F_GETFL, 0);
fcntl(client, F_SETFL, flags | O_NONBLOCK);
if (client < 0) {
if (errno == EINTR && !running) {
printf("Accept interrupted by shutdown\n");
break;
}
printf("Accept failed with error: %s\n", strerror(errno));
continue;
}
printf("New connection accepted from %s:%d\n",
inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
/* configure TCP socket options for robustness */
int flag = 1;
if (setsockopt(client, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int)) < 0) {
perror("Failed to set TCP_NODELAY");
}
if (setsockopt(client, SOL_SOCKET, SO_KEEPALIVE, &flag, sizeof(int)) < 0) {
perror("Failed to set SO_KEEPALIVE");
}
#ifdef __linux__
/* Linux-specific keepalive parameters */
int idle = 10; /* Start sending keepalive probes after 10 seconds of idle */
if (setsockopt(client, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(int)) < 0) {
perror("Failed to set TCP_KEEPIDLE");
}
int interval = 5; /* Send keepalive probes every 5 seconds */
if (setsockopt(client, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(int)) < 0) {
perror("Failed to set TCP_KEEPINTVL");
}
int count = 3; /* Consider connection dead after 3 failed probes */
if (setsockopt(client, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(int)) < 0) {
perror("Failed to set TCP_KEEPCNT");
}
#endif
#ifdef __APPLE__
/* macOS has different keepalive settings */
/* macOS uses system-wide settings by default */
/* You can use sysctl to check/change system-wide settings */
printf("TCP keepalive enabled (using system defaults for macOS)\n");
#endif
/* find free switch slot */
printf("Finding free switch slot\n");
// printf("MUTEX: Locking switches array\n");
pthread_mutex_lock(&switches_lock);
int i;
for (i = 0; i < MAX_SWITCHES; i++) {
printf("Checking switch slot %d\n", i);
if (!switches[i].active) {
printf("Using switch slot %d\n", i);
switches[i].socket = client;
switches[i].active = 1;
/* create handler thread */
printf("Creating handler thread for switch %d\n", i);
if (pthread_create(&switches[i].thread, NULL, switch_handler, &switches[i]) != 0) {
perror("Failed to create switch handler thread");
close(client);
switches[i].active = 0;
printf("Failed to create handler thread for switch %d\n", i);
} else {
printf("Successfully created handler thread for switch %d\n", i);
}
break;
}
printf("Switch slot %d is active\n", i);
}
pthread_mutex_unlock(&switches_lock);
// printf("MUTEX: Unlocked switches array\n");
if (i == MAX_SWITCHES) {
printf("Maximum number of switches reached, rejecting connection\n");
close(client);
}
}
printf("Accept handler exiting\n");
return NULL;
}
ssize_t read_complete_message(int socket, uint8_t *buffer, size_t max_size) {
struct ofp_header header;
ssize_t total_bytes = 0;
ssize_t bytes_read;
/* first read just the header */
bytes_read = recv(socket, &header, sizeof(header), MSG_PEEK);
if (bytes_read < sizeof(header)) {
return bytes_read;
}
/* determine message length from the header */
uint16_t msg_length = ntohs(header.length);
if (msg_length > max_size) {
return -1; /* too largee */
}
/* now read the complete message */
while (total_bytes < msg_length) {
bytes_read = recv(socket, buffer + total_bytes, msg_length - total_bytes, 0);
if (bytes_read <= 0) {
return bytes_read; /* error or connection closed */
}
total_bytes += bytes_read;
}
return total_bytes;
}
/* handler for each connected switch, manages the lifecycle of a connection */
void *switch_handler(void *arg) {
struct switch_info *sw = (struct switch_info *)arg;
uint8_t buf[OFP_MAX_MSG_SIZE];
ssize_t len;
time_t next_echo = 0;
time_t now;
time_t connection_start = time(NULL);
printf("Switch handler started for new connection\n");
/* initialize switch state */
sw->hello_received = 0;
sw->features_received = 0;
sw->last_echo_xid = 0;
sw->echo_pending = false;
/* initialize message queue */
sw->outgoing_queue = NULL;
/* initialize flow table */
switches->num_flows = 0;
/* start OpenFlow handshake */
send_hello(sw);
/* message handling loop */
while (sw->active && running) {
/* switch while loop */
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
fd_set readfds;
fd_set writefds;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_SET(sw->socket, &readfds);
if (sw->outgoing_queue) {
FD_SET(sw->socket, &writefds);
}
/* pull from the socket */
int ret = select(sw->socket + 1, &readfds,
(sw->outgoing_queue ? &writefds : NULL),
NULL, &tv);
now = time(NULL);
/* ----------------------------------------------- ECHO INTERVAL ------------------------------------------- */
/* handle echo timing independent of message receipt */
/* switch echo processing */
if (sw->features_received && sw->hello_received) {
if (next_echo == 0) {
next_echo = now + ECHO_INTERVAL;
}
if (sw->echo_pending && (now - sw->last_echo) > ECHO_TIMEOUT) {
log_msg(sw, "Connection to switch timed out\n");
sw->echo_pending = false;
cleanup_switch(sw); /* clean up now that connection ended */
log_msg(sw,"Switch cleaned, exiting...\n");
return NULL; /* connection endded */
}
if (!sw->echo_pending && now >= next_echo) {
if (send_echo_request(sw)) {
next_echo = now + ECHO_INTERVAL;
}
}
}
/* ---------------------------------------------- INCOMING MESSAGE ----------------------------------------- */
/* handle incoming messages if any */
if (ret > 0 && FD_ISSET(sw->socket, &readfds)) {
len = read_complete_message(sw->socket, buf, sizeof(buf));
if (len == 0) {
log_msg(sw, "DEBUG: Connection closed cleanly after %ld seconds uptime\n", time(NULL) - connection_start);
break;
} else if (len < 0) {
if (errno == EINTR) {
log_msg(sw, "ERROR: Connection error after %ld seconds uptime\n", time(NULL) - connection_start);
continue;
} else if (errno == ECONNRESET) {
log_msg(sw, "ERROR: Connection reset by switch\n");
} else {
log_msg(sw, "ERROR: Receive error on switch: %s\n", sw->datapath_id, strerror(errno));
}
break;
}
/* process message */
handle_switch_message(sw, buf, len);
}
if (ret > 0 && FD_ISSET(sw->socket, &writefds)) {
process_outgoing_queue(sw);
}
}
log_msg(sw, "Cleaning switch\n");
cleanup_switch(sw);
printf("Switch handler exiting\n");
return NULL;
}
/* ------------------------------------------------- MESSAGE IN/OUT ------------------------------------------------ */
/* handle incoming OpenFlow message, see while loop in switch handler */
void handle_switch_message(struct switch_info *sw, uint8_t *msg, size_t len) {
struct ofp_header *oh = (struct ofp_header *)msg;
/* verify message length */
if (len < sizeof(*oh)) {
printf("Message too short\n");
return;
}
/* handle based on message type */
switch (oh->type) {
case OFPT_HELLO:
handle_hello(sw, oh);
break;
case OFPT_ECHO_REQUEST:
handle_echo_request(sw, oh);
break;
case OFPT_ECHO_REPLY:
handle_echo_reply(sw, oh);
break;
case OFPT_FEATURES_REPLY:
handle_features_reply(sw, (struct ofp_switch_features *)msg);
sw->features_received = 1;
break;
case OFPT_PACKET_IN:
handle_packet_in(sw, (struct ofp_packet_in *)msg);
break;
case OFPT_PORT_STATUS:
handle_port_status(sw, (struct ofp_port_status *)msg);
break;
case OFPT_ERROR:
{
struct ofp_error_msg *err = (struct ofp_error_msg *)msg;
log_msg(sw, "ERROR: Received OpenFlow error from switch: type=%d, code=%d\n",
ntohs(err->type), ntohs(err->code));
if (ntohs(err->type) == OFPET_FLOW_MOD_FAILED) {
log_msg(sw, "ERROR: Flow modification failed: ");
switch(ntohs(err->code)) {
case OFPFMFC_ALL_TABLES_FULL:
log_msg(sw, "All tables full\n");
break;
case OFPFMFC_OVERLAP:
log_msg(sw, "Overlapping entry\n");
break;
case OFPFMFC_EPERM:
log_msg(sw, "Permissions error\n");
break;
case OFPFMFC_BAD_EMERG_TIMEOUT:
log_msg(sw, "Bad emergency timeout\n");
break;
case OFPFMFC_BAD_COMMAND:
log_msg(sw, "Bad command\n");
break;
case OFPFMFC_UNSUPPORTED:
log_msg(sw, "Unsupported action list\n");
break;
default:
log_msg(sw, "Unknown code: %d\n", ntohs(err->code));
}
} else if (ntohs(err->type) == OFPET_BAD_ACTION) {
log_msg(sw, "ERROR: Bad action: ");
switch(ntohs(err->code)) {
case OFPBAC_BAD_TYPE:
log_msg(sw, "Bad action type\n");
break;
case OFPBAC_BAD_LEN:
log_msg(sw, "Bad action length\n");
break;
case OFPBAC_BAD_OUT_PORT:
log_msg(sw, "Bad output port\n");
break;
default:
log_msg(sw, "Other error: %d\n", ntohs(err->code));
}
}
/* Print the first 16 bytes of the error data if available */
size_t data_len = ntohs(oh->length) - sizeof(struct ofp_error_msg);
if (data_len > 0) {
log_msg(sw, "ERROR data (%zu bytes): ", data_len);
for (size_t i = 0; i < data_len && i < 16; i++) {
printf("%02x ", err->data[i]);
}
printf("\n");
}
}
break;
default:
log_msg(sw, "ERROR: Unhandled message type: %d\n", oh->type);
}
}
/* ------------------------------------------------- MESSAGE QUEUE ------------------------------------------------- */
/* Add this to controller.h */
#define MESSAGE_QUEUE_TIMEOUT 5 /* 5 seconds timeout for queued messages */
/* Improve process_outgoing_queue to handle timeouts */
void process_outgoing_queue(struct switch_info *sw) {
pthread_mutex_lock(&sw->queue_lock);
time_t current_time = time(NULL);
struct pending_message *msg = sw->outgoing_queue;
struct pending_message *prev = NULL;
while (msg) {
struct pending_message *next = msg->next;