#include "login_client.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace ava2 { struct LoginClient::Resolution { struct Address { sockaddr_storage address{}; socklen_t size=0; int family=0; }; std::atomic ready{false}; std::vector
addresses; std::string error; }; LoginClient::~LoginClient() { close_socket(); } void LoginClient::close_socket() { if(fd_>=0) close(fd_);fd_=-1; } void LoginClient::cancel() { ++generation_;close_socket();resolution_.reset();session_.reset();outgoing_.clear();events_.clear();send_offset_=0;status_=Status::Idle;direct_enter_=warp_=false; } void LoginClient::notify(EventType type,std::string reason,bool connection_failure) { events_.push_back({type,std::move(reason),connection_failure,generation_}); } void LoginClient::fail(std::string reason,bool connection_failure) { if(status_==Status::Failed) return; close_socket();resolution_.reset();outgoing_.clear();status_=Status::Failed;auto type=on_game_ && reason=="server disconnected"?EventType::RemoteDisconnect:EventType::Failure;notify(type,std::move(reason),connection_failure); } void LoginClient::connect(Endpoint auth,Endpoint game,std::string account,std::string password) { if(auth.host.empty() || game.host.empty() || auth.port<1 || auth.port>65535 || game.port<1 || game.port>65535) throw std::invalid_argument("invalid auth/game endpoint"); std::random_device random;wire::Key key{};for(auto& v:key) v=random(); auto candidate=std::make_unique(std::move(account),std::move(password),key); cancel();session_=std::move(candidate);game_=std::move(game);on_game_=false;handshake_notified_=false;login_notified_=selection_notified_=loading_notified_=false; deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15);start_endpoint(auth); } void LoginClient::start_endpoint(const Endpoint& endpoint) { close_socket();outgoing_.clear();send_offset_=0;address_index_=0; resolution_=std::make_shared();status_=Status::Resolving; // Each request owns its result; cancelled/old DNS requests cannot touch client state. auto result=resolution_; std::thread([result,endpoint] { addrinfo hint{};hint.ai_family=AF_UNSPEC;hint.ai_socktype=SOCK_STREAM; addrinfo* list=nullptr;auto service=std::to_string(endpoint.port); int code=getaddrinfo(endpoint.host.c_str(),service.c_str(),&hint,&list); if(code) result->error="cannot resolve endpoint"; else { for(auto* a=list;a;a=a->ai_next) { if(a->ai_addrlen>sizeof(sockaddr_storage)) continue; Resolution::Address copy;copy.family=a->ai_family;copy.size=a->ai_addrlen;std::memcpy(©.address,a->ai_addr,a->ai_addrlen);result->addresses.push_back(copy); } freeaddrinfo(list); } result->ready.store(true,std::memory_order_release); }).detach(); } bool LoginClient::try_next_address() { close_socket(); while(address_index_addresses.size()) { const auto& a=resolution_->addresses[address_index_++];fd_=socket(a.family,SOCK_STREAM,0);if(fd_<0) continue; int flags=fcntl(fd_,F_GETFL,0);if(flags<0 || fcntl(fd_,F_SETFL,flags|O_NONBLOCK)<0) { close_socket();continue; } #ifdef SO_NOSIGPIPE int one=1;setsockopt(fd_,SOL_SOCKET,SO_NOSIGPIPE,&one,sizeof(one)); #endif int rc=::connect(fd_,reinterpret_cast(&a.address),a.size); if(rc==0) { status_=Status::Authenticating;return true; } if(errno==EINPROGRESS) { status_=Status::Connecting;return true; } close_socket(); } fail("cannot connect endpoint",true);return false; } void LoginClient::enqueue() { for(auto& bytes:session_->take_output()) outgoing_.push_back(std::move(bytes)); std::size_t total=0;for(const auto& bytes:outgoing_) total+=bytes.size(); if(total>128*1024) fail("send queue limit exceeded"); } void LoginClient::flush() { // Limit work per frame and retain unsent suffixes across EAGAIN/short writes. std::size_t budget=64*1024; while(!outgoing_.empty() && budget && fd_>=0) { auto& bytes=outgoing_.front();auto count=std::min(budget,bytes.size()-send_offset_); #ifdef MSG_NOSIGNAL constexpr int flags=MSG_NOSIGNAL; #else constexpr int flags=0; #endif auto n=send(fd_,bytes.data()+send_offset_,count,flags); if(n<0 && errno==EINTR) continue; if(n<0 && (errno==EWOULDBLOCK || errno==EAGAIN)) return; if(n<=0) { fail("connection lost while sending");return; } send_offset_+=n;budget-=n;if(send_offset_==bytes.size()) { outgoing_.pop_front();send_offset_=0; } } } void LoginClient::pump() { if(status_==Status::Idle || status_==Status::Failed) return; if(status_!=Status::Selecting && status_!=Status::Loading && std::chrono::steady_clock::now()>deadline_) { fail("connection timed out",status_==Status::Resolving || status_==Status::Connecting);return; } if(status_==Status::Resolving) { if(!resolution_->ready.load(std::memory_order_acquire)) return; if(!resolution_->error.empty()) { fail(resolution_->error,true);return; } if(!try_next_address()) return; } if(status_==Status::Connecting) { pollfd writable{fd_,POLLOUT,0};int ready=poll(&writable,1,0);if(ready<0 && errno==EINTR) return; if(ready<0) { fail("connect poll failed",true);return; }if(!ready) return; int error=0;socklen_t size=sizeof(error); if(getsockopt(fd_,SOL_SOCKET,SO_ERROR,&error,&size)!=0 || error) { if(!try_next_address() || status_==Status::Connecting) return; } else status_=Status::Authenticating; } flush();if(status_==Status::Failed) return; for(int iteration=0;iteration<16;++iteration) { // CNetworkStream::__RecvInternalBuffer: no recv() while the 128 KB buffer is full; TCP back-pressure instead of an error. std::size_t space=std::min(4096,session_->receive_space());if(!space) break; std::uint8_t buffer[4096];auto n=recv(fd_,buffer,space,0); if(n<0 && errno==EINTR) continue; if(n<0 && (errno==EAGAIN || errno==EWOULDBLOCK)) break; if(n<=0) { fail("server disconnected");return; } session_->feed({buffer,static_cast(n)});enqueue();if(status_==Status::Failed) return; if(!advance()) return; flush();if(status_==Status::Failed) return; } } // Session state transitions after new input; false when pump() must stop for this frame. bool LoginClient::advance() { if(session_->state()==LoginSession::State::Failed) { fail(session_->failure());return false; } if(session_->state()==LoginSession::State::Authenticated && !on_game_) { on_game_=true;session_->begin_game();start_endpoint(game_);return false; } if(on_game_ && session_->handshake_phase_entered() && !handshake_notified_) { handshake_notified_=true;if(!direct_enter_) notify(EventType::Handshake); } if(on_game_ && session_->game_login_sent() && !login_notified_) { login_notified_=true;if(!direct_enter_) notify(EventType::LoginStart); } // __RecvLoginSuccessPacket4 in SelectPhase: PHASE_WINDOW_SELECT.Refresh. if(session_->state()==LoginSession::State::Selecting && selection_notified_ && !direct_enter_ && session_->roster_version()!=roster_version_) notify(EventType::SelectRefresh); if(session_->state()==LoginSession::State::Selecting && !selection_notified_) { selection_notified_=true;status_=Status::Selecting; if(direct_enter_) { select(direct_enter_slot_); // Do not notify DirectEnterReady here before the server actually transitions to Loading! } else { notify(EventType::SelectReady); } } roster_version_=session_->roster_version(); if(session_->state()==LoginSession::State::Loading && !loading_notified_) { loading_notified_=true;status_=Status::Loading; notify(EventType::Loading);return false; } return true; } void LoginClient::return_to_select(std::span leftover) { if(!session_ || status_!=Status::Loading) throw std::logic_error("select phase requires an entered game session"); session_->return_to_select(leftover); // The next character choice is a fresh DirectEnter/select from the select window. direct_enter_=warp_=false;selection_notified_=loading_notified_=false; status_=Status::Entering;deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15); enqueue();advance();flush(); } wire::Bytes LoginClient::take_game_input(std::size_t max) { return session_?session_->take_game_input(max):wire::Bytes{}; } void LoginClient::send_game_packet(wire::Bytes packet,bool sequence) { if(status_!=Status::Loading || !session_) throw std::logic_error("game transport is not ready"); session_->send_game_packet(std::move(packet),sequence);enqueue();flush(); } void LoginClient::direct_enter(std::uint8_t slot) { if(!session_ || status_!=Status::Selecting || slot>=session_->characters().size() || !session_->characters()[slot].id) throw std::invalid_argument("DirectEnter requires an occupied character slot"); const auto& character=session_->characters()[slot]; reconnect(character.address,character.port,slot,false); } void LoginClient::warp(std::uint32_t address,std::uint16_t port) { if(!session_ || status_!=Status::Loading) throw std::logic_error("warp requires an entered game session"); reconnect(address,port,selected_slot_,true); } void LoginClient::reconnect(std::uint32_t wire_address,std::uint16_t port,std::uint8_t slot,bool warp) { // Windows CNetworkAddress::Set(DWORD) copies the little-endian wire DWORD to sin_addr. in_addr address{};address.s_addr=wire_address; char host[INET_ADDRSTRLEN]{}; if(!wire_address || !port || !inet_ntop(AF_INET,&address,host,sizeof(host))) throw std::invalid_argument("character server endpoint is missing"); session_->reconnect_game(); // A new game connection: stale events are dropped and the handshake clock is re-synchronized. ++generation_;events_.clear(); direct_enter_=true;warp_=warp;direct_enter_slot_=slot;handshake_notified_=false;login_notified_=selection_notified_=loading_notified_=false; deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15); start_endpoint({host,port}); } void LoginClient::select(std::uint8_t slot) { if(!session_) throw std::logic_error("not connected");session_->select(slot);selected_slot_=slot;status_=Status::Entering;deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15);enqueue(); } std::vector LoginClient::take_events() { auto events=std::move(events_);events_.clear();return events; } }