1 /*
2  * Copyright (c) 2024 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 #include "p2p_v1_processor.h"
16 
17 #include <memory>
18 #include "securec.h"
19 
20 #include "conn_log.h"
21 #include "softbus_adapter_timer.h"
22 #include "softbus_error_code.h"
23 
24 #include "adapter/p2p_adapter.h"
25 #include "channel/auth_negotiate_channel.h"
26 #include "data/interface_manager.h"
27 #include "data/link_manager.h"
28 #include "entity/p2p_entity.h"
29 #include "utils/wifi_direct_anonymous.h"
30 #include "utils/wifi_direct_utils.h"
31 #include "wifi_direct_scheduler_factory.h"
32 #include "wifi_direct_manager.h"
33 
34 namespace OHOS::SoftBus {
35 std::map<std::string, P2pV1Processor::ProcessorState> P2pV1Processor::stateNameMapping = {
36     {"AvailableState",             &P2pV1Processor::AvailableState           },
37     { "WaitingReqResponseState",   &P2pV1Processor::WaitingReqResponseState  },
38     { "WaitingClientJoiningState", &P2pV1Processor::WaitingClientJoiningState},
39     { "WaitingRequestState",       &P2pV1Processor::WaitingRequestState      },
40     { "WaitingReuseResponseState", &P2pV1Processor::WaitingReuseResponseState},
41     { "WaitAuthHandShakeState",    &P2pV1Processor::WaitAuthHandShakeState   },
42     { "NullState",                 nullptr                                   }
43 };
44 
45 // SoftBusErrNo to WifiDirectErrorCode
46 static std::map<int, int> p1ErrorMapping = {
47     {SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE,                     V1_ERROR_IF_NOT_AVAILABLE                   },
48     { SOFTBUS_CONN_PV1_BOTH_GO_ERR,                         V1_ERROR_BOTH_GO                            },
49     { SOFTBUS_CONN_PV1_APPLY_GC_IP_FAIL,                    ERROR_P2P_APPLY_GC_IP_FAIL                  },
50     { SOFTBUS_CONN_PV1_REUSE_FAIL,                          V1_ERROR_REUSE_FAILED                       },
51     { SOFTBUS_CONN_PV1_CONNECT_GROUP_FAIL,                  V1_ERROR_CONNECT_GROUP_FAILED               },
52     { SOFTBUS_CONN_PV1_BUSY_ERR,                            V1_ERROR_BUSY                               },
53     { SOFTBUS_CONN_PV1_PEER_GC_CONNECTED_TO_ANOTHER_DEVICE, V1_ERROR_PEER_GC_CONNECTED_TO_ANOTHER_DEVICE},
54 };
55 
ErrorCodeToV1ProtocolCode(int reason)56 int P2pV1Processor::ErrorCodeToV1ProtocolCode(int reason)
57 {
58     if (p1ErrorMapping.find(reason) != p1ErrorMapping.end()) {
59         auto code = p1ErrorMapping[reason];
60         if (code > V1_ERROR_END && code < V1_ERROR_START) {
61             return code - V1_ERROR_START;
62         }
63         return code;
64     }
65     return reason;
66 }
67 
ErrorCodeFromV1ProtocolCode(int reason)68 int P2pV1Processor::ErrorCodeFromV1ProtocolCode(int reason)
69 {
70     if (reason < 0 && reason > V1_ERROR_END - V1_ERROR_START) {
71         auto code = reason + V1_ERROR_START;
72         for (const auto it : p1ErrorMapping) {
73             if (it.second == code) {
74                 return it.first;
75             }
76         }
77         return code;
78     }
79     return reason;
80 }
81 
P2pV1Processor(const std::string & remoteDeviceId)82 P2pV1Processor::P2pV1Processor(const std::string &remoteDeviceId)
83     : WifiDirectProcessor(remoteDeviceId), state_(&P2pV1Processor::AvailableState), timer_("P2pProcessor", TIMER_TIME),
84     timerId_(Utils::TIMER_ERR_INVALID_VALUE)
85 {
86     CONN_LOGI(CONN_WIFI_DIRECT, "remoteDeviceId=%{public}s", WifiDirectAnonymizeDeviceId(remoteDeviceId_).c_str());
87     timer_.Setup();
88     active_ = false;
89 }
90 
~P2pV1Processor()91 P2pV1Processor::~P2pV1Processor()
92 {
93     CONN_LOGI(CONN_WIFI_DIRECT, "remoteDeviceId=%{public}s", WifiDirectAnonymizeDeviceId(remoteDeviceId_).c_str());
94     StopTimer();
95     timer_.Shutdown();
96     RemoveExclusive();
97     if (hasRun_) {
98         WifiDirectUtils::SerialFlowExit();
99     }
100 }
101 
Run()102 [[noreturn]] void P2pV1Processor::Run()
103 {
104     WifiDirectUtils::SerialFlowEnter();
105     hasRun_ = true;
106     for (;;) {
107         (this->*state_)();
108     }
109 }
110 
CanAcceptNegotiateDataAtState(WifiDirectCommand & command)111 bool P2pV1Processor::CanAcceptNegotiateDataAtState(WifiDirectCommand &command)
112 {
113     if (!canAcceptNegotiateData_) {
114         return false;
115     }
116 
117     auto nc = dynamic_cast<NegotiateCommand *>(&command);
118     if (nc == nullptr) {
119         return false;
120     }
121     return nc->GetNegotiateMessage().GetLegacyP2pCommandType() != LegacyCommandType::CMD_INVALID &&
122         nc->GetNegotiateMessage().GetLegacyP2pCommandType() != LegacyCommandType::CMD_DISCONNECT_V1_REQ;
123 }
124 
HandleCommandAfterTerminate(WifiDirectCommand & command)125 void P2pV1Processor::HandleCommandAfterTerminate(WifiDirectCommand &command)
126 {
127     CONN_LOGI(CONN_WIFI_DIRECT, "enter");
128     auto nc = dynamic_cast<NegotiateCommand *>(&command);
129     if (nc == nullptr) {
130         return;
131     }
132     auto messageType = nc->GetNegotiateMessage().GetLegacyP2pCommandType();
133     CONN_LOGI(CONN_WIFI_DIRECT, "messageType = %{public}d", messageType);
134     std::set<LegacyCommandType> vaildMessageTypes = {
135         LegacyCommandType::CMD_CONN_V1_REQ,
136         LegacyCommandType::CMD_DISCONNECT_V1_REQ,
137         LegacyCommandType::CMD_REUSE_REQ,
138         LegacyCommandType::CMD_FORCE_DISCONNECT_V1_REQ,
139     };
140     if (vaildMessageTypes.find(messageType) == vaildMessageTypes.end()) {
141         return;
142     }
143     WifiDirectSchedulerFactory::GetInstance().GetScheduler().QueueCommandFront(*nc);
144 }
145 
SwitchState(ProcessorState state,int timeoutInMillis)146 void P2pV1Processor::SwitchState(ProcessorState state, int timeoutInMillis)
147 {
148     StartTimer(timeoutInMillis);
149     auto old = state_;
150     state_ = state;
151     CONN_LOGI(CONN_WIFI_DIRECT, "%{public}s => %{public}s", GetStateName(old).c_str(), GetStateName(state).c_str());
152 }
153 
GetStateName(ProcessorState state)154 std::string P2pV1Processor::GetStateName(ProcessorState state)
155 {
156     for (const auto &it : stateNameMapping) {
157         if (it.second == state) {
158             return it.first;
159         }
160     }
161     return "UNKNOWN_STATE";
162 }
163 
AvailableState()164 void P2pV1Processor::AvailableState()
165 {
166     executor_->WaitEvent()
167         .Handle<std::shared_ptr<ConnectCommand>>([this](std::shared_ptr<ConnectCommand> &command) {
168             ProcessConnectCommand(command);
169         })
170         .Handle<std::shared_ptr<DisconnectCommand>>([this](std::shared_ptr<DisconnectCommand> &command) {
171             ProcessDisconnectCommand(command);
172         })
173         .Handle<std::shared_ptr<NegotiateCommand>>([this](std::shared_ptr<NegotiateCommand> &command) {
174             ProcessNegotiateCommandAtAvailableState(command);
175         })
176         .Handle<std::shared_ptr<ForceDisconnectCommand>>([this](std::shared_ptr<ForceDisconnectCommand> &command) {
177             ProcessForceDisconnectCommand(command);
178         });
179 }
180 
WaitingReqResponseState()181 void P2pV1Processor::WaitingReqResponseState()
182 {
183     executor_->WaitEvent()
184         .Handle<std::shared_ptr<NegotiateCommand>>([this](std::shared_ptr<NegotiateCommand> &command) {
185             ProcessNegotiateCommandAtWaitingReqResponseState(command);
186         })
187         .Handle<std::shared_ptr<TimeoutEvent>>([this](std::shared_ptr<TimeoutEvent> &event) {
188             OnWaitReqResponseTimeoutEvent();
189         });
190 }
191 
WaitingClientJoiningState()192 void P2pV1Processor::WaitingClientJoiningState()
193 {
194     executor_->WaitEvent()
195         .Handle<std::shared_ptr<NegotiateCommand>>([this](std::shared_ptr<NegotiateCommand> &command) {
196             ProcessNegotiateCommandAtWaitingClientJoiningState(command);
197         })
198         .Handle<std::shared_ptr<ClientJoinEvent>>([this](std::shared_ptr<ClientJoinEvent> &event) {
199             auto ret = OnClientJoinEvent(event);
200             CleanupIfNeed(ret, event->remoteDeviceId_);
201             if (ret != SOFTBUS_OK) {
202                 if (connectCommand_ != nullptr) {
203                     connectCommand_->OnFailure(ret);
204                     connectCommand_ = nullptr;
205                 }
206                 Terminate();
207             }
208         });
209 }
210 
WaitAuthHandShakeState()211 void P2pV1Processor::WaitAuthHandShakeState()
212 {
213     executor_->WaitEvent()
214         .Handle<std::shared_ptr<NegotiateCommand>>([this](std::shared_ptr<NegotiateCommand> &command) {
215             ProcessNegotiateCommandAtWaitingAuthHandShakeState(command);
216         })
217         .Handle<std::shared_ptr<AuthOpenEvent>>([this](std::shared_ptr<AuthOpenEvent> &event) {
218             ProcessAuthConnEvent(event);
219         })
220         .Handle<std::shared_ptr<TimeoutEvent>>([this](std::shared_ptr<TimeoutEvent> &event) {
221             OnWaitAuthHandShakeTimeoutEvent();
222         });
223 }
224 
WaitingRequestState()225 void P2pV1Processor::WaitingRequestState()
226 {
227     executor_->WaitEvent()
228         .Handle<std::shared_ptr<NegotiateCommand>>([this](std::shared_ptr<NegotiateCommand> &command) {
229             ProcessNegotiateCommandAtWaitingRequestState(command);
230         })
231         .Handle<std::shared_ptr<TimeoutEvent>>([this](std::shared_ptr<TimeoutEvent> &event) {
232             OnWaitRequestTimeoutEvent();
233         });
234 }
235 
WaitingReuseResponseState()236 void P2pV1Processor::WaitingReuseResponseState()
237 {
238     executor_->WaitEvent()
239         .Handle<std::shared_ptr<NegotiateCommand>>([this](std::shared_ptr<NegotiateCommand> &command) {
240             ProcessNegotiateCommandAtWaitingReuseResponseState(command);
241         })
242         .Handle<std::shared_ptr<TimeoutEvent>>([this](std::shared_ptr<TimeoutEvent> &event) {
243             OnWaitReuseResponseTimeoutEvent();
244         });
245 }
246 
ProcessConnectCommand(std::shared_ptr<ConnectCommand> & command)247 void P2pV1Processor::ProcessConnectCommand(std::shared_ptr<ConnectCommand> &command)
248 {
249     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
250     connectCommand_ = command;
251     active_ = true;
252     Exclusive(connectCommand_->GetRemoteDeviceId());
253 
254     auto info = command->GetConnectInfo().info_;
255     auto link = LinkManager::GetInstance().GetReuseLink(info.connectType, command->GetRemoteDeviceId());
256     int ret = SOFTBUS_OK;
257     if (link != nullptr) {
258         ret = ReuseLink(command, *link);
259     } else {
260         ret = CreateLink();
261         CleanupIfNeed(ret, connectCommand_->GetRemoteDeviceId());
262     }
263     if (ret != SOFTBUS_OK) {
264         CONN_LOGE(CONN_WIFI_DIRECT, "connect failed, error=%{public}d", ret);
265         command->OnFailure(ret);
266         Terminate();
267     }
268 }
269 
RemoveLinkFromManager(const std::string & remoteDeviceId,int linkId,size_t & refCnt,std::string & remoteMac)270 static void RemoveLinkFromManager(const std::string &remoteDeviceId, int linkId, size_t &refCnt, std::string &remoteMac)
271 {
272     LinkManager::GetInstance().ProcessIfPresent(
273         InnerLink::LinkType::P2P, remoteDeviceId, [linkId, &refCnt, &remoteMac](InnerLink &link) {
274             if (!link.IsContainId(linkId)) {
275                 return;
276             }
277             refCnt = link.GetReference();
278             link.RemoveId(linkId);
279             remoteMac = link.GetRemoteBaseMac();
280         });
281 }
282 
ProcessDisconnectCommand(std::shared_ptr<DisconnectCommand> & command)283 void P2pV1Processor::ProcessDisconnectCommand(std::shared_ptr<DisconnectCommand> &command)
284 {
285     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
286     Exclusive(command->GetRemoteDeviceId());
287     canAcceptNegotiateData_ = false;
288 
289     auto linkId = command->GetDisconnectInfo().info_.linkId;
290     auto requestId = command->GetDisconnectInfo().info_.requestId;
291     CONN_LOGI(CONN_WIFI_DIRECT, "disconnect device, linkId=%{public}d", linkId);
292     std::string remoteMac;
293     size_t refCnt = 0;
294     RemoveLinkFromManager(command->GetRemoteDeviceId(), linkId, refCnt, remoteMac);
295     if (refCnt == 0 || refCnt > 1) {
296         CONN_LOGI(CONN_WIFI_DIRECT, "link is not exist or ref by others, refCnt=%{public}zu", refCnt);
297         command->OnSuccess();
298         Terminate();
299     }
300     auto ret = SendDisconnectRequest(*command->GetNegotiateChannel());
301     if (ret != SOFTBUS_OK) {
302         CONN_LOGE(CONN_WIFI_DIRECT, "send disconnect request failed, error=%{public}d", ret);
303         command->OnFailure(ret);
304         Terminate();
305     }
306 
307     int reuseCnt = 0;
308     InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&reuseCnt](const InterfaceInfo &interface) {
309         reuseCnt = interface.GetReuseCount();
310         return SOFTBUS_OK;
311     });
312     CONN_LOGI(CONN_WIFI_DIRECT, "requestId=%{public}d, remoteMac=%{public}s, reuseCount=%{public}d", requestId,
313         WifiDirectAnonymizeMac(remoteMac).c_str(), reuseCnt);
314     if (reuseCnt == 0) {
315         CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount already 0");
316         command->OnSuccess();
317         Terminate();
318     }
319 
320     CONN_LOGI(CONN_WIFI_DIRECT, "wait for p2p auth to send data, DISCONNECT_WAIT_POST_REQUEST_MS=%{public}dms",
321         DISCONNECT_WAIT_POST_REQUEST_MS);
322     SoftBusSleepMs(DISCONNECT_WAIT_POST_REQUEST_MS);
323     ret = RemoveLink(command->GetRemoteDeviceId());
324     if (ret != SOFTBUS_OK) {
325         CONN_LOGI(CONN_WIFI_DIRECT, "remove link failed, error=%{public}d", ret);
326         command->OnFailure(ret);
327         Terminate();
328     }
329     CONN_LOGI(CONN_WIFI_DIRECT, "remove link success");
330     command->OnSuccess();
331     Terminate();
332 }
333 
ProcessForceDisconnectCommand(std::shared_ptr<ForceDisconnectCommand> & command)334 void P2pV1Processor::ProcessForceDisconnectCommand(std::shared_ptr<ForceDisconnectCommand> &command)
335 {
336     Exclusive(command->GetRemoteDeviceId());
337     canAcceptNegotiateData_ = false;
338     auto info = command->GetDisconnectInfo();
339     auto requestId = info.info_.requestId;
340     CONN_LOGI(CONN_WIFI_DIRECT, "force disconnect device, requestId=%{public}d commandId=%{public}d", requestId,
341         command->GetId());
342 
343     auto innerLink = LinkManager::GetInstance().GetReuseLink(info.info_.linkType, info.info_.remoteUuid);
344     if (innerLink == nullptr) {
345         CONN_LOGI(CONN_WIFI_DIRECT, "link is already not exist");
346         command->OnSuccess();
347         Terminate();
348     }
349 
350     auto ret = SendForceDisconnectRequest(*command->GetNegotiateChannel());
351     CONN_LOGE(CONN_WIFI_DIRECT, "send force disconnect request, ret=%{public}d", ret);
352     if (ret == SOFTBUS_OK) {
353         CONN_LOGI(
354             CONN_WIFI_DIRECT, "wait for p2p auth to send data, sleep%{public}dms", DISCONNECT_WAIT_POST_REQUEST_MS);
355         SoftBusSleepMs(DISCONNECT_WAIT_POST_REQUEST_MS);
356     }
357 
358     LinkManager::GetInstance().RemoveLink(InnerLink::LinkType::P2P, remoteDeviceId_);
359     DestroyGroup();
360 
361     command->OnSuccess();
362     Terminate();
363 }
364 
ProcessNegotiateCommandAtAvailableState(std::shared_ptr<NegotiateCommand> & command)365 void P2pV1Processor::ProcessNegotiateCommandAtAvailableState(std::shared_ptr<NegotiateCommand> &command)
366 {
367     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
368     Exclusive(command->GetRemoteDeviceId());
369 
370     bool reply = true;
371     bool terminate = false;
372     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
373     int32_t ret = SOFTBUS_CONN_PV1_INTERNAL_ERR0R;
374     switch (msgType) {
375         case LegacyCommandType::CMD_CONN_V1_REQ:
376             ret = ProcessConnectRequest(command);
377             CleanupIfNeed(ret, command->GetRemoteDeviceId());
378             break;
379         case LegacyCommandType::CMD_REUSE_REQ:
380             terminate = true;
381             ret = ProcessReuseRequest(command);
382             CleanupIfNeed(ret, command->GetRemoteDeviceId());
383             break;
384         case LegacyCommandType::CMD_DISCONNECT_V1_REQ:
385             reply = false;
386             terminate = true;
387             canAcceptNegotiateData_ = false;
388             ret = ProcessDisconnectRequest(command);
389             break;
390         case LegacyCommandType::CMD_FORCE_DISCONNECT_V1_REQ:
391             reply = false;
392             terminate = true;
393             canAcceptNegotiateData_ = false;
394             ret = ProcessForceDisconnectRequest(command);
395             break;
396         default:
397             reply = false;
398             terminate = true;
399             ret = ProcessNegotiateCommandCommon(command);
400             break;
401     }
402 
403     if (ret != SOFTBUS_OK) {
404         terminate = true;
405         if (reply) {
406             SendNegotiateResult(*command->GetNegotiateChannel(), ret);
407         }
408     }
409     if (terminate) {
410         Terminate();
411     }
412 }
413 
ProcessNegotiateCommandAtWaitingReqResponseState(std::shared_ptr<NegotiateCommand> & command)414 void P2pV1Processor::ProcessNegotiateCommandAtWaitingReqResponseState(std::shared_ptr<NegotiateCommand> &command)
415 {
416     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
417     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
418     int32_t ret = SOFTBUS_OK;
419     switch (msgType) {
420         case LegacyCommandType::CMD_CONN_V1_REQ:
421             ret = ProcessConflictRequest(command);
422             CleanupIfNeed(ret, command->GetRemoteDeviceId());
423             break;
424         case LegacyCommandType::CMD_CONN_V1_RESP:
425             ret = ProcessConnectResponseAtWaitingReqResponseState(command);
426             CleanupIfNeed(ret, command->GetRemoteDeviceId());
427             break;
428         default:
429             (void)ProcessNegotiateCommandCommon(command);
430             break;
431     }
432     if (ret != SOFTBUS_OK) {
433         connectCommand_->OnFailure(ret);
434         connectCommand_ = nullptr;
435         Terminate();
436     }
437 }
438 
ProcessNegotiateCommandAtWaitingRequestState(std::shared_ptr<NegotiateCommand> & command)439 void P2pV1Processor::ProcessNegotiateCommandAtWaitingRequestState(std::shared_ptr<NegotiateCommand> &command)
440 {
441     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
442     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
443     int32_t ret = SOFTBUS_OK;
444     switch (msgType) {
445         case LegacyCommandType::CMD_CONN_V1_REQ:
446             StopTimer();
447             ret = ProcessConnectRequest(command);
448             CleanupIfNeed(ret, command->GetRemoteDeviceId());
449             break;
450         default:
451             (void)ProcessNegotiateCommandCommon(command);
452             break;
453     }
454     if (ret != SOFTBUS_OK) {
455         SendNegotiateResult(*command->GetNegotiateChannel(), static_cast<WifiDirectErrorCode>(ret));
456         Terminate();
457     }
458 }
459 
ProcessNegotiateCommandAtWaitingReuseResponseState(std::shared_ptr<NegotiateCommand> & command)460 void P2pV1Processor::ProcessNegotiateCommandAtWaitingReuseResponseState(std::shared_ptr<NegotiateCommand> &command)
461 {
462     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
463     int32_t ret = SOFTBUS_OK;
464     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
465     switch (msgType) {
466         case LegacyCommandType::CMD_REUSE_RESP:
467             StopTimer();
468             ret = ProcessReuseResponse(command);
469             CleanupIfNeed(ret, command->GetRemoteDeviceId());
470             break;
471         default:
472             (void)ProcessNegotiateCommandCommon(command);
473             break;
474     }
475     if (ret != SOFTBUS_OK) {
476         connectCommand_->OnFailure(ret);
477         connectCommand_ = nullptr;
478         Terminate();
479     }
480 }
481 
ProcessNegotiateCommandAtWaitingAuthHandShakeState(std::shared_ptr<NegotiateCommand> & command)482 void P2pV1Processor::ProcessNegotiateCommandAtWaitingAuthHandShakeState(std::shared_ptr<NegotiateCommand> &command)
483 {
484     CONN_LOGI(CONN_WIFI_DIRECT, "commandId=%{public}u", command->GetId());
485     int32_t ret = SOFTBUS_OK;
486     bool terminate = false;
487     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
488     switch (msgType) {
489         case LegacyCommandType::CMD_CTRL_CHL_HANDSHAKE:
490             terminate = true;
491             StopTimer();
492             ret = ProcessAuthHandShakeRequest(command);
493             CleanupIfNeed(ret, command->GetRemoteDeviceId());
494             break;
495         case LegacyCommandType::CMD_CONN_V1_RESP:
496             ret = ProcessConnectResponseAtWaitAuthHandShake(command);
497             CleanupIfNeed(ret, command->GetRemoteDeviceId());
498             break;
499         case LegacyCommandType::CMD_REUSE_REQ:
500             ret = ProcessReuseRequest(command);
501             CleanupIfNeed(ret, command->GetRemoteDeviceId());
502             break;
503         default:
504             (void)ProcessNegotiateCommandCommon(command);
505             break;
506     }
507     if (ret != SOFTBUS_OK) {
508         terminate = true;
509         if (connectCommand_ != nullptr) {
510             connectCommand_->OnFailure(ret);
511             connectCommand_ = nullptr;
512         }
513     }
514     if (ret == SOFTBUS_OK && terminate) {
515         WifiDirectSinkLink sinkLink {};
516         if (GenerateSinkLink(sinkLink) == SOFTBUS_OK) {
517             GetWifiDirectManager()->notifyOnline(sinkLink.remoteMac, sinkLink.remoteIp, sinkLink.remoteUuid, active_);
518             if (!active_) {
519                 GetWifiDirectManager()->notifyConnectedForSink(&sinkLink);
520             }
521         }
522     }
523     if (terminate) {
524         Terminate();
525     }
526 }
527 
ProcessNegotiateCommandAtWaitingClientJoiningState(std::shared_ptr<NegotiateCommand> & command)528 void P2pV1Processor::ProcessNegotiateCommandAtWaitingClientJoiningState(std::shared_ptr<NegotiateCommand> &command)
529 {
530     int32_t ret = SOFTBUS_OK;
531     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
532     switch (msgType) {
533         case LegacyCommandType::CMD_CTRL_CHL_HANDSHAKE:
534             CONN_LOGW(CONN_WIFI_DIRECT, "receive auth handshake early, remoteDeviceId=%{public}s",
535                 WifiDirectAnonymizeDeviceId(command->GetRemoteDeviceId()).c_str());
536             ret = ProcessAuthHandShakeRequest(command);
537             CleanupIfNeed(ret, command->GetRemoteDeviceId());
538             P2pEntity::GetInstance().CancelNewClientJoining(clientJoiningMac_);
539             Terminate();
540         case LegacyCommandType::CMD_CONN_V1_RESP:
541             ret = ProcessConnectResponseAtWaitingClientJoiningState(command);
542             CleanupIfNeed(ret, command->GetRemoteDeviceId());
543             break;
544         default:
545             (void)ProcessNegotiateCommandCommon(command);
546             break;
547     }
548     if (ret != SOFTBUS_OK) {
549         if (connectCommand_ != nullptr) {
550             connectCommand_->OnFailure(ret);
551             connectCommand_ = nullptr;
552         }
553         Terminate();
554     }
555 }
556 
ProcessNegotiateCommandCommon(std::shared_ptr<NegotiateCommand> & command)557 int P2pV1Processor::ProcessNegotiateCommandCommon(std::shared_ptr<NegotiateCommand> &command)
558 {
559     auto msgType = command->GetNegotiateMessage().GetLegacyP2pCommandType();
560     switch (msgType) {
561         case LegacyCommandType::CMD_PC_GET_INTERFACE_INFO_REQ:
562             return ProcessGetInterfaceInfoRequest(command);
563         default:
564             CONN_LOGI(CONN_WIFI_DIRECT, "unexpected message type=%{public}d, current state=%{public}s",
565                 static_cast<int>(msgType), GetStateName(state_).c_str());
566             return SOFTBUS_NOT_FIND;
567     }
568 }
569 
ProcessAuthConnEvent(std::shared_ptr<AuthOpenEvent> & event)570 void P2pV1Processor::ProcessAuthConnEvent(std::shared_ptr<AuthOpenEvent> &event)
571 {
572     StopTimer();
573     if (event->reason_ != SOFTBUS_OK) {
574         CONN_LOGE(CONN_WIFI_DIRECT, "auth connect failed, error=%{public}d", event->reason_);
575         Terminate();
576     }
577     auto channel = std::make_shared<AuthNegotiateChannel>(event->handle_);
578     channel->SetClose();
579     auto ret = SendHandShakeMessage(*channel);
580     if (ret != SOFTBUS_OK) {
581         CONN_LOGE(CONN_WIFI_DIRECT, "send hand shake message failed, error=%{public}d", ret);
582         Terminate();
583     }
584     LinkManager::GetInstance().ProcessIfPresent(InnerLink::LinkType::P2P, remoteDeviceId_, [&channel](InnerLink &link) {
585         link.SetNegotiateChannel(channel);
586     });
587 
588     CONN_LOGI(CONN_WIFI_DIRECT, "send hand shake message success");
589     WifiDirectSinkLink sinkLink {};
590     if (GenerateSinkLink(sinkLink) == SOFTBUS_OK) {
591         GetWifiDirectManager()->notifyOnline(sinkLink.remoteMac, sinkLink.remoteIp, sinkLink.remoteUuid, active_);
592         if (!active_) {
593             GetWifiDirectManager()->notifyConnectedForSink(&sinkLink);
594         }
595     }
596     Terminate();
597 }
598 
OnWaitReqResponseTimeoutEvent()599 void P2pV1Processor::OnWaitReqResponseTimeoutEvent()
600 {
601     CONN_LOGE(CONN_WIFI_DIRECT, "wait connect response timeout");
602     if (connectCommand_ != nullptr) {
603         CleanupIfNeed(SOFTBUS_CONN_PV1_WAIT_CONNECT_RESPONSE_TIMEOUT, connectCommand_->GetRemoteDeviceId());
604         connectCommand_->OnFailure(static_cast<WifiDirectErrorCode>(SOFTBUS_CONN_PV1_WAIT_CONNECT_RESPONSE_TIMEOUT));
605         connectCommand_ = nullptr;
606     }
607     Terminate();
608 }
609 
OnWaitReuseResponseTimeoutEvent()610 void P2pV1Processor::OnWaitReuseResponseTimeoutEvent()
611 {
612     CONN_LOGE(CONN_WIFI_DIRECT, "wait reuse response timeout");
613     if (connectCommand_ != nullptr) {
614         connectCommand_->OnFailure(SOFTBUS_CONN_SOURCE_REUSE_LINK_FAILED);
615         connectCommand_ = nullptr;
616     }
617     Terminate();
618 }
619 
OnWaitAuthHandShakeTimeoutEvent()620 void P2pV1Processor::OnWaitAuthHandShakeTimeoutEvent()
621 {
622     CONN_LOGE(CONN_WIFI_DIRECT, "wait auth hand shake timeout");
623     if (connectCommand_ != nullptr) {
624         connectCommand_->OnFailure(SOFTBUS_CONN_PV1_WAIT_AUTH_HANDSHAKE_TIMEOUT);
625         connectCommand_ = nullptr;
626     }
627     Terminate();
628 }
629 
OnWaitRequestTimeoutEvent()630 void P2pV1Processor::OnWaitRequestTimeoutEvent()
631 {
632     CONN_LOGE(CONN_WIFI_DIRECT, "wait request timeout");
633     Terminate();
634 }
635 
OnClientJoinEvent(std::shared_ptr<ClientJoinEvent> & event)636 int P2pV1Processor::OnClientJoinEvent(std::shared_ptr<ClientJoinEvent> &event)
637 {
638     CONN_CHECK_AND_RETURN_RET_LOGW(event->result_ == SOFTBUS_OK, event->result_, CONN_WIFI_DIRECT,
639         "client join failed, error=%{public}d", event->result_);
640     SwitchState(&P2pV1Processor::WaitAuthHandShakeState, P2P_V1_WAITING_AUTH_TIME_MS);
641     return SOFTBUS_OK;
642 }
643 
CreateLink()644 int P2pV1Processor::CreateLink()
645 {
646     auto requestId = connectCommand_->GetConnectInfo().info_.requestId;
647     CONN_LOGI(CONN_WIFI_DIRECT, "requestId=%{public}d, remoteDeviceId=%{public}s", requestId,
648         WifiDirectAnonymizeDeviceId(connectCommand_->GetRemoteDeviceId()).c_str());
649 
650     if (connectCommand_->GetConnectInfo().info_.reuseOnly) {
651         CONN_LOGI(CONN_WIFI_DIRECT, "reuseOnly=true");
652         return SOFTBUS_CONN_SOURCE_REUSE_LINK_FAILED;
653     }
654 
655     auto role = LinkInfo::LinkMode::NONE;
656     auto ret = InterfaceManager::GetInstance().UpdateInterface(
657         InterfaceInfo::InterfaceType::P2P, [&role](InterfaceInfo &interface) {
658             role = interface.GetRole();
659             return SOFTBUS_OK;
660         });
661     CONN_CHECK_AND_RETURN_RET_LOGW(
662         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get current p2p role failed, error=%{public}d", ret);
663 
664     CONN_LOGI(CONN_WIFI_DIRECT, "myRole=%{public}d", WifiDirectUtils::ToWifiDirectRole(role));
665     switch (role) {
666         case LinkInfo::LinkMode::NONE:
667             return CreateLinkAsNone();
668         case LinkInfo::LinkMode::GO:
669             return CreateLinkAsGo();
670         case LinkInfo::LinkMode::GC:
671             return CreateLinkAsGc();
672         default:
673             return SOFTBUS_CONN_PV1_IF_ROLE_INVALID;
674     }
675 }
676 
CreateLinkAsNone()677 int P2pV1Processor::CreateLinkAsNone()
678 {
679     bool p2pEnable = false;
680     InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&p2pEnable](const InterfaceInfo &interface) {
681         p2pEnable = interface.IsEnable();
682         return SOFTBUS_OK;
683     });
684     if (!p2pEnable) {
685         CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE");
686         return SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE;
687     }
688 
689     auto expectApiRole = connectCommand_->GetConnectInfo().info_.expectApiRole;
690     WifiDirectRole expectedRole = WifiDirectRole::WIFI_DIRECT_ROLE_NONE;
691     switch (expectApiRole) {
692         case WIFI_DIRECT_API_ROLE_NONE:
693             expectedRole = WifiDirectRole::WIFI_DIRECT_ROLE_NONE;
694             break;
695         case WIFI_DIRECT_API_ROLE_GO:
696             expectedRole = WifiDirectRole::WIFI_DIRECT_ROLE_GO;
697             break;
698         case WIFI_DIRECT_API_ROLE_GC:
699             expectedRole = WifiDirectRole::WIFI_DIRECT_ROLE_GC;
700             break;
701         case WIFI_DIRECT_API_ROLE_GO | WIFI_DIRECT_API_ROLE_GC:
702             expectedRole = WifiDirectRole::WIFI_DIRECT_ROLE_AUTO;
703             break;
704         default:
705             CONN_LOGE(CONN_WIFI_DIRECT, "illegal expected role, role=%{public}d", expectApiRole);
706             return SOFTBUS_CONN_PV1_REQUEST_ROLE_INVALID;
707     }
708 
709     connectCommand_->PreferNegotiateChannel();
710     auto ret = SendConnectRequestAsNone(*connectCommand_->GetConnectInfo().channel_, expectedRole);
711     CONN_CHECK_AND_RETURN_RET_LOGW(
712         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send message failed, error=%{public}d", ret);
713 
714     SwitchState(&P2pV1Processor::WaitingReqResponseState, P2P_V1_WAITING_RESPONSE_TIME_MS);
715     return SOFTBUS_OK;
716 }
717 
CreateLinkAsGo()718 int P2pV1Processor::CreateLinkAsGo()
719 {
720     auto ret = ReuseP2p();
721     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "reuse p2p failed, error=%{public}d", ret);
722 
723     std::string localIp;
724     std::string localMac;
725     ret = InterfaceManager::GetInstance().ReadInterface(
726         InterfaceInfo::P2P, [&localIp, &localMac](const InterfaceInfo &interface) {
727             localIp = interface.GetIpString().ToIpString();
728             localMac = interface.GetBaseMac();
729             return SOFTBUS_OK;
730         });
731     CONN_CHECK_AND_RETURN_RET_LOGW(
732         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get local ip failed, error=%{public}d", ret);
733 
734     auto remoteMac = std::string(connectCommand_->GetConnectInfo().info_.remoteMac);
735     std::string gcIp;
736     ret = P2pAdapter::RequestGcIp(remoteMac, gcIp);
737     CONN_CHECK_AND_RETURN_RET_LOGW(
738         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "request gc ip failed, error=%{public}d", ret);
739     auto success = LinkManager::GetInstance().ProcessIfAbsent(InnerLink::LinkType::P2P,
740         connectCommand_->GetRemoteDeviceId(), [remoteMac, gcIp, localIp, localMac](InnerLink &link) {
741             link.SetRemoteBaseMac(remoteMac);
742             link.SetRemoteIpv4(gcIp);
743             link.SetLocalBaseMac(localMac);
744             link.SetLocalIpv4(localIp);
745             link.SetState(InnerLink::LinkState::CONNECTING);
746         });
747     CONN_CHECK_AND_RETURN_RET_LOGW(success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "save remote ip failed");
748 
749     P2pEntity::GetInstance().NotifyNewClientJoining(remoteMac);
750 
751     connectCommand_->PreferNegotiateChannel();
752     ret = SendConnectRequestAsGo(*connectCommand_->GetConnectInfo().channel_, remoteMac);
753     CONN_CHECK_AND_RETURN_RET_LOGW(
754         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send message failed, error=%{public}d", ret);
755     SwitchState(&P2pV1Processor::WaitingClientJoiningState, 0);
756     return SOFTBUS_OK;
757 }
758 
CreateLinkAsGc()759 int P2pV1Processor::CreateLinkAsGc()
760 {
761     CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE");
762     return SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE;
763 }
764 
ProcessConnectRequest(std::shared_ptr<NegotiateCommand> & command)765 int P2pV1Processor::ProcessConnectRequest(std::shared_ptr<NegotiateCommand> &command)
766 {
767     auto msg = command->GetNegotiateMessage();
768     auto peerRole = msg.GetLegacyP2pRole();
769     auto expectRole = msg.GetLegacyP2pExpectedRole();
770     LinkInfo::LinkMode myRole = LinkInfo::LinkMode::NONE;
771     bool p2pEnable = false;
772     auto ret = InterfaceManager::GetInstance().ReadInterface(
773         InterfaceInfo::P2P, [&myRole, &p2pEnable](const InterfaceInfo &interface) {
774             myRole = interface.GetRole();
775             p2pEnable = interface.IsEnable();
776             return SOFTBUS_OK;
777         });
778     CONN_CHECK_AND_RETURN_RET_LOGW(
779         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get role info failed, error=%{public}d", ret);
780 
781     if (myRole == LinkInfo::LinkMode::NONE && !p2pEnable) {
782         CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE");
783         return SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE;
784     }
785 
786     auto remoteConfig = msg.GetLegacyP2pWifiConfigInfo();
787     if (!remoteConfig.empty()) {
788         CONN_LOGI(CONN_WIFI_DIRECT, "remoteConfigSize=%{public}zu", remoteConfig.size());
789         ret = P2pAdapter::SetPeerWifiConfigInfo(remoteConfig);
790         CONN_CHECK_AND_RETURN_RET_LOGW(
791             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "set wifi cfg failed, error=%{public}d", ret);
792     }
793 
794     auto localGoMac = GetGoMac(myRole);
795     auto remoteGoMac = msg.GetLegacyP2pGoMac();
796     auto finalRole = GetFinalRoleWithPeerExpectedRole(
797         WifiDirectUtils::ToWifiDirectRole(myRole), peerRole, expectRole, localGoMac, remoteGoMac);
798     CONN_LOGI(CONN_WIFI_DIRECT, "finalRole=%{public}d", finalRole);
799     if (finalRole == static_cast<int>(WifiDirectRole::WIFI_DIRECT_ROLE_GO)) {
800         return ProcessConnectRequestAsGo(command, myRole);
801     } else if (finalRole == static_cast<int>(WifiDirectRole::WIFI_DIRECT_ROLE_GC)) {
802         return ProcessConnectRequestAsGc(command, myRole);
803     } else if (finalRole == static_cast<int>(SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE)) {
804         return ProcessNoAvailableInterface(command, myRole);
805     }
806 
807     CONN_LOGI(CONN_WIFI_DIRECT, "finalRole invalid");
808     return finalRole;
809 }
810 
ProcessConnectRequestAsGo(std::shared_ptr<NegotiateCommand> & command,LinkInfo::LinkMode myRole)811 int P2pV1Processor::ProcessConnectRequestAsGo(std::shared_ptr<NegotiateCommand> &command, LinkInfo::LinkMode myRole)
812 {
813     auto msg = command->GetNegotiateMessage();
814     CONN_CHECK_AND_RETURN_RET_LOGW(msg.GetLegacyP2pContentType() == LegacyContentType::GC_INFO,
815         SOFTBUS_CONN_PV1_BOTH_GO_ERR, CONN_WIFI_DIRECT, "content type not equal gc info");
816 
817     auto remoteMac = msg.GetLegacyP2pGcMac();
818     if (myRole != LinkInfo::LinkMode::GO) {
819         auto ret = CreateGroup(msg);
820         CONN_CHECK_AND_RETURN_RET_LOGW(
821             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "create group failed, error=%{public}d", ret);
822     } else {
823         std::string remoteIp;
824         auto ret = P2pAdapter::RequestGcIp(remoteMac, remoteIp);
825         CONN_CHECK_AND_RETURN_RET_LOGW(
826             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "apply gc ip failed, error=%{public}d", ret);
827         CONN_LOGI(CONN_WIFI_DIRECT, "apply gc ip %{public}s", WifiDirectAnonymizeIp(remoteIp).c_str());
828 
829         ret = ReuseP2p();
830         CONN_CHECK_AND_RETURN_RET_LOGW(
831             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "reuse p2p failed, error=%{public}d", ret);
832 
833         std::string localMac;
834         std::string localIp;
835         ret = InterfaceManager::GetInstance().ReadInterface(
836             InterfaceInfo::P2P, [&localMac, &localIp](const InterfaceInfo &interface) {
837                 localMac = interface.GetBaseMac();
838                 localIp = interface.GetIpString().ToIpString();
839                 return SOFTBUS_OK;
840             });
841         CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, SOFTBUS_CONN_PV1_REUSE_FAIL, CONN_WIFI_DIRECT,
842             "update inner link failed, error=%{public}d", ret);
843         auto success = LinkManager::GetInstance().ProcessIfAbsent(InnerLink::LinkType::P2P, msg.GetRemoteDeviceId(),
844             [localMac, remoteMac, localIp, remoteIp](InnerLink &link) {
845                 link.SetLocalBaseMac(localMac);
846                 link.SetRemoteBaseMac(remoteMac);
847                 link.SetBeingUsedByRemote(true);
848                 link.SetLocalIpv4(localIp);
849                 link.SetRemoteIpv4(remoteIp);
850 
851                 link.SetState(InnerLink::LinkState::CONNECTING);
852             });
853         CONN_CHECK_AND_RETURN_RET_LOGW(
854             success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "update inner link failed");
855     }
856 
857     P2pEntity::GetInstance().NotifyNewClientJoining(remoteMac);
858     auto ret = SendConnectResponseAsGo(*command->GetNegotiateChannel(), remoteMac);
859     CONN_CHECK_AND_RETURN_RET_LOGW(
860         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send connection response failed, error=%{public}d", ret);
861 
862     SwitchState(&P2pV1Processor::WaitingClientJoiningState, -1);
863     return SOFTBUS_OK;
864 }
865 
SendConnectResponseAsGo(const NegotiateChannel & channel,const std::string & remoteMac)866 int P2pV1Processor::SendConnectResponseAsGo(const NegotiateChannel &channel, const std::string &remoteMac)
867 {
868     std::string selfWifiConfig;
869     auto ret = P2pAdapter::GetSelfWifiConfigInfo(selfWifiConfig);
870     CONN_CHECK_AND_RETURN_RET_LOGW(
871         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get wifi cfg failed, error=%{public}d", ret);
872 
873     NegotiateMessage response;
874     response.SetLegacyP2pVersion(P2P_VERSION);
875     response.SetLegacyP2pCommandType(LegacyCommandType::CMD_CONN_V1_RESP);
876     response.SetLegacyP2pContentType(LegacyContentType::GO_INFO);
877     response.SetLegacyP2pGcMac(remoteMac);
878     response.SetLegacyP2pWifiConfigInfo(selfWifiConfig);
879 
880     auto success = LinkManager::GetInstance().ProcessIfPresent(remoteMac, [&response](InnerLink &link) {
881         response.SetLegacyP2pGcIp(link.GetRemoteIpv4());
882     });
883     CONN_CHECK_AND_RETURN_RET_LOGW(success, SOFTBUS_NOT_FIND, CONN_WIFI_DIRECT, "link not found");
884 
885     ret =
886         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&response](const InterfaceInfo &interface) {
887             response.SetLegacyP2pMac(interface.GetBaseMac());
888             response.SetLegacyP2pIp(interface.GetIpString().ToIpString());
889             response.SetLegacyP2pGoIp(interface.GetIpString().ToIpString());
890             response.SetLegacyP2pGoMac(interface.GetBaseMac());
891             response.SetLegacyP2pGoPort(interface.GetP2pListenPort());
892             response.SetLegacyP2pGroupConfig(interface.GetP2pGroupConfig());
893             return SOFTBUS_OK;
894         });
895     CONN_CHECK_AND_RETURN_RET_LOGW(
896         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build response failed, error=%{public}d", ret);
897     return channel.SendMessage(response);
898 }
899 
ProcessConnectRequestAsGc(std::shared_ptr<NegotiateCommand> & command,LinkInfo::LinkMode myRole)900 int P2pV1Processor::ProcessConnectRequestAsGc(std::shared_ptr<NegotiateCommand> &command, LinkInfo::LinkMode myRole)
901 {
902     auto msg = command->GetNegotiateMessage();
903     std::string localMac;
904     auto ret =
905         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&localMac](const InterfaceInfo &interface) {
906             localMac = interface.GetBaseMac();
907             return SOFTBUS_OK;
908         });
909     CONN_CHECK_AND_RETURN_RET_LOGE(
910         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get local mac failed, error=%{public}d", ret);
911     auto remoteMac = msg.GetLegacyP2pMac();
912     auto contentType = msg.GetLegacyP2pContentType();
913     CONN_LOGI(CONN_WIFI_DIRECT, "localMac=%{public}s, remoteMac=%{public}s, contentType=%{public}d",
914         WifiDirectAnonymizeMac(localMac).c_str(), WifiDirectAnonymizeMac(remoteMac).c_str(),
915         static_cast<int>(contentType));
916 
917     if (contentType == LegacyContentType::GC_INFO) {
918         ret = SendConnectResponseAsNone(*command->GetNegotiateChannel(), remoteMac);
919         CONN_CHECK_AND_RETURN_RET_LOGW(
920             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send message failed, error=%{public}d", ret);
921 
922         SwitchState(&P2pV1Processor::WaitingRequestState, P2P_V1_WAITING_REQUEST_TIME_MS);
923         CONN_LOGD(CONN_WIFI_DIRECT, "send response with gc info success");
924         return SOFTBUS_OK;
925     }
926 
927     if (myRole == LinkInfo::LinkMode::GC) {
928         ret = ReuseP2p();
929         CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_REUSE_FAIL");
930         ret = SendNegotiateResult(*command->GetNegotiateChannel(), SOFTBUS_OK);
931         CONN_CHECK_AND_RETURN_RET_LOGW(
932             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send result message failed, error=%{public}d", ret);
933         Terminate();
934     }
935 
936     CONN_LOGI(CONN_WIFI_DIRECT, "start connect group");
937     ret = ConnectGroup(msg, command->GetNegotiateChannel());
938     CONN_CHECK_AND_RETURN_RET_LOGW(
939         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "connect group failed, error=%{public}d", ret);
940     ret = SendNegotiateResult(*command->GetNegotiateChannel(), SOFTBUS_OK);
941     CONN_CHECK_AND_RETURN_RET_LOGW(
942         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send result message failed, error=%{public}d", ret);
943 
944     RemoveExclusive();
945     SwitchState(&P2pV1Processor::WaitAuthHandShakeState, P2P_V1_WAITING_AUTH_TIME_MS);
946     return SOFTBUS_OK;
947 }
948 
SendConnectResponseAsNone(const NegotiateChannel & channel,const std::string & remoteMac)949 int P2pV1Processor::SendConnectResponseAsNone(const NegotiateChannel &channel, const std::string &remoteMac)
950 {
951     std::vector<int> channels;
952     auto ret = P2pAdapter::GetChannel5GListIntArray(channels);
953     CONN_CHECK_AND_RETURN_RET_LOGW(
954         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get 5g channels failed, error=%{public}d", ret);
955     auto channelString = WifiDirectUtils::ChannelListToString(channels);
956 
957     std::string selfWifiConfig;
958     ret = P2pAdapter::GetSelfWifiConfigInfo(selfWifiConfig);
959     CONN_CHECK_AND_RETURN_RET_LOGW(
960         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get wifi cfg failed, error=%{public}d", ret);
961 
962     NegotiateMessage response;
963     response.SetLegacyP2pVersion(P2P_VERSION);
964     response.SetLegacyP2pCommandType(LegacyCommandType::CMD_CONN_V1_RESP);
965     response.SetLegacyP2pContentType(LegacyContentType::GC_INFO);
966     response.SetLegacyP2pGcChannelList(channelString);
967     response.SetLegacyP2pGoMac(remoteMac);
968     response.SetLegacyP2pStationFrequency(P2pAdapter::GetStationFrequencyWithFilter());
969     response.SetLegacyP2pWideBandSupported(P2pAdapter::IsWideBandSupported());
970     response.SetLegacyP2pWifiConfigInfo(selfWifiConfig);
971 
972     ret =
973         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&response](const InterfaceInfo &interface) {
974             response.SetLegacyP2pMac(interface.GetBaseMac());
975             response.SetLegacyP2pIp(interface.GetIpString().ToIpString());
976             response.SetLegacyP2pGcMac(interface.GetBaseMac());
977             return SOFTBUS_OK;
978         });
979     CONN_CHECK_AND_RETURN_RET_LOGW(
980         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build response failed, error=%{public}d", ret);
981     return channel.SendMessage(response);
982 }
SendInterfaceInfoResponse(const NegotiateChannel & channel)983 int P2pV1Processor::SendInterfaceInfoResponse(const NegotiateChannel &channel)
984 {
985     NegotiateMessage response;
986     response.SetLegacyP2pCommandType(LegacyCommandType::CMD_PC_GET_INTERFACE_INFO_RESP);
987     auto ret =
988         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&response](const InterfaceInfo &interface) {
989             response.SetLegacyP2pMac(interface.GetBaseMac());
990             response.SetLegacyP2pGcIp(interface.GetIpString().ToIpString());
991             return SOFTBUS_OK;
992         });
993     CONN_CHECK_AND_RETURN_RET_LOGW(
994         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build response failed, error=%{public}d", ret);
995     return channel.SendMessage(response);
996 }
997 
SendNegotiateResult(const NegotiateChannel & channel,int reason)998 int P2pV1Processor::SendNegotiateResult(const NegotiateChannel &channel, int reason)
999 {
1000     NegotiateMessage result;
1001     result.SetLegacyP2pVersion(P2P_VERSION);
1002     result.SetLegacyP2pCommandType(LegacyCommandType::CMD_CONN_V1_RESP);
1003     result.SetLegacyP2pContentType(LegacyContentType::RESULT);
1004     result.SetLegacyP2pResult(static_cast<LegacyResult>(ErrorCodeToV1ProtocolCode(reason)));
1005 
1006     auto ret =
1007         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&result](const InterfaceInfo &interface) {
1008             result.SetLegacyP2pMac(interface.GetBaseMac());
1009             result.SetLegacyP2pIp(interface.GetIpString().ToIpString());
1010             return SOFTBUS_OK;
1011         });
1012     CONN_CHECK_AND_RETURN_RET_LOGW(
1013         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build result failed, error=%{public}d", ret);
1014     return channel.SendMessage(result);
1015 }
1016 
SendReuseRequest(const NegotiateChannel & channel)1017 int P2pV1Processor::SendReuseRequest(const NegotiateChannel &channel)
1018 {
1019     NegotiateMessage result;
1020     result.SetLegacyP2pCommandType(LegacyCommandType::CMD_REUSE_REQ);
1021     auto ret =
1022         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&result](const InterfaceInfo &interface) {
1023             result.SetLegacyP2pMac(interface.GetBaseMac());
1024             return SOFTBUS_OK;
1025         });
1026     CONN_CHECK_AND_RETURN_RET_LOGW(
1027         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build result failed, error=%{public}d", ret);
1028     return channel.SendMessage(result);
1029 }
1030 
SendReuseResponse(const NegotiateChannel & channel,int32_t result)1031 int P2pV1Processor::SendReuseResponse(const NegotiateChannel &channel, int32_t result)
1032 {
1033     NegotiateMessage response;
1034     response.SetLegacyP2pCommandType(LegacyCommandType::CMD_REUSE_RESP);
1035     response.SetLegacyP2pResult(static_cast<LegacyResult>(ErrorCodeToV1ProtocolCode(result)));
1036 
1037     auto ret =
1038         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&response](const InterfaceInfo &interface) {
1039             response.SetLegacyP2pMac(interface.GetBaseMac());
1040             return SOFTBUS_OK;
1041         });
1042     CONN_CHECK_AND_RETURN_RET_LOGW(
1043         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build response failed, error=%{public}d", ret);
1044     return channel.SendMessage(response);
1045 }
1046 
SendDisconnectRequest(const NegotiateChannel & channel)1047 int P2pV1Processor::SendDisconnectRequest(const NegotiateChannel &channel)
1048 {
1049     NegotiateMessage request;
1050     request.SetLegacyP2pCommandType(LegacyCommandType::CMD_DISCONNECT_V1_REQ);
1051     auto ret =
1052         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&request](const InterfaceInfo &interface) {
1053             request.SetLegacyP2pMac(interface.GetBaseMac());
1054             return SOFTBUS_OK;
1055         });
1056     CONN_CHECK_AND_RETURN_RET_LOGW(
1057         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build request failed, error=%{public}d", ret);
1058     return channel.SendMessage(request);
1059 }
1060 
SendForceDisconnectRequest(const NegotiateChannel & channel)1061 int P2pV1Processor::SendForceDisconnectRequest(const NegotiateChannel &channel)
1062 {
1063     NegotiateMessage request;
1064     request.SetLegacyP2pCommandType(LegacyCommandType::CMD_FORCE_DISCONNECT_V1_REQ);
1065     auto ret =
1066         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&request](const InterfaceInfo &interface) {
1067             request.SetLegacyP2pMac(interface.GetBaseMac());
1068             return SOFTBUS_OK;
1069         });
1070     CONN_CHECK_AND_RETURN_RET_LOGW(
1071         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build request failed, error=%{public}d", ret);
1072     return channel.SendMessage(request);
1073 }
1074 
ProcessNoAvailableInterface(std::shared_ptr<NegotiateCommand> & command,LinkInfo::LinkMode myRole)1075 int P2pV1Processor::ProcessNoAvailableInterface(std::shared_ptr<NegotiateCommand> &command, LinkInfo::LinkMode myRole)
1076 {
1077     auto msg = command->GetNegotiateMessage();
1078     auto remoteDeviceId = command->GetRemoteDeviceId();
1079     CONN_LOGI(CONN_WIFI_DIRECT, "remoteDeviceId=%{public}s", WifiDirectAnonymizeDeviceId(remoteDeviceId).c_str());
1080 
1081     bool needFix = false;
1082     LinkManager::GetInstance().Dump();
1083     LinkManager::GetInstance().ForEach([remoteDeviceId, myRole, &needFix](InnerLink &link) {
1084         if (remoteDeviceId != link.GetRemoteDeviceId()) {
1085             return false;
1086         }
1087         if (myRole == LinkInfo::LinkMode::GC) {
1088             needFix = true;
1089             return true;
1090         }
1091         return false;
1092     });
1093     if (needFix) {
1094         CONN_LOGI(CONN_WIFI_DIRECT, "fix the obsolete link");
1095         (void)DestroyGroup();
1096         return SOFTBUS_CONN_PV1_LOCAL_DISCONNECTED_REMOTE_CONNECTED;
1097     }
1098 
1099     return SOFTBUS_CONN_PV1_GC_AVAILABLE_WITH_MISMATCHED_ROLE_ERR;
1100 }
1101 
ProcessConflictRequest(std::shared_ptr<NegotiateCommand> & command)1102 int P2pV1Processor::ProcessConflictRequest(std::shared_ptr<NegotiateCommand> &command)
1103 {
1104     auto localMac = P2pAdapter::GetMacAddress();
1105     auto remoteMac = command->GetNegotiateMessage().GetLegacyP2pMac();
1106 
1107     CONN_LOGI(CONN_WIFI_DIRECT, "localMac=%{public}s, remoteMac=%{public}s", WifiDirectAnonymizeMac(localMac).c_str(),
1108         WifiDirectAnonymizeMac(remoteMac).c_str());
1109     auto reversal = WifiDirectUtils::CompareIgnoreCase(localMac, remoteMac) < 0;
1110     if (!reversal) {
1111         CONN_LOGI(CONN_WIFI_DIRECT, "no need reversal, ignore remote request");
1112         auto ret = SendNegotiateResult(*command->GetNegotiateChannel(), SOFTBUS_CONN_PV1_BUSY_ERR);
1113         CONN_CHECK_AND_RETURN_RET_LOGW(
1114             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send result message failed, error=%{public}d", ret);
1115         return SOFTBUS_OK;
1116     }
1117 
1118     StopTimer();
1119     CONN_LOGI(CONN_WIFI_DIRECT, "need reversal, process remote request and retry local command");
1120 
1121     LinkInfo::LinkMode myRole = LinkInfo::LinkMode::NONE;
1122     auto ret =
1123         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&myRole](const InterfaceInfo &interface) {
1124             myRole = interface.GetRole();
1125             return SOFTBUS_OK;
1126         });
1127     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get role failed, error=%{public}d", ret);
1128     if (myRole == LinkInfo::LinkMode::GO) {
1129         CONN_LOGI(CONN_WIFI_DIRECT, "decrease reuseCount and stop new client timer");
1130         RemoveLink(command->GetRemoteDeviceId());
1131         P2pEntity::GetInstance().CancelNewClientJoining(remoteMac);
1132         return SOFTBUS_OK;
1133     }
1134     executor_->SendEvent(command);
1135     CONN_LOGI(CONN_WIFI_DIRECT, "activeCommand=NULL");
1136     SwitchState(&P2pV1Processor::AvailableState, 0);
1137     return SOFTBUS_OK;
1138 }
1139 
ProcessReuseRequest(std::shared_ptr<NegotiateCommand> & command)1140 int P2pV1Processor::ProcessReuseRequest(std::shared_ptr<NegotiateCommand> &command)
1141 {
1142     auto msg = command->GetNegotiateMessage();
1143     auto remoteMac = msg.GetLegacyP2pMac();
1144     int result = SOFTBUS_CONN_PV1_REUSE_FAIL;
1145 
1146     int ret = SOFTBUS_OK;
1147     bool success = false;
1148 
1149     auto oldLink =
1150         LinkManager::GetInstance().GetReuseLink(WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P, msg.GetRemoteDeviceId());
1151     if (oldLink == nullptr) {
1152         CONN_LOGE(CONN_WIFI_DIRECT, "link is null");
1153         goto Failed;
1154     }
1155 
1156     ret = ReuseP2p();
1157     if (ret != SOFTBUS_OK) {
1158         CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_REUSE_FAIL");
1159         goto Failed;
1160     }
1161 
1162     success = LinkManager::GetInstance().ProcessIfPresent(remoteMac, [&](InnerLink &link) {
1163         link.SetBeingUsedByRemote(true);
1164     });
1165     if (!success) {
1166         CONN_LOGE(CONN_WIFI_DIRECT, "update inner link failed");
1167         goto Failed;
1168     }
1169     result = SOFTBUS_OK;
1170 
1171 Failed:
1172     ret = SendReuseResponse(*command->GetNegotiateChannel(), result);
1173     CONN_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT,
1174         "send reuse response failed, remote=%{public}s, error=%{public}d", WifiDirectAnonymizeMac(remoteMac).c_str(),
1175         ret);
1176     return SOFTBUS_OK;
1177 }
1178 
ProcessReuseResponse(std::shared_ptr<NegotiateCommand> & command)1179 int P2pV1Processor::ProcessReuseResponse(std::shared_ptr<NegotiateCommand> &command)
1180 {
1181     auto msg = command->GetNegotiateMessage();
1182     auto result = ErrorCodeFromV1ProtocolCode(static_cast<int32_t>(msg.GetLegacyP2pResult()));
1183     auto remoteMac = msg.GetLegacyP2pMac();
1184 
1185     CONN_LOGI(
1186         CONN_WIFI_DIRECT, "result=%{public}d, remoteMac=%{public}s", result, WifiDirectAnonymizeMac(remoteMac).c_str());
1187     CONN_CHECK_AND_RETURN_RET_LOGW(
1188         result == SOFTBUS_OK, result, CONN_WIFI_DIRECT, "remote response failed. result=%{public}d", result);
1189 
1190     auto ret = ReuseP2p();
1191     if (ret != SOFTBUS_OK) {
1192         CONN_LOGE(CONN_WIFI_DIRECT,
1193             "local reuse failed, send disconnect to remote for decreasing reference, error=%{public}d", ret);
1194         SendDisconnectRequest(*command->GetNegotiateChannel());
1195         CONN_LOGI(CONN_WIFI_DIRECT,
1196             "wait for p2p auth to send data, DISCONNECT_WAIT_POST_REQUEST_MS=%{public}dms",
1197             DISCONNECT_WAIT_POST_REQUEST_MS);
1198         SoftBusSleepMs(DISCONNECT_WAIT_POST_REQUEST_MS);
1199         connectCommand_->OnFailure(ret);
1200         connectCommand_ = nullptr;
1201         Terminate();
1202     }
1203 
1204     auto requestId = connectCommand_->GetConnectInfo().info_.requestId;
1205     auto pid = connectCommand_->GetConnectInfo().info_.pid;
1206     WifiDirectLink dlink {};
1207     auto success = LinkManager::GetInstance().ProcessIfPresent(remoteMac, [requestId, pid, &dlink](InnerLink &link) {
1208         link.GenerateLink(requestId, pid, dlink, true);
1209         dlink.channelId = WifiDirectUtils::FrequencyToChannel(link.GetFrequency());
1210     });
1211     CONN_CHECK_AND_RETURN_RET_LOGW(
1212         success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "update inner link failed");
1213     connectCommand_->OnSuccess(dlink);
1214     connectCommand_ = nullptr;
1215     Terminate();
1216 }
1217 
ProcessDisconnectRequest(std::shared_ptr<NegotiateCommand> & command)1218 int P2pV1Processor::ProcessDisconnectRequest(std::shared_ptr<NegotiateCommand> &command)
1219 {
1220     int reuseCountOld = 0;
1221     auto ret =
1222         InterfaceManager::GetInstance().UpdateInterface(InterfaceInfo::P2P, [&reuseCountOld](InterfaceInfo &interface) {
1223             reuseCountOld = interface.GetReuseCount();
1224             return SOFTBUS_OK;
1225         });
1226     CONN_CHECK_AND_RETURN_RET_LOGW(
1227         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get reuse count for interface info failed, error=%{public}d", ret);
1228 
1229     if (reuseCountOld <= 0) {
1230         CONN_LOGI(CONN_WIFI_DIRECT, "reuseCountOld already 0, do not call RemoveLink");
1231         return static_cast<int>(SOFTBUS_OK);
1232     }
1233 
1234     WifiDirectSinkLink sinkLink {};
1235     if (GenerateSinkLink(sinkLink) == SOFTBUS_OK) {
1236         GetWifiDirectManager()->notifyDisconnectedForSink(&sinkLink);
1237     }
1238 
1239     ret = RemoveLink(command->GetRemoteDeviceId());
1240     CONN_CHECK_AND_RETURN_RET_LOGW(
1241         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "remove link failed, error=%{public}d", ret);
1242     return SOFTBUS_OK;
1243 }
1244 
ProcessForceDisconnectRequest(std::shared_ptr<NegotiateCommand> & command)1245 int P2pV1Processor::ProcessForceDisconnectRequest(std::shared_ptr<NegotiateCommand> &command)
1246 {
1247     CONN_LOGI(CONN_WIFI_DIRECT, "process force disconnect request, remoteUuid=%{public}s",
1248         WifiDirectAnonymizeDeviceId(command->GetRemoteDeviceId()).c_str());
1249     LinkManager::GetInstance().RemoveLink(InnerLink::LinkType::P2P, command->GetRemoteDeviceId());
1250 
1251     return DestroyGroup();
1252 }
1253 
ProcessGetInterfaceInfoRequest(std::shared_ptr<NegotiateCommand> & command)1254 int P2pV1Processor::ProcessGetInterfaceInfoRequest(std::shared_ptr<NegotiateCommand> &command)
1255 {
1256     auto msg = command->GetNegotiateMessage();
1257     auto interfaceName = msg.GetLegacyInterfaceName();
1258 
1259     auto ret = SendInterfaceInfoResponse(*command->GetNegotiateChannel());
1260     CONN_CHECK_AND_RETURN_RET_LOGW(
1261         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send interface info response failed, error=%{public}d", ret);
1262     return SOFTBUS_OK;
1263 }
1264 
ProcessAuthHandShakeRequest(std::shared_ptr<NegotiateCommand> & command)1265 int P2pV1Processor::ProcessAuthHandShakeRequest(std::shared_ptr<NegotiateCommand> &command)
1266 {
1267     auto channel = std::dynamic_pointer_cast<AuthNegotiateChannel>(command->GetNegotiateChannel());
1268     if (channel != nullptr) {
1269         channel->SetClose();
1270     }
1271     auto remoteDeviceId = command->GetRemoteDeviceId();
1272 
1273     WifiDirectLink dlink {};
1274     auto success = LinkManager::GetInstance().ProcessIfPresent(
1275         InnerLink::LinkType::P2P, remoteDeviceId, [channel, this, &dlink](InnerLink &link) {
1276             link.SetState(InnerLink::LinkState::CONNECTED);
1277             link.SetNegotiateChannel(channel);
1278             if (connectCommand_ != nullptr) {
1279                 link.GenerateLink(connectCommand_->GetConnectInfo().info_.requestId,
1280                     connectCommand_->GetConnectInfo().info_.pid, dlink, true);
1281                 dlink.channelId = WifiDirectUtils::FrequencyToChannel(link.GetFrequency());
1282             }
1283         });
1284     CONN_CHECK_AND_RETURN_RET_LOGW(success, SOFTBUS_NOT_FIND, CONN_WIFI_DIRECT,
1285         "update inner link failed, remoteDeviceId=%{public}s", WifiDirectAnonymizeDeviceId(remoteDeviceId).c_str());
1286     if (connectCommand_ != nullptr) {
1287         connectCommand_->OnSuccess(dlink);
1288         connectCommand_ = nullptr;
1289     }
1290     return SOFTBUS_OK;
1291 }
1292 
SendConnectRequestAsNone(const NegotiateChannel & channel,WifiDirectRole expectedRole)1293 int P2pV1Processor::SendConnectRequestAsNone(const NegotiateChannel &channel, WifiDirectRole expectedRole)
1294 {
1295     std::vector<int> channels;
1296     int32_t ret = P2pAdapter::GetChannel5GListIntArray(channels);
1297     CONN_CHECK_AND_RETURN_RET_LOGW(
1298         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get 5g channels failed, error=%{public}d", ret);
1299     auto channelString = WifiDirectUtils::ChannelListToString(channels);
1300 
1301     std::string selfWifiConfig;
1302     ret = P2pAdapter::GetSelfWifiConfigInfo(selfWifiConfig);
1303     CONN_CHECK_AND_RETURN_RET_LOGW(
1304         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get self wifi cfg failed, error=%{public}d", ret);
1305 
1306     NegotiateMessage request;
1307     request.SetLegacyP2pCommandType(LegacyCommandType::CMD_CONN_V1_REQ);
1308     request.SetLegacyP2pVersion(P2P_VERSION);
1309     request.SetLegacyP2pContentType(LegacyContentType::GC_INFO);
1310     request.SetLegacyP2pBridgeSupport(false);
1311     request.SetLegacyP2pRole(WifiDirectRole::WIFI_DIRECT_ROLE_NONE);
1312     request.SetLegacyP2pExpectedRole(expectedRole);
1313     request.SetLegacyP2pGoMac("");
1314     request.SetLegacyP2pGcChannelList(channelString);
1315     request.SetLegacyP2pStationFrequency(P2pAdapter::GetStationFrequencyWithFilter());
1316     request.SetLegacyP2pWideBandSupported(P2pAdapter::IsWideBandSupported());
1317     request.SetLegacyP2pWifiConfigInfo(selfWifiConfig);
1318     ret = InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&request](const InterfaceInfo &interface) {
1319         request.SetLegacyP2pMac(interface.GetBaseMac());
1320         request.SetLegacyP2pGcMac(interface.GetBaseMac());
1321         return SOFTBUS_OK;
1322     });
1323     CONN_CHECK_AND_RETURN_RET_LOGW(
1324         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build request failed, error=%{public}d", ret);
1325     return channel.SendMessage(request);
1326 }
1327 
SendConnectRequestAsGo(const NegotiateChannel & channel,const std::string & remoteMac)1328 int P2pV1Processor::SendConnectRequestAsGo(const NegotiateChannel &channel, const std::string &remoteMac)
1329 {
1330     NegotiateMessage request;
1331     request.SetLegacyP2pVersion(P2P_VERSION);
1332     request.SetLegacyP2pCommandType(LegacyCommandType::CMD_CONN_V1_REQ);
1333     request.SetLegacyP2pContentType(LegacyContentType::GO_INFO);
1334     request.SetLegacyP2pRole(WifiDirectRole::WIFI_DIRECT_ROLE_GO);
1335     request.SetLegacyP2pExpectedRole(WifiDirectRole::WIFI_DIRECT_ROLE_GO);
1336     request.SetLegacyP2pGcMac(remoteMac);
1337     request.SetLegacyP2pBridgeSupport(false);
1338     request.SetLegacyP2pWifiConfigInfo("");
1339 
1340     auto success = LinkManager::GetInstance().ProcessIfPresent(remoteMac, [&request](InnerLink &link) {
1341         request.SetLegacyP2pGcIp(link.GetRemoteIpv4());
1342     });
1343     CONN_CHECK_AND_RETURN_RET_LOGW(success, SOFTBUS_NOT_FIND, CONN_WIFI_DIRECT, "link not found");
1344 
1345     auto ret =
1346         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&request](const InterfaceInfo &interface) {
1347             request.SetLegacyP2pMac(interface.GetBaseMac());
1348             request.SetLegacyP2pGroupConfig(interface.GetP2pGroupConfig());
1349             request.SetLegacyP2pGoMac(interface.GetBaseMac());
1350             request.SetLegacyP2pGoIp(interface.GetIpString().ToIpString());
1351             request.SetLegacyP2pGoPort(interface.GetP2pListenPort());
1352             return SOFTBUS_OK;
1353         });
1354     CONN_CHECK_AND_RETURN_RET_LOGW(
1355         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build request failed, error=%{public}d", ret);
1356     return channel.SendMessage(request);
1357 }
1358 
SendHandShakeMessage(const NegotiateChannel & channel)1359 int P2pV1Processor::SendHandShakeMessage(const NegotiateChannel &channel)
1360 {
1361     NegotiateMessage message;
1362     message.SetLegacyP2pCommandType(LegacyCommandType::CMD_CTRL_CHL_HANDSHAKE);
1363     auto ret =
1364         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&message](const InterfaceInfo &interfce) {
1365             message.SetLegacyP2pMac(interfce.GetBaseMac());
1366             message.SetLegacyP2pIp(interfce.GetIpString().ToIpString());
1367             return SOFTBUS_OK;
1368         });
1369     CONN_CHECK_AND_RETURN_RET_LOGW(
1370         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "build message failed, error=%{public}d", ret);
1371     return channel.SendMessage(message);
1372 }
1373 
ProcessConnectResponseAtWaitingReqResponseState(std::shared_ptr<NegotiateCommand> & command)1374 int P2pV1Processor::ProcessConnectResponseAtWaitingReqResponseState(std::shared_ptr<NegotiateCommand> &command)
1375 {
1376     StopTimer();
1377     LinkInfo::LinkMode myRole = LinkInfo::LinkMode::NONE;
1378     auto ret =
1379         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&myRole](const InterfaceInfo &interface) {
1380             myRole = interface.GetRole();
1381             return SOFTBUS_OK;
1382         });
1383     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get role failed, error=%{public}d", ret);
1384 
1385     CONN_LOGI(CONN_WIFI_DIRECT, "myRole=%{public}d", WifiDirectUtils::ToWifiDirectRole(myRole));
1386     if (myRole == LinkInfo::LinkMode::NONE) {
1387         return ProcessConnectResponseAsNone(command);
1388     }
1389     CONN_LOGE(CONN_WIFI_DIRECT, "negotiate failed, my role invalid and changed during negotiation");
1390     return SOFTBUS_CONN_PV1_CONNECTED_WITH_MISMATCHED_ROLE_ERR;
1391 }
1392 
ProcessConnectResponseAtWaitingClientJoiningState(std::shared_ptr<NegotiateCommand> & command)1393 int P2pV1Processor::ProcessConnectResponseAtWaitingClientJoiningState(std::shared_ptr<NegotiateCommand> &command)
1394 {
1395     LinkInfo::LinkMode myRole = LinkInfo::LinkMode::NONE;
1396     auto ret =
1397         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&myRole](const InterfaceInfo &interface) {
1398             myRole = interface.GetRole();
1399             return SOFTBUS_OK;
1400         });
1401     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get role failed, error=%{public}d", ret);
1402 
1403     CONN_LOGI(CONN_WIFI_DIRECT, "myRole=%{public}d", WifiDirectUtils::ToWifiDirectRole(myRole));
1404     if (myRole == LinkInfo::LinkMode::GO) {
1405         return ProcessConnectResponseAsGo(command);
1406     }
1407     CONN_LOGE(CONN_WIFI_DIRECT, "negotiate failed, my role invalid and changed during negotiation");
1408     return SOFTBUS_CONN_PV1_CONNECTED_WITH_MISMATCHED_ROLE_ERR;
1409 }
1410 
ProcessConnectResponseAsGo(std::shared_ptr<NegotiateCommand> & command)1411 int P2pV1Processor::ProcessConnectResponseAsGo(std::shared_ptr<NegotiateCommand> &command)
1412 {
1413     auto msg = command->GetNegotiateMessage();
1414     auto contentType = msg.GetLegacyP2pContentType();
1415     if (contentType != LegacyContentType::RESULT) {
1416         CONN_LOGE(CONN_WIFI_DIRECT, "content type not equal result type");
1417         return SOFTBUS_CONN_PV1_WRONG_NEGOTIATION_MSG_ERR;
1418     }
1419 
1420     auto remoteMac = msg.GetLegacyP2pMac();
1421     CONN_LOGI(CONN_WIFI_DIRECT, "remoteMac=%{public}s", WifiDirectAnonymizeMac(remoteMac).c_str());
1422 
1423     auto result = ErrorCodeFromV1ProtocolCode(static_cast<int32_t>(msg.GetLegacyP2pResult()));
1424     CONN_CHECK_AND_RETURN_RET_LOGW(
1425         result == SOFTBUS_OK, result, CONN_WIFI_DIRECT, "peer response error. result=%{public}d", result);
1426 
1427     auto requestId = connectCommand_->GetConnectInfo().info_.requestId;
1428     auto pid = connectCommand_->GetConnectInfo().info_.pid;
1429     bool alreadyAuthHandShake = false;
1430     WifiDirectLink dlink {};
1431     auto success = LinkManager::GetInstance().ProcessIfPresent(
1432         remoteMac, [msg, requestId, pid, &dlink, &alreadyAuthHandShake](InnerLink &link) {
1433             link.SetState(InnerLink::LinkState::CONNECTED);
1434             link.SetRemoteIpv4(msg.GetLegacyP2pIp());
1435             link.GenerateLink(requestId, pid, dlink, true);
1436             link.GetNegotiateChannel();
1437             dlink.channelId = WifiDirectUtils::FrequencyToChannel(link.GetFrequency());
1438             alreadyAuthHandShake = link.GetNegotiateChannel() != nullptr;
1439         });
1440     CONN_CHECK_AND_RETURN_RET_LOGW(success, SOFTBUS_NOT_FIND, CONN_WIFI_DIRECT, "update inner link failed");
1441     P2pEntity::GetInstance().CancelNewClientJoining(clientJoiningMac_);
1442     connectCommand_->OnSuccess(dlink);
1443     connectCommand_ = nullptr;
1444 
1445     RemoveExclusive();
1446     SwitchState(&P2pV1Processor::WaitAuthHandShakeState, P2P_V1_WAITING_AUTH_TIME_MS);
1447     return SOFTBUS_OK;
1448 }
1449 
ProcessConnectResponseAsNone(std::shared_ptr<NegotiateCommand> & command)1450 int P2pV1Processor::ProcessConnectResponseAsNone(std::shared_ptr<NegotiateCommand> &command)
1451 {
1452     auto msg = command->GetNegotiateMessage();
1453     auto remoteConfig = msg.GetLegacyP2pWifiConfigInfo();
1454     if (!remoteConfig.empty()) {
1455         CONN_LOGI(CONN_WIFI_DIRECT, "remoteConfigSize=%{public}zu, remoteConfig=%{public}s", remoteConfig.size(),
1456             remoteConfig.c_str());
1457         int32_t ret = P2pAdapter::SetPeerWifiConfigInfo(remoteConfig);
1458         CONN_CHECK_AND_RETURN_RET_LOGW(
1459             ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "set wifi cfg failed, error=%{public}d", ret);
1460     }
1461 
1462     auto contentType = msg.GetLegacyP2pContentType();
1463     if (contentType == LegacyContentType::GO_INFO) {
1464         return ProcessConnectResponseWithGoInfoAsNone(command);
1465     }
1466 
1467     if (contentType == LegacyContentType::GC_INFO) {
1468         return ProcessConnectResponseWithGcInfoAsNone(command);
1469     }
1470 
1471     auto errorCode = ErrorCodeFromV1ProtocolCode(static_cast<int32_t>(msg.GetLegacyP2pResult()));
1472     CONN_LOGI(CONN_WIFI_DIRECT, "contentType=%{public}d, errorCode=%{public}d", contentType, errorCode);
1473     if (errorCode == SOFTBUS_OK) {
1474         // when content type is invalid and error code is OK
1475         return SOFTBUS_CONN_PV1_INTERNAL_ERR0R;
1476     }
1477     return errorCode;
1478 }
1479 
ProcessConnectResponseWithGoInfoAsNone(std::shared_ptr<NegotiateCommand> & command)1480 int P2pV1Processor::ProcessConnectResponseWithGoInfoAsNone(std::shared_ptr<NegotiateCommand> &command)
1481 {
1482     auto msg = command->GetNegotiateMessage();
1483     auto ret = ConnectGroup(msg, command->GetNegotiateChannel());
1484     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, SOFTBUS_CONN_PV1_CONNECT_GROUP_FAIL, CONN_WIFI_DIRECT,
1485         "connect group failed, error=%{public}d", ret);
1486 
1487     auto requestId = connectCommand_->GetConnectInfo().info_.requestId;
1488     auto pid = connectCommand_->GetConnectInfo().info_.pid;
1489     WifiDirectLink dlink {};
1490     auto success = LinkManager::GetInstance().ProcessIfPresent(
1491         InnerLink::LinkType::P2P, command->GetRemoteDeviceId(), [requestId, pid, &dlink](InnerLink &link) {
1492             link.GenerateLink(requestId, pid, dlink, true);
1493             dlink.channelId = WifiDirectUtils::FrequencyToChannel(link.GetFrequency());
1494         });
1495     CONN_CHECK_AND_RETURN_RET_LOGW(
1496         success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "update inner link failed");
1497     connectCommand_->OnSuccess(dlink);
1498     connectCommand_ = nullptr;
1499 
1500     RemoveExclusive();
1501     SwitchState(&P2pV1Processor::WaitAuthHandShakeState, P2P_V1_WAITING_AUTH_TIME_MS);
1502     return SOFTBUS_OK;
1503 }
1504 
ProcessConnectResponseWithGcInfoAsNone(std::shared_ptr<NegotiateCommand> & command)1505 int P2pV1Processor::ProcessConnectResponseWithGcInfoAsNone(std::shared_ptr<NegotiateCommand> &command)
1506 {
1507     auto msg = command->GetNegotiateMessage();
1508     auto ret = CreateGroup(msg);
1509     CONN_CHECK_AND_RETURN_RET_LOGW(
1510         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "create group failed, error=%{public}d", ret);
1511     std::string remoteMac = msg.GetLegacyP2pMac();
1512     ret = SendConnectRequestAsGo(*command->GetNegotiateChannel(), remoteMac);
1513     CONN_CHECK_AND_RETURN_RET_LOGW(
1514         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "send message failed, error=%{public}d", ret);
1515 
1516     SwitchState(&P2pV1Processor::WaitingClientJoiningState, -1);
1517     return SOFTBUS_OK;
1518 }
1519 
ProcessConnectResponseAtWaitAuthHandShake(std::shared_ptr<NegotiateCommand> & command)1520 int P2pV1Processor::ProcessConnectResponseAtWaitAuthHandShake(std::shared_ptr<NegotiateCommand> &command)
1521 {
1522     auto msg = command->GetNegotiateMessage();
1523     auto remoteMac = msg.GetLegacyP2pMac();
1524     CONN_LOGI(CONN_WIFI_DIRECT, "remoteMac=%{public}s", WifiDirectAnonymizeMac(remoteMac).c_str());
1525 
1526     auto contentType = msg.GetLegacyP2pContentType();
1527     if (contentType != LegacyContentType::RESULT) {
1528         CONN_LOGE(CONN_WIFI_DIRECT, "content type not equal result type");
1529         return SOFTBUS_CONN_PV1_WRONG_NEGOTIATION_MSG_ERR;
1530     }
1531 
1532     auto result = ErrorCodeFromV1ProtocolCode(static_cast<int32_t>(msg.GetLegacyP2pResult()));
1533     CONN_CHECK_AND_RETURN_RET_LOGW(
1534         result == SOFTBUS_OK, result, CONN_WIFI_DIRECT, "peer response error. result=%{public}d", result);
1535 
1536     if (connectCommand_ != nullptr) {
1537         auto requestId = connectCommand_->GetConnectInfo().info_.requestId;
1538         auto pid = connectCommand_->GetConnectInfo().info_.pid;
1539         WifiDirectLink dlink {};
1540         auto success = LinkManager::GetInstance().ProcessIfPresent(
1541             remoteMac, [msg, requestId, pid, &dlink](InnerLink &link) {
1542                 link.SetState(InnerLink::LinkState::CONNECTED);
1543                 link.GenerateLink(requestId, pid, dlink, true);
1544                 dlink.channelId = WifiDirectUtils::FrequencyToChannel(link.GetFrequency());
1545             });
1546         CONN_CHECK_AND_RETURN_RET_LOGW(success, SOFTBUS_NOT_FIND, CONN_WIFI_DIRECT,
1547             "link not found, remoteMac=%{public}s", WifiDirectAnonymizeMac(remoteMac).c_str());
1548         connectCommand_->OnSuccess(dlink);
1549         connectCommand_ = nullptr;
1550     }
1551     return SOFTBUS_OK;
1552 }
1553 
CreateGroup(const NegotiateMessage & msg)1554 int P2pV1Processor::CreateGroup(const NegotiateMessage &msg)
1555 {
1556     auto isRemoteWideBandSupported = msg.GetLegacyP2pWideBandSupported();
1557     auto stationFrequency = msg.GetLegacyP2pStationFrequency();
1558     auto channelListString = msg.GetLegacyP2pGcChannelList();
1559     auto finalFrequency = ChooseFrequency(stationFrequency, WifiDirectUtils::StringToChannelList(channelListString));
1560     CONN_CHECK_AND_RETURN_RET_LOGW(finalFrequency > 0, finalFrequency, CONN_WIFI_DIRECT,
1561         "choose frequency failed, frequency=%{public}d", finalFrequency);
1562 
1563     bool isLocalWideBandSupported = P2pAdapter::IsWideBandSupported();
1564     CONN_LOGI(CONN_WIFI_DIRECT,
1565         "stationFrequency=%{public}d, finalFrequency=%{public}d, "
1566         "localWideBand=%{public}d, remoteWideBand=%{public}d",
1567         stationFrequency, finalFrequency, isLocalWideBandSupported, isRemoteWideBandSupported);
1568 
1569     P2pAdapter::CreateGroupParam param {};
1570     param.frequency = finalFrequency;
1571     param.isWideBandSupported = isLocalWideBandSupported && isRemoteWideBandSupported;
1572     auto result = P2pEntity::GetInstance().CreateGroup(param);
1573     if (connectCommand_ != nullptr) {
1574         connectCommand_->GetConnectInfo().info_.dfxInfo.frequency = param.frequency;
1575     }
1576     CONN_CHECK_AND_RETURN_RET_LOGW(result.errorCode_ == SOFTBUS_OK, result.errorCode_, CONN_WIFI_DIRECT,
1577         "create group failed, error=%{public}d", result.errorCode_);
1578 
1579     std::string remoteMac = msg.GetLegacyP2pMac();
1580     std::string remoteIp;
1581     int32_t ret = P2pAdapter::RequestGcIp(remoteMac, remoteIp);
1582     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, SOFTBUS_CONN_PV1_APPLY_GC_IP_FAIL, CONN_WIFI_DIRECT,
1583         "apply gc ip failed, error=%{public}d", ret);
1584 
1585     std::string localMac;
1586     std::string localIp;
1587     ret = InterfaceManager::GetInstance().UpdateInterface(
1588         InterfaceInfo::P2P, [&localMac, &localIp](InterfaceInfo &interface) {
1589             localMac = interface.GetBaseMac();
1590             localIp = interface.GetIpString().ToIpString();
1591             interface.SetReuseCount(interface.GetReuseCount() + 1);
1592             CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount=%{public}d", interface.GetReuseCount());
1593             return SOFTBUS_OK;
1594         });
1595     CONN_CHECK_AND_RETURN_RET_LOGW(
1596         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "update interface failed, error=%{public}d", ret);
1597 
1598     auto success = LinkManager::GetInstance().ProcessIfAbsent(
1599         InnerLink::LinkType::P2P, msg.GetRemoteDeviceId(), [localMac, localIp, remoteMac, remoteIp](InnerLink &link) {
1600             link.SetLocalBaseMac(localMac);
1601             link.SetLocalIpv4(localIp);
1602             link.SetRemoteBaseMac(remoteMac);
1603             link.SetRemoteIpv4(remoteIp);
1604             link.SetState(InnerLink::LinkState::CONNECTING);
1605         });
1606     CONN_CHECK_AND_RETURN_RET_LOGW(
1607         success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "update inner link failed");
1608 
1609     P2pEntity::GetInstance().NotifyNewClientJoining(remoteMac);
1610     return StartAuthListening(localIp);
1611 }
1612 
UpdateWhenConnectSuccess(std::string groupConfig,const NegotiateMessage & msg)1613 int P2pV1Processor::UpdateWhenConnectSuccess(std::string groupConfig, const NegotiateMessage &msg)
1614 {
1615     std::string localMac;
1616     std::string localIp;
1617     auto myRole = LinkInfo::LinkMode::NONE;
1618     auto ret = InterfaceManager::GetInstance().UpdateInterface(
1619         InterfaceInfo::P2P, [groupConfig, &myRole, &localMac, &localIp](InterfaceInfo &interface) {
1620             interface.SetP2pGroupConfig(groupConfig);
1621             int32_t reuseCount = interface.GetReuseCount();
1622             interface.SetReuseCount(reuseCount + 1);
1623             CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount=%{public}d", interface.GetReuseCount());
1624             localMac = interface.GetBaseMac();
1625             localIp = interface.GetIpString().ToIpString();
1626             myRole = interface.GetRole();
1627             return SOFTBUS_OK;
1628         });
1629     CONN_CHECK_AND_RETURN_RET_LOGW(
1630         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "update interface failed, error=%{public}d", ret);
1631     std::string remoteMac = msg.GetLegacyP2pMac();
1632     auto success = LinkManager::GetInstance().ProcessIfPresent(remoteMac, [localMac, localIp](InnerLink &link) {
1633         link.SetLocalBaseMac(localMac);
1634         link.SetLocalIpv4(localIp);
1635         link.SetState(InnerLink::LinkState::CONNECTED);
1636     });
1637     CONN_CHECK_AND_RETURN_RET_LOGW(
1638         success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "update inner link failed");
1639     WifiDirectUtils::SyncLnnInfoForP2p(WifiDirectUtils::ToWifiDirectRole(myRole), localMac, msg.GetLegacyP2pGoMac());
1640     ret = StartAuthListening(localIp);
1641     CONN_CHECK_AND_RETURN_RET_LOGW(
1642         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "start auth listen failed, error=%{public}d", ret);
1643     return SOFTBUS_OK;
1644 }
1645 
ConnectGroup(const NegotiateMessage & msg,const std::shared_ptr<NegotiateChannel> & channel)1646 int P2pV1Processor::ConnectGroup(const NegotiateMessage &msg, const std::shared_ptr<NegotiateChannel> &channel)
1647 {
1648     auto goPort = msg.GetLegacyP2pGoPort();
1649     auto groupConfig = msg.GetLegacyP2pGroupConfig();
1650     auto gcIp = msg.GetLegacyP2pGcIp();
1651     CONN_LOGI(CONN_WIFI_DIRECT, "goPort=%{public}d, gcIp=%{public}s", goPort, WifiDirectAnonymizeIp(gcIp).c_str());
1652     std::string remoteMac = msg.GetLegacyP2pMac();
1653     std::string remoteIp = msg.GetLegacyP2pGoIp();
1654     auto success = LinkManager::GetInstance().ProcessIfAbsent(
1655         InnerLink::LinkType::P2P, msg.GetRemoteDeviceId(), [remoteMac, remoteIp](InnerLink &link) {
1656             link.SetRemoteBaseMac(remoteMac);
1657             link.SetRemoteIpv4(remoteIp);
1658         });
1659     CONN_CHECK_AND_RETURN_RET_LOGW(
1660         success, SOFTBUS_CONN_PV1_INTERNAL_ERR0R, CONN_WIFI_DIRECT, "update inner link failed");
1661 
1662     P2pAdapter::ConnectParam params {};
1663     params.isNeedDhcp = IsNeedDhcp(gcIp, groupConfig);
1664     params.groupConfig = groupConfig;
1665     params.gcIp = gcIp;
1666     auto result = P2pEntity::GetInstance().Connect(params);
1667     if (result.errorCode_ != SOFTBUS_OK) {
1668         CONN_LOGI(CONN_WIFI_DIRECT, "connect group failed, error=%{public}d", result.errorCode_);
1669         LinkManager::GetInstance().RemoveLink(InnerLink::LinkType::P2P, msg.GetRemoteDeviceId());
1670         P2pEntity::GetInstance().Disconnect(P2pAdapter::DestroyGroupParam { IF_NAME_P2P0 });
1671         return result.errorCode_;
1672     }
1673     auto ret = UpdateWhenConnectSuccess(groupConfig, msg);
1674     CONN_CHECK_AND_RETURN_RET_LOGW(
1675         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "update date failed, error=%{public}d", ret);
1676     ret = OpenAuthConnection(msg, channel);
1677     CONN_CHECK_AND_RETURN_RET_LOGW(
1678         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "open auth connection failed, error=%{public}d", ret);
1679     return SOFTBUS_OK;
1680 }
1681 
IsNeedDhcp(const std::string & gcIp,const std::string & groupConfig)1682 bool P2pV1Processor::IsNeedDhcp(const std::string &gcIp, const std::string &groupConfig)
1683 {
1684     if (gcIp.empty()) {
1685         CONN_LOGI(CONN_WIFI_DIRECT, "gcIp is empty, DHCP is true");
1686         return true;
1687     }
1688 
1689     auto configs = WifiDirectUtils::SplitString(groupConfig, "\n");
1690     if (configs.size() == P2P_GROUP_CONFIG_INDEX_MAX && configs[P2P_GROUP_CONFIG_INDEX_MODE] == "1") {
1691         CONN_LOGI(CONN_WIFI_DIRECT, "DHCP is true");
1692         return true;
1693     }
1694     CONN_LOGI(CONN_WIFI_DIRECT, "DHCP is false");
1695     return false;
1696 }
1697 
ChooseFrequency(int gcFreq,const std::vector<int> & gcChannels)1698 int P2pV1Processor::ChooseFrequency(int gcFreq, const std::vector<int> &gcChannels)
1699 {
1700     auto goFreq = P2pAdapter::GetStationFrequencyWithFilter();
1701     CONN_LOGI(CONN_WIFI_DIRECT, "goFreq=%{public}d, gcFreq=%{public}d", goFreq, gcFreq);
1702 
1703     if (goFreq != CHANNEL_INVALID || gcFreq != CHANNEL_INVALID) {
1704         int32_t recommendChannel = P2pAdapter::GetRecommendChannel();
1705         if (recommendChannel != CHANNEL_INVALID) {
1706             CONN_LOGI(CONN_WIFI_DIRECT, "recommendChannel=%{public}d", recommendChannel);
1707             return WifiDirectUtils::ChannelToFrequency(recommendChannel);
1708         }
1709     }
1710 
1711     std::vector<int> goChannels;
1712     int32_t ret = P2pAdapter::GetChannel5GListIntArray(goChannels);
1713     CONN_CHECK_AND_RETURN_RET_LOGW(
1714         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get local channel list failed, error=%{public}d", ret);
1715 
1716     for (auto goChannel : goChannels) {
1717         if (std::find(gcChannels.begin(), gcChannels.end(), goChannel) != gcChannels.end()) {
1718             return WifiDirectUtils::ChannelToFrequency(goChannel);
1719         }
1720     }
1721 
1722     if (WifiDirectUtils::Is2GBand(goFreq)) {
1723         CONN_LOGI(CONN_WIFI_DIRECT, "use goFreq=%{public}d", goFreq);
1724         return goFreq;
1725     }
1726     if (WifiDirectUtils::Is2GBand(gcFreq)) {
1727         CONN_LOGI(CONN_WIFI_DIRECT, "use gcFreq=%{public}d", gcFreq);
1728         return gcFreq;
1729     }
1730 
1731     CONN_LOGI(CONN_WIFI_DIRECT, "use 2G_FIRST=%{public}d", FREQUENCY_2G_FIRST);
1732     return FREQUENCY_2G_FIRST;
1733 }
1734 
DestroyGroup()1735 int P2pV1Processor::DestroyGroup()
1736 {
1737     CONN_LOGI(CONN_WIFI_DIRECT, "start to destroy group");
1738     P2pAdapter::DestroyGroupParam param { IF_NAME_P2P0 };
1739     auto result = P2pEntity::GetInstance().DestroyGroup(param);
1740     CONN_CHECK_AND_RETURN_RET_LOGW(result.errorCode_ == SOFTBUS_OK, result.errorCode_, CONN_WIFI_DIRECT,
1741         "destroy group failed, error=%{public}d", result.errorCode_);
1742     return SOFTBUS_OK;
1743 }
1744 
ReuseP2p()1745 int P2pV1Processor::ReuseP2p()
1746 {
1747     auto ret = P2pEntity::GetInstance().ReuseLink();
1748     CONN_CHECK_AND_RETURN_RET_LOGW(
1749         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "reuse link failed, error=%{public}d", ret);
1750     return InterfaceManager::GetInstance().UpdateInterface(InterfaceInfo::P2P, [](InterfaceInfo &interface) {
1751         auto reuseCnt = interface.GetReuseCount();
1752         interface.SetReuseCount(reuseCnt + 1);
1753         CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount=%{public}d", interface.GetReuseCount());
1754         return SOFTBUS_OK;
1755     });
1756 }
1757 
ReuseLink(const std::shared_ptr<ConnectCommand> & command,InnerLink & link)1758 int P2pV1Processor::ReuseLink(const std::shared_ptr<ConnectCommand> &command, InnerLink &link)
1759 {
1760     auto requestId = command->GetConnectInfo().info_.requestId;
1761     auto pid = command->GetConnectInfo().info_.pid;
1762     bool isBeingUsedByLocal = link.IsBeingUsedByLocal();
1763     CONN_LOGI(CONN_WIFI_DIRECT, "isBeingUsedByLocal=%{public}d", isBeingUsedByLocal);
1764     if (isBeingUsedByLocal) {
1765         CONN_LOGI(CONN_WIFI_DIRECT, "reuse success");
1766         WifiDirectLink dlink {};
1767         link.GenerateLink(requestId, pid, dlink, true);
1768         command->OnSuccess(dlink);
1769         Terminate();
1770         return SOFTBUS_OK;
1771     }
1772 
1773     CONN_LOGI(CONN_WIFI_DIRECT, "requestId=%{public}d, remoteMac=%{public}s", requestId,
1774         WifiDirectAnonymizeMac(command->GetConnectInfo().info_.remoteMac).c_str());
1775     auto ipv4Info = link.GetRemoteIpv4();
1776     CONN_CHECK_AND_RETURN_RET_LOGW(!ipv4Info.empty(), SOFTBUS_CONN_PV1_USED_BY_OTHER_SERVICE_ERR, CONN_WIFI_DIRECT,
1777         "p2p link is used by another service");
1778 
1779     command->PreferNegotiateChannel();
1780     auto ret = SendReuseRequest(*command->GetConnectInfo().channel_);
1781     CONN_CHECK_AND_RETURN_RET_LOGW(
1782         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "post request failed, error=%{public}d", ret);
1783     SwitchState(&P2pV1Processor::WaitingReuseResponseState, P2P_V1_WAITING_REUSE_RESPONSE_TIME_MS);
1784     return SOFTBUS_OK;
1785 }
1786 
GetGoMac(LinkInfo::LinkMode myRole)1787 std::string P2pV1Processor::GetGoMac(LinkInfo::LinkMode myRole)
1788 {
1789     if (myRole == LinkInfo::LinkMode::NONE) {
1790         return "";
1791     }
1792 
1793     std::string goMac;
1794     if (myRole == LinkInfo::LinkMode::GO) {
1795         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&goMac](const InterfaceInfo &interface) {
1796             goMac = interface.GetBaseMac();
1797             return SOFTBUS_OK;
1798         });
1799         return goMac;
1800     }
1801     LinkManager::GetInstance().ForEach([&goMac](InnerLink &link) {
1802         if (link.GetLinkType() == InnerLink::LinkType::P2P) {
1803             goMac = link.GetRemoteBaseMac();
1804             return true;
1805         }
1806         return false;
1807     });
1808     return goMac;
1809 }
1810 
StartAuthListening(const std::string & localIp)1811 int P2pV1Processor::StartAuthListening(const std::string &localIp)
1812 {
1813     int port = 0;
1814     auto ret =
1815         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&port](const InterfaceInfo &interface) {
1816             port = interface.GetP2pListenPort();
1817             return SOFTBUS_OK;
1818         });
1819     CONN_CHECK_AND_RETURN_RET_LOGW(
1820         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get go port failed, error=%{public}d", ret);
1821     if (port > 0) {
1822         CONN_LOGI(CONN_WIFI_DIRECT, "already has started listening, port=%{public}d", port);
1823         return SOFTBUS_OK;
1824     }
1825 
1826     auto pair = AuthNegotiateChannel::StartListening(AUTH_LINK_TYPE_P2P, localIp, 0);
1827     CONN_CHECK_AND_RETURN_RET_LOGW(pair.first > 0, pair.first, CONN_WIFI_DIRECT, "start listen failed");
1828     ret = InterfaceManager::GetInstance().UpdateInterface(InterfaceInfo::P2P, [&pair](InterfaceInfo &interface) {
1829         interface.SetP2pListenPort(pair.first);
1830         interface.SetP2pListenModule(pair.second);
1831         return SOFTBUS_OK;
1832     });
1833     if (ret != SOFTBUS_OK) {
1834         CONN_LOGE(CONN_WIFI_DIRECT, "update interface failed, error=%{public}d", ret);
1835         AuthNegotiateChannel::StopListening(AUTH_LINK_TYPE_P2P, pair.second);
1836     }
1837     return ret;
1838 }
1839 
OpenAuthConnection(const NegotiateMessage & msg,const std::shared_ptr<NegotiateChannel> & channel)1840 int P2pV1Processor::OpenAuthConnection(const NegotiateMessage &msg, const std::shared_ptr<NegotiateChannel> &channel)
1841 {
1842     AuthNegotiateChannel::OpenParam param {};
1843     param.type = AUTH_LINK_TYPE_P2P;
1844     param.remoteUuid = msg.GetRemoteDeviceId();
1845     param.remoteIp = msg.GetLegacyP2pGoIp();
1846     param.remotePort = msg.GetLegacyP2pGoPort();
1847     auto ret =
1848         InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&param](const InterfaceInfo &interface) {
1849             int module = interface.GetP2pListenModule();
1850             param.module = static_cast<ListenerModule>(module);
1851             return SOFTBUS_OK;
1852         });
1853     CONN_CHECK_AND_RETURN_RET_LOGW(
1854         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get listen module failed, error=%{public}d", ret);
1855 
1856     auto authChannel = std::dynamic_pointer_cast<AuthNegotiateChannel>(channel);
1857     ret = AuthNegotiateChannel::OpenConnection(param, authChannel);
1858     CONN_CHECK_AND_RETURN_RET_LOGW(
1859         ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "open p2p auth failed, error=%{public}d", ret);
1860     return SOFTBUS_OK;
1861 }
1862 
RemoveLink(const std::string & remoteDeviceId)1863 int P2pV1Processor::RemoveLink(const std::string &remoteDeviceId)
1864 {
1865     P2pEntity::GetInstance().CancelNewClientJoining(clientJoiningMac_);
1866     int reuseCount = 0;
1867     auto ret = InterfaceManager::GetInstance().ReadInterface(
1868         InterfaceInfo::P2P, [&reuseCount](const InterfaceInfo &interface) {
1869             reuseCount = interface.GetReuseCount();
1870             return SOFTBUS_OK;
1871         });
1872     CONN_CHECK_AND_RETURN_RET_LOGW(ret == SOFTBUS_OK, ret, CONN_WIFI_DIRECT, "get port failed, error=%{public}d", ret);
1873 
1874     CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount=%{public}d", reuseCount);
1875     if (reuseCount == 0) {
1876         CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount already 0, do not call entity disconnect");
1877         return SOFTBUS_OK;
1878     }
1879     P2pAdapter::DestroyGroupParam param { IF_NAME_P2P0 };
1880     auto result = P2pEntity::GetInstance().Disconnect(param);
1881     CONN_CHECK_AND_RETURN_RET_LOGW(result.errorCode_ == SOFTBUS_OK, result.errorCode_, CONN_WIFI_DIRECT,
1882         "entity disconnect failed, error=%{public}d", result.errorCode_);
1883 
1884     return InterfaceManager::GetInstance().UpdateInterface(InterfaceInfo::P2P, [](InterfaceInfo &interface) {
1885         auto reuseCount = interface.GetReuseCount();
1886         if (reuseCount == 0) {
1887             CONN_LOGW(CONN_WIFI_DIRECT, "reuseCount already 0 and can not be reduced");
1888             return SOFTBUS_OK;
1889         }
1890         interface.SetReuseCount(reuseCount - 1);
1891         CONN_LOGI(CONN_WIFI_DIRECT, "reuseCount=%{public}d", interface.GetReuseCount());
1892         return SOFTBUS_OK;
1893     });
1894 }
1895 
GetFinalRoleWithPeerExpectedRole(WifiDirectRole myRole,WifiDirectRole peerRole,WifiDirectRole expectedRole,const std::string & localGoMac,const std::string & remoteGoMac)1896 int P2pV1Processor::GetFinalRoleWithPeerExpectedRole(WifiDirectRole myRole, WifiDirectRole peerRole,
1897     WifiDirectRole expectedRole, const std::string &localGoMac, const std::string &remoteGoMac)
1898 {
1899     CONN_LOGI(CONN_WIFI_DIRECT,
1900         "myRole=%{public}d, peerRole=%{public}d, expectedRole=%{public}d, localGoMac=%{public}s, "
1901         "remoteGoMac=%{public}s",
1902         static_cast<int>(myRole), static_cast<int>(peerRole), static_cast<int>(expectedRole),
1903         WifiDirectAnonymizeMac(localGoMac).c_str(), WifiDirectAnonymizeMac(remoteGoMac).c_str());
1904 
1905     if (myRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1906         return GetFinalRoleAsGo(peerRole, expectedRole, localGoMac, remoteGoMac);
1907     } else if (myRole == WifiDirectRole::WIFI_DIRECT_ROLE_GC) {
1908         return GetFinalRoleAsGc(peerRole, expectedRole, localGoMac, remoteGoMac);
1909     } else if (myRole == WifiDirectRole::WIFI_DIRECT_ROLE_NONE) {
1910         return GetFinalRoleAsNone(peerRole, expectedRole);
1911     } else {
1912         CONN_LOGE(CONN_WIFI_DIRECT, "myRole invalid. myRole=%{public}d", static_cast<int>(myRole));
1913         return SOFTBUS_INVALID_PARAM;
1914     }
1915 }
1916 
GetFinalRoleAsGo(WifiDirectRole peerRole,WifiDirectRole expectedRole,const std::string & localGoMac,const std::string & remoteGoMac)1917 int P2pV1Processor::GetFinalRoleAsGo(
1918     WifiDirectRole peerRole, WifiDirectRole expectedRole, const std::string &localGoMac, const std::string &remoteGoMac)
1919 {
1920     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1921         CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_BOTH_GO_ERR");
1922         return SOFTBUS_CONN_PV1_BOTH_GO_ERR;
1923     }
1924     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_GC) {
1925         if (remoteGoMac.empty() || WifiDirectUtils::CompareIgnoreCase(remoteGoMac, localGoMac) != 0) {
1926             return SOFTBUS_CONN_PV1_PEER_GC_CONNECTED_TO_ANOTHER_DEVICE;
1927         }
1928         if (expectedRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1929             CONN_LOGE(CONN_WIFI_DIRECT, "mismatched role, remote expect GO");
1930             return SOFTBUS_CONN_PV1_GC_AVAILABLE_WITH_MISMATCHED_ROLE_ERR;
1931         }
1932         return WifiDirectRole::WIFI_DIRECT_ROLE_GO;
1933     }
1934     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_NONE) {
1935         if (expectedRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1936             CONN_LOGE(CONN_WIFI_DIRECT, "mismatched role, remote expect GO");
1937             return SOFTBUS_CONN_PV1_GC_AVAILABLE_WITH_MISMATCHED_ROLE_ERR;
1938         }
1939         return WifiDirectRole::WIFI_DIRECT_ROLE_GO;
1940     }
1941 
1942     CONN_LOGE(CONN_WIFI_DIRECT, "peer role invalid. peerRole=%{public}d ", static_cast<int>(peerRole));
1943     return SOFTBUS_CONN_PV1_PEER_ROLE_INVALID;
1944 }
1945 
GetFinalRoleAsGc(WifiDirectRole peerRole,WifiDirectRole expectedRole,const std::string & localGoMac,const std::string & remoteGoMac)1946 int P2pV1Processor::GetFinalRoleAsGc(
1947     WifiDirectRole peerRole, WifiDirectRole expectedRole, const std::string &localGoMac, const std::string &remoteGoMac)
1948 {
1949     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1950         if (!localGoMac.empty() && WifiDirectUtils::CompareIgnoreCase(localGoMac, remoteGoMac) == 0) {
1951             return WifiDirectRole::WIFI_DIRECT_ROLE_GC;
1952         }
1953         CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE");
1954         return SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE;
1955     }
1956     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_NONE) {
1957         CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE");
1958         return SOFTBUS_CONN_PV1_IF_NOT_AVAILABLE;
1959     }
1960     CONN_LOGE(CONN_WIFI_DIRECT, "SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE");
1961     return SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE;
1962 }
1963 
GetFinalRoleAsNone(WifiDirectRole peerRole,WifiDirectRole expectedRole)1964 int P2pV1Processor::GetFinalRoleAsNone(WifiDirectRole peerRole, WifiDirectRole expectedRole)
1965 {
1966     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1967         if (expectedRole == WifiDirectRole::WIFI_DIRECT_ROLE_GC) {
1968             CONN_LOGE(CONN_WIFI_DIRECT, "mismatched role, peerRole=%{public}d, expectRole=%{public}d",
1969                 static_cast<int>(peerRole), static_cast<int>(expectedRole));
1970             return SOFTBUS_CONN_PV1_GC_AVAILABLE_WITH_MISMATCHED_ROLE_ERR;
1971         }
1972         return WifiDirectRole::WIFI_DIRECT_ROLE_GC;
1973     }
1974     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_GC) {
1975         if (expectedRole == WifiDirectRole::WIFI_DIRECT_ROLE_GO) {
1976             CONN_LOGE(CONN_WIFI_DIRECT, "mismatched role, remote expect GO");
1977             return SOFTBUS_CONN_PV1_GC_AVAILABLE_WITH_MISMATCHED_ROLE_ERR;
1978         }
1979         return SOFTBUS_CONN_PV1_GC_CONNECTED_TO_ANOTHER_DEVICE;
1980     }
1981     if (peerRole == WifiDirectRole::WIFI_DIRECT_ROLE_NONE) {
1982         if (expectedRole == WifiDirectRole::WIFI_DIRECT_ROLE_GC) {
1983             return WifiDirectRole::WIFI_DIRECT_ROLE_GO;
1984         }
1985         return WifiDirectRole::WIFI_DIRECT_ROLE_GC;
1986     }
1987 
1988     CONN_LOGE(CONN_WIFI_DIRECT, "peer role invalid. peerRole=%{public}d ", static_cast<int>(peerRole));
1989     return SOFTBUS_INVALID_PARAM;
1990 }
1991 
GenerateSinkLink(WifiDirectSinkLink & sinkLink)1992 int P2pV1Processor::GenerateSinkLink(WifiDirectSinkLink &sinkLink)
1993 {
1994     bool cpyRet = strcpy_s(sinkLink.remoteUuid, sizeof(sinkLink.remoteUuid), remoteDeviceId_.c_str()) == EOK;
1995     CONN_CHECK_AND_RETURN_RET_LOGW(cpyRet, SOFTBUS_STRCPY_ERR, CONN_WIFI_DIRECT, "strcpy failed");
1996 
1997     InterfaceManager::GetInstance().ReadInterface(InterfaceInfo::P2P, [&sinkLink](const InterfaceInfo &interface) {
1998         sinkLink.bandWidth = static_cast<WifiDirectBandWidth>(interface.GetBandWidth());
1999         sinkLink.channelId = WifiDirectUtils::FrequencyToChannel(interface.GetCenter20M());
2000         return SOFTBUS_OK;
2001     });
2002     sinkLink.linkType = WIFI_DIRECT_LINK_TYPE_P2P;
2003     LinkManager::GetInstance().ProcessIfPresent(
2004         InnerLink::LinkType::P2P, remoteDeviceId_, [&sinkLink, &cpyRet](InnerLink &link) {
2005             cpyRet = cpyRet &&
2006                 (strcpy_s(sinkLink.localIp, sizeof(sinkLink.localIp), link.GetLocalIpv4().c_str()) == EOK) &&
2007                 (strcpy_s(sinkLink.remoteIp, sizeof(sinkLink.remoteIp), link.GetRemoteIpv4().c_str()) == EOK) &&
2008                 (strcpy_s(sinkLink.remoteMac, sizeof(sinkLink.remoteMac), link.GetRemoteBaseMac().c_str()) == EOK);
2009         });
2010 
2011     CONN_CHECK_AND_RETURN_RET_LOGW(cpyRet, SOFTBUS_STRCPY_ERR, CONN_WIFI_DIRECT, "strcpy failed");
2012     return SOFTBUS_OK;
2013 }
2014 
CleanupIfNeed(int32_t reason,const std::string & remoteDeviceId)2015 void P2pV1Processor::CleanupIfNeed(int32_t reason, const std::string &remoteDeviceId)
2016 {
2017     if (reason == SOFTBUS_OK) {
2018         return;
2019     }
2020 
2021     bool exist =
2022         LinkManager::GetInstance().ProcessIfPresent(InnerLink::LinkType::P2P, remoteDeviceId, [](InnerLink &link) {});
2023     if (!exist) {
2024         return;
2025     }
2026     CONN_LOGI(CONN_WIFI_DIRECT, "start cleanup ctx, reason=%{public}d", reason);
2027     (void)RemoveLink(remoteDeviceId);
2028     LinkManager::GetInstance().RemoveLink(InnerLink::LinkType::P2P, remoteDeviceId);
2029 }
2030 
Exclusive(const std::string & remoteDeviceId)2031 void P2pV1Processor::Exclusive(const std::string &remoteDeviceId)
2032 {
2033     if (exclusive_) {
2034         CONN_LOGE(CONN_WIFI_DIRECT, "already exclusive, skip");
2035         return;
2036     }
2037     InterfaceManager::GetInstance().LockInterface(InterfaceInfo::P2P, remoteDeviceId);
2038     exclusive_ = true;
2039 }
2040 
RemoveExclusive()2041 void P2pV1Processor::RemoveExclusive()
2042 {
2043     if (!exclusive_) {
2044         return;
2045     }
2046     InterfaceManager::GetInstance().UnlockInterface(InterfaceInfo::P2P);
2047     exclusive_ = false;
2048 }
2049 
StartTimer(int timeoutInMillis)2050 void P2pV1Processor::StartTimer(int timeoutInMillis)
2051 {
2052     StopTimer();
2053     if (timeoutInMillis <= 0) {
2054         return;
2055     }
2056 
2057     timerId_ = timer_.Register(
2058         [this]() {
2059             CONN_LOGE(CONN_WIFI_DIRECT, "timeout");
2060             executor_->SendEvent(std::make_shared<TimeoutEvent>());
2061         },
2062         timeoutInMillis, true);
2063     CONN_LOGD(CONN_WIFI_DIRECT, "timerId=%{public}u", timerId_);
2064 }
2065 
StopTimer()2066 void P2pV1Processor::StopTimer()
2067 {
2068     if (timerId_ != Utils::TIMER_ERR_INVALID_VALUE) {
2069         CONN_LOGD(CONN_WIFI_DIRECT, "timerId=%{public}u", timerId_);
2070         timer_.Unregister(timerId_);
2071         timerId_ = Utils::TIMER_ERR_INVALID_VALUE;
2072     }
2073 }
2074 
Terminate()2075 void P2pV1Processor::Terminate()
2076 {
2077     StopTimer();
2078     RemoveExclusive();
2079     throw ProcessorTerminate();
2080 }
2081 
2082 } // namespace OHOS::SoftBus
2083