1 /*
2 * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "dhcp_server.h"
17 #include <arpa/inet.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <net/if.h>
21 #include <netinet/in.h>
22 #include <securec.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/select.h>
28 #include <sys/socket.h>
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include "address_utils.h"
33 #include "common_util.h"
34 #include "dhcp_address_pool.h"
35 #include "dhcp_binding.h"
36 #include "dhcp_config.h"
37 #include "dhcp_ipv4.h"
38 #include "dhcp_logger.h"
39 #include "dhcp_option.h"
40 #include "hash_table.h"
41
42 #undef LOG_TAG
43 #define LOG_TAG "DhcpServer"
44
45 #ifndef DHCP_SEL_WAIT_TIMEOUTS
46 #define DHCP_SEL_WAIT_TIMEOUTS 1000
47 #endif
48 #define OPT_MESSAGE_TYPE_LEGTH 1
49 #define OPT_HEADER_LENGTH 2
50 #define OPT_TIME_LENGTH 4
51 #define OPT_TYPE_FIELD_LENGTH 1
52 #define OPT_MAC_ADDR_LENGTH 6
53 #define MAGIC_COOKIE_LENGTH 4
54 #define OPT_BROADCAST_FLAG_ENABLE 0
55
56 #define OFFER_MIN_INTERVAL_TIME 5
57
58 #define PENDING_DEFAULT_TIMEOUT 1200
59 #define PENDING_DEFAULT_INTERVAL 1
60 #define PENDING_INTERVAL_CHECKING_ENABLE 1
61 #define DHCP_MAGIC_COOKIE 0x63825363
62 #define RECV_BUFFER_SIZE 2048
63 #define ALLOW_NOBINDING_REQUEST 1
64 #define REUSE_ADDRESS_ENABLE 1
65 #define WAIT_STOPED_TIME 5
66
67 const uint8_t MAGIC_COOKIE_DATA[MAGIC_COOKIE_LENGTH] = {0x63, 0x82, 0x53, 0x63}; // Vendor Information "Magic Cookie"
68
69 enum AssignedNumbers {
70 ETHERNET = 1, // Ethernet (10Mb)
71 EXPERIMENTAL_ETHERNET, // Experimental Ethernet (3Mb)
72 AMATEUR_RADIO_AX_25, // Amateur Radio AX.25
73 PROTEON_PRONET_TOKEN_RING, // Proteon ProNET Token Ring
74 CHAOS,
75 IEEE802_NETWORKS,
76 ARCNET,
77 HYPERCHANNEL,
78 LANSTAR
79 };
80
81 struct ServerContext {
82 int broadCastFlagEnable;
83 DhcpAddressPool addressPool;
84 DhcpServerCallback callback;
85 DhcpConfig config;
86 int serverFd;
87 int looperState;
88 int initialized;
89 };
90
91 enum LooperState {
92 LS_IDLE = 0,
93 LS_STARING,
94 LS_RUNNING,
95 LS_RELOADNG,
96 LS_STOPING,
97 LS_STOPED
98 };
99 typedef struct sockaddr_in sockaddr_in;
100 int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply);
101 static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply);
102 static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply);
103 static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply);
104 static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply);
105 static int OnReceivedInform(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply);
106 static int SendDhcpOffer(PDhcpServerContext ctx, PDhcpMsgInfo reply);
107 static int SendDhcpAck(PDhcpServerContext ctx, PDhcpMsgInfo reply);
108 static int SendDhcpNak(PDhcpServerContext ctx, PDhcpMsgInfo reply);
109 static int ParseMessageOptions(PDhcpMsgInfo msg);
110
111 static int ParseReplyOptions(PDhcpMsgInfo reply);
112 struct sockaddr_in *BroadcastAddrIn(void);
113
GetServerInstance(const DhcpServerContext * ctx)114 static struct ServerContext *GetServerInstance(const DhcpServerContext *ctx)
115 {
116 if (!ctx || !ctx->instance) {
117 return NULL;
118 }
119 return (struct ServerContext *)ctx->instance;
120 }
121
HasFixSocket(int fd)122 int HasFixSocket(int fd)
123 {
124 int flags;
125 if ((flags = fcntl(fd, F_GETFL)) == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
126 return DHCP_FALSE;
127 }
128 return DHCP_TRUE;
129 }
130
131 typedef struct ifreq ifreq;
132 typedef struct sockaddr sockaddr;
133
BindNetInterface(int fd,const char * ifname)134 int BindNetInterface(int fd, const char *ifname)
135 {
136 if (!fd || !ifname) {
137 return RET_FAILED;
138 }
139 ifreq iface;
140 if (memset_s(&iface, sizeof(iface), 0, sizeof(iface)) != EOK) {
141 return RET_FAILED;
142 }
143 if (ifname) {
144 ssize_t ifnameSize = strlen(ifname);
145 if (strncpy_s(iface.ifr_ifrn.ifrn_name, sizeof(iface.ifr_ifrn.ifrn_name), ifname, ifnameSize) != EOK) {
146 return RET_FAILED;
147 };
148 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&iface, sizeof(iface)) == -1) {
149 LOGE("failed to bind network device interface[%s].", ifname);
150 return RET_FAILED;
151 }
152 } else {
153 LOGW("no interface specified.");
154 }
155 return RET_SUCCESS;
156 }
157
InitServer(const char * ifname)158 int InitServer(const char *ifname)
159 {
160 sockaddr_in srvAddrIn = {0};
161 int optval = 1;
162 int optrval = 0;
163 srvAddrIn.sin_family = AF_INET;
164 srvAddrIn.sin_port = htons(DHCP_SERVER_PORT);
165 srvAddrIn.sin_addr.s_addr = INADDR_ANY;
166 int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
167 if (fd == -1) {
168 LOGE("failed to create server socket!");
169 return -1;
170 }
171 if (!HasFixSocket(fd)) {
172 LOGD("failed to fcntl O_NONBLOCK flag!");
173 }
174 if (BindNetInterface(fd, ifname) != RET_SUCCESS) {
175 close(fd);
176 return -1;
177 }
178 socklen_t optlen = sizeof(optrval);
179 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&optrval, &optlen) == -1) {
180 LOGD("failed to receive buffer size.");
181 } else {
182 LOGD("receive buffer size is %d", optrval);
183 }
184 if (REUSE_ADDRESS_ENABLE && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1) {
185 LOGW("failed to setsockopt 'SO_REUSEADDR' for server socket!");
186 }
187 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) == -1) {
188 LOGE("failed to setsockopt 'SO_BROADCAST' for server socket!");
189 close(fd);
190 return -1;
191 }
192 if (bind(fd, (sockaddr *)&srvAddrIn, sizeof(sockaddr)) == -1) {
193 LOGE("failed to bind server!");
194 close(fd);
195 return -1;
196 }
197 return fd;
198 }
199
BroadcastAddrIn(void)200 struct sockaddr_in *BroadcastAddrIn(void)
201 {
202 static struct sockaddr_in broadcastAddrIn = {0};
203 if (broadcastAddrIn.sin_port == 0) {
204 broadcastAddrIn.sin_port = htons(DHCP_CLIENT_PORT);
205 broadcastAddrIn.sin_family = AF_INET;
206 broadcastAddrIn.sin_addr.s_addr = INADDR_BROADCAST;
207 }
208 return &broadcastAddrIn;
209 }
210
SourceAddrIn(void)211 struct sockaddr_in *SourceAddrIn(void)
212 {
213 static struct sockaddr_in sourceAddrIn = {0};
214 sourceAddrIn.sin_port = htons(DHCP_CLIENT_PORT);
215 sourceAddrIn.sin_family = AF_INET;
216 sourceAddrIn.sin_addr.s_addr = INADDR_ANY;
217 return &sourceAddrIn;
218 }
219
ResetSourceAddr(void)220 struct sockaddr_in *ResetSourceAddr(void)
221 {
222 struct sockaddr_in *srcAddr = SourceAddrIn();
223 srcAddr->sin_port = htons(DHCP_CLIENT_PORT);
224 srcAddr->sin_family = AF_INET;
225 srcAddr->sin_addr.s_addr = INADDR_ANY;
226 return srcAddr;
227 }
228
SourceIpAddress(void)229 uint32_t SourceIpAddress(void)
230 {
231 uint32_t srcIp = SourceAddrIn()->sin_addr.s_addr;
232 return srcIp;
233 }
DestinationAddrIn(void)234 struct sockaddr_in *DestinationAddrIn(void)
235 {
236 static struct sockaddr_in destAddrIn = {0};
237 if (destAddrIn.sin_port == 0) {
238 destAddrIn.sin_port = htons(DHCP_CLIENT_PORT);
239 destAddrIn.sin_family = AF_INET;
240 }
241 return &destAddrIn;
242 }
243
DestinationAddr(uint32_t ipAddress)244 struct sockaddr_in *DestinationAddr(uint32_t ipAddress)
245 {
246 struct sockaddr_in *destAddr = DestinationAddrIn();
247 destAddr->sin_addr.s_addr = htonl(ipAddress);
248 return destAddr;
249 }
250
ReceiveDhcpMessage(int sock,PDhcpMsgInfo msgInfo)251 int ReceiveDhcpMessage(int sock, PDhcpMsgInfo msgInfo)
252 {
253 static uint8_t recvBuffer[RECV_BUFFER_SIZE] = {0};
254 struct timeval tmt;
255 fd_set recvFd;
256 FD_ZERO(&recvFd);
257 FD_SET(sock, &recvFd);
258 time_t seconds = DHCP_SEL_WAIT_TIMEOUTS;
259 tmt.tv_sec = seconds;
260 tmt.tv_usec = 0;
261 if (select(sock + 1, &recvFd, NULL, NULL, &tmt) < 0) {
262 LOGE("select error, %d", errno);
263 return ERR_SELECT;
264 }
265 if (!FD_ISSET(sock, &recvFd)) {
266 LOGE("failed to select isset.");
267 return RET_ERROR;
268 }
269 socklen_t ssize = sizeof(sockaddr_in);
270 struct sockaddr_in *srcAddrIn = ResetSourceAddr();
271 srcAddrIn->sin_addr.s_addr = INADDR_ANY;
272 int rsize = recvfrom(sock, recvBuffer, RECV_BUFFER_SIZE, 0, (struct sockaddr *)srcAddrIn, (socklen_t *)&ssize);
273 if (!rsize) {
274 LOGE("receive error, %d", errno);
275 return RET_FAILED;
276 }
277 if (rsize > (int)sizeof(DhcpMessage) || rsize < DHCP_MSG_HEADER_SIZE) {
278 LOGW("message length error, received %d bytes.", rsize);
279 return RET_FAILED;
280 }
281 msgInfo->length = rsize;
282 if (memcpy_s(&msgInfo->packet, sizeof(DhcpMessage), recvBuffer, rsize) != EOK) {
283 return RET_FAILED;
284 }
285 if (msgInfo->packet.op != BOOTREQUEST) {
286 LOGW("dhcp message type error!");
287 return RET_FAILED;
288 }
289 if (msgInfo->packet.hlen > DHCP_HWADDR_LENGTH) {
290 LOGW("hlen error!");
291 return RET_FAILED;
292 }
293 if (IsEmptyHWAddr(msgInfo->packet.chaddr)) {
294 LOGW("client hardware address error!");
295 return RET_FAILED;
296 }
297 if (IsReserved(msgInfo->packet.chaddr)) {
298 LOGD("ignore client, %s", ParseLogMac(msgInfo->packet.chaddr));
299 return RET_FAILED;
300 }
301 return RET_SUCCESS;
302 }
303
InitReply(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)304 void InitReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
305 {
306 if (!reply) {
307 LOGE("reply message pointer is null!");
308 return;
309 }
310 reply->packet.op = BOOTREPLY;
311 reply->packet.htype = ETHERNET;
312 reply->packet.hlen = OPT_MAC_ADDR_LENGTH;
313 reply->packet.secs = 0;
314 reply->packet.ciaddr = 0;
315 if (memset_s(reply->packet.sname, sizeof(reply->packet.sname), '\0', sizeof(reply->packet.sname)) != EOK) {
316 LOGE("failed to reset message packet[sname]!");
317 return;
318 };
319 if (memset_s(reply->packet.file, sizeof(reply->packet.file), '\0', sizeof(reply->packet.file)) != EOK) {
320 LOGE("failed to reset message packet[file]!");
321 return;
322 }
323
324 if (FillReply(ctx, received, reply) != RET_SUCCESS) {
325 LOGW("failed to fill reply message.");
326 }
327 }
328
OnUpdateServerConfig(PDhcpServerContext ctx)329 void OnUpdateServerConfig(PDhcpServerContext ctx)
330 {
331 LOGD("OnUpdateServerConfig ...");
332 ServerContext *srvIns = GetServerInstance(ctx);
333 if (!srvIns) {
334 LOGE("dhcp server context pointer is null.");
335 return;
336 }
337 if (srvIns->callback) {
338 srvIns->callback(ST_RELOADNG, 0, ctx->ifname);
339 }
340 }
341
OnServerStoping(PDhcpServerContext ctx)342 static void OnServerStoping(PDhcpServerContext ctx)
343 {
344 LOGD("server stopping ...");
345 ServerContext *srvIns = GetServerInstance(ctx);
346 if (!srvIns) {
347 LOGE("dhcp server context pointer is null.");
348 return;
349 }
350 if (srvIns->callback) {
351 srvIns->callback(ST_STOPING, 0, ctx->ifname);
352 }
353 }
354
OnServerStoped(PDhcpServerContext ctx,int code)355 void OnServerStoped(PDhcpServerContext ctx, int code)
356 {
357 LOGD("OnServerStoped.");
358 ServerContext *srvIns = GetServerInstance(ctx);
359 if (!srvIns) {
360 LOGE("dhcp server context pointer is null.");
361 return;
362 }
363 if (srvIns->callback) {
364 srvIns->callback(ST_STOPED, code, ctx->ifname);
365 }
366 }
367
SendDhcpReply(PDhcpServerContext ctx,int replyType,PDhcpMsgInfo reply)368 int SendDhcpReply(PDhcpServerContext ctx, int replyType, PDhcpMsgInfo reply)
369 {
370 if (!reply) {
371 LOGE("reply message pointer is null.");
372 return RET_FAILED;
373 }
374 int sendRet = -1;
375 ServerContext *srvIns = GetServerInstance(ctx);
376 if (!srvIns) {
377 LOGE("dhcp server context pointer is null.");
378 return RET_FAILED;
379 }
380 switch (replyType) {
381 case REPLY_OFFER:
382 LOGD("<== send reply dhcp offer.");
383 sendRet = SendDhcpOffer(ctx, reply);
384 break;
385 case REPLY_ACK:
386 LOGD("<== send reply dhcp ack.");
387 sendRet = SendDhcpAck(ctx, reply);
388 break;
389 case REPLY_NAK:
390 LOGD("<== send reply dhcp nak.");
391 sendRet = SendDhcpNak(ctx, reply);
392 break;
393 default:
394 break;
395 }
396 if (replyType && sendRet != RET_SUCCESS) {
397 return RET_FAILED;
398 }
399 return RET_SUCCESS;
400 }
401
MessageProcess(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)402 static int MessageProcess(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
403 {
404 int replyType = REPLY_NONE;
405 if (!received) {
406 return replyType;
407 }
408 PDhcpOption opt = GetOption(&received->options, DHCP_MESSAGE_TYPE_OPTION);
409 if (!opt) {
410 LOGE("error dhcp message, missing required message type option.");
411 return replyType;
412 }
413 uint8_t messageType = opt->data[0];
414 switch (messageType) {
415 case DHCPDISCOVER: {
416 LOGD("==> Received DHCPDISCOVER message.");
417 replyType = OnReceivedDiscover(ctx, received, reply);
418 break;
419 }
420 case DHCPREQUEST: {
421 LOGD("==> Received DHCPREQUEST message.");
422 replyType = OnReceivedRequest(ctx, received, reply);
423 break;
424 }
425 case DHCPDECLINE: {
426 LOGD("==> Received DHCPDECLINE message.");
427 replyType = OnReceivedDecline(ctx, received, reply);
428 break;
429 }
430 case DHCPRELEASE: {
431 LOGD("==> Received DHCPRELEASE message.");
432 replyType = OnReceivedRelease(ctx, received, reply);
433 break;
434 }
435 case DHCPINFORM: {
436 LOGD("==> Received DHCPINFORM message.");
437 replyType = OnReceivedInform(ctx, received, reply);
438 break;
439 }
440 default:
441 break;
442 }
443 return replyType;
444 }
445
SaveLease(PDhcpServerContext ctx)446 int SaveLease(PDhcpServerContext ctx)
447 {
448 ServerContext *srvIns = GetServerInstance(ctx);
449 if (!srvIns) {
450 LOGE("dhcp server context pointer is null.");
451 return RET_FAILED;
452 }
453 int saveRet = SaveBindingRecoders(&srvIns->addressPool, 1);
454 if (saveRet == RET_FAILED) {
455 LOGD("failed to save lease recoders. total: %zu", srvIns->addressPool.leaseTable.size);
456 } else if (saveRet == RET_SUCCESS) {
457 LOGD("lease recoders saved.");
458 }
459 return saveRet;
460 }
461
OnLooperStateChanged(PDhcpServerContext ctx)462 static int OnLooperStateChanged(PDhcpServerContext ctx)
463 {
464 ServerContext *srvIns = GetServerInstance(ctx);
465 if (!srvIns) {
466 LOGE("dhcp server context pointer is null.");
467 return RET_FAILED;
468 }
469
470 if (srvIns->looperState == LS_RELOADNG) {
471 OnUpdateServerConfig(ctx);
472 srvIns->looperState = LS_RUNNING;
473 } else if (srvIns->looperState == LS_STOPING) {
474 OnServerStoping(ctx);
475 return RET_BREAK;
476 }
477 return RET_SUCCESS;
478 }
479
ContinueReceive(PDhcpMsgInfo from,int recvRet)480 static int ContinueReceive(PDhcpMsgInfo from, int recvRet)
481 {
482 if (!from) {
483 return DHCP_TRUE;
484 }
485 if (recvRet != RET_SUCCESS) {
486 return DHCP_TRUE;
487 }
488 size_t recLength = from->length;
489 LOGD("received, length:%zu", recLength);
490 if (ParseMessageOptions(from) != 0) {
491 LOGE("invalid dhcp message.");
492 return DHCP_TRUE;
493 }
494 if (!GetOption(&from->options, DHCP_MESSAGE_TYPE_OPTION)) {
495 LOGW("can't found 'message type' option.");
496 return DHCP_TRUE;
497 }
498 return DHCP_FALSE;
499 }
500
BeginLooper(PDhcpServerContext ctx)501 static int BeginLooper(PDhcpServerContext ctx)
502 {
503 DhcpMsgInfo from = { 0 };
504 DhcpMsgInfo reply = { 0 };
505 ServerContext *srvIns = GetServerInstance(ctx);
506 if (!srvIns) {
507 LOGE("dhcp server context pointer is null.");
508 return RET_FAILED;
509 }
510 ctx->instance->serverFd = InitServer(ctx->ifname);
511 if (ctx->instance->serverFd < 0) {
512 LOGE("failed to initialize server socket.");
513 return RET_FAILED;
514 }
515 InitOptionList(&from.options);
516 InitOptionList(&reply.options);
517 srvIns->looperState = LS_RUNNING;
518 while (srvIns->looperState) {
519 if (OnLooperStateChanged(ctx) != RET_SUCCESS) {
520 break;
521 }
522 ClearOptions(&from.options);
523 ClearOptions(&reply.options);
524 int recvRet = ReceiveDhcpMessage(ctx->instance->serverFd, &from);
525 if (recvRet == RET_ERROR || recvRet == ERR_SELECT) {
526 break;
527 }
528 if (ContinueReceive(&from, recvRet)) {
529 continue;
530 }
531 InitReply(ctx, &from, &reply);
532 int replyType = MessageProcess(ctx, &from, &reply);
533 if (replyType && SendDhcpReply(ctx, replyType, &reply) != RET_SUCCESS) {
534 LOGE("failed to send reply message.");
535 }
536 if (replyType == REPLY_ACK || replyType == REPLY_OFFER) {
537 int saveRet = SaveBindingRecoders(&srvIns->addressPool, 0);
538 if (saveRet != RET_SUCCESS && saveRet != RET_WAIT_SAVE) {
539 LOGW("failed to save lease recoders.");
540 }
541 }
542 }
543 FreeOptionList(&from.options);
544 FreeOptionList(&reply.options);
545 LOGD("dhcp server message looper stopped.");
546 close(ctx->instance->serverFd);
547 ctx->instance->serverFd = -1;
548 srvIns->looperState = LS_STOPED;
549 return 0;
550 }
551
CheckAddressRange(DhcpAddressPool * pool)552 static int CheckAddressRange(DhcpAddressPool *pool)
553 {
554 uint32_t serverNetwork = NetworkAddress(pool->serverId, pool->netmask);
555 uint32_t firstNetwork = NetworkAddress(pool->addressRange.beginAddress, pool->netmask);
556 uint32_t secondNetwork = NetworkAddress(pool->addressRange.endAddress, pool->netmask);
557 if (!serverNetwork || !firstNetwork || !secondNetwork) {
558 LOGE("network config error.");
559 return DHCP_FALSE;
560 }
561 if (serverNetwork != firstNetwork || serverNetwork != secondNetwork) {
562 LOGE("server network and address pool network belong to different networks.");
563 return DHCP_FALSE;
564 }
565 return DHCP_TRUE;
566 }
567
InitBindingRecoders(DhcpAddressPool * pool)568 void InitBindingRecoders(DhcpAddressPool *pool)
569 {
570 if (!pool) {
571 LOGE("address pool pointer is null.");
572 return;
573 }
574 HashTable *table = &pool->leaseTable;
575 if (!Initialized(table)) {
576 LOGE("pool does not init.");
577 return;
578 }
579 uint32_t realLeaseTotal = 0;
580 for (size_t current = 0; current < table->capacity; ++current) {
581 HashNode *node = table->nodes[current];
582 int invalidBindig;
583 while (node) {
584 HashNode *next = node->next;
585 AddressBinding *binding = (AddressBinding*)node->value;
586 if (binding && !IsEmptyHWAddr(binding->chaddr) && binding->ipAddress) {
587 AddBinding(binding);
588 realLeaseTotal++;
589 invalidBindig = 0;
590 } else {
591 LOGE("bad binding recoder.");
592 invalidBindig = 1;
593 }
594 if (!invalidBindig && binding && pool->distribution < binding->ipAddress) {
595 pool->distribution = binding->ipAddress;
596 }
597 node = next;
598 }
599 }
600 LOGD("lease recoder total: %u", realLeaseTotal);
601 }
602
InitLeaseFile(DhcpAddressPool * pool)603 void InitLeaseFile(DhcpAddressPool *pool)
604 {
605 const char *leasePath = GetFilePath(DHCPD_LEASE_FILE);
606 if (!leasePath || strlen(leasePath) == 0) {
607 LOGE("failed to get lease file path.");
608 return;
609 }
610 if (access(leasePath, 0) != 0) {
611 LOGD("lease file path does not exist.");
612 if (!CreatePath(leasePath)) {
613 LOGE("failed to create lease file directory.");
614 return;
615 } else {
616 LOGD("lease file directory created.");
617 }
618 }
619 if (LoadBindingRecoders(pool) != RET_SUCCESS) {
620 LOGW("failed to load lease recoders.");
621 }
622 InitBindingRecoders(pool);
623 }
624
ExitProcess(void)625 static void ExitProcess(void)
626 {
627 LOGD("dhcp server stopped.");
628 sleep(1);
629 }
630
StartDhcpServer(PDhcpServerContext ctx)631 int StartDhcpServer(PDhcpServerContext ctx)
632 {
633 LOGD("dhcp server starting ...");
634 if (!ctx) {
635 LOGE("server context pointer is null.");
636 return RET_FAILED;
637 }
638 if (strlen(ctx->ifname) == 0) {
639 LOGE("context interface is null or empty.");
640 return RET_FAILED;
641 }
642 ServerContext *srvIns = GetServerInstance(ctx);
643 if (!srvIns) {
644 LOGE("dhcp server context instance pointer is null.");
645 return RET_FAILED;
646 }
647 if (atexit(ExitProcess) != 0) {
648 LOGW("failed to regiester exit process function.");
649 }
650 if (!srvIns->initialized) {
651 LOGE("dhcp server no initialized.");
652 return RET_FAILED;
653 }
654 LOGD("bind interface: %s", ctx->ifname);
655 LOGI("begin dhcp message looper");
656 if (srvIns->callback) {
657 srvIns->callback(ST_STARTING, 1, ctx->ifname);
658 }
659 int ret = BeginLooper(ctx);
660 if (ret != RET_SUCCESS) {
661 LOGD("failed to start dhcp server.");
662 OnServerStoped(ctx, ret);
663 return RET_FAILED;
664 }
665 OnServerStoped(ctx, ret);
666 return RET_SUCCESS;
667 }
668
StopDhcpServer(PDhcpServerContext ctx)669 int StopDhcpServer(PDhcpServerContext ctx)
670 {
671 ServerContext *srvIns = GetServerInstance(ctx);
672 if (!srvIns) {
673 return RET_FAILED;
674 }
675 srvIns->looperState = LS_STOPING;
676 return RET_SUCCESS;
677 }
678
GetServerStatus(PDhcpServerContext ctx)679 int GetServerStatus(PDhcpServerContext ctx)
680 {
681 ServerContext *srvIns = GetServerInstance(ctx);
682 if (!srvIns) {
683 LOGE("dhcp server context pointer is null.");
684 return -1;
685 }
686 return srvIns->looperState;
687 }
688
FillReply(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)689 int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
690 {
691 if (!received || !reply) {
692 return RET_ERROR;
693 }
694 ServerContext *srvIns = GetServerInstance(ctx);
695 if (!srvIns) {
696 LOGE("dhcp server context pointer is null.");
697 return RET_FAILED;
698 }
699 if (received->packet.ciaddr && received->packet.ciaddr != INADDR_BROADCAST) {
700 reply->packet.ciaddr = received->packet.ciaddr;
701 }
702 if (received->packet.flags) {
703 reply->packet.flags = received->packet.flags;
704 }
705 if (received->packet.xid) {
706 reply->packet.xid = received->packet.xid;
707 }
708 if (received->packet.siaddr && received->packet.siaddr != INADDR_BROADCAST) {
709 reply->packet.siaddr = received->packet.siaddr;
710 } else {
711 reply->packet.siaddr = srvIns->addressPool.serverId;
712 }
713 if (received->packet.giaddr && received->packet.giaddr != INADDR_BROADCAST) {
714 reply->packet.giaddr = received->packet.giaddr;
715 } else {
716 if (srvIns->addressPool.gateway) {
717 reply->packet.giaddr = srvIns->addressPool.gateway;
718 }
719 }
720 if (received->packet.hlen) {
721 reply->packet.hlen = received->packet.hlen;
722 LOGD("fill reply - chaddr:%s", ParseLogMac(received->packet.chaddr));
723 if (memset_s(reply->packet.chaddr, sizeof(reply->packet.chaddr), 0, sizeof(reply->packet.chaddr)) != EOK) {
724 LOGE("failed to reset message packet[chaddr]!");
725 return RET_ERROR;
726 }
727 if (memcpy_s(reply->packet.chaddr, sizeof(reply->packet.chaddr),
728 received->packet.chaddr, sizeof(received->packet.chaddr)) != EOK) {
729 LOGE("failed to copy message packet[chaddr]!");
730 return RET_ERROR;
731 }
732 }
733 if (received->packet.giaddr) {
734 reply->packet.giaddr = received->packet.giaddr;
735 }
736 return 0;
737 }
738
AppendReplyTimeOptions(PDhcpServerContext ctx,PDhcpOptionList options)739 int AppendReplyTimeOptions(PDhcpServerContext ctx, PDhcpOptionList options)
740 {
741 if (!ctx || !options) {
742 LOGE("server context or options pointer is null.");
743 return RET_FAILED;
744 }
745 ServerContext *srvIns = GetServerInstance(ctx);
746 if (!srvIns) {
747 LOGE("dhcp server context pointer is null.");
748 return RET_FAILED;
749 }
750 uint32_t leaseTime = HostToNetwork(DHCP_LEASE_TIME);
751 if (srvIns->addressPool.leaseTime) {
752 leaseTime = HostToNetwork(srvIns->addressPool.leaseTime);
753 }
754 DhcpOption optLeaseTime = {IP_ADDRESS_LEASE_TIME_OPTION, OPT_TIME_LENGTH, {0}};
755 FillU32Option(&optLeaseTime, leaseTime);
756 PushBackOption(options, &optLeaseTime);
757
758 uint32_t t1Time = HostToNetwork(DHCP_RENEWAL_TIME);
759 if (srvIns->addressPool.renewalTime) {
760 t1Time = HostToNetwork(srvIns->addressPool.renewalTime);
761 }
762 DhcpOption optRenewTime = {RENEWAL_TIME_VALUE_OPTION, OPT_TIME_LENGTH, {0}};
763 FillU32Option(&optLeaseTime, t1Time);
764 PushBackOption(options, &optRenewTime);
765
766 uint32_t t2Time = HostToNetwork(DHCP_REBINDING_TIME);
767 if (srvIns->addressPool.rebindingTime) {
768 t2Time = HostToNetwork(srvIns->addressPool.rebindingTime);
769 }
770 DhcpOption optRebindTime = {REBINDING_TIME_VALUE_OPTION, OPT_TIME_LENGTH, {0}};
771 FillU32Option(&optRebindTime, t2Time);
772 PushBackOption(options, &optRebindTime);
773
774 return RET_SUCCESS;
775 }
776
Repending(DhcpAddressPool * pool,AddressBinding * binding)777 static int Repending(DhcpAddressPool *pool, AddressBinding *binding)
778 {
779 if (!pool) {
780 return REPLY_NONE;
781 }
782 uint32_t bindingIp = binding->ipAddress;
783 LOGD(" binding found, bindIp:%s", ParseStrIp(bindingIp));
784 binding->pendingInterval = NextPendingInterval(binding->pendingInterval);
785 uint64_t tms = Tmspsec() - binding->pendingTime;
786 if (tms < binding->pendingInterval) {
787 binding->pendingTime = Tmspsec();
788 LOGW("message interval is too short, ignore the message.");
789 return REPLY_NONE;
790 }
791 binding->pendingTime = Tmspsec();
792 binding->pendingInterval = 0;
793 binding->bindingStatus = BIND_PENDING;
794 uint32_t srcIp = SourceIpAddress();
795 if (srcIp && srcIp != INADDR_BROADCAST && bindingIp != INADDR_BROADCAST && srcIp != bindingIp) {
796 LOGW("source ip address and bound ip address inconsistency.");
797 return REPLY_NAK;
798 }
799 if (srcIp && srcIp == bindingIp) {
800 if (!ContainsKey(&pool->leaseTable, (uintptr_t)&srcIp)) {
801 LOGD("can't find lease information.");
802 if (Insert(&pool->leaseTable, (uintptr_t)&srcIp, (uintptr_t)binding) != HASH_INSERTED) {
803 LOGE("failed to insert lease information.");
804 }
805 } else {
806 if (Insert(&pool->leaseTable, (uintptr_t)&srcIp, (uintptr_t)binding) != HASH_UPDATED) {
807 LOGE("failed to update lease information.");
808 }
809 }
810 }
811 return REPLY_OFFER;
812 }
813
Rebinding(DhcpAddressPool * pool,AddressBinding * binding)814 static int Rebinding(DhcpAddressPool *pool, AddressBinding *binding)
815 {
816 uint64_t pendingTime = binding->pendingTime;
817 int replyType = Repending(pool, binding);
818 binding->bindingStatus = BIND_ASSOCIATED;
819 if (!binding->leaseTime) {
820 binding->leaseTime = pool->leaseTime;
821 }
822 binding->bindingTime = Tmspsec();
823 binding->expireIn = binding->bindingTime + binding->leaseTime;
824 binding->pendingTime = pendingTime;
825 if (replyType == REPLY_OFFER) {
826 replyType = REPLY_ACK;
827 }
828 return replyType;
829 }
830
AddAddressOption(PDhcpMsgInfo reply,uint8_t code,int32_t address)831 static void AddAddressOption(PDhcpMsgInfo reply, uint8_t code, int32_t address)
832 {
833 if (!reply) {
834 return;
835 }
836 DhcpOption optAddress = {0, 0, {0}};
837 optAddress.code = code;
838 if (AppendAddressOption(&optAddress, address) != RET_SUCCESS) {
839 LOGE("failed to append address option.");
840 return;
841 };
842 PushBackOption(&reply->options, &optAddress);
843 }
844
AddReplyServerIdOption(PDhcpOptionList options,uint32_t serverId)845 int AddReplyServerIdOption(PDhcpOptionList options, uint32_t serverId)
846 {
847 if (!options) {
848 LOGE("option list pointer is null.");
849 return RET_FAILED;
850 }
851 if (!serverId || serverId == INADDR_BROADCAST) {
852 LOGE("servier id error.");
853 return RET_FAILED;
854 }
855 DhcpOption optSrvId = {SERVER_IDENTIFIER_OPTION, 0, {0}};
856 if (AppendAddressOption(&optSrvId, serverId) != RET_SUCCESS) {
857 LOGE("failed to append server id option.");
858 return RET_FAILED;
859 }
860 if (GetOption(options, SERVER_IDENTIFIER_OPTION)) {
861 LOGD("server identifier option exists.");
862 return RET_SUCCESS;
863 }
864 PushBackOption(options, &optSrvId);
865 return RET_SUCCESS;
866 }
867
AddReplyMessageTypeOption(PDhcpMsgInfo reply,uint8_t replyMessageType)868 static void AddReplyMessageTypeOption(PDhcpMsgInfo reply, uint8_t replyMessageType)
869 {
870 if (!reply) {
871 return;
872 }
873 DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {replyMessageType, 0}};
874 PushBackOption(&reply->options, &optMsgType);
875 }
876
877
GetBinding(DhcpAddressPool * pool,PDhcpMsgInfo received)878 AddressBinding *GetBinding(DhcpAddressPool *pool, PDhcpMsgInfo received)
879 {
880 if (!pool) {
881 return NULL;
882 }
883 if (!received) {
884 return NULL;
885 }
886 AddressBinding *binding = pool->binding(received->packet.chaddr, &received->options);
887 if (!binding) {
888 binding = pool->newBinding(received->packet.chaddr, &received->options);
889 if (binding == NULL) {
890 LOGE("new binding is null");
891 return NULL;
892 }
893 if (pool->leaseTime) {
894 binding->leaseTime = pool->leaseTime;
895 }
896 binding->ipAddress = pool->distribue(pool, received->packet.chaddr);
897 LOGD("new binding ip");
898 } else {
899 LOGD("rebinding ip");
900 }
901 return binding;
902 }
903
OnReceivedDiscover(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)904 static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
905 {
906 if (!received || !reply) {
907 return REPLY_NONE;
908 }
909 LOGI("received 'Discover' message from: %s", ParseLogMac(received->packet.chaddr));
910 ServerContext *srvIns = GetServerInstance(ctx);
911 if (!srvIns) {
912 return REPLY_NONE;
913 }
914 uint32_t reqIp = 0;
915 PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION);
916 if (optReqIp) {
917 reqIp = ParseIp(optReqIp->data);
918 if (reqIp) {
919 LOGD(" request ip: %s", ParseStrIp(reqIp));
920 }
921 }
922 uint32_t srcIp = SourceIpAddress();
923 if (!srvIns->broadCastFlagEnable) {
924 if (srcIp) {
925 LOGD(" client repending:%s", ParseStrIp(srcIp));
926 } else {
927 srcIp = INADDR_BROADCAST;
928 }
929 DestinationAddr(srcIp);
930 }
931 AddressBinding *binding = GetBinding(&srvIns->addressPool, received);
932 if (!binding) {
933 return REPLY_NONE;
934 }
935 if (!binding->ipAddress) {
936 LOGE("no ip address available.");
937 return REPLY_NONE;
938 }
939 if (reqIp != 0 && reqIp != binding->ipAddress) {
940 LOGE("error request message.");
941 return REPLY_NONE;
942 }
943 AddressBinding *lease = GetLease(&srvIns->addressPool, binding->ipAddress);
944 if (!lease) {
945 LOGD("add lease recoder.");
946 AddLease(&srvIns->addressPool, binding);
947 lease = GetLease(&srvIns->addressPool, binding->ipAddress);
948 }
949 if (!lease) {
950 return REPLY_NONE;
951 }
952 AddReplyMessageTypeOption(reply, DHCPOFFER);
953 reply->packet.yiaddr = lease->ipAddress;
954 return REPLY_OFFER;
955 }
956
957
GetRequestIpAddress(PDhcpMsgInfo received)958 static uint32_t GetRequestIpAddress(PDhcpMsgInfo received)
959 {
960 uint32_t reqIp = 0;
961 if (!received) {
962 return reqIp;
963 }
964 PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION);
965 if (optReqIp) {
966 reqIp = ParseIp(optReqIp->data);
967 }
968 return reqIp;
969 }
970
GetYourIpAddress(PDhcpMsgInfo received,uint32_t * yourIpAddr)971 static int GetYourIpAddress(PDhcpMsgInfo received, uint32_t *yourIpAddr)
972 {
973 uint32_t cliIp = received->packet.ciaddr;
974 uint32_t srcIp = SourceIpAddress();
975 uint32_t reqIp = GetRequestIpAddress(received);
976 if (cliIp && srcIp && cliIp != srcIp) {
977 LOGE("error dhcp request message, missing required request option.");
978 return RET_FAILED;
979 }
980 if (reqIp && srcIp && reqIp != srcIp) {
981 LOGE("error dhcp request message, request ip error.");
982 return RET_FAILED;
983 }
984 if (cliIp && reqIp && cliIp != reqIp) {
985 LOGE("error dhcp request message, client ip error.");
986 return RET_FAILED;
987 }
988
989 if (srcIp && srcIp != INADDR_BROADCAST) {
990 *yourIpAddr = srcIp;
991 } else if (cliIp && cliIp != INADDR_BROADCAST) {
992 *yourIpAddr = cliIp;
993 } else if (reqIp && reqIp != INADDR_BROADCAST) {
994 *yourIpAddr = reqIp;
995 }
996
997 if (srcIp && srcIp != INADDR_BROADCAST) {
998 DestinationAddr(srcIp);
999 } else if (srcIp == INADDR_ANY) {
1000 DestinationAddr(INADDR_BROADCAST);
1001 }
1002 return RET_SUCCESS;
1003 }
1004
NotBindingRequest(DhcpAddressPool * pool,PDhcpMsgInfo received,PDhcpMsgInfo reply)1005 static int NotBindingRequest(DhcpAddressPool *pool, PDhcpMsgInfo received, PDhcpMsgInfo reply)
1006 {
1007 uint32_t yourIpAddr = 0;
1008 if (GetYourIpAddress(received, &yourIpAddr) != RET_SUCCESS) {
1009 return REPLY_NONE;
1010 }
1011 AddressBinding *lease = GetLease(pool, yourIpAddr);
1012 if (!lease) {
1013 if (SourceIpAddress()) {
1014 return REPLY_ACK;
1015 }
1016 return REPLY_NONE;
1017 }
1018 int sameAddr = AddrEquels(lease->chaddr, received->packet.chaddr, MAC_ADDR_LENGTH);
1019 if (lease->bindingStatus == BIND_ASSOCIATED && !sameAddr) {
1020 if (!IsExpire(lease)) {
1021 return REPLY_NAK;
1022 }
1023 RemoveLease(pool, lease);
1024 }
1025 AddressBinding *binding = pool->newBinding(received->packet.chaddr, &received->options);
1026 if (binding == NULL) {
1027 LOGE("Not binding request binding is null.");
1028 return REPLY_NONE;
1029 }
1030 binding->ipAddress = yourIpAddr;
1031 if (pool->leaseTime) {
1032 binding->leaseTime = pool->leaseTime;
1033 }
1034 int replyType = Repending(pool, binding);
1035 if (replyType != REPLY_OFFER) {
1036 return replyType;
1037 }
1038 lease = GetLease(pool, yourIpAddr);
1039 if (!lease) {
1040 LOGD("add new lease recoder.");
1041 AddLease(pool, binding);
1042 lease = GetLease(pool, binding->ipAddress);
1043 }
1044 if (!lease) {
1045 LOGD("failed to get lease.");
1046 return REPLY_NONE;
1047 }
1048 lease->bindingStatus = BIND_ASSOCIATED;
1049 lease->bindingTime = Tmspsec();
1050 lease->expireIn = lease->bindingTime + binding->leaseTime;
1051 reply->packet.yiaddr = lease->ipAddress;
1052 return REPLY_ACK;
1053 }
1054
ValidateRequestMessage(const PDhcpServerContext ctx,const PDhcpMsgInfo received,PDhcpMsgInfo reply,uint32_t * yourIp)1055 static int ValidateRequestMessage(const PDhcpServerContext ctx, const PDhcpMsgInfo received,
1056 PDhcpMsgInfo reply, uint32_t *yourIp)
1057 {
1058 if (!received || !reply) {
1059 return REPLY_NONE;
1060 }
1061 LOGI("received 'Request' message from: %s.", ParseLogMac(received->packet.chaddr));
1062 uint32_t yourIpAddr = INADDR_BROADCAST;
1063 ServerContext *srvIns = GetServerInstance(ctx);
1064 if (!srvIns) {
1065 return RET_FAILED;
1066 }
1067 if (GetYourIpAddress(received, &yourIpAddr) != RET_SUCCESS) {
1068 if (yourIpAddr && yourIpAddr != INADDR_BROADCAST) {
1069 return REPLY_NAK;
1070 }
1071 return REPLY_NONE;
1072 }
1073 PDhcpOption optReqSrvId = GetOption(&received->options, SERVER_IDENTIFIER_OPTION);
1074 if (optReqSrvId) {
1075 uint32_t reqSrvId = ParseIp(optReqSrvId->data);
1076 LOGD(" reuquest server id is:%s", ParseStrIp(reqSrvId));
1077 if (reqSrvId != srvIns->addressPool.serverId) {
1078 LOGW("other dhcp server process.");
1079 return REPLY_NONE;
1080 }
1081 } else {
1082 LOGW("request message not specified server identifier option.");
1083 }
1084 *yourIp = yourIpAddr;
1085 return REPLY_ACK;
1086 }
1087
HasNobindgRequest(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)1088 static int HasNobindgRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
1089 {
1090 if (!received || !reply) {
1091 LOGE("receive or reply message pointer is null.");
1092 return REPLY_NONE;
1093 }
1094 ServerContext *srvIns = GetServerInstance(ctx);
1095 if (!srvIns) {
1096 LOGE("dhcp server context pointer is null.");
1097 return REPLY_NONE;
1098 }
1099 AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options);
1100 if (!binding && ALLOW_NOBINDING_REQUEST) {
1101 LOGE("client not binding.");
1102 uint32_t srcIp = SourceIpAddress();
1103 uint32_t reqIp = GetRequestIpAddress(received);
1104 LOGD("allow no binding request mode.");
1105 if (reqIp == 0 && srcIp == 0) {
1106 LOGE("error dhcp message.");
1107 return REPLY_NONE;
1108 }
1109 if (!IpInNetwork(reqIp, srvIns->addressPool.serverId, srvIns->addressPool.netmask)) {
1110 LOGE("error request ip.");
1111 return REPLY_NAK;
1112 }
1113 return NotBindingRequest(&srvIns->addressPool, received, reply);
1114 }
1115 return REPLY_NONE;
1116 }
1117
OnReceivedRequest(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)1118 static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
1119 {
1120 int ret;
1121 uint32_t yourIpAddr;
1122 if ((ret = ValidateRequestMessage(ctx, received, reply, &yourIpAddr)) != REPLY_ACK) {
1123 return ret;
1124 }
1125 ServerContext *srvIns = GetServerInstance(ctx);
1126 if (srvIns == NULL) {
1127 LOGE("OnReceivedRequest, srvIns is null");
1128 return REPLY_NONE;
1129 }
1130 AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options);
1131 if (binding == NULL) {
1132 LOGE("OnReceivedRequest, binding is null");
1133 return HasNobindgRequest(ctx, received, reply);
1134 }
1135 Rebinding(&srvIns->addressPool, binding);
1136 AddressBinding *lease = GetLease(&srvIns->addressPool, yourIpAddr);
1137 if (lease) {
1138 int sameAddr = AddrEquels(lease->chaddr, received->packet.chaddr, MAC_ADDR_LENGTH);
1139 if (!sameAddr && !IsExpire(lease)) {
1140 LOGW("invalid request ip address.");
1141 return REPLY_NAK;
1142 }
1143 if (!sameAddr && IsExpire(lease)) {
1144 if (memcpy_s(lease->chaddr, DHCP_HWADDR_LENGTH, binding->chaddr, MAC_ADDR_LENGTH) != EOK) {
1145 LOGW("failed to update lease client address.");
1146 }
1147 }
1148 lease->bindingStatus = BIND_ASSOCIATED;
1149 lease->bindingTime = binding->bindingTime;
1150 lease->expireIn = binding->expireIn;
1151 } else {
1152 LOGW("can not found lease recoder.");
1153 }
1154 uint32_t bindingIp = binding->ipAddress;
1155 if (bindingIp && yourIpAddr != INADDR_BROADCAST && yourIpAddr != bindingIp) {
1156 LOGE("error request ip binding.");
1157 return REPLY_NAK;
1158 }
1159 AddAddressOption(reply, SUBNET_MASK_OPTION, srvIns->addressPool.netmask);
1160 if (srvIns->addressPool.gateway) {
1161 AddAddressOption(reply, ROUTER_OPTION, srvIns->addressPool.gateway);
1162 }
1163 reply->packet.yiaddr = bindingIp;
1164 return REPLY_ACK;
1165 }
1166
OnReceivedDecline(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)1167 static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
1168 {
1169 if (!received || !reply) {
1170 return REPLY_NONE;
1171 }
1172 ServerContext *srvIns = GetServerInstance(ctx);
1173 if (!srvIns) {
1174 return REPLY_NONE;
1175 }
1176 LOGI("received 'Decline' message from: %s.", ParseLogMac(received->packet.chaddr));
1177 uint32_t reqIp = 0;
1178 PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION);
1179 if (optReqIp) {
1180 reqIp = ParseIp(optReqIp->data);
1181 }
1182 if (!reqIp) {
1183 LOGD("invalid request ip address.");
1184 return REPLY_NONE;
1185 }
1186 AddressBinding* binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options);
1187 if (!binding) {
1188 LOGD("client not binding.");
1189 return REPLY_NONE;
1190 }
1191 if (binding->ipAddress != reqIp) {
1192 LOGD("invalid request ip address.");
1193 return REPLY_NONE;
1194 }
1195 if (ContainsKey(&srvIns->addressPool.leaseTable, (uintptr_t)&binding->ipAddress)) {
1196 AddressBinding *lease = GetBindingByIp(&srvIns->addressPool.leaseTable, binding->ipAddress);
1197 if (lease) {
1198 lease->bindingStatus = BIND_MODE_RESERVED;
1199 lease->expireIn = Tmspsec() + lease->leaseTime;
1200 } else {
1201 LOGE("failed to get lease info.");
1202 }
1203 }
1204 RemoveBinding(received->packet.chaddr);
1205 return REPLY_NONE;
1206 }
1207
OnReceivedRelease(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)1208 static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
1209 {
1210 if (!received || !reply) {
1211 return REPLY_NONE;
1212 }
1213 LOGI("received 'Release' message from: %s", ParseLogMac(received->packet.chaddr));
1214 if (!ctx || !ctx->instance) {
1215 return RET_FAILED;
1216 }
1217 PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION);
1218 if (!optReqIp) {
1219 LOGW("missing required request option.");
1220 }
1221 ServerContext *srvIns = GetServerInstance(ctx);
1222 if (!srvIns) {
1223 LOGE("dhcp server context pointer is null.");
1224 return RET_FAILED;
1225 }
1226 AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options);
1227 if (!binding) {
1228 LOGD("client not binding.");
1229 return REPLY_NONE;
1230 }
1231 uint32_t bindIp = binding->ipAddress;
1232 uint32_t reqIp = 0;
1233 if (optReqIp) {
1234 reqIp = ParseIp(optReqIp->data);
1235 }
1236 uint32_t srcIp = SourceIpAddress();
1237 if (srcIp != 0 && reqIp != 0 && reqIp != srcIp) {
1238 LOGE("error release message, invalid request ip address.");
1239 return REPLY_NONE;
1240 }
1241 if (bindIp != 0 && reqIp != 0 && reqIp != bindIp) {
1242 LOGE("error release message, invalid request ip address.");
1243 return REPLY_NONE;
1244 }
1245 AddressBinding *lease = GetLease(&srvIns->addressPool, bindIp);
1246 if (lease) {
1247 RemoveLease(&srvIns->addressPool, lease);
1248 LOGD("lease recoder has been removed.");
1249 } else {
1250 LOGW("can't found lease recoder.");
1251 }
1252
1253 if (ReleaseBinding(received->packet.chaddr) != RET_SUCCESS) {
1254 LOGW("failed to release client[%s] bind.", ParseLogMac(received->packet.chaddr));
1255 }
1256 LOGD("client released.");
1257 return REPLY_NONE;
1258 }
1259
OnReceivedInform(PDhcpServerContext ctx,PDhcpMsgInfo received,PDhcpMsgInfo reply)1260 static int OnReceivedInform(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply)
1261 {
1262 if (!received || !reply) {
1263 return REPLY_NONE;
1264 }
1265 ServerContext *srvIns = GetServerInstance(ctx);
1266 if (!srvIns) {
1267 LOGE("dhcp server context pointer is null.");
1268 return RET_FAILED;
1269 }
1270 LOGI("received 'Inform' message from: %s", ParseLogMac(received->packet.chaddr));
1271 if (IsEmptyHWAddr(received->packet.chaddr)) {
1272 LOGD("error dhcp 'Inform' message.");
1273 }
1274 return REPLY_ACK;
1275 }
1276
AppendFixedOptions(PDhcpServerContext ctx,PDhcpMsgInfo reply)1277 static int AppendFixedOptions(PDhcpServerContext ctx, PDhcpMsgInfo reply)
1278 {
1279 ServerContext *srvIns = GetServerInstance(ctx);
1280 if (!srvIns) {
1281 return RET_FAILED;
1282 }
1283 if (!reply) {
1284 return RET_FAILED;
1285 }
1286 if (srvIns->addressPool.fixedOptions.size > 0) {
1287 DhcpOptionNode *pNode = srvIns->addressPool.fixedOptions.first->next;
1288 for (size_t i = 0; pNode != NULL && i < srvIns->addressPool.fixedOptions.size; i++) {
1289 PDhcpOption opt = NULL;
1290 if (pNode->option.code) {
1291 opt = GetOption(&reply->options, pNode->option.code);
1292 }
1293 if (opt == NULL) {
1294 PushBackOption(&reply->options, &pNode->option);
1295 }
1296 pNode = pNode->next;
1297 }
1298 }
1299 return RET_SUCCESS;
1300 }
AppendReplyTypeOption(PDhcpMsgInfo reply,int replyType)1301 int AppendReplyTypeOption(PDhcpMsgInfo reply, int replyType)
1302 {
1303 if (!reply) {
1304 return RET_FAILED;
1305 }
1306 if (!replyType) {
1307 return RET_FAILED;
1308 }
1309 uint8_t msgType = 0;
1310 switch (replyType) {
1311 case REPLY_OFFER:
1312 msgType = DHCPOFFER;
1313 break;
1314 case REPLY_ACK:
1315 msgType = DHCPACK;
1316 break;
1317 case REPLY_NAK:
1318 msgType = DHCPNAK;
1319 break;
1320 default:
1321 break;
1322 }
1323 PDhcpOption pOptMsgType = GetOption(&reply->options, DHCP_MESSAGE_TYPE_OPTION);
1324 if (!pOptMsgType) {
1325 LOGD("append message type option for reply message, type:%hhu", msgType);
1326 DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {msgType, 0}};
1327 PushFrontOption(&reply->options, &optMsgType);
1328 } else {
1329 if (pOptMsgType->data[0] != msgType) {
1330 LOGD("error dhcp nak message type.");
1331 return RET_FAILED;
1332 }
1333 }
1334 return RET_SUCCESS;
1335 }
1336
SendDhcpOffer(PDhcpServerContext ctx,PDhcpMsgInfo reply)1337 static int SendDhcpOffer(PDhcpServerContext ctx, PDhcpMsgInfo reply)
1338 {
1339 ServerContext *srvIns = GetServerInstance(ctx);
1340 if (!srvIns) {
1341 return RET_FAILED;
1342 }
1343 if (AppendReplyTypeOption(reply, REPLY_OFFER) != RET_SUCCESS) {
1344 return RET_FAILED;
1345 }
1346 if (AppendReplyTimeOptions(ctx, &reply->options) != RET_SUCCESS ||
1347 AddReplyServerIdOption(&reply->options, srvIns->addressPool.serverId) != RET_SUCCESS) {
1348 return RET_FAILED;
1349 }
1350 if (AppendFixedOptions(ctx, reply) != RET_SUCCESS) {
1351 LOGW("failed to append fixed reply options.");
1352 }
1353 if (ParseReplyOptions(reply) != RET_SUCCESS) {
1354 LOGE("failed to parse reply options.");
1355 return RET_FAILED;
1356 }
1357 int ret;
1358 struct sockaddr_in *bcastAddrIn = BroadcastAddrIn();
1359 struct sockaddr_in *destAddrIn = DestinationAddrIn();
1360 if (srvIns->broadCastFlagEnable == 1 && destAddrIn) {
1361 int broadCastFlag = 1;
1362 if (reply->packet.flags && (reply->packet.flags >> (DHCP_MESSAGE_FLAG_LENGTH - 1)) == 0) {
1363 broadCastFlag = 0;
1364 }
1365 if (!broadCastFlag && destAddrIn->sin_addr.s_addr) {
1366 ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)destAddrIn,
1367 sizeof(*destAddrIn));
1368 } else {
1369 ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)bcastAddrIn,
1370 sizeof(*bcastAddrIn));
1371 }
1372 } else {
1373 ret = sendto(
1374 srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)bcastAddrIn, sizeof(*bcastAddrIn));
1375 }
1376 if (!ret) {
1377 LOGD("failed to send dhcp offer message.");
1378 return RET_FAILED;
1379 }
1380 LOGI(" send reply offer, length:%d", reply->length);
1381 return RET_SUCCESS;
1382 }
1383
SendDhcpAck(PDhcpServerContext ctx,PDhcpMsgInfo reply)1384 static int SendDhcpAck(PDhcpServerContext ctx, PDhcpMsgInfo reply)
1385 {
1386 if (AppendReplyTypeOption(reply, REPLY_ACK) != RET_SUCCESS) {
1387 return RET_FAILED;
1388 }
1389 if (AppendFixedOptions(ctx, reply) != RET_SUCCESS) {
1390 LOGW("failed to append fixed reply options.");
1391 }
1392 if (!ctx || !ctx->instance) {
1393 LOGE("dhcp server context pointer is null.");
1394 return RET_FAILED;
1395 }
1396 ServerContext *srvIns = GetServerInstance(ctx);
1397
1398 if (AppendReplyTimeOptions(ctx, &reply->options) != RET_SUCCESS) {
1399 return RET_FAILED;
1400 }
1401 if (AddReplyServerIdOption(&reply->options, srvIns->addressPool.serverId) != RET_SUCCESS) {
1402 return RET_FAILED;
1403 }
1404 if (ParseReplyOptions(reply) != RET_SUCCESS) {
1405 return RET_FAILED;
1406 }
1407 sockaddr_in *destAddrIn = DestinationAddrIn();
1408 int ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)destAddrIn,
1409 sizeof(*destAddrIn));
1410 if (!ret) {
1411 LOGD("failed to send dhcp ack message.");
1412 return RET_FAILED;
1413 }
1414 LOGI(" send reply ack, size:%d", reply->length);
1415 return RET_SUCCESS;
1416 }
1417
SendDhcpNak(PDhcpServerContext ctx,PDhcpMsgInfo reply)1418 static int SendDhcpNak(PDhcpServerContext ctx, PDhcpMsgInfo reply)
1419 {
1420 if (AppendReplyTypeOption(reply, REPLY_NAK) != RET_SUCCESS) {
1421 return RET_FAILED;
1422 }
1423 ServerContext *srvIns = GetServerInstance(ctx);
1424 if (srvIns == NULL) {
1425 LOGE("SendDhcpNak, srvIns is null");
1426 return RET_FAILED;
1427 }
1428 if (ParseReplyOptions(reply) != RET_SUCCESS) {
1429 return RET_FAILED;
1430 }
1431
1432 struct sockaddr_in *destAddrIn = DestinationAddrIn();
1433 int ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)destAddrIn,
1434 sizeof(*destAddrIn));
1435 if (!ret) {
1436 LOGD("failed to send dhcp ack message.");
1437 return RET_FAILED;
1438 }
1439 LOGI(" send reply nak, size:%d", reply->length);
1440 return RET_SUCCESS;
1441 }
1442
ParseMessageOptions(PDhcpMsgInfo msg)1443 static int ParseMessageOptions(PDhcpMsgInfo msg)
1444 {
1445 if (msg->length < (DHCP_MSG_HEADER_SIZE + MAGIC_COOKIE_LENGTH)) {
1446 return RET_FAILED;
1447 }
1448 DhcpOption *current, *end;
1449 current = (DhcpOption *)msg->packet.options;
1450 end = (DhcpOption *)(((uint8_t *)msg->packet.options) + (msg->length - DHCP_MSG_HEADER_SIZE));
1451
1452 if (memcmp(current, MAGIC_COOKIE_DATA, sizeof(MAGIC_COOKIE_DATA)) != 0) {
1453 LOGD("bad magic cookie.");
1454 return RET_FAILED;
1455 }
1456 current = (DhcpOption *)(((uint8_t *)current) + MAGIC_COOKIE_LENGTH);
1457 uint8_t *pos = (((uint8_t *)current) + MAGIC_COOKIE_LENGTH);
1458 uint8_t *maxPos = (((uint8_t *)current) + (DHCP_OPTION_SIZE - MAGIC_COOKIE_LENGTH - OPT_HEADER_LENGTH -1));
1459 int optTotal = 0;
1460 while (current < end && current->code != END_OPTION) {
1461 pos += (OPT_HEADER_LENGTH + current->length);
1462 if (pos >= maxPos) {
1463 LOGD("out of option max pos.");
1464 return RET_FAILED;
1465 }
1466 if (PushBackOption(&msg->options, current) != RET_SUCCESS) {
1467 LOGD("failed to PushOption.");
1468 }
1469 current = (DhcpOption *)(((uint8_t *)current) + OPT_HEADER_LENGTH + current->length);
1470 optTotal++;
1471 }
1472 if (current < end && current->code == END_OPTION) {
1473 LOGD("option list size:%zu xid:%u", msg->options.size, msg->packet.xid);
1474 return RET_SUCCESS;
1475 }
1476
1477 LOGD("option list parse failed.");
1478 return RET_FAILED;
1479 }
1480
ResetMessageOptions(PDhcpMsgInfo reply)1481 static int ResetMessageOptions(PDhcpMsgInfo reply)
1482 {
1483 if (!reply || reply->options.size == 0) {
1484 LOGE("message pointer is null.");
1485 return RET_ERROR;
1486 }
1487 if (memset_s(reply->packet.options, DHCP_OPTIONS_SIZE, 0, DHCP_OPTIONS_SIZE) != EOK) {
1488 LOGE("failed to reset message options!");
1489 return RET_ERROR;
1490 }
1491 return RET_SUCCESS;
1492 }
1493
ValidateReplyOptions(PDhcpMsgInfo reply)1494 static int ValidateReplyOptions(PDhcpMsgInfo reply)
1495 {
1496 if (!reply) {
1497 LOGE("reply message pointer is null.");
1498 return RET_FAILED;
1499 }
1500 int ret = RET_FAILED;
1501 if ((ret = ResetMessageOptions(reply)) != RET_SUCCESS) {
1502 return ret;
1503 }
1504 reply->length = DHCP_MSG_HEADER_SIZE;
1505 PDhcpOptionNode pNode = reply->options.first;
1506 if (!pNode) {
1507 return RET_ERROR;
1508 }
1509 PDhcpOption pOptMsgType = GetOption(&reply->options, DHCP_MESSAGE_TYPE_OPTION);
1510 if (!pOptMsgType) {
1511 LOGE("unknown reply message type.");
1512 return ret;
1513 }
1514 return RET_SUCCESS;
1515 }
1516
ParseReplyOptions(PDhcpMsgInfo reply)1517 static int ParseReplyOptions(PDhcpMsgInfo reply)
1518 {
1519 int ret = RET_FAILED;
1520 if ((ret = ValidateReplyOptions(reply)) != RET_SUCCESS) {
1521 return ret;
1522 }
1523 PDhcpOptionNode pNode = reply->options.first->next;
1524 DhcpOption endOpt = {END_OPTION, 0, {0}};
1525 PushBackOption(&reply->options, &endOpt);
1526 int replyOptsLength = 0;
1527 uint8_t *current = reply->packet.options, olen = MAGIC_COOKIE_LENGTH;
1528 size_t remainingSize = sizeof(reply->packet.options);
1529 uint32_t cookie = htonl(DHCP_MAGIC_COOKIE);
1530 if (memcpy_s(current, remainingSize, &cookie, olen) != EOK) {
1531 LOGE("memcpy cookie out of options buffer!");
1532 return RET_FAILED;
1533 }
1534 replyOptsLength += olen;
1535 remainingSize -= olen;
1536 current += olen;
1537 ret = RET_SUCCESS;
1538 while (pNode && (uint32_t)pNode->option.length < DHCP_OPTION_SIZE) {
1539 if ((uint32_t)pNode->option.code == END_OPTION) {
1540 olen = OPT_HEADER_LENGTH + 1;
1541 } else {
1542 olen = OPT_HEADER_LENGTH + pNode->option.length;
1543 }
1544 if (memcpy_s(current, remainingSize, &pNode->option, olen) != EOK) {
1545 LOGE("memcpy current option out of options buffer!");
1546 ret = RET_FAILED;
1547 break;
1548 }
1549 remainingSize -= olen;
1550 current += olen;
1551 replyOptsLength += olen;
1552 if ((uint32_t)pNode->option.code == END_OPTION) {
1553 break;
1554 }
1555 pNode = pNode->next;
1556 if (replyOptsLength >= DHCP_OPTIONS_SIZE) {
1557 LOGE("current option out of options buffer!");
1558 ret = RET_FAILED;
1559 break;
1560 }
1561 }
1562 reply->length += replyOptsLength;
1563 return ret;
1564 }
1565
RegisterDhcpCallback(PDhcpServerContext ctx,DhcpServerCallback callback)1566 void RegisterDhcpCallback(PDhcpServerContext ctx, DhcpServerCallback callback)
1567 {
1568 LOGI("register server callback.");
1569 ServerContext *srvIns = GetServerInstance(ctx);
1570 if (!srvIns) {
1571 LOGE("dhcp server context pointer is null.");
1572 return;
1573 }
1574 srvIns->callback = callback;
1575 }
1576
InitServerContext(DhcpConfig * config,DhcpServerContext * ctx)1577 static int InitServerContext(DhcpConfig *config, DhcpServerContext *ctx)
1578 {
1579 if (!config) {
1580 LOGE("server configure pointer is null.");
1581 return RET_FAILED;
1582 }
1583 ServerContext *srvIns = GetServerInstance(ctx);
1584 if (!srvIns) {
1585 LOGE("dhcp server context pointer is null.");
1586 return RET_FAILED;
1587 }
1588 if (InitAddressPool(&srvIns->addressPool, config->ifname, NULL) != RET_SUCCESS) {
1589 LOGD("failed to init address pool.");
1590 return RET_FAILED;
1591 }
1592 if (memcpy_s(ctx->ifname, sizeof(ctx->ifname), config->ifname, strlen(config->ifname)) != EOK) {
1593 LOGD("failed to set interface name.");
1594 return RET_FAILED;
1595 }
1596 srvIns->serverFd = 0;
1597 srvIns->callback = 0;
1598 srvIns->looperState = LS_IDLE;
1599 srvIns->broadCastFlagEnable = config->broadcast;
1600 srvIns->addressPool.serverId = config->serverId;
1601 srvIns->addressPool.netmask = config->netmask;
1602 srvIns->addressPool.gateway = config->gateway;
1603 if (config->pool.beginAddress && config->pool.endAddress) {
1604 srvIns->addressPool.addressRange.beginAddress = config->pool.beginAddress;
1605 srvIns->addressPool.addressRange.endAddress = config->pool.endAddress;
1606 } else {
1607 srvIns->addressPool.addressRange.beginAddress = FirstIpAddress(config->serverId, config->netmask);
1608 srvIns->addressPool.addressRange.endAddress = LastIpAddress(config->serverId, config->netmask);
1609 }
1610 if (memcpy_s(srvIns->addressPool.ifname, sizeof(srvIns->addressPool.ifname),
1611 config->ifname, strlen(config->ifname)) != EOK) {
1612 LOGD("failed to set interface name.");
1613 return RET_FAILED;
1614 }
1615 if (!CheckAddressRange(&srvIns->addressPool)) {
1616 LOGE("failed to validate address range.");
1617 return RET_FAILED;
1618 }
1619 InitLeaseFile(&srvIns->addressPool);
1620 return RET_SUCCESS;
1621 }
1622
InitServerFixedOptions(DhcpConfig * config,DhcpServerContext * ctx)1623 int InitServerFixedOptions(DhcpConfig *config, DhcpServerContext *ctx)
1624 {
1625 if (!config) {
1626 LOGE("server configure pointer is null.");
1627 return RET_FAILED;
1628 }
1629 ServerContext *srvIns = GetServerInstance(ctx);
1630 if (!srvIns) {
1631 LOGE("dhcp server context pointer is null.");
1632 return RET_FAILED;
1633 }
1634
1635 if (!HasInitialized(&config->options)) {
1636 LOGE("dhcp configure has not been initialized.");
1637 return RET_FAILED;
1638 }
1639 if (InitOptionList(&srvIns->addressPool.fixedOptions) != RET_SUCCESS) {
1640 return RET_FAILED;
1641 }
1642 if (config->options.first != NULL && config->options.size > 0) {
1643 DhcpOptionNode *pNode = config->options.first->next;
1644 for (size_t i = 0; pNode != NULL && i < config->options.size; i++) {
1645 PushBackOption(&srvIns->addressPool.fixedOptions, &pNode->option);
1646 LOGD("append fixed option ==> %hhu,%d", pNode->option.code,
1647 pNode->option.length);
1648 pNode = pNode->next;
1649 }
1650 }
1651 return RET_SUCCESS;
1652 }
1653
InitializeServer(DhcpConfig * config)1654 PDhcpServerContext InitializeServer(DhcpConfig *config)
1655 {
1656 DhcpServerContext *context = NULL;
1657 if (!config) {
1658 LOGE("dhcp server config pointer is null.");
1659 return NULL;
1660 }
1661 if (strlen(config->ifname) == 0) {
1662 LOGE("can't found interface name config.");
1663 return NULL;
1664 }
1665 if (!config->serverId || !config->netmask) {
1666 LOGE("missing required parameter or config item: \"serverId\", \"netmask\"");
1667 return NULL;
1668 }
1669 if ((context = (DhcpServerContext *)calloc(1, sizeof(DhcpServerContext))) == NULL) {
1670 LOGE("failed to calloc server context.");
1671 return NULL;
1672 }
1673 if ((context->instance = calloc(1, sizeof(ServerContext))) == NULL) {
1674 LOGE("failed to calloc server instance.");
1675 FreeServerContext(&context);
1676 return NULL;
1677 }
1678 if (InitServerContext(config, context) != RET_SUCCESS) {
1679 LOGE("failed initialize dhcp server context.");
1680 FreeServerContext(&context);
1681 return NULL;
1682 }
1683 if (InitServerFixedOptions(config, context) != RET_SUCCESS) {
1684 LOGE("failed initialize dhcp server fixed options.");
1685 FreeServerContext(&context);
1686 return NULL;
1687 }
1688 LOGD("server id: %s", ParseStrIp(config->serverId));
1689 LOGD("netmask: %s", ParseStrIp(config->netmask));
1690 if (config->gateway) {
1691 LOGD("gateway: %s", ParseStrIp(config->gateway));
1692 }
1693 LOGD("address range begin of: %s", ParseStrIp(config->pool.beginAddress));
1694 LOGD("address range end of: %s", ParseStrIp(config->pool.endAddress));
1695 context->instance->initialized = 1;
1696 return context;
1697 }
1698
FreeServerContext(PDhcpServerContext * ctx)1699 int FreeServerContext(PDhcpServerContext *ctx)
1700 {
1701 if (ctx == NULL || *ctx == NULL) {
1702 LOGE("dhcp server context pointer is null.");
1703 return RET_FAILED;
1704 }
1705 ServerContext *srvIns = GetServerInstance(*ctx);
1706 if (!srvIns) {
1707 LOGE("dhcp server instance pointer is null.");
1708 return RET_FAILED;
1709 }
1710 FreeAddressPool(&srvIns->addressPool);
1711 if ((*ctx)->instance != NULL) {
1712 free((*ctx)->instance);
1713 (*ctx)->instance = NULL;
1714 free(*ctx);
1715 *ctx = NULL;
1716 }
1717 return RET_SUCCESS;
1718 }
1719