v5_handler.go 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056
  1. package icq_legacy
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "fmt"
  7. "log/slog"
  8. "net"
  9. "time"
  10. "github.com/mk6i/open-oscar-server/state"
  11. "github.com/mk6i/open-oscar-server/wire"
  12. )
  13. // V5Handler handles ICQ V5 protocol packets
  14. // V5 has full packet encryption and META_USER commands
  15. type V5Handler struct {
  16. sessions *LegacySessionManager
  17. service LegacyService
  18. sender PacketSender
  19. packetBuilder V5PacketBuilder // Packet builder for constructing V5 protocol packets
  20. dispatcher MessageDispatcher // Central dispatcher for cross-protocol messaging
  21. logger *slog.Logger
  22. }
  23. // NewV5Handler creates a new V5 protocol handler
  24. func NewV5Handler(
  25. sessions *LegacySessionManager,
  26. service LegacyService,
  27. sender PacketSender,
  28. packetBuilder V5PacketBuilder,
  29. logger *slog.Logger,
  30. ) *V5Handler {
  31. return &V5Handler{
  32. sessions: sessions,
  33. service: service,
  34. sender: sender,
  35. packetBuilder: packetBuilder,
  36. dispatcher: nil, // Set later via SetDispatcher to avoid circular dependency
  37. logger: logger,
  38. }
  39. }
  40. // SetSender sets the packet sender (for circular dependency resolution)
  41. func (h *V5Handler) SetSender(sender PacketSender) {
  42. h.sender = sender
  43. }
  44. // SetDispatcher sets the message dispatcher for cross-protocol messaging
  45. func (h *V5Handler) SetDispatcher(dispatcher MessageDispatcher) {
  46. h.dispatcher = dispatcher
  47. }
  48. // Handle processes a V5 protocol packet
  49. func (h *V5Handler) Handle(session *LegacySession, addr *net.UDPAddr, packet []byte) error {
  50. // V5 packet format (encrypted from offset 0x0A):
  51. // Version(2) + Zero(4) + UIN(4) + [Encrypted: SessionID(4) + Command(2) + SeqNum1(2) + SeqNum2(2)] + CheckCode(4) + [Encrypted: Data...]
  52. if len(packet) < 24 {
  53. return fmt.Errorf("V5 packet too short: %d bytes", len(packet))
  54. }
  55. h.logger.Debug("raw V5 packet before decryption",
  56. "hex", fmt.Sprintf("%X", packet),
  57. "len", len(packet),
  58. )
  59. // Make a copy for decryption
  60. decrypted := make([]byte, len(packet))
  61. copy(decrypted, packet)
  62. // Decrypt the packet (sessionID is not used - key is derived from packet)
  63. DecryptV5Packet(decrypted, 0)
  64. h.logger.Debug("V5 packet after decryption",
  65. "hex", fmt.Sprintf("%X", decrypted),
  66. )
  67. // Parse decrypted packet
  68. pkt, err := UnmarshalV5ClientPacket(decrypted)
  69. if err != nil {
  70. return fmt.Errorf("parsing V5 packet: %w", err)
  71. }
  72. h.logger.Info("V5 packet received",
  73. "command", fmt.Sprintf("0x%04X", pkt.Command),
  74. "uin", pkt.UIN,
  75. "session_id", pkt.SessionID,
  76. "seq1", pkt.SeqNum1,
  77. "seq2", pkt.SeqNum2,
  78. "data_len", len(pkt.Data),
  79. "addr", addr.String(),
  80. )
  81. // Update session activity if we have one
  82. if session != nil {
  83. session.UpdateActivity()
  84. session.SeqNumClient = pkt.SeqNum1
  85. }
  86. // If no session exists and this is not a login/registration/ack command,
  87. // send NOT_CONNECTED (0x00F0) to force the client to reconnect.
  88. // This handles the case where the server restarted but the UDP client
  89. // kept sending packets (keep-alives, commands) to the old session.
  90. // The V5 client (licq) handles this as "Server says you are not logged on"
  91. // and triggers icqRelogon().
  92. if session == nil {
  93. switch pkt.Command {
  94. case ICQLegacyCmdAck, ICQLegacyCmdFirstLogin,
  95. ICQLegacyCmdGetDeps, ICQLegacyCmdLogin,
  96. ICQLegacyCmdRegNewUser:
  97. // Allow these through - they don't require a session
  98. default:
  99. h.logger.Info("V5 packet from unknown session, sending NOT_CONNECTED",
  100. "command", fmt.Sprintf("0x%04X", pkt.Command),
  101. "uin", pkt.UIN,
  102. "addr", addr.String(),
  103. )
  104. return h.sendV5NotConnected(addr, pkt.SessionID, pkt.UIN, pkt.SeqNum1, pkt.SeqNum2)
  105. }
  106. }
  107. // Handle ALL V5 commands directly - NO fallback to V2!
  108. switch pkt.Command {
  109. case ICQLegacyCmdAck:
  110. h.logger.Debug("received V5 ACK", "seq1", pkt.SeqNum1, "seq2", pkt.SeqNum2)
  111. return nil
  112. case ICQLegacyCmdFirstLogin:
  113. return h.handleFirstLogin(session, addr, pkt)
  114. case ICQLegacyCmdGetDeps:
  115. return h.handleGetDeps(session, addr, pkt)
  116. case ICQLegacyCmdLogin:
  117. return h.handleLogin(session, addr, pkt)
  118. case ICQLegacyCmdContactList:
  119. return h.handleContactList(session, pkt)
  120. case ICQLegacyCmdKeepAlive, ICQLegacyCmdKeepAlive2:
  121. return h.handlePing(session, pkt)
  122. case ICQLegacyCmdLogoff:
  123. return h.handleLogoff(session, pkt)
  124. case ICQLegacyCmdSetStatus:
  125. return h.handleSetStatus(session, pkt)
  126. case ICQLegacyCmdThruServer, ICQLegacyCmdAuthorize:
  127. return h.handleMessage(session, pkt)
  128. case ICQLegacyCmdUserAdd:
  129. return h.handleUserAdd(session, pkt)
  130. case ICQLegacyCmdSysMsgReq:
  131. return h.handleOfflineMsgReq(session, pkt)
  132. case ICQLegacyCmdSysMsgDoneAck:
  133. return h.handleOfflineMsgAck(session, pkt)
  134. case ICQLegacyCmdMetaUser:
  135. return h.handleMetaUser(session, addr, pkt)
  136. case ICQLegacyCmdVisibleList:
  137. return h.handleVisibleList(session, pkt)
  138. case ICQLegacyCmdInvisibleList:
  139. return h.handleInvisibleList(session, pkt)
  140. case ICQLegacyCmdChangeVILists:
  141. return h.handleChangeVILists(session, pkt)
  142. case ICQLegacyCmdSearchUIN:
  143. return h.handleOldSearchUIN(session, pkt)
  144. case ICQLegacyCmdSearchUser:
  145. return h.handleOldSearch(session, pkt)
  146. case ICQLegacyCmdInfoReq:
  147. return h.handleOldInfoReq(session, pkt)
  148. case ICQLegacyCmdExtInfoReq:
  149. return h.handleOldExtInfoReq(session, pkt)
  150. case ICQLegacyCmdRegNewUser:
  151. return h.handleAckNewUIN(session, pkt)
  152. case 0x0532, 0x0533: // CMD_META_SEARCH_WHITE - white pages search sent directly
  153. return h.handleDirectWhiteSearch(session, pkt)
  154. case 0x0514, 0x0515: // CMD_META_SEARCH_NAME - name search sent directly
  155. return h.handleDirectNameSearch(session, pkt)
  156. case 0x051F: // CMD_META_SEARCH_UIN2 - UIN search sent directly (0x051E is PING2, handled above)
  157. return h.handleDirectUINSearch(session, pkt)
  158. case 0x0528, 0x0529: // CMD_META_SEARCH_EMAIL - email search sent directly
  159. return h.handleDirectEmailSearch(session, pkt)
  160. default:
  161. h.logger.Info("unhandled V5 command",
  162. "command", fmt.Sprintf("0x%04X", pkt.Command),
  163. "uin", pkt.UIN,
  164. "data_len", len(pkt.Data),
  165. )
  166. // Send ACK for unknown commands
  167. if session != nil {
  168. return h.sendV5Ack(session, pkt.SeqNum1)
  169. }
  170. return h.sendV5AckToAddr(addr, pkt.SessionID, pkt.UIN, pkt.SeqNum1, pkt.SeqNum2)
  171. }
  172. }
  173. // handleMetaUser processes META_USER commands
  174. func (h *V5Handler) handleMetaUser(session *LegacySession, addr *net.UDPAddr, pkt *V5ClientPacket) error {
  175. if len(pkt.Data) < 2 {
  176. return fmt.Errorf("META_USER packet too short")
  177. }
  178. // Send ACK first (as per iserverd v5_process_user_meta)
  179. // ACK echoes both seq1 and seq2 from the client
  180. if session != nil {
  181. _ = h.sendV5AckWithSeq2(session, pkt.SeqNum1, pkt.SeqNum2)
  182. }
  183. subCommand := binary.LittleEndian.Uint16(pkt.Data[0:2])
  184. subData := pkt.Data[2:]
  185. h.logger.Info("META_USER command",
  186. "sub_command", fmt.Sprintf("0x%04X", subCommand),
  187. "uin", pkt.UIN,
  188. "sub_data_len", len(subData),
  189. )
  190. switch subCommand {
  191. case 0x07D0: // CMD_META_LOGIN - client requests login meta info
  192. return h.handleMetaLogin(session, pkt, subData)
  193. case 0x04CE, 0x04CF: // CMD_META_USER_LOGININFO, CMD_META_USER_LOGININFO2 - request own info after login
  194. return h.handleMetaLoginInfo(session, pkt, subData)
  195. case ICQLegacyMetaSetBasic, ICQLegacyMetaSetBasic2:
  196. return h.handleMetaSetBasic(session, pkt, subData)
  197. case ICQLegacyMetaSetWork, ICQLegacyMetaSetWork2:
  198. return h.handleMetaSetWork(session, pkt, subData)
  199. case ICQLegacyMetaSetMore, ICQLegacyMetaSetMore2:
  200. return h.handleMetaSetMore(session, pkt, subData)
  201. case ICQLegacyMetaSetAbout:
  202. return h.handleMetaSetAbout(session, pkt, subData)
  203. case ICQLegacyMetaSetInterests:
  204. return h.handleMetaSetInterests(session, pkt, subData)
  205. case ICQLegacyMetaSetAffiliations:
  206. return h.handleMetaSetAffiliations(session, pkt, subData)
  207. case ICQLegacyMetaSetSecurity:
  208. return h.handleMetaSetSecurity(session, pkt, subData)
  209. case ICQLegacyMetaSetPass:
  210. return h.handleMetaSetPassword(session, pkt, subData)
  211. case ICQLegacyMetaSetHPCat:
  212. return h.handleMetaSetHPCat(session, pkt, subData)
  213. case ICQLegacyMetaUserUnreg:
  214. return h.handleMetaUnregister(session, pkt, subData)
  215. case ICQLegacyMetaUserFullInfo:
  216. return h.handleMetaUserFullInfo(session, pkt, subData)
  217. case ICQLegacyMetaUserFullInfo2:
  218. return h.handleMetaUserFullInfo2(session, pkt, subData)
  219. case ICQLegacyMetaUserInfo:
  220. return h.handleMetaUserInfo(session, pkt, subData)
  221. case ICQLegacyMetaSearchName, ICQLegacyMetaSearchName2:
  222. return h.handleMetaSearchName(session, pkt, subData)
  223. case ICQLegacyMetaSearchUIN, ICQLegacyMetaSearchUIN2:
  224. return h.handleMetaSearchUIN(session, pkt, subData)
  225. case ICQLegacyMetaSearchEmail, ICQLegacyMetaSearchEmail2:
  226. return h.handleMetaSearchEmail(session, pkt, subData)
  227. case ICQLegacyMetaSearchWhite:
  228. return h.handleMetaSearchWhite(session, pkt, subData)
  229. case ICQLegacyMetaSearchWhite2:
  230. return h.handleMetaSearchWhite2(session, pkt, subData)
  231. default:
  232. h.logger.Info("unhandled META_USER sub-command",
  233. "sub_command", fmt.Sprintf("0x%04X", subCommand),
  234. "uin", pkt.UIN,
  235. "data_len", len(subData),
  236. )
  237. return h.sendMetaAck(session, pkt.SeqNum2, subCommand)
  238. }
  239. }
  240. // handleVisibleList processes a visible list update (V5)
  241. func (h *V5Handler) handleVisibleList(session *LegacySession, pkt *V5ClientPacket) error {
  242. if session == nil {
  243. return nil
  244. }
  245. contactList, err := ParseV2ContactList(pkt.Data)
  246. if err != nil {
  247. h.logger.Info("visible list parse failed", "uin", session.UIN, "err", err)
  248. return h.sendV5Ack(session, pkt.SeqNum1)
  249. }
  250. session.SetVisibleList(contactList.UINs)
  251. h.logger.Info("visible list updated", "uin", session.UIN, "count", len(contactList.UINs), "uins", contactList.UINs)
  252. return h.sendV5Ack(session, pkt.SeqNum1)
  253. }
  254. // handleInvisibleList processes an invisible list update (V5)
  255. func (h *V5Handler) handleInvisibleList(session *LegacySession, pkt *V5ClientPacket) error {
  256. if session == nil {
  257. return nil
  258. }
  259. contactList, err := ParseV2ContactList(pkt.Data)
  260. if err != nil {
  261. h.logger.Info("invisible list parse failed", "uin", session.UIN, "err", err)
  262. return h.sendV5Ack(session, pkt.SeqNum1)
  263. }
  264. session.SetInvisibleList(contactList.UINs)
  265. h.logger.Info("invisible list updated", "uin", session.UIN, "count", len(contactList.UINs), "uins", contactList.UINs)
  266. return h.sendV5Ack(session, pkt.SeqNum1)
  267. }
  268. // handleChangeVILists processes a change to visible/invisible lists
  269. func (h *V5Handler) handleChangeVILists(session *LegacySession, pkt *V5ClientPacket) error {
  270. if session == nil {
  271. return nil
  272. }
  273. // Parse the change request
  274. // Format: action(1) + uin(4)
  275. // Action: 1=add to visible, 2=remove from visible, 3=add to invisible, 4=remove from invisible
  276. if len(pkt.Data) < 5 {
  277. h.logger.Info("change VI lists - data too short", "uin", session.UIN)
  278. return h.sendV5Ack(session, pkt.SeqNum1)
  279. }
  280. action := pkt.Data[0]
  281. targetUIN := binary.LittleEndian.Uint32(pkt.Data[1:5])
  282. actionName := "unknown"
  283. switch action {
  284. case 1:
  285. actionName = "add_visible"
  286. case 2:
  287. actionName = "remove_visible"
  288. case 3:
  289. actionName = "add_invisible"
  290. case 4:
  291. actionName = "remove_invisible"
  292. }
  293. h.logger.Info("change VI lists",
  294. "uin", session.UIN,
  295. "action", actionName,
  296. "target_uin", targetUIN,
  297. )
  298. // TODO: Implement list modifications
  299. return h.sendV5Ack(session, pkt.SeqNum1)
  300. }
  301. // handleFirstLogin processes the first login packet (0x04EC)
  302. // This is sent before the actual login to set up the connection
  303. // From iserverd v5_process_firstlog()
  304. func (h *V5Handler) handleFirstLogin(session *LegacySession, addr *net.UDPAddr, pkt *V5ClientPacket) error {
  305. // Parse session_id2 from data (4 bytes at offset 0)
  306. var sessionID2 uint32
  307. if len(pkt.Data) >= 4 {
  308. sessionID2 = binary.LittleEndian.Uint32(pkt.Data[0:4])
  309. }
  310. h.logger.Info("V5 first login",
  311. "uin", pkt.UIN,
  312. "session_id", pkt.SessionID,
  313. "session_id2", sessionID2,
  314. "addr", addr.String(),
  315. )
  316. // Send special ACK response with session_id2
  317. // From iserverd: reply includes session_id2 and 0x0001
  318. return h.sendV5FirstLoginReply(addr, pkt.SessionID, pkt.UIN, pkt.SeqNum1, pkt.SeqNum2, sessionID2)
  319. }
  320. // handleGetDeps processes the pre-auth pseudo-login packet (0x03F2)
  321. // Historically called "get departments list" in iserverd - the original ICQ server
  322. // had a departments database for organizational hierarchies. In V5, iserverd sends
  323. // a deprecated empty V3-format response. The licq.5 client does NOT use this command;
  324. // it goes straight to login. This is used by older V3/V4 clients (e.g., ICQ98a).
  325. //
  326. // The command validates credentials before the actual login.
  327. // From iserverd v5_process_getdeps()
  328. //
  329. // Refactored to use service layer (AuthenticateUser) and packet builder.
  330. // Following the OSCAR pattern: unmarshal -> call service -> build response
  331. func (h *V5Handler) handleGetDeps(session *LegacySession, addr *net.UDPAddr, pkt *V5ClientPacket) error {
  332. ctx := context.Background()
  333. // 1. Unmarshal packet to typed struct
  334. // V5 getdeps data format: UIN(4) + PWD_LEN(2) + PASSWORD + CLIENT_VERSION(4)
  335. if len(pkt.Data) < 6 {
  336. h.logger.Debug("V5 getdeps packet too short", "len", len(pkt.Data))
  337. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  338. }
  339. offset := 0
  340. // Read UIN (4 bytes)
  341. uin := binary.LittleEndian.Uint32(pkt.Data[offset : offset+4])
  342. offset += 4
  343. // Read password length (2 bytes)
  344. pwdLen := binary.LittleEndian.Uint16(pkt.Data[offset : offset+2])
  345. offset += 2
  346. if pwdLen > 20 {
  347. pwdLen = 20
  348. }
  349. // Read password
  350. if offset+int(pwdLen) > len(pkt.Data) {
  351. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, uin, pkt.SeqNum2))
  352. }
  353. password := string(pkt.Data[offset : offset+int(pwdLen)])
  354. if len(password) > 0 && password[len(password)-1] == 0 {
  355. password = password[:len(password)-1]
  356. }
  357. h.logger.Info("V5 getdeps (pseudo-login)",
  358. "uin", uin,
  359. "password", password,
  360. "session_id", pkt.SessionID,
  361. )
  362. // 2. Call service layer with typed request
  363. authReq := AuthRequest{
  364. UIN: uin,
  365. Password: password,
  366. Version: ICQLegacyVersionV5,
  367. }
  368. loginOK, err := h.service.ValidateCredentials(ctx, authReq.UIN, authReq.Password)
  369. if err != nil {
  370. h.logger.Error("V5 getdeps authentication error", "err", err, "uin", uin)
  371. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, uin, pkt.SeqNum2))
  372. }
  373. if !loginOK {
  374. h.logger.Info("V5 getdeps FAILED - invalid credentials",
  375. "uin", uin,
  376. )
  377. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, uin, pkt.SeqNum2))
  378. }
  379. h.logger.Info("V5 getdeps OK - credentials valid", "uin", uin)
  380. // 3. Build and send responses using packet builder
  381. // Send ACK first
  382. _ = h.sender.SendPacket(addr, h.packetBuilder.BuildAckToAddr(pkt.SessionID, uin, pkt.SeqNum1, pkt.SeqNum2))
  383. // Send depslist response (V3 format packet!) using packet builder
  384. return h.sender.SendPacket(addr, h.packetBuilder.BuildDepsListReply(uin, pkt.SeqNum2))
  385. }
  386. // handleContactList processes contact list (0x0406)
  387. // From iserverd v5_process_contact_list(): processes contact list and sends online notifications
  388. //
  389. // Refactored to use service layer (ProcessContactList) and packet builder.
  390. // Following the OSCAR pattern: unmarshal -> call service -> send notifications
  391. func (h *V5Handler) handleContactList(session *LegacySession, pkt *V5ClientPacket) error {
  392. if session == nil {
  393. return nil
  394. }
  395. // 1. Send ACK using packet builder
  396. _ = h.sender.SendPacket(session.Addr, h.packetBuilder.BuildAck(session, pkt.SeqNum1))
  397. // 2. Unmarshal packet to typed request struct
  398. req, err := h.parseContactListPacket(pkt.Data, session.UIN)
  399. if err != nil {
  400. h.logger.Debug("V5 contact list parse error", "uin", session.UIN, "err", err)
  401. // Send contact list done even on parse error
  402. return h.sender.SendToSession(session, h.packetBuilder.BuildContactListDone(session, pkt.SeqNum2))
  403. }
  404. h.logger.Info("V5 contact list",
  405. "uin", session.UIN,
  406. "count", len(req.Contacts),
  407. "contacts", req.Contacts,
  408. )
  409. // Store contact list in session (handler responsibility - session management)
  410. session.SetContactList(req.Contacts)
  411. // 3. Call service layer with typed request
  412. ctx := context.Background()
  413. result, err := h.service.ProcessContactList(ctx, session.Instance, req)
  414. if err != nil {
  415. h.logger.Error("contact list processing failed", "uin", session.UIN, "err", err)
  416. // Still send contact list done on error
  417. return h.sender.SendToSession(session, h.packetBuilder.BuildContactListDone(session, pkt.SeqNum2))
  418. }
  419. // 4. Send online notifications based on service result
  420. for _, contact := range result.OnlineContacts {
  421. if contact.Online {
  422. if h.dispatcher != nil {
  423. // Use central dispatcher - routes to correct protocol based on session's version
  424. _ = h.dispatcher.SendUserOnline(session, contact.UIN, contact.Status)
  425. } else {
  426. // Fallback to V5 format if dispatcher not set using packet builder
  427. _ = h.sender.SendToSession(session, h.packetBuilder.BuildUserOnline(session, contact.UIN, contact.Status))
  428. }
  429. }
  430. }
  431. h.notifyContactsUserOnline(session)
  432. // 5. Send contact list done using packet builder
  433. return h.sender.SendToSession(session, h.packetBuilder.BuildContactListDone(session, pkt.SeqNum2))
  434. }
  435. // parseContactListPacket parses a V5 contact list packet into a typed ContactListRequest struct.
  436. // Format: COUNT(1) + UIN(4)*COUNT
  437. func (h *V5Handler) parseContactListPacket(data []byte, ownerUIN uint32) (ContactListRequest, error) {
  438. req := ContactListRequest{
  439. UIN: ownerUIN,
  440. Contacts: make([]uint32, 0),
  441. }
  442. if len(data) < 1 {
  443. return req, fmt.Errorf("contact list packet too short: %d bytes", len(data))
  444. }
  445. // Contact count (1 byte)
  446. count := int(data[0])
  447. offset := 1
  448. // Parse contact UINs
  449. for i := 0; i < count && offset+4 <= len(data); i++ {
  450. contactUIN := binary.LittleEndian.Uint32(data[offset : offset+4])
  451. req.Contacts = append(req.Contacts, contactUIN)
  452. offset += 4
  453. }
  454. return req, nil
  455. }
  456. // notifyContactsUserOnline notifies all contacts who have this user in their list that we're online
  457. // Following iserverd's pattern: when user comes online, notify everyone who cares
  458. func (h *V5Handler) notifyContactsUserOnline(session *LegacySession) {
  459. if h.dispatcher == nil {
  460. return
  461. }
  462. // Find all sessions that have this user in their contact list
  463. contactsToNotify := h.sessions.NotifyContactsOfStatus(session)
  464. h.logger.Debug("notifying contacts of user online",
  465. "uin", session.UIN,
  466. "contacts_to_notify", contactsToNotify,
  467. )
  468. for _, contactUIN := range contactsToNotify {
  469. contactSession := h.sessions.GetSession(contactUIN)
  470. if contactSession != nil {
  471. // Use dispatcher to send in correct protocol format for each contact
  472. _ = h.dispatcher.SendUserOnline(contactSession, session.UIN, session.GetStatus())
  473. }
  474. }
  475. }
  476. // handlePing processes keep-alive packets (0x042E, 0x051E)
  477. func (h *V5Handler) handlePing(session *LegacySession, pkt *V5ClientPacket) error {
  478. if session == nil {
  479. return nil
  480. }
  481. return h.sendV5Ack(session, pkt.SeqNum1)
  482. }
  483. // handleLogoff processes logout (0x0438)
  484. func (h *V5Handler) handleLogoff(session *LegacySession, pkt *V5ClientPacket) error {
  485. if session == nil {
  486. return nil
  487. }
  488. h.logger.Info("V5 logout",
  489. "uin", session.UIN,
  490. "session_id", session.SessionID,
  491. "addr", session.Addr.String(),
  492. )
  493. // Notify contacts that this user is going offline BEFORE removing session
  494. h.notifyContactsUserOffline(session)
  495. // Notify OSCAR clients that this user went offline
  496. ctx := context.Background()
  497. if err := h.service.NotifyUserOffline(ctx, session.UIN); err != nil {
  498. h.logger.Debug("V5 failed to notify OSCAR clients of offline", "uin", session.UIN, "err", err)
  499. }
  500. h.sessions.RemoveSession(session.UIN)
  501. return nil
  502. }
  503. // notifyContactsUserOffline notifies all contacts who have this user in their list that we're offline
  504. func (h *V5Handler) notifyContactsUserOffline(session *LegacySession) {
  505. if h.dispatcher == nil {
  506. return
  507. }
  508. // Find all sessions that have this user in their contact list
  509. contactsToNotify := h.sessions.NotifyContactsOfStatus(session)
  510. h.logger.Debug("notifying contacts of user offline",
  511. "uin", session.UIN,
  512. "contacts_to_notify", contactsToNotify,
  513. )
  514. for _, contactUIN := range contactsToNotify {
  515. contactSession := h.sessions.GetSession(contactUIN)
  516. if contactSession != nil {
  517. // Use dispatcher to send offline notification in correct protocol format
  518. _ = h.dispatcher.SendUserOffline(contactSession, session.UIN)
  519. }
  520. }
  521. }
  522. // handleSetStatus processes status change (0x04D8)
  523. // From iserverd v5_process_status() - when a user changes their status
  524. // (e.g., Online -> Away, Away -> DND), this handler updates the session
  525. // and broadcasts the status change to all contacts.
  526. //
  527. // Refactored to use service layer (ProcessStatusChange) and packet builder.
  528. // Following the OSCAR pattern: unmarshal -> call service -> broadcast
  529. //
  530. // Data format: STATUS(4)
  531. // - STATUS: Combined status value (low 16 bits = status, high 16 bits = extended status)
  532. func (h *V5Handler) handleSetStatus(session *LegacySession, pkt *V5ClientPacket) error {
  533. if session == nil {
  534. return nil
  535. }
  536. // 1. Send ACK using packet builder
  537. _ = h.sender.SendPacket(session.Addr, h.packetBuilder.BuildAck(session, pkt.SeqNum1))
  538. // 2. Unmarshal packet to typed request struct
  539. req, err := h.parseStatusChangePacket(pkt.Data, session)
  540. if err != nil {
  541. h.logger.Debug("V5 status change parse error", "uin", session.UIN, "err", err)
  542. return nil
  543. }
  544. h.logger.Info("V5 status change",
  545. "uin", req.UIN,
  546. "old_status", fmt.Sprintf("0x%08X", req.OldStatus),
  547. "new_status", fmt.Sprintf("0x%08X", req.NewStatus),
  548. )
  549. // Update session status (handler responsibility - session management)
  550. session.SetStatus(req.NewStatus)
  551. // 3. Call service layer with typed request
  552. ctx := context.Background()
  553. result, err := h.service.ProcessStatusChange(ctx, req)
  554. if err != nil {
  555. h.logger.Error("status change processing failed", "uin", req.UIN, "err", err)
  556. return nil
  557. }
  558. // 4. Broadcast status change to contacts based on service result
  559. h.broadcastStatusChangeToTargets(session, req.NewStatus, result)
  560. return nil
  561. }
  562. // parseStatusChangePacket parses a V5 status change packet into a typed StatusChangeRequest struct.
  563. // Format: STATUS(4)
  564. func (h *V5Handler) parseStatusChangePacket(data []byte, session *LegacySession) (StatusChangeRequest, error) {
  565. req := StatusChangeRequest{
  566. UIN: session.UIN,
  567. OldStatus: session.GetStatus(),
  568. }
  569. if len(data) < 4 {
  570. return req, fmt.Errorf("status change packet too short: %d bytes", len(data))
  571. }
  572. // Parse new status (4 bytes)
  573. req.NewStatus = binary.LittleEndian.Uint32(data[0:4])
  574. return req, nil
  575. }
  576. // broadcastStatusChangeToTargets notifies all contacts in the service result
  577. // that the user's status has changed.
  578. // Following the OSCAR pattern: the service layer determines WHO to notify,
  579. // the handler determines HOW to notify (protocol-specific packets).
  580. func (h *V5Handler) broadcastStatusChangeToTargets(session *LegacySession, newStatus uint32, result *StatusChangeResult) {
  581. if result == nil || len(result.NotifyTargets) == 0 {
  582. return
  583. }
  584. h.logger.Debug("broadcasting status change to contacts",
  585. "uin", session.UIN,
  586. "new_status", fmt.Sprintf("0x%08X", newStatus),
  587. "notify_count", len(result.NotifyTargets),
  588. )
  589. for _, target := range result.NotifyTargets {
  590. targetSession := h.sessions.GetSession(target.UIN)
  591. if targetSession != nil {
  592. if h.dispatcher != nil {
  593. // Use dispatcher to send status change in correct protocol format
  594. // This routes to V3 or V5 handler based on the contact's protocol version
  595. _ = h.dispatcher.SendStatusChange(targetSession, session.UIN, newStatus)
  596. } else {
  597. // Fallback to V5 format if dispatcher not set using packet builder
  598. _ = h.sender.SendToSession(targetSession, h.packetBuilder.BuildUserStatus(targetSession, session.UIN, newStatus))
  599. }
  600. }
  601. }
  602. }
  603. // handleMessage processes through-server messages (0x010E)
  604. // From iserverd v5_process_sysmsg(): forwards messages to target user
  605. // Format: TARGET_UIN(4) + MSG_TYPE(2) + MSG_LEN(2) + MESSAGE
  606. //
  607. // Refactored to use service layer (ProcessMessage) and packet builder.
  608. // Following the OSCAR pattern: unmarshal -> call service -> route
  609. func (h *V5Handler) handleMessage(session *LegacySession, pkt *V5ClientPacket) error {
  610. if session == nil {
  611. return nil
  612. }
  613. // 1. Send ACK using packet builder
  614. _ = h.sender.SendPacket(session.Addr, h.packetBuilder.BuildAck(session, pkt.SeqNum1))
  615. // 2. Unmarshal packet to typed request struct
  616. req, err := h.parseMessagePacket(pkt.Data, session.UIN)
  617. if err != nil {
  618. h.logger.Debug("V5 message parse error", "from", session.UIN, "err", err)
  619. return nil
  620. }
  621. h.logger.Info("V5 message received",
  622. "from", req.FromUIN,
  623. "to", req.ToUIN,
  624. "type", fmt.Sprintf("0x%04X", req.MsgType),
  625. "msg_len", len(req.Message),
  626. )
  627. // 3. Call service layer with typed request
  628. ctx := context.Background()
  629. result, err := h.service.ProcessMessage(ctx, session, req)
  630. if err != nil {
  631. h.logger.Error("message processing failed",
  632. "from", req.FromUIN,
  633. "to", req.ToUIN,
  634. "err", err,
  635. )
  636. return nil
  637. }
  638. // 4. Route message based on service result
  639. if result.TargetOnline {
  640. // Target is online - forward message via dispatcher or direct send
  641. targetSession := h.sessions.GetSession(req.ToUIN)
  642. if targetSession != nil {
  643. if h.dispatcher != nil {
  644. // Use central dispatcher - routes to correct protocol based on target's version
  645. _ = h.dispatcher.SendOnlineMessage(targetSession, req.FromUIN, req.MsgType, req.Message)
  646. } else {
  647. // Fallback to V5 format if dispatcher not set
  648. _ = h.sendOnlineMessage(targetSession, req.FromUIN, req.MsgType, req.Message)
  649. }
  650. h.logger.Debug("V5 message forwarded",
  651. "from", req.FromUIN,
  652. "to", req.ToUIN,
  653. "target_version", targetSession.Version,
  654. )
  655. }
  656. } else if result.StoredOffline {
  657. // Message was stored for offline delivery by the service layer
  658. h.logger.Info("V5 message stored for offline delivery",
  659. "from", req.FromUIN,
  660. "to", req.ToUIN,
  661. "type", fmt.Sprintf("0x%04X", req.MsgType),
  662. )
  663. }
  664. return nil
  665. }
  666. // parseMessagePacket parses a V5 message packet into a typed MessageRequest struct.
  667. // Format: TARGET_UIN(4) + MSG_TYPE(2) + MSG_LEN(2) + MESSAGE
  668. func (h *V5Handler) parseMessagePacket(data []byte, fromUIN uint32) (MessageRequest, error) {
  669. req := MessageRequest{
  670. FromUIN: fromUIN,
  671. }
  672. if len(data) < 8 {
  673. return req, fmt.Errorf("message packet too short: %d bytes", len(data))
  674. }
  675. offset := 0
  676. // Target UIN (4 bytes)
  677. req.ToUIN = binary.LittleEndian.Uint32(data[offset : offset+4])
  678. offset += 4
  679. // Message type (2 bytes)
  680. req.MsgType = binary.LittleEndian.Uint16(data[offset : offset+2])
  681. offset += 2
  682. // Message length (2 bytes)
  683. msgLen := binary.LittleEndian.Uint16(data[offset : offset+2])
  684. offset += 2
  685. // Message content
  686. if msgLen > 0 && offset+int(msgLen) <= len(data) {
  687. req.Message = string(data[offset : offset+int(msgLen)])
  688. }
  689. return req, nil
  690. }
  691. // handleUserAdd processes user add to contact list (0x053C)
  692. // From iserverd v5_process_useradd(): adds user and sends "you were added" notification
  693. //
  694. // Refactored to use service layer (ProcessUserAdd) and packet builder.
  695. // Following the OSCAR pattern: unmarshal -> call service -> send notifications
  696. func (h *V5Handler) handleUserAdd(session *LegacySession, pkt *V5ClientPacket) error {
  697. if session == nil {
  698. return nil
  699. }
  700. // 1. Send ACK using packet builder
  701. _ = h.sender.SendPacket(session.Addr, h.packetBuilder.BuildAck(session, pkt.SeqNum1))
  702. // 2. Unmarshal packet to typed request struct
  703. req, err := h.parseUserAddPacket(pkt.Data, session.UIN)
  704. if err != nil {
  705. h.logger.Debug("V5 user add parse error", "uin", session.UIN, "err", err)
  706. return nil
  707. }
  708. h.logger.Info("V5 user add",
  709. "from", req.FromUIN,
  710. "target", req.TargetUIN,
  711. )
  712. // Add to contact list (handler responsibility - session management)
  713. contacts := session.GetContactList()
  714. contacts = append(contacts, req.TargetUIN)
  715. session.SetContactList(contacts)
  716. // 3. Call service layer with typed request
  717. ctx := context.Background()
  718. result, err := h.service.ProcessUserAdd(ctx, session.Instance, req)
  719. if err != nil {
  720. h.logger.Error("user add processing failed", "from", req.FromUIN, "target", req.TargetUIN, "err", err)
  721. return nil
  722. }
  723. // 4. Send notifications based on service result
  724. if result.TargetOnline {
  725. // Send target's online status to the user who added them using packet builder
  726. _ = h.sender.SendToSession(session, h.packetBuilder.BuildUserOnline(session, req.TargetUIN, result.TargetStatus))
  727. // Send "you were added" notification to target user if service says to
  728. if result.SendYouWereAdded {
  729. targetSession := h.sessions.GetSession(req.TargetUIN)
  730. if targetSession != nil {
  731. // Message format: nick#FE#first#FE#last#FE#email#FE#auth
  732. // Using UIN as nick for now since we don't have user info
  733. youWereAddedMsg := fmt.Sprintf("%d\xFE\xFE\xFE\xFE0", req.FromUIN)
  734. if h.dispatcher != nil {
  735. // Use dispatcher for cross-protocol support
  736. _ = h.dispatcher.SendOnlineMessage(targetSession, req.FromUIN, ICQLegacyMsgAdded, youWereAddedMsg)
  737. } else {
  738. // Fallback to V5 format using packet builder
  739. _ = h.sender.SendToSession(targetSession, h.packetBuilder.BuildOnlineMessage(targetSession, req.FromUIN, ICQLegacyMsgAdded, youWereAddedMsg))
  740. }
  741. // Also send the adder's online status to the target.
  742. // The target receives "you were added" but won't see the
  743. // adder as online unless we explicitly tell them. Without
  744. // this, the target's client shows the adder as offline
  745. // even though they're connected.
  746. if h.dispatcher != nil {
  747. _ = h.dispatcher.SendUserOnline(targetSession, req.FromUIN, session.GetStatus())
  748. } else {
  749. _ = h.sender.SendToSession(targetSession, h.packetBuilder.BuildUserOnline(targetSession, req.FromUIN, session.GetStatus()))
  750. }
  751. h.logger.Debug("V5 sent 'you were added' notification",
  752. "from", req.FromUIN,
  753. "to", req.TargetUIN,
  754. )
  755. }
  756. }
  757. }
  758. return nil
  759. }
  760. // parseUserAddPacket parses a V5 user add packet into a typed UserAddRequest struct.
  761. // Format: TARGET_UIN(4)
  762. func (h *V5Handler) parseUserAddPacket(data []byte, fromUIN uint32) (UserAddRequest, error) {
  763. req := UserAddRequest{
  764. FromUIN: fromUIN,
  765. }
  766. if len(data) < 4 {
  767. return req, fmt.Errorf("user add packet too short: %d bytes", len(data))
  768. }
  769. // Target UIN (4 bytes)
  770. req.TargetUIN = binary.LittleEndian.Uint32(data[0:4])
  771. return req, nil
  772. }
  773. // handleOfflineMsgReq processes offline message request (0x044C)
  774. func (h *V5Handler) handleOfflineMsgReq(session *LegacySession, pkt *V5ClientPacket) error {
  775. if session == nil {
  776. return nil
  777. }
  778. _ = h.sendV5Ack(session, pkt.SeqNum1)
  779. ctx := context.Background()
  780. // Fetch offline messages from database
  781. messages, err := h.service.GetOfflineMessages(ctx, session.UIN)
  782. if err != nil {
  783. h.logger.Error("failed to get offline messages", "uin", session.UIN, "err", err)
  784. return h.sendV5OfflineMsgDone(session, pkt.SeqNum2)
  785. }
  786. h.logger.Info("V5 offline message request",
  787. "uin", session.UIN,
  788. "message_count", len(messages),
  789. )
  790. // Send each offline message
  791. for _, msg := range messages {
  792. if err := h.sendV5OfflineMessage(session, &msg); err != nil {
  793. h.logger.Error("failed to send offline message",
  794. "uin", session.UIN,
  795. "from", msg.FromUIN,
  796. "err", err,
  797. )
  798. }
  799. }
  800. // Send end of offline messages
  801. return h.sendV5OfflineMsgDone(session, pkt.SeqNum2)
  802. }
  803. // handleOfflineMsgAck processes offline message acknowledgment (0x0442)
  804. // From iserverd v5_process_sysmsg_delete() - client acknowledges receipt of offline messages
  805. // After receiving this, we delete the offline messages from the database
  806. func (h *V5Handler) handleOfflineMsgAck(session *LegacySession, pkt *V5ClientPacket) error {
  807. if session == nil {
  808. return nil
  809. }
  810. _ = h.sendV5Ack(session, pkt.SeqNum1)
  811. ctx := context.Background()
  812. // Delete offline messages for this user
  813. if err := h.service.AckOfflineMessages(ctx, session.UIN); err != nil {
  814. h.logger.Error("failed to delete offline messages", "uin", session.UIN, "err", err)
  815. } else {
  816. h.logger.Info("V5 offline messages deleted", "uin", session.UIN)
  817. }
  818. return nil
  819. }
  820. // handleOldSearchUIN processes old-style search by UIN (0x041A)
  821. // From iserverd v5_process_old_srchuin()
  822. func (h *V5Handler) handleOldSearchUIN(session *LegacySession, pkt *V5ClientPacket) error {
  823. if session == nil {
  824. return nil
  825. }
  826. _ = h.sendV5Ack(session, pkt.SeqNum1)
  827. // Parse - format: TARGET_UIN(4)
  828. if len(pkt.Data) < 4 {
  829. h.logger.Info("V5 old search by UIN - data too short", "uin", session.UIN)
  830. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  831. }
  832. ctx := context.Background()
  833. targetUIN := binary.LittleEndian.Uint32(pkt.Data[0:4])
  834. h.logger.Info("V5 old search by UIN",
  835. "uin", session.UIN,
  836. "target_uin", targetUIN,
  837. )
  838. result, err := h.service.SearchByUIN(ctx, targetUIN)
  839. if err != nil {
  840. h.logger.Info("V5 old search by UIN - error", "target_uin", targetUIN, "err", err)
  841. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  842. }
  843. if result == nil {
  844. h.logger.Info("V5 old search by UIN - NOT FOUND", "target_uin", targetUIN)
  845. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  846. }
  847. h.logger.Info("V5 old search by UIN - FOUND",
  848. "target_uin", targetUIN,
  849. "nickname", result.Nickname,
  850. "firstname", result.FirstName,
  851. "lastname", result.LastName,
  852. "email", result.Email,
  853. )
  854. // Send search result
  855. _ = h.sendV5OldSearchFound(session, pkt.SeqNum2, result)
  856. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  857. }
  858. // handleOldSearch processes old-style search by name/email (0x0424)
  859. // From iserverd v5_process_old_search()
  860. func (h *V5Handler) handleOldSearch(session *LegacySession, pkt *V5ClientPacket) error {
  861. if session == nil {
  862. return nil
  863. }
  864. _ = h.sendV5Ack(session, pkt.SeqNum1)
  865. h.logger.Info("V5 old search", "uin", session.UIN, "data_len", len(pkt.Data), "status", "not_implemented")
  866. // TODO: Parse search parameters and search
  867. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  868. }
  869. // handleOldInfoReq processes old-style info request (0x0460)
  870. // From iserverd v5_process_old_info()
  871. func (h *V5Handler) handleOldInfoReq(session *LegacySession, pkt *V5ClientPacket) error {
  872. if session == nil {
  873. return nil
  874. }
  875. _ = h.sendV5Ack(session, pkt.SeqNum1)
  876. // Parse - format: TARGET_UIN(4)
  877. if len(pkt.Data) < 4 {
  878. h.logger.Info("V5 old info request - data too short", "uin", session.UIN)
  879. return nil
  880. }
  881. ctx := context.Background()
  882. targetUIN := binary.LittleEndian.Uint32(pkt.Data[0:4])
  883. h.logger.Info("V5 old info request",
  884. "uin", session.UIN,
  885. "target_uin", targetUIN,
  886. )
  887. info, err := h.service.GetUserInfo(ctx, targetUIN)
  888. if err != nil {
  889. h.logger.Info("V5 old info request - error", "target_uin", targetUIN, "err", err)
  890. return h.sendV5InvalidUIN(session, targetUIN)
  891. }
  892. if info == nil {
  893. h.logger.Info("V5 old info request - NOT FOUND", "target_uin", targetUIN)
  894. return h.sendV5InvalidUIN(session, targetUIN)
  895. }
  896. h.logger.Info("V5 old info request - FOUND",
  897. "target_uin", targetUIN,
  898. "nickname", info.Nickname,
  899. "firstname", info.FirstName,
  900. "lastname", info.LastName,
  901. )
  902. // Send basic info only - extended info is requested separately via 0x046A
  903. return h.sendV5OldStyleInfo(session, info)
  904. }
  905. // handleOldExtInfoReq processes old-style extended info request (0x046A)
  906. // From iserverd v5_process_old_info_ext()
  907. func (h *V5Handler) handleOldExtInfoReq(session *LegacySession, pkt *V5ClientPacket) error {
  908. if session == nil {
  909. return nil
  910. }
  911. _ = h.sendV5Ack(session, pkt.SeqNum1)
  912. // Parse - format: TARGET_UIN(4)
  913. if len(pkt.Data) < 4 {
  914. h.logger.Info("V5 old ext info request - data too short", "uin", session.UIN)
  915. return nil
  916. }
  917. ctx := context.Background()
  918. targetUIN := binary.LittleEndian.Uint32(pkt.Data[0:4])
  919. h.logger.Info("V5 old ext info request",
  920. "uin", session.UIN,
  921. "target_uin", targetUIN,
  922. )
  923. // Use GetFullUserInfo to get all extended info fields (city, state, phone, homepage, notes)
  924. // From iserverd v5_process_old_info_ext() which uses full_user_info and notes_user_info
  925. user, err := h.service.GetFullUserInfo(ctx, targetUIN)
  926. if err != nil {
  927. h.logger.Info("V5 old ext info request - error", "target_uin", targetUIN, "err", err)
  928. return h.sendV5InvalidUIN(session, targetUIN)
  929. }
  930. if user == nil {
  931. h.logger.Info("V5 old ext info request - NOT FOUND", "target_uin", targetUIN)
  932. return h.sendV5InvalidUIN(session, targetUIN)
  933. }
  934. h.logger.Info("V5 old ext info request - FOUND", "target_uin", targetUIN)
  935. return h.sendV5OldStyleInfoExt(session, targetUIN, user)
  936. }
  937. // handleAckNewUIN processes registration acknowledgment (0x03FC)
  938. // From iserverd v5_process_ack_new_uin()
  939. func (h *V5Handler) handleAckNewUIN(session *LegacySession, pkt *V5ClientPacket) error {
  940. if session == nil {
  941. return nil
  942. }
  943. _ = h.sendV5Ack(session, pkt.SeqNum1)
  944. h.logger.Info("V5 ack new UIN", "uin", session.UIN)
  945. // This is just an acknowledgment from client, no action needed
  946. return nil
  947. }
  948. // handleLogin processes the login packet (0x03E8)
  949. // From iserverd v5_process_login()
  950. //
  951. // Refactored to use service layer (AuthenticateUser) and packet builder.
  952. // Following the OSCAR pattern: unmarshal -> call service -> build response
  953. func (h *V5Handler) handleLogin(session *LegacySession, addr *net.UDPAddr, pkt *V5ClientPacket) error {
  954. ctx := context.Background()
  955. // 1. Send ACK first (iserverd does this immediately) using packet builder
  956. _ = h.sender.SendPacket(addr, h.packetBuilder.BuildAckToAddr(pkt.SessionID, pkt.UIN, pkt.SeqNum1, pkt.SeqNum2))
  957. // 2. Unmarshal packet to typed struct
  958. // V5 login data format (verified against licq.5 CPU_Logon):
  959. // TIME(4) + TCP_PORT(4) + PWD_LEN(2) + PASSWORD + UNKNOWN(4, =0x98) +
  960. // REAL_IP(4) + MODE(1) + STATUS(4) + DC_VERSION(4) + trailing(28 bytes)
  961. // Note: STATUS and DC_VERSION are both PackUnsignedLong (4 bytes each).
  962. if len(pkt.Data) < 10 {
  963. h.logger.Debug("V5 login packet too short", "len", len(pkt.Data))
  964. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  965. }
  966. offset := 0
  967. // Skip time(NULL) timestamp (4 bytes) - client sends current time here
  968. offset += 4
  969. // Read TCP port (4 bytes)
  970. port := binary.LittleEndian.Uint32(pkt.Data[offset : offset+4])
  971. offset += 4
  972. // Read password length (2 bytes)
  973. if offset+2 > len(pkt.Data) {
  974. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  975. }
  976. pwdLen := binary.LittleEndian.Uint16(pkt.Data[offset : offset+2])
  977. offset += 2
  978. // Sanity check password length
  979. if pwdLen > 20 {
  980. pwdLen = 20
  981. }
  982. // Read password
  983. if offset+int(pwdLen) > len(pkt.Data) {
  984. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  985. }
  986. password := string(pkt.Data[offset : offset+int(pwdLen)])
  987. // Remove null terminator if present
  988. if len(password) > 0 && password[len(password)-1] == 0 {
  989. password = password[:len(password)-1]
  990. }
  991. offset += int(pwdLen)
  992. // Parse additional fields if available
  993. // V5 login data format (from licq.5 CPU_Logon):
  994. // TIME(4) + PORT(4) + PWD_LEN(2) + PASSWORD + UNKNOWN(4) + REAL_IP(4) +
  995. // MODE(1) + STATUS(4) + DC_VERSION(4) + trailing(28 bytes)
  996. // Note: STATUS is PackUnsignedLong (4 bytes), NOT 2+2.
  997. // DC_VERSION is PackUnsignedLong (4 bytes), NOT 2 bytes.
  998. var internalIP uint32
  999. var dcType uint8
  1000. var status uint32
  1001. var dcVersion uint32
  1002. if offset+4+4+1+4+4 <= len(pkt.Data) {
  1003. offset += 4 // skip unknown (0x98 constant)
  1004. internalIP = binary.LittleEndian.Uint32(pkt.Data[offset : offset+4])
  1005. offset += 4
  1006. dcType = pkt.Data[offset]
  1007. offset++
  1008. status = binary.LittleEndian.Uint32(pkt.Data[offset : offset+4])
  1009. offset += 4
  1010. dcVersion = binary.LittleEndian.Uint32(pkt.Data[offset : offset+4])
  1011. }
  1012. h.logger.Info("V5 login attempt",
  1013. "uin", pkt.UIN,
  1014. "password", password,
  1015. "port", port,
  1016. "internal_ip", fmt.Sprintf("0x%08X", internalIP),
  1017. "dc_type", dcType,
  1018. "status", fmt.Sprintf("0x%08X", status),
  1019. "dc_version", dcVersion,
  1020. "data_len", len(pkt.Data),
  1021. )
  1022. // 3. Call service layer with typed request
  1023. authReq := AuthRequest{
  1024. UIN: pkt.UIN,
  1025. Password: password,
  1026. Status: status,
  1027. TCPPort: port,
  1028. Version: ICQLegacyVersionV5,
  1029. }
  1030. authResult, err := h.service.AuthenticateUser(ctx, authReq)
  1031. if err != nil {
  1032. h.logger.Error("V5 login authentication error", "err", err, "uin", pkt.UIN)
  1033. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  1034. }
  1035. if !authResult.Success {
  1036. h.logger.Info("V5 login FAILED - invalid credentials",
  1037. "uin", pkt.UIN,
  1038. "error_code", authResult.ErrorCode,
  1039. )
  1040. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  1041. }
  1042. // 4. Create session (handler responsibility - session management)
  1043. newSession, err := h.sessions.CreateSession(pkt.UIN, addr, ICQLegacyVersionV5, authResult.oscarSession)
  1044. if err != nil {
  1045. h.logger.Error("failed to create V5 session", "err", err, "uin", pkt.UIN)
  1046. return h.sender.SendPacket(addr, h.packetBuilder.BuildBadPassword(pkt.SessionID, pkt.UIN, pkt.SeqNum2))
  1047. }
  1048. // Use the client's session ID
  1049. newSession.SessionID = pkt.SessionID
  1050. newSession.Password = password
  1051. newSession.SetStatus(status)
  1052. // Store direct connection info for peer-to-peer
  1053. newSession.SetDirectConnectionInfo(port, internalIP, uint16(dcVersion), dcType)
  1054. // 5. Build and send response using packet builder
  1055. loginReplyPkt := h.packetBuilder.BuildLoginReply(newSession, pkt.SeqNum1, pkt.SeqNum2)
  1056. if err := h.sender.SendToSession(newSession, loginReplyPkt); err != nil {
  1057. return err
  1058. }
  1059. h.logger.Info("V5 login successful",
  1060. "uin", pkt.UIN,
  1061. "session_id", newSession.SessionID,
  1062. )
  1063. if err := h.service.NotifyUserOnline(ctx, newSession.UIN, newSession.GetStatus()); err != nil {
  1064. h.logger.Debug("V5 failed to notify OSCAR clients of online", "uin", newSession.UIN, "err", err)
  1065. }
  1066. return nil
  1067. }
  1068. // sendV5UserOnline sends user online notification
  1069. // From iserverd v5_send_user_online()
  1070. //
  1071. // Verified against licq.5 client (icqd-udp.cpp ICQ_CMDxRCV_USERxONLINE):
  1072. // Client reads: UIN(4) + IP(4) + PORT(2) + JUNK_SHORT(2) + REAL_IP(4) +
  1073. //
  1074. // MODE(1) + STATUS(4) + DC_VERSION(4)
  1075. //
  1076. // Total client reads: 25 bytes. Extra bytes after that are ignored.
  1077. //
  1078. // Our packet format (49 bytes data, iserverd-compatible):
  1079. // - UIN(4) + IP(4) + TCP_PORT(4) + INT_IP(4) + DC_TYPE(1) +
  1080. // STATUS(2)+ESTAT(2) + DCVER(4) + DC_COOKIE(4) + WEB_PORT(4) +
  1081. // CLI_FUTURES(4) + INFO_UTIME(4) + MORE_UTIME(4) + STAT_UTIME(4)
  1082. func (h *V5Handler) sendV5UserOnline(session *LegacySession, uin uint32, status uint32) error {
  1083. data := make([]byte, 49)
  1084. offset := 0
  1085. // UIN of the user who is online
  1086. binary.LittleEndian.PutUint32(data[offset:], uin)
  1087. offset += 4
  1088. // Get the online user's session to retrieve their connection info
  1089. onlineSession := h.sessions.GetSession(uin)
  1090. // From iserverd: V3 clients get zeroed connection info for TCP protection
  1091. // V5 clients get real connection info for peer-to-peer
  1092. var externalIP, tcpPort, internalIP uint32
  1093. var dcType uint8
  1094. var dcVersion uint32
  1095. if onlineSession != nil && onlineSession.Version == ICQLegacyVersionV5 {
  1096. // V5 client - send real connection info for peer-to-peer
  1097. externalIP = onlineSession.GetExternalIP()
  1098. tcpPort = onlineSession.GetTCPPort()
  1099. internalIP = onlineSession.GetInternalIP()
  1100. dcType = onlineSession.DCType
  1101. dcVersion = uint32(onlineSession.GetDCVersion())
  1102. }
  1103. // else: V3/V4 clients or unknown - keep zeros for privacy
  1104. // IP address
  1105. binary.LittleEndian.PutUint32(data[offset:], externalIP)
  1106. offset += 4
  1107. // TCP port
  1108. binary.LittleEndian.PutUint32(data[offset:], tcpPort)
  1109. offset += 4
  1110. // Internal IP
  1111. binary.LittleEndian.PutUint32(data[offset:], internalIP)
  1112. offset += 4
  1113. // DC type
  1114. data[offset] = dcType
  1115. offset++
  1116. // Status (low word)
  1117. binary.LittleEndian.PutUint16(data[offset:], uint16(status&0xFFFF))
  1118. offset += 2
  1119. // Extended status (high word)
  1120. binary.LittleEndian.PutUint16(data[offset:], uint16(status>>16))
  1121. offset += 2
  1122. // DC version
  1123. binary.LittleEndian.PutUint32(data[offset:], dcVersion)
  1124. offset += 4
  1125. // DC cookie (not implemented - would need to be stored per session)
  1126. binary.LittleEndian.PutUint32(data[offset:], 0)
  1127. offset += 4
  1128. // Web port (not implemented)
  1129. binary.LittleEndian.PutUint32(data[offset:], 0)
  1130. offset += 4
  1131. // Client futures (not implemented)
  1132. binary.LittleEndian.PutUint32(data[offset:], 0)
  1133. offset += 4
  1134. // Info update time (not implemented)
  1135. binary.LittleEndian.PutUint32(data[offset:], 0)
  1136. offset += 4
  1137. // More update time (not implemented)
  1138. binary.LittleEndian.PutUint32(data[offset:], 0)
  1139. offset += 4
  1140. // Status update time (not implemented)
  1141. binary.LittleEndian.PutUint32(data[offset:], 0)
  1142. pkt := &V5ServerPacket{
  1143. Version: ICQLegacyVersionV5,
  1144. SessionID: session.SessionID,
  1145. Command: ICQLegacySrvUserOnline,
  1146. SeqNum1: session.NextServerSeqNum(),
  1147. SeqNum2: 0,
  1148. UIN: session.UIN,
  1149. Data: data,
  1150. }
  1151. h.logger.Debug("sending V5 user online notification",
  1152. "to", session.UIN,
  1153. "online_uin", uin,
  1154. "status", fmt.Sprintf("0x%08X", status),
  1155. "external_ip", fmt.Sprintf("0x%08X", externalIP),
  1156. "tcp_port", tcpPort,
  1157. )
  1158. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  1159. }
  1160. // sendV5OfflineMessage sends an offline message to a V5 client
  1161. // From iserverd v5_send_offline_message()
  1162. // Format: FROM_UIN(4) + YEAR(2) + MONTH(1) + DAY(1) + HOUR(1) + MINUTE(1) + MSG_TYPE(2) + MSG_LEN(2) + MESSAGE
  1163. func (h *V5Handler) sendV5OfflineMessage(session *LegacySession, msg *LegacyOfflineMessage) error {
  1164. // Build message data
  1165. msgBytes := []byte(msg.Message)
  1166. dataLen := 4 + 2 + 1 + 1 + 1 + 1 + 2 + 2 + len(msgBytes) + 1
  1167. data := make([]byte, dataLen)
  1168. offset := 0
  1169. // From UIN
  1170. binary.LittleEndian.PutUint32(data[offset:], msg.FromUIN)
  1171. offset += 4
  1172. // Timestamp: YEAR(2) + MONTH(1) + DAY(1) + HOUR(1) + MINUTE(1)
  1173. binary.LittleEndian.PutUint16(data[offset:], uint16(msg.Timestamp.Year()))
  1174. offset += 2
  1175. data[offset] = byte(msg.Timestamp.Month())
  1176. offset++
  1177. data[offset] = byte(msg.Timestamp.Day())
  1178. offset++
  1179. data[offset] = byte(msg.Timestamp.Hour())
  1180. offset++
  1181. data[offset] = byte(msg.Timestamp.Minute())
  1182. offset++
  1183. // Message type
  1184. binary.LittleEndian.PutUint16(data[offset:], msg.MsgType)
  1185. offset += 2
  1186. // Message length (including null terminator)
  1187. binary.LittleEndian.PutUint16(data[offset:], uint16(len(msgBytes)+1))
  1188. offset += 2
  1189. // Message content
  1190. copy(data[offset:], msgBytes)
  1191. offset += len(msgBytes)
  1192. data[offset] = 0 // null terminator
  1193. pkt := &V5ServerPacket{
  1194. Version: ICQLegacyVersionV5,
  1195. SessionID: session.SessionID,
  1196. Command: ICQLegacySrvSysMsgOffline, // 0x00DC
  1197. SeqNum1: session.NextServerSeqNum(),
  1198. SeqNum2: 0,
  1199. UIN: session.UIN,
  1200. Data: data,
  1201. }
  1202. h.logger.Debug("sending V5 offline message",
  1203. "to", session.UIN,
  1204. "from", msg.FromUIN,
  1205. "type", fmt.Sprintf("0x%04X", msg.MsgType),
  1206. "timestamp", msg.Timestamp,
  1207. )
  1208. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  1209. }
  1210. // sendV5OfflineMsgDone sends end of offline messages
  1211. func (h *V5Handler) sendV5OfflineMsgDone(session *LegacySession, seq2 uint16) error {
  1212. pkt := &V5ServerPacket{
  1213. Version: ICQLegacyVersionV5,
  1214. SessionID: session.SessionID,
  1215. Command: ICQLegacySrvSysMsgDone,
  1216. SeqNum1: session.NextServerSeqNum(),
  1217. SeqNum2: seq2,
  1218. UIN: session.UIN,
  1219. }
  1220. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  1221. }
  1222. // META_USER sub-command handlers
  1223. // handleMetaLogin handles CMD_META_LOGIN (0x07D0)
  1224. // This is sent after login to get login meta info
  1225. // From iserverd: v5_send_lmeta()
  1226. func (h *V5Handler) handleMetaLogin(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1227. if session == nil {
  1228. return nil
  1229. }
  1230. h.logger.Info("META login request", "uin", pkt.UIN, "status", "sending_reply")
  1231. // Send login meta response
  1232. // From iserverd v5_send_lmeta(): sends 0x07D0 + 0x0000 + 0x0046
  1233. return h.sendMetaLoginReply(session, pkt.SeqNum2)
  1234. }
  1235. // handleMetaLoginInfo handles CMD_META_USER_LOGININFO/LOGININFO2 (0x04CE/0x04CF)
  1236. // This is sent after login to get the user's own info
  1237. // From iserverd: v5_reply_metafullinfo_request2()
  1238. func (h *V5Handler) handleMetaLoginInfo(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1239. if session == nil {
  1240. return nil
  1241. }
  1242. // Parse target UIN from data (4 bytes)
  1243. var targetUIN uint32
  1244. if len(data) >= 4 {
  1245. targetUIN = binary.LittleEndian.Uint32(data[0:4])
  1246. } else {
  1247. targetUIN = session.UIN
  1248. }
  1249. h.logger.Info("META login info request",
  1250. "uin", pkt.UIN,
  1251. "target_uin", targetUIN,
  1252. )
  1253. ctx := context.Background()
  1254. user, err := h.service.GetFullUserInfo(ctx, targetUIN)
  1255. if err != nil || user == nil {
  1256. h.logger.Info("META login info - NOT FOUND", "target_uin", targetUIN, "err", err)
  1257. return h.sendMetaFail(session, pkt.SeqNum2, 0x00C8)
  1258. }
  1259. info, _ := h.service.GetUserInfo(ctx, targetUIN)
  1260. h.logger.Info("META login info - FOUND, sending 7 info packets",
  1261. "target_uin", targetUIN,
  1262. "nickname", user.ICQInfo.Basic.Nickname,
  1263. )
  1264. // Send all 7 info packets as per iserverd v5_reply_metafullinfo_request2()
  1265. _ = h.sendMetaInfo3(session, pkt.SeqNum2, user) // Basic info (0x00C8)
  1266. _ = h.sendMetaMore2(session, pkt.SeqNum2, user) // More info (0x00DC)
  1267. _ = h.sendMetaHpageCat(session, pkt.SeqNum2, info) // Homepage category (0x010E)
  1268. _ = h.sendMetaWork2(session, pkt.SeqNum2, info) // Work info (0x00D2)
  1269. _ = h.sendMetaAbout(session, pkt.SeqNum2, info) // About/notes (0x00E6)
  1270. _ = h.sendMetaInterests(session, pkt.SeqNum2, info) // Interests (0x00F0)
  1271. _ = h.sendMetaAffiliations(session, pkt.SeqNum2, info) // Affiliations (0x00FA)
  1272. h.logger.Info("META login info - all packets sent", "target_uin", targetUIN)
  1273. return nil
  1274. }
  1275. func (h *V5Handler) handleMetaSetBasic(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1276. ctx := context.Background()
  1277. // V5 0x03E9 format differs from OSCAR 0x03EA: V5 sends 3 email fields
  1278. // (primary, secondary, old) while OSCAR sends 1. Manual parsing required.
  1279. r := bytes.NewReader(data)
  1280. nickname, _ := parseLEString(r)
  1281. firstName, _ := parseLEString(r)
  1282. lastName, _ := parseLEString(r)
  1283. primaryEmail, _ := parseLEString(r)
  1284. // Secondary and old email — skip (not stored in ICQBasicInfo)
  1285. _, _ = parseLEString(r) // secondary email
  1286. _, _ = parseLEString(r) // old email
  1287. city, _ := parseLEString(r)
  1288. st, _ := parseLEString(r)
  1289. phone, _ := parseLEString(r)
  1290. fax, _ := parseLEString(r)
  1291. address, _ := parseLEString(r)
  1292. cellPhone, _ := parseLEString(r)
  1293. zip, _ := parseLEString(r)
  1294. var countryCode uint16
  1295. _ = binary.Read(r, binary.LittleEndian, &countryCode)
  1296. var gmtOffset uint8
  1297. _ = binary.Read(r, binary.LittleEndian, &gmtOffset)
  1298. var publishEmail uint8
  1299. _ = binary.Read(r, binary.LittleEndian, &publishEmail)
  1300. info := state.ICQBasicInfo{
  1301. Nickname: nickname,
  1302. FirstName: firstName,
  1303. LastName: lastName,
  1304. EmailAddress: primaryEmail,
  1305. City: city,
  1306. State: st,
  1307. Phone: phone,
  1308. Fax: fax,
  1309. Address: address,
  1310. CellPhone: cellPhone,
  1311. ZIPCode: zip,
  1312. CountryCode: countryCode,
  1313. GMTOffset: gmtOffset,
  1314. PublishEmail: publishEmail == wire.ICQUserFlagPublishEmailYes,
  1315. }
  1316. if err := h.service.UpdateBasicInfo(ctx, pkt.UIN, info); err != nil {
  1317. h.logger.Error("META set basic failed", "uin", pkt.UIN, "err", err)
  1318. }
  1319. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetBasicAck)
  1320. }
  1321. // parseLEString reads a little-endian uint16 length-prefixed null-terminated string.
  1322. func parseLEString(r *bytes.Reader) (string, error) {
  1323. var length uint16
  1324. if err := binary.Read(r, binary.LittleEndian, &length); err != nil {
  1325. return "", err
  1326. }
  1327. if length == 0 {
  1328. return "", nil
  1329. }
  1330. buf := make([]byte, length)
  1331. if _, err := r.Read(buf); err != nil {
  1332. return "", err
  1333. }
  1334. // Strip null terminator
  1335. if len(buf) > 0 && buf[len(buf)-1] == 0 {
  1336. buf = buf[:len(buf)-1]
  1337. }
  1338. return string(buf), nil
  1339. }
  1340. func (h *V5Handler) handleMetaSetWork(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1341. ctx := context.Background()
  1342. var body wire.ICQ_0x07D0_0x03F3_DBQueryMetaReqSetWorkInfo
  1343. if err := wire.UnmarshalLE(&body, bytes.NewBuffer(data)); err != nil {
  1344. h.logger.Debug("META set work parse error", "uin", pkt.UIN, "err", err)
  1345. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetWorkAck)
  1346. }
  1347. info := state.ICQWorkInfo{
  1348. Company: body.Company,
  1349. Department: body.Department,
  1350. Position: body.Position,
  1351. OccupationCode: body.OccupationCode,
  1352. City: body.City,
  1353. State: body.State,
  1354. Phone: body.Phone,
  1355. Fax: body.Fax,
  1356. Address: body.Address,
  1357. ZIPCode: body.ZIP,
  1358. CountryCode: body.CountryCode,
  1359. WebPage: body.WebPage,
  1360. }
  1361. if err := h.service.UpdateWorkInfo(ctx, pkt.UIN, info); err != nil {
  1362. h.logger.Error("META set work failed", "uin", pkt.UIN, "err", err)
  1363. }
  1364. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetWorkAck)
  1365. }
  1366. func (h *V5Handler) handleMetaSetMore(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1367. ctx := context.Background()
  1368. var body wire.ICQ_0x07D0_0x03FD_DBQueryMetaReqSetMoreInfo
  1369. if err := wire.UnmarshalLE(&body, bytes.NewBuffer(data)); err != nil {
  1370. h.logger.Debug("META set more parse error", "uin", pkt.UIN, "err", err)
  1371. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetMoreAck)
  1372. }
  1373. info := state.ICQMoreInfo{
  1374. Gender: body.Gender,
  1375. HomePageAddr: body.HomePageAddr,
  1376. BirthYear: body.BirthYear,
  1377. BirthMonth: body.BirthMonth,
  1378. BirthDay: body.BirthDay,
  1379. Lang1: body.Lang1,
  1380. Lang2: body.Lang2,
  1381. Lang3: body.Lang3,
  1382. }
  1383. if err := h.service.UpdateMoreInfo(ctx, pkt.UIN, info); err != nil {
  1384. h.logger.Error("META set more failed", "uin", pkt.UIN, "err", err)
  1385. }
  1386. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetMoreAck)
  1387. }
  1388. func (h *V5Handler) handleMetaSetAbout(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1389. ctx := context.Background()
  1390. var body wire.ICQ_0x07D0_0x0406_DBQueryMetaReqSetNotes
  1391. if err := wire.UnmarshalLE(&body, bytes.NewBuffer(data)); err != nil {
  1392. h.logger.Debug("META set about parse error", "uin", pkt.UIN, "err", err)
  1393. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetAboutAck)
  1394. }
  1395. if err := h.service.SetNotes(ctx, pkt.UIN, body.Notes); err != nil {
  1396. h.logger.Error("META set about failed", "uin", pkt.UIN, "err", err)
  1397. }
  1398. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetAboutAck)
  1399. }
  1400. func (h *V5Handler) handleMetaSetInterests(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1401. ctx := context.Background()
  1402. var body wire.ICQ_0x07D0_0x0410_DBQueryMetaReqSetInterests
  1403. if err := wire.UnmarshalLE(&body, bytes.NewBuffer(data)); err != nil {
  1404. h.logger.Debug("META set interests parse error", "uin", pkt.UIN, "err", err)
  1405. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetInterestsAck)
  1406. }
  1407. if len(body.Interests) != 4 {
  1408. h.logger.Debug("META set interests: expected 4 interests", "uin", pkt.UIN, "got", len(body.Interests))
  1409. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetInterestsAck)
  1410. }
  1411. info := state.ICQInterests{
  1412. Code1: body.Interests[0].Code,
  1413. Keyword1: body.Interests[0].Keyword,
  1414. Code2: body.Interests[1].Code,
  1415. Keyword2: body.Interests[1].Keyword,
  1416. Code3: body.Interests[2].Code,
  1417. Keyword3: body.Interests[2].Keyword,
  1418. Code4: body.Interests[3].Code,
  1419. Keyword4: body.Interests[3].Keyword,
  1420. }
  1421. if err := h.service.SetInterests(ctx, pkt.UIN, info); err != nil {
  1422. h.logger.Error("META set interests failed", "uin", pkt.UIN, "err", err)
  1423. }
  1424. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetInterestsAck)
  1425. }
  1426. func (h *V5Handler) handleMetaSetAffiliations(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1427. ctx := context.Background()
  1428. var body wire.ICQ_0x07D0_0x041A_DBQueryMetaReqSetAffiliations
  1429. if err := wire.UnmarshalLE(&body, bytes.NewBuffer(data)); err != nil {
  1430. h.logger.Debug("META set affiliations parse error", "uin", pkt.UIN, "err", err)
  1431. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetAffilAck)
  1432. }
  1433. if len(body.PastAffiliations) != 3 || len(body.Affiliations) != 3 {
  1434. h.logger.Debug("META set affiliations: expected 3+3", "uin", pkt.UIN,
  1435. "past", len(body.PastAffiliations), "current", len(body.Affiliations))
  1436. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetAffilAck)
  1437. }
  1438. info := state.ICQAffiliations{
  1439. PastCode1: body.PastAffiliations[0].Code,
  1440. PastKeyword1: body.PastAffiliations[0].Keyword,
  1441. PastCode2: body.PastAffiliations[1].Code,
  1442. PastKeyword2: body.PastAffiliations[1].Keyword,
  1443. PastCode3: body.PastAffiliations[2].Code,
  1444. PastKeyword3: body.PastAffiliations[2].Keyword,
  1445. CurrentCode1: body.Affiliations[0].Code,
  1446. CurrentKeyword1: body.Affiliations[0].Keyword,
  1447. CurrentCode2: body.Affiliations[1].Code,
  1448. CurrentKeyword2: body.Affiliations[1].Keyword,
  1449. CurrentCode3: body.Affiliations[2].Code,
  1450. CurrentKeyword3: body.Affiliations[2].Keyword,
  1451. }
  1452. if err := h.service.SetAffiliations(ctx, pkt.UIN, info); err != nil {
  1453. h.logger.Error("META set affiliations failed", "uin", pkt.UIN, "err", err)
  1454. }
  1455. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetAffilAck)
  1456. }
  1457. func (h *V5Handler) handleMetaSetSecurity(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1458. ctx := context.Background()
  1459. var body wire.ICQ_0x07D0_0x0424_DBQueryMetaReqSetPermissions
  1460. if err := wire.UnmarshalLE(&body, bytes.NewBuffer(data)); err != nil {
  1461. h.logger.Debug("META set security parse error", "uin", pkt.UIN, "err", err)
  1462. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetSecureAck)
  1463. }
  1464. info := state.ICQPermissions{
  1465. AuthRequired: body.Authorization == 0, // 0 is true
  1466. WebAware: body.WebAware == 1,
  1467. }
  1468. if err := h.service.UpdatePermissions(ctx, pkt.UIN, info); err != nil {
  1469. h.logger.Error("META set security failed", "uin", pkt.UIN, "err", err)
  1470. }
  1471. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetSecureAck)
  1472. }
  1473. func (h *V5Handler) handleMetaSetPassword(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1474. ctx := context.Background()
  1475. // Parse password from data
  1476. // V5 META format: PASSWORD_LEN(2) + PASSWORD
  1477. // From iserverd v5_set_password(): v5_extract_string(password, int_pack, 32, "password", user)
  1478. if len(data) < 2 {
  1479. h.logger.Info("META set password - data too short", "uin", pkt.UIN, "data_len", len(data))
  1480. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetPassAck)
  1481. }
  1482. offset := 0
  1483. // Read password length (2 bytes)
  1484. pwdLen := binary.LittleEndian.Uint16(data[offset : offset+2])
  1485. offset += 2
  1486. // Sanity check password length
  1487. if pwdLen > 32 {
  1488. pwdLen = 32
  1489. }
  1490. // Read new password
  1491. if offset+int(pwdLen) > len(data) {
  1492. h.logger.Info("META set password - password truncated", "uin", pkt.UIN)
  1493. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetPassAck)
  1494. }
  1495. newPassword := string(data[offset : offset+int(pwdLen)])
  1496. // Remove null terminator if present
  1497. if len(newPassword) > 0 && newPassword[len(newPassword)-1] == 0 {
  1498. newPassword = newPassword[:len(newPassword)-1]
  1499. }
  1500. h.logger.Info("META set password request",
  1501. "uin", pkt.UIN,
  1502. "new_password_len", len(newPassword),
  1503. )
  1504. // Update password using service
  1505. // Note: iserverd doesn't validate old password, so we pass empty string
  1506. if err := h.service.SetPassword(ctx, pkt.UIN, "", newPassword); err != nil {
  1507. h.logger.Error("META set password failed",
  1508. "uin", pkt.UIN,
  1509. "err", err,
  1510. )
  1511. // Still send ACK to match iserverd behavior
  1512. } else {
  1513. h.logger.Info("META password updated successfully", "uin", pkt.UIN)
  1514. }
  1515. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetPassAck)
  1516. }
  1517. // handleMetaSetHPCat processes set homepage category (0x0442)
  1518. // From iserverd v5_set_hpcat_info()
  1519. func (h *V5Handler) handleMetaSetHPCat(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1520. ctx := context.Background()
  1521. // Format from iserverd v5_set_hpcat_info(): ENABLED(1) + INDEX(2) + DESC_LEN(2) + DESC
  1522. if len(data) < 5 {
  1523. h.logger.Debug("META set hpcat data too short", "uin", pkt.UIN, "len", len(data))
  1524. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetHPCatAck)
  1525. }
  1526. enabled := data[0] == 1
  1527. index := binary.LittleEndian.Uint16(data[1:3])
  1528. descLen := binary.LittleEndian.Uint16(data[3:5])
  1529. desc := ""
  1530. if descLen > 0 && 5+int(descLen) <= len(data) {
  1531. desc = string(data[5 : 5+int(descLen)])
  1532. if len(desc) > 0 && desc[len(desc)-1] == 0 {
  1533. desc = desc[:len(desc)-1]
  1534. }
  1535. }
  1536. info := state.ICQHomepageCategory{
  1537. Enabled: enabled,
  1538. Index: index,
  1539. Description: desc,
  1540. }
  1541. if err := h.service.SetHomepageCategory(ctx, pkt.UIN, info); err != nil {
  1542. h.logger.Error("META set hpcat failed", "uin", pkt.UIN, "err", err)
  1543. }
  1544. return h.sendMetaAck(session, pkt.SeqNum2, ICQLegacySrvMetaSetHPCatAck)
  1545. }
  1546. // handleMetaUnregister processes unregister account (0x04C4)
  1547. // From iserverd v5_unregister_user()
  1548. func (h *V5Handler) handleMetaUnregister(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1549. ctx := context.Background()
  1550. // Parse password from data
  1551. // Format: UIN(4) + PASSWORD_LEN(2) + PASSWORD
  1552. if len(data) < 6 {
  1553. h.logger.Info("META unregister - data too short", "uin", pkt.UIN, "data_len", len(data))
  1554. return h.sendMetaUnregAck(session, pkt.SeqNum2, false)
  1555. }
  1556. offset := 0
  1557. // Skip UIN (4 bytes) - we already have it from the packet
  1558. offset += 4
  1559. // Read password length (2 bytes)
  1560. pwdLen := binary.LittleEndian.Uint16(data[offset : offset+2])
  1561. offset += 2
  1562. // Sanity check password length
  1563. if pwdLen > 32 {
  1564. pwdLen = 32
  1565. }
  1566. // Read password
  1567. if offset+int(pwdLen) > len(data) {
  1568. h.logger.Info("META unregister - password truncated", "uin", pkt.UIN)
  1569. return h.sendMetaUnregAck(session, pkt.SeqNum2, false)
  1570. }
  1571. password := string(data[offset : offset+int(pwdLen)])
  1572. // Remove null terminator if present
  1573. if len(password) > 0 && password[len(password)-1] == 0 {
  1574. password = password[:len(password)-1]
  1575. }
  1576. h.logger.Info("META unregister request",
  1577. "uin", pkt.UIN,
  1578. "password_len", len(password),
  1579. )
  1580. // Delete the user account
  1581. err := h.service.DeleteUser(ctx, pkt.UIN, password)
  1582. if err != nil {
  1583. h.logger.Info("META unregister FAILED", "uin", pkt.UIN, "err", err)
  1584. return h.sendMetaUnregAck(session, pkt.SeqNum2, false)
  1585. }
  1586. h.logger.Info("META unregister SUCCESS - user deleted", "uin", pkt.UIN)
  1587. // Send success acknowledgment
  1588. return h.sendMetaUnregAck(session, pkt.SeqNum2, true)
  1589. }
  1590. // handleMetaUserFullInfo processes CMD_META_USER_FULLINFO requests (0x04B0)
  1591. // From iserverd v5_reply_metafullinfo_request() - older format
  1592. //
  1593. // Sends 7 separate META_USER packets using the older format functions:
  1594. // info2, more, hpage_cat, work, about, interests, affiliations
  1595. // This matches iserverd's v5_reply_metafullinfo_request() exactly.
  1596. func (h *V5Handler) handleMetaUserFullInfo(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1597. if session == nil {
  1598. return nil
  1599. }
  1600. if len(data) < 4 {
  1601. h.logger.Info("META user full info - data too short", "uin", pkt.UIN)
  1602. return h.sendMetaFail(session, pkt.SeqNum2, ICQLegacySrvMetaUserInfo2)
  1603. }
  1604. targetUIN := binary.LittleEndian.Uint32(data[0:4])
  1605. h.logger.Info("META user full info request (0x04B0)",
  1606. "uin", pkt.UIN,
  1607. "target_uin", targetUIN,
  1608. )
  1609. ctx := context.Background()
  1610. user, err := h.service.GetFullUserInfo(ctx, targetUIN)
  1611. if err != nil || user == nil {
  1612. h.logger.Info("META user full info - NOT FOUND", "target_uin", targetUIN, "err", err)
  1613. return h.sendMetaFail(session, pkt.SeqNum2, ICQLegacySrvMetaUserInfo2)
  1614. }
  1615. info, _ := h.service.GetUserInfo(ctx, targetUIN)
  1616. h.logger.Info("META user full info - FOUND, sending 7 info packets (older format)",
  1617. "target_uin", targetUIN,
  1618. "nickname", user.ICQInfo.Basic.Nickname,
  1619. )
  1620. // Send all 7 info packets as per iserverd v5_reply_metafullinfo_request()
  1621. // Uses older format: sendMetaFullUserInfo (info2), sendMetaMore, sendMetaWork
  1622. _ = h.sendMetaFullUserInfo(session, pkt.SeqNum2, info) // Basic info (0x00C8) - older format
  1623. _ = h.sendMetaMore(session, pkt.SeqNum2, user) // More info (0x00DC)
  1624. _ = h.sendMetaHpageCat(session, pkt.SeqNum2, info) // Homepage category (0x010E)
  1625. _ = h.sendMetaWork(session, pkt.SeqNum2, info) // Work info (0x00D2) - older format
  1626. _ = h.sendMetaAbout(session, pkt.SeqNum2, info) // About/notes (0x00E6)
  1627. _ = h.sendMetaInterests(session, pkt.SeqNum2, info) // Interests (0x00F0)
  1628. _ = h.sendMetaAffiliations(session, pkt.SeqNum2, info) // Affiliations (0x00FA)
  1629. return nil
  1630. }
  1631. // handleMetaUserFullInfo2 processes CMD_META_USER_INFO2 requests (0x04B1)
  1632. // From iserverd v5_reply_metafullinfo_request2() - newer format
  1633. //
  1634. // Sends 7 separate META_USER packets using the newer format functions:
  1635. // info3, more2, hpage_cat, work2, about, interests, affiliations
  1636. // This matches iserverd's v5_reply_metafullinfo_request2() exactly.
  1637. func (h *V5Handler) handleMetaUserFullInfo2(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1638. if session == nil {
  1639. return nil
  1640. }
  1641. if len(data) < 4 {
  1642. h.logger.Info("META user full info2 - data too short", "uin", pkt.UIN)
  1643. return h.sendMetaFail(session, pkt.SeqNum2, ICQLegacySrvMetaUserInfo2)
  1644. }
  1645. targetUIN := binary.LittleEndian.Uint32(data[0:4])
  1646. h.logger.Info("META user full info2 request (0x04B1)",
  1647. "uin", pkt.UIN,
  1648. "target_uin", targetUIN,
  1649. )
  1650. ctx := context.Background()
  1651. user, err := h.service.GetFullUserInfo(ctx, targetUIN)
  1652. if err != nil || user == nil {
  1653. h.logger.Info("META user full info2 - NOT FOUND", "target_uin", targetUIN, "err", err)
  1654. return h.sendMetaFail(session, pkt.SeqNum2, ICQLegacySrvMetaUserInfo2)
  1655. }
  1656. info, _ := h.service.GetUserInfo(ctx, targetUIN)
  1657. h.logger.Info("META user full info2 - FOUND, sending 7 info packets (newer format)",
  1658. "target_uin", targetUIN,
  1659. "nickname", user.ICQInfo.Basic.Nickname,
  1660. )
  1661. // Send all 7 info packets as per iserverd v5_reply_metafullinfo_request2()
  1662. // Uses newer format: sendMetaInfo3, sendMetaMore2, sendMetaWork2
  1663. _ = h.sendMetaInfo3(session, pkt.SeqNum2, user) // Basic info (0x00C8) - newer format
  1664. _ = h.sendMetaMore2(session, pkt.SeqNum2, user) // More info (0x00DC)
  1665. _ = h.sendMetaHpageCat(session, pkt.SeqNum2, info) // Homepage category (0x010E)
  1666. _ = h.sendMetaWork2(session, pkt.SeqNum2, info) // Work info (0x00D2) - newer format
  1667. _ = h.sendMetaAbout(session, pkt.SeqNum2, info) // About/notes (0x00E6)
  1668. _ = h.sendMetaInterests(session, pkt.SeqNum2, info) // Interests (0x00F0)
  1669. _ = h.sendMetaAffiliations(session, pkt.SeqNum2, info) // Affiliations (0x00FA)
  1670. return nil
  1671. }
  1672. // handleMetaUserInfo processes CMD_META_USER_INFO requests (0x04BA)
  1673. // From iserverd v5_reply_metainfo_request() - short info only
  1674. //
  1675. // Unlike handleMetaUserFullInfo/handleMetaUserFullInfo2, this sends only a
  1676. // single short user info packet (SRV_META_USER_INFO = 0x0104).
  1677. // This matches iserverd's v5_send_meta_info() exactly.
  1678. func (h *V5Handler) handleMetaUserInfo(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1679. if session == nil {
  1680. return nil
  1681. }
  1682. if len(data) < 4 {
  1683. h.logger.Info("META user info - data too short", "uin", pkt.UIN)
  1684. return h.sendMetaFail(session, pkt.SeqNum2, ICQLegacySrvMetaUserInfo)
  1685. }
  1686. targetUIN := binary.LittleEndian.Uint32(data[0:4])
  1687. h.logger.Info("META user info request (0x04BA)",
  1688. "uin", pkt.UIN,
  1689. "target_uin", targetUIN,
  1690. )
  1691. ctx := context.Background()
  1692. info, err := h.service.GetUserInfo(ctx, targetUIN)
  1693. if err != nil || info == nil {
  1694. h.logger.Info("META user info - NOT FOUND", "target_uin", targetUIN, "err", err)
  1695. return h.sendMetaUserInfo(session, pkt.SeqNum2, nil)
  1696. }
  1697. h.logger.Info("META user info - FOUND",
  1698. "target_uin", targetUIN,
  1699. "nickname", info.Nickname,
  1700. )
  1701. // Send single short info packet (SRV_META_USER_INFO = 0x0104)
  1702. return h.sendMetaUserInfo(session, pkt.SeqNum2, info)
  1703. }
  1704. // handleMetaSearchName processes META_SEARCH_NAME requests (0x0514, 0x0515)
  1705. // From iserverd v5_search_by_name()
  1706. //
  1707. // Packet format (subData after sub_command):
  1708. // - First string (length-prefixed, null-terminated) - nick in iserverd
  1709. // - Second string (length-prefixed, null-terminated) - first name
  1710. // - Third string (length-prefixed, null-terminated) - last name
  1711. //
  1712. // Note: iserverd's variable naming is confusing - it reads into first_str, last_str,
  1713. // nick_str but the actual packet order from the client is nick, first, last.
  1714. func (h *V5Handler) handleMetaSearchName(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1715. if session == nil {
  1716. return nil
  1717. }
  1718. // Parse three length-prefixed strings: nick, first, last
  1719. offset := 0
  1720. nick, n := readLPString(data, offset)
  1721. offset += n
  1722. first, n := readLPString(data, offset)
  1723. offset += n
  1724. last, _ := readLPString(data, offset)
  1725. h.logger.Info("META search by name",
  1726. "uin", pkt.UIN,
  1727. "nick", nick,
  1728. "first", first,
  1729. "last", last,
  1730. )
  1731. ctx := context.Background()
  1732. results, err := h.service.SearchByName(ctx, nick, first, last, "")
  1733. if err != nil {
  1734. h.logger.Info("META search by name - error", "uin", pkt.UIN, "err", err)
  1735. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1736. }
  1737. if len(results) == 0 {
  1738. h.logger.Info("META search by name - no results", "uin", pkt.UIN)
  1739. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1740. }
  1741. h.logger.Info("META search by name - found",
  1742. "uin", pkt.UIN,
  1743. "count", len(results),
  1744. )
  1745. // Convert to UserInfoResult and send
  1746. var infoResults []UserInfoResult
  1747. for _, r := range results {
  1748. infoResults = append(infoResults, UserInfoResult{
  1749. UIN: r.UIN,
  1750. Nickname: r.Nickname,
  1751. FirstName: r.FirstName,
  1752. LastName: r.LastName,
  1753. Email: r.Email,
  1754. AuthRequired: r.AuthRequired,
  1755. })
  1756. }
  1757. // Send each result, last one with isLast=true
  1758. for i, info := range infoResults {
  1759. isLast := i == len(infoResults)-1
  1760. err := h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, []UserInfoResult{info}, isLast))
  1761. if err != nil {
  1762. return err
  1763. }
  1764. }
  1765. return nil
  1766. }
  1767. // handleMetaSearchUIN processes META_SEARCH_UIN requests (0x051E, 0x051F)
  1768. // From iserverd v5_search_by_uin()
  1769. //
  1770. // Refactored to use service layer (GetUserInfoForProtocol) and packet builder.
  1771. // Following the OSCAR pattern: unmarshal -> call service -> build response
  1772. func (h *V5Handler) handleMetaSearchUIN(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1773. if session == nil {
  1774. return nil
  1775. }
  1776. // 1. Unmarshal packet - extract target UIN
  1777. if len(data) < 4 {
  1778. h.logger.Info("META search by UIN - data too short", "uin", pkt.UIN)
  1779. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1780. }
  1781. targetUIN := binary.LittleEndian.Uint32(data[0:4])
  1782. h.logger.Info("META search by UIN",
  1783. "uin", pkt.UIN,
  1784. "target_uin", targetUIN,
  1785. )
  1786. // 2. Call service layer with typed request
  1787. ctx := context.Background()
  1788. result, err := h.service.GetUserInfoForProtocol(ctx, targetUIN)
  1789. if err != nil {
  1790. h.logger.Info("META search by UIN - error",
  1791. "target_uin", targetUIN,
  1792. "err", err,
  1793. )
  1794. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1795. }
  1796. if result == nil {
  1797. h.logger.Info("META search by UIN - NOT FOUND",
  1798. "target_uin", targetUIN,
  1799. )
  1800. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1801. }
  1802. h.logger.Info("META search by UIN - FOUND",
  1803. "target_uin", targetUIN,
  1804. "nickname", result.Nickname,
  1805. "firstname", result.FirstName,
  1806. "lastname", result.LastName,
  1807. "email", result.Email,
  1808. )
  1809. // 3. Build and send response using packet builder
  1810. results := []UserInfoResult{*result}
  1811. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, results, true))
  1812. }
  1813. // handleMetaSearchEmail processes META_SEARCH_EMAIL requests (0x0528, 0x0529)
  1814. // From iserverd v5_search_by_email()
  1815. //
  1816. // Packet format (subData after sub_command):
  1817. // - Email string (length-prefixed, null-terminated)
  1818. func (h *V5Handler) handleMetaSearchEmail(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1819. if session == nil {
  1820. return nil
  1821. }
  1822. // Parse one length-prefixed string: email
  1823. email, _ := readLPString(data, 0)
  1824. h.logger.Info("META search by email",
  1825. "uin", pkt.UIN,
  1826. "email", email,
  1827. )
  1828. ctx := context.Background()
  1829. results, err := h.service.SearchByName(ctx, "", "", "", email)
  1830. if err != nil {
  1831. h.logger.Info("META search by email - error", "uin", pkt.UIN, "err", err)
  1832. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1833. }
  1834. if len(results) == 0 {
  1835. h.logger.Info("META search by email - no results", "uin", pkt.UIN)
  1836. return h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, nil, true))
  1837. }
  1838. h.logger.Info("META search by email - found",
  1839. "uin", pkt.UIN,
  1840. "count", len(results),
  1841. )
  1842. var infoResults []UserInfoResult
  1843. for _, r := range results {
  1844. infoResults = append(infoResults, UserInfoResult{
  1845. UIN: r.UIN,
  1846. Nickname: r.Nickname,
  1847. FirstName: r.FirstName,
  1848. LastName: r.LastName,
  1849. Email: r.Email,
  1850. AuthRequired: r.AuthRequired,
  1851. })
  1852. }
  1853. for i, info := range infoResults {
  1854. isLast := i == len(infoResults)-1
  1855. err := h.sender.SendToSession(session, h.packetBuilder.BuildSearchResult(session, pkt.SeqNum2, []UserInfoResult{info}, isLast))
  1856. if err != nil {
  1857. return err
  1858. }
  1859. }
  1860. return nil
  1861. }
  1862. // handleMetaSearchWhite processes META_SEARCH_WHITE (0x0532) - white pages search
  1863. // From iserverd v5_search_by_white()
  1864. //
  1865. // This is the original white pages search (without homepage category fields).
  1866. // Packet format:
  1867. // - First name (length-prefixed string)
  1868. // - Last name (length-prefixed string)
  1869. // - Nickname (length-prefixed string)
  1870. // - Email (length-prefixed string)
  1871. // - Min age (uint16)
  1872. // - Max age (uint16)
  1873. // - Gender (uint8)
  1874. // - Language (uint8)
  1875. // - City (length-prefixed string)
  1876. // - State (length-prefixed string)
  1877. // - Country (uint16)
  1878. // - Company (length-prefixed string)
  1879. // - Department (length-prefixed string)
  1880. // - Position (length-prefixed string)
  1881. // - Work code/occupation (uint8)
  1882. // - Past code (uint16)
  1883. // - Past keywords (length-prefixed string)
  1884. // - Interest index (uint16)
  1885. // - Interest keywords (length-prefixed string)
  1886. // - Affiliation index (uint16)
  1887. // - Affiliation keywords (length-prefixed string)
  1888. // - Online only (uint8)
  1889. func (h *V5Handler) handleMetaSearchWhite(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  1890. if session == nil {
  1891. return nil
  1892. }
  1893. h.logger.Info("META white pages search",
  1894. "uin", pkt.UIN,
  1895. "data_len", len(data),
  1896. )
  1897. // Parse the white pages search packet
  1898. // Following iserverd v5_search_by_white() packet format
  1899. offset := 0
  1900. // Helper function to read length-prefixed string
  1901. readString := func(maxLen int) string {
  1902. if offset+2 > len(data) {
  1903. return ""
  1904. }
  1905. strLen := int(binary.LittleEndian.Uint16(data[offset : offset+2]))
  1906. offset += 2
  1907. if strLen > maxLen {
  1908. strLen = maxLen
  1909. }
  1910. if strLen == 0 || offset+strLen > len(data) {
  1911. return ""
  1912. }
  1913. s := string(data[offset : offset+strLen])
  1914. offset += strLen
  1915. // Remove null terminator if present
  1916. if len(s) > 0 && s[len(s)-1] == 0 {
  1917. s = s[:len(s)-1]
  1918. }
  1919. return s
  1920. }
  1921. // First block - personal information
  1922. firstName := readString(32)
  1923. lastName := readString(32)
  1924. nickname := readString(32)
  1925. email := readString(63)
  1926. // Second block - age, gender, language
  1927. var minAge, maxAge uint16
  1928. var gender, language uint8
  1929. if offset+4 <= len(data) {
  1930. minAge = binary.LittleEndian.Uint16(data[offset : offset+2])
  1931. offset += 2
  1932. maxAge = binary.LittleEndian.Uint16(data[offset : offset+2])
  1933. offset += 2
  1934. }
  1935. if offset+2 <= len(data) {
  1936. gender = data[offset]
  1937. offset++
  1938. language = data[offset]
  1939. offset++
  1940. }
  1941. // Third block - location
  1942. city := readString(32)
  1943. state := readString(32)
  1944. var country uint16
  1945. if offset+2 <= len(data) {
  1946. country = binary.LittleEndian.Uint16(data[offset : offset+2])
  1947. offset += 2
  1948. }
  1949. // Fourth block - work information
  1950. company := readString(32)
  1951. department := readString(32)
  1952. position := readString(32)
  1953. var workCode uint8
  1954. if offset+1 <= len(data) {
  1955. workCode = data[offset]
  1956. offset++
  1957. }
  1958. // Fifth block - past information
  1959. var pastCode uint16
  1960. if offset+2 <= len(data) {
  1961. pastCode = binary.LittleEndian.Uint16(data[offset : offset+2])
  1962. offset += 2
  1963. }
  1964. pastKeywords := readString(127)
  1965. // Sixth block - interests information
  1966. var interestIndex uint16
  1967. if offset+2 <= len(data) {
  1968. interestIndex = binary.LittleEndian.Uint16(data[offset : offset+2])
  1969. offset += 2
  1970. }
  1971. interestKeywords := readString(127)
  1972. // Seventh block - affiliations information
  1973. var affiliationIndex uint16
  1974. if offset+2 <= len(data) {
  1975. affiliationIndex = binary.LittleEndian.Uint16(data[offset : offset+2])
  1976. offset += 2
  1977. }
  1978. affiliationKeywords := readString(127)
  1979. // Online only flag
  1980. var onlineOnly uint8
  1981. if offset+1 <= len(data) {
  1982. onlineOnly = data[offset]
  1983. offset++
  1984. }
  1985. h.logger.Info("META white pages search parsed",
  1986. "uin", pkt.UIN,
  1987. "first_name", firstName,
  1988. "last_name", lastName,
  1989. "nickname", nickname,
  1990. "email", email,
  1991. "min_age", minAge,
  1992. "max_age", maxAge,
  1993. "gender", gender,
  1994. "language", language,
  1995. "city", city,
  1996. "state", state,
  1997. "country", country,
  1998. "company", company,
  1999. "department", department,
  2000. "position", position,
  2001. "work_code", workCode,
  2002. "past_code", pastCode,
  2003. "past_keywords", pastKeywords,
  2004. "interest_index", interestIndex,
  2005. "interest_keywords", interestKeywords,
  2006. "affiliation_index", affiliationIndex,
  2007. "affiliation_keywords", affiliationKeywords,
  2008. "online_only", onlineOnly,
  2009. )
  2010. // Build search criteria
  2011. criteria := WhitePagesSearchCriteria{
  2012. FirstName: firstName,
  2013. LastName: lastName,
  2014. Nickname: nickname,
  2015. Email: email,
  2016. MinAge: minAge,
  2017. MaxAge: maxAge,
  2018. Gender: gender,
  2019. Language: language,
  2020. City: city,
  2021. State: state,
  2022. Country: country,
  2023. Company: company,
  2024. Department: department,
  2025. Position: position,
  2026. WorkCode: workCode,
  2027. PastCode: pastCode,
  2028. PastKeywords: pastKeywords,
  2029. InterestIndex: interestIndex,
  2030. InterestKeywords: interestKeywords,
  2031. AffiliationIndex: affiliationIndex,
  2032. AffiliationKeywords: affiliationKeywords,
  2033. OnlineOnly: onlineOnly != 0,
  2034. }
  2035. // Check if we have any basic search criteria
  2036. hasBasicCriteria := firstName != "" || lastName != "" || nickname != "" || email != ""
  2037. if hasBasicCriteria {
  2038. ctx := context.Background()
  2039. results, err := h.service.WhitePagesSearch(ctx, criteria)
  2040. if err != nil {
  2041. h.logger.Info("META white pages search - error", "uin", pkt.UIN, "err", err)
  2042. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, false)
  2043. }
  2044. if len(results) == 0 {
  2045. h.logger.Info("META white pages search - no results", "uin", pkt.UIN)
  2046. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, false)
  2047. }
  2048. // Send results (limit to 40 as per iserverd)
  2049. maxResults := 40
  2050. if len(results) > maxResults {
  2051. results = results[:maxResults]
  2052. }
  2053. for i, result := range results {
  2054. isLast := i == len(results)-1
  2055. moreAvailable := len(results) >= maxResults && isLast
  2056. _ = h.sendMetaWhiteFound(session, pkt.SeqNum2, &result, isLast, moreAvailable)
  2057. }
  2058. return nil
  2059. }
  2060. // No basic search criteria - return empty result
  2061. h.logger.Info("META white pages search - no basic criteria for search", "uin", pkt.UIN)
  2062. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, false)
  2063. }
  2064. // handleMetaSearchWhite2 processes META_SEARCH_WHITE2 (0x0533) - extended white pages search
  2065. // From iserverd v5_search_by_white2()
  2066. //
  2067. // This is the extended white pages search that includes homepage category search.
  2068. // Packet format:
  2069. // - First name (length-prefixed string)
  2070. // - Last name (length-prefixed string)
  2071. // - Nickname (length-prefixed string)
  2072. // - Email (length-prefixed string)
  2073. // - Min age (uint16)
  2074. // - Max age (uint16)
  2075. // - Gender (uint8)
  2076. // - Language (uint8)
  2077. // - City (length-prefixed string)
  2078. // - State (length-prefixed string)
  2079. // - Country (uint16)
  2080. // - Company (length-prefixed string)
  2081. // - Department (length-prefixed string)
  2082. // - Position (length-prefixed string)
  2083. // - Work code/occupation (uint8)
  2084. // - Past code (uint16)
  2085. // - Past keywords (length-prefixed string)
  2086. // - Interest index (uint16)
  2087. // - Interest keywords (length-prefixed string)
  2088. // - Affiliation index (uint16)
  2089. // - Affiliation keywords (length-prefixed string)
  2090. // - Homepage category index (uint16) - EXTRA field in White2
  2091. // - Homepage keywords (length-prefixed string) - EXTRA field in White2
  2092. // - Online only (uint8)
  2093. func (h *V5Handler) handleMetaSearchWhite2(session *LegacySession, pkt *V5ClientPacket, data []byte) error {
  2094. if session == nil {
  2095. return nil
  2096. }
  2097. h.logger.Info("META white pages search 2 (extended)",
  2098. "uin", pkt.UIN,
  2099. "data_len", len(data),
  2100. )
  2101. // Parse the extended white pages search packet
  2102. // Following iserverd v5_search_by_white2() packet format
  2103. offset := 0
  2104. // Helper function to read length-prefixed string
  2105. readString := func(maxLen int) string {
  2106. if offset+2 > len(data) {
  2107. return ""
  2108. }
  2109. strLen := int(binary.LittleEndian.Uint16(data[offset : offset+2]))
  2110. offset += 2
  2111. if strLen > maxLen {
  2112. strLen = maxLen
  2113. }
  2114. if strLen == 0 || offset+strLen > len(data) {
  2115. return ""
  2116. }
  2117. s := string(data[offset : offset+strLen])
  2118. offset += strLen
  2119. // Remove null terminator if present
  2120. if len(s) > 0 && s[len(s)-1] == 0 {
  2121. s = s[:len(s)-1]
  2122. }
  2123. return s
  2124. }
  2125. // First block - personal information
  2126. firstName := readString(32)
  2127. lastName := readString(32)
  2128. nickname := readString(32)
  2129. email := readString(63)
  2130. // Second block - age, gender, language
  2131. var minAge, maxAge uint16
  2132. var gender, language uint8
  2133. if offset+4 <= len(data) {
  2134. minAge = binary.LittleEndian.Uint16(data[offset : offset+2])
  2135. offset += 2
  2136. maxAge = binary.LittleEndian.Uint16(data[offset : offset+2])
  2137. offset += 2
  2138. }
  2139. if offset+2 <= len(data) {
  2140. gender = data[offset]
  2141. offset++
  2142. language = data[offset]
  2143. offset++
  2144. }
  2145. // Third block - location
  2146. city := readString(32)
  2147. state := readString(32)
  2148. var country uint16
  2149. if offset+2 <= len(data) {
  2150. country = binary.LittleEndian.Uint16(data[offset : offset+2])
  2151. offset += 2
  2152. }
  2153. // Fourth block - work information
  2154. company := readString(32)
  2155. department := readString(32)
  2156. position := readString(32)
  2157. var workCode uint8
  2158. if offset+1 <= len(data) {
  2159. workCode = data[offset]
  2160. offset++
  2161. }
  2162. // Fifth block - past information
  2163. var pastCode uint16
  2164. if offset+2 <= len(data) {
  2165. pastCode = binary.LittleEndian.Uint16(data[offset : offset+2])
  2166. offset += 2
  2167. }
  2168. pastKeywords := readString(63)
  2169. // Sixth block - interests
  2170. var interestIndex uint16
  2171. if offset+2 <= len(data) {
  2172. interestIndex = binary.LittleEndian.Uint16(data[offset : offset+2])
  2173. offset += 2
  2174. }
  2175. interestKeywords := readString(127)
  2176. // Seventh block - affiliations
  2177. var affiliationIndex uint16
  2178. if offset+2 <= len(data) {
  2179. affiliationIndex = binary.LittleEndian.Uint16(data[offset : offset+2])
  2180. offset += 2
  2181. }
  2182. affiliationKeywords := readString(127)
  2183. // Eighth block - homepage category (EXTRA in White2)
  2184. var pageIndex uint16
  2185. if offset+2 <= len(data) {
  2186. pageIndex = binary.LittleEndian.Uint16(data[offset : offset+2])
  2187. offset += 2
  2188. }
  2189. pageKeywords := readString(127)
  2190. // Online only flag
  2191. var onlineOnly uint8
  2192. if offset+1 <= len(data) {
  2193. onlineOnly = data[offset]
  2194. offset++
  2195. }
  2196. h.logger.Info("META white pages search 2 - parsed",
  2197. "uin", pkt.UIN,
  2198. "first_name", firstName,
  2199. "last_name", lastName,
  2200. "nickname", nickname,
  2201. "email", email,
  2202. "min_age", minAge,
  2203. "max_age", maxAge,
  2204. "gender", gender,
  2205. "language", language,
  2206. "city", city,
  2207. "state", state,
  2208. "country", country,
  2209. "company", company,
  2210. "department", department,
  2211. "position", position,
  2212. "work_code", workCode,
  2213. "past_code", pastCode,
  2214. "past_keywords", pastKeywords,
  2215. "interest_index", interestIndex,
  2216. "interest_keywords", interestKeywords,
  2217. "affiliation_index", affiliationIndex,
  2218. "affiliation_keywords", affiliationKeywords,
  2219. "page_index", pageIndex,
  2220. "page_keywords", pageKeywords,
  2221. "online_only", onlineOnly,
  2222. )
  2223. // Check if any search criteria was provided
  2224. hasSearchCriteria := firstName != "" || lastName != "" || nickname != "" || email != "" ||
  2225. (minAge > 0 && maxAge > 0) || (gender > 0 && gender < 16) ||
  2226. (language > 0 && language < 127) || city != "" || state != "" ||
  2227. (country > 0 && country < 20000) || company != "" || position != "" ||
  2228. (workCode > 0 && workCode < 127) || (pastCode > 0 && pastCode < 60000) ||
  2229. (interestIndex > 0 && interestIndex < 60000) ||
  2230. (affiliationIndex > 0 && affiliationIndex < 60000) ||
  2231. (pageIndex > 0 && pageIndex < 60000)
  2232. if !hasSearchCriteria {
  2233. // No search criteria provided - return "not implemented" style response
  2234. // Following iserverd behavior when not_implemented is true
  2235. h.logger.Info("META white pages search 2 - no criteria provided", "uin", pkt.UIN)
  2236. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, true)
  2237. }
  2238. // For now, use the basic name/email search if those fields are provided
  2239. // A full implementation would need a more complex search method in the service layer
  2240. ctx := context.Background()
  2241. if nickname != "" || firstName != "" || lastName != "" || email != "" {
  2242. results, err := h.service.SearchByName(ctx, nickname, firstName, lastName, email)
  2243. if err != nil {
  2244. h.logger.Info("META white pages search 2 - error",
  2245. "uin", pkt.UIN,
  2246. "err", err,
  2247. )
  2248. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, false)
  2249. }
  2250. if len(results) == 0 {
  2251. h.logger.Info("META white pages search 2 - no results", "uin", pkt.UIN)
  2252. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, false)
  2253. }
  2254. // Send results (limit to 40 as per iserverd)
  2255. maxResults := 40
  2256. if len(results) > maxResults {
  2257. results = results[:maxResults]
  2258. }
  2259. for i, result := range results {
  2260. isLast := i == len(results)-1
  2261. moreAvailable := len(results) >= maxResults && isLast
  2262. _ = h.sendMetaWhiteSearchResult2(session, pkt.SeqNum2, &result, isLast, moreAvailable)
  2263. }
  2264. return nil
  2265. }
  2266. // No basic search criteria - return empty result
  2267. h.logger.Info("META white pages search 2 - no basic criteria for search", "uin", pkt.UIN)
  2268. return h.sendMetaWhiteSearchEnd(session, pkt.SeqNum2, false)
  2269. }
  2270. // sendMetaWhiteSearchResult2 sends a META white pages search result (White2 format)
  2271. // From iserverd v5_send_white_user_found2()
  2272. func (h *V5Handler) sendMetaWhiteSearchResult2(session *LegacySession, seqNum uint16, result *LegacyUserSearchResult, isLast bool, moreAvailable bool) error {
  2273. if session == nil {
  2274. return nil
  2275. }
  2276. // Use White2 response codes (0x01A4 for found, 0x01AE for last found)
  2277. subCommand := ICQLegacySrvMetaWhiteFound // 0x01A4
  2278. if isLast {
  2279. subCommand = ICQLegacySrvMetaWhiteLastFound // 0x01AE
  2280. }
  2281. buf := new(bytes.Buffer)
  2282. _ = binary.Write(buf, binary.LittleEndian, subCommand)
  2283. if result != nil {
  2284. buf.WriteByte(0x0A) // success
  2285. // Calculate pack_len: 15 + strings + 4 for users_left
  2286. packLen := uint16(15 + len(result.Nickname) + len(result.FirstName) + len(result.LastName) + len(result.Email) + 4)
  2287. _ = binary.Write(buf, binary.LittleEndian, packLen)
  2288. _ = binary.Write(buf, binary.LittleEndian, result.UIN)
  2289. writeLegacyString(buf, result.Nickname)
  2290. writeLegacyString(buf, result.FirstName)
  2291. writeLegacyString(buf, result.LastName)
  2292. writeLegacyString(buf, result.Email)
  2293. buf.WriteByte(result.AuthRequired) // auth flag
  2294. buf.WriteByte(result.WebAware) // webaware flag
  2295. buf.WriteByte(0) // unknown
  2296. // users_left indicator
  2297. var usersLeft uint32
  2298. if moreAvailable {
  2299. usersLeft = 1 // indicate more results available
  2300. }
  2301. _ = binary.Write(buf, binary.LittleEndian, usersLeft)
  2302. } else {
  2303. buf.WriteByte(0x32) // fail - no results
  2304. _ = binary.Write(buf, binary.LittleEndian, uint32(0)) // users_left
  2305. }
  2306. pkt := &V5ServerPacket{
  2307. Version: ICQLegacyVersionV5,
  2308. SessionID: session.SessionID,
  2309. Command: ICQLegacySrvMetaUser,
  2310. SeqNum1: session.NextServerSeqNum(),
  2311. SeqNum2: seqNum,
  2312. UIN: session.UIN,
  2313. Data: buf.Bytes(),
  2314. }
  2315. packetData := MarshalV5ServerPacket(pkt)
  2316. if result != nil {
  2317. h.logger.Info("sending META white search 2 result",
  2318. "uin", session.UIN,
  2319. "sub_command", fmt.Sprintf("0x%04X", subCommand),
  2320. "result_uin", result.UIN,
  2321. "result_nickname", result.Nickname,
  2322. "is_last", isLast,
  2323. "more_available", moreAvailable,
  2324. "packet_len", len(packetData),
  2325. )
  2326. }
  2327. return h.sender.SendToSession(session, packetData)
  2328. }
  2329. // sendMetaWhiteFound sends a META white pages search result (original format)
  2330. // From iserverd v5_send_white_user_found()
  2331. //
  2332. // This is the original white pages search result format (0x01A4).
  2333. // Packet format (data portion):
  2334. // - SubCommand (2 bytes): 0x01A4 (found) or 0x01AE (last found)
  2335. // - Success (1 byte): 0x0A (success) or 0x32 (fail)
  2336. // - If success:
  2337. // - UIN (4 bytes)
  2338. // - Nickname (length-prefixed string)
  2339. // - First name (length-prefixed string)
  2340. // - Last name (length-prefixed string)
  2341. // - Email (length-prefixed string)
  2342. // - Auth flag (1 byte)
  2343. // - Webaware flag (1 byte)
  2344. // - If last:
  2345. // - Users left (4 bytes)
  2346. //
  2347. // Note: Unlike White2 format, this does NOT have a pack_len field.
  2348. func (h *V5Handler) sendMetaWhiteFound(session *LegacySession, seqNum uint16, result *LegacyUserSearchResult, isLast bool, moreAvailable bool) error {
  2349. if session == nil {
  2350. return nil
  2351. }
  2352. // Use White response codes (0x01A4 for found, 0x01AE for last found)
  2353. subCommand := ICQLegacySrvMetaWhiteFound // 0x01A4
  2354. if isLast {
  2355. subCommand = ICQLegacySrvMetaWhiteLastFound // 0x01AE
  2356. }
  2357. buf := new(bytes.Buffer)
  2358. _ = binary.Write(buf, binary.LittleEndian, subCommand)
  2359. if result != nil {
  2360. buf.WriteByte(0x0A) // success
  2361. // Original format: NO pack_len field (unlike White2)
  2362. _ = binary.Write(buf, binary.LittleEndian, result.UIN)
  2363. writeLegacyString(buf, result.Nickname)
  2364. writeLegacyString(buf, result.FirstName)
  2365. writeLegacyString(buf, result.LastName)
  2366. writeLegacyString(buf, result.Email)
  2367. buf.WriteByte(result.AuthRequired) // auth flag
  2368. buf.WriteByte(result.WebAware) // webaware flag
  2369. // users_left indicator (only if last)
  2370. if isLast {
  2371. var usersLeft uint32
  2372. if moreAvailable {
  2373. usersLeft = 1 // indicate more results available
  2374. }
  2375. _ = binary.Write(buf, binary.LittleEndian, usersLeft)
  2376. }
  2377. } else {
  2378. buf.WriteByte(0x32) // fail - no results
  2379. // users_left indicator (only if last)
  2380. if isLast {
  2381. _ = binary.Write(buf, binary.LittleEndian, uint32(0)) // users_left
  2382. }
  2383. }
  2384. pkt := &V5ServerPacket{
  2385. Version: ICQLegacyVersionV5,
  2386. SessionID: session.SessionID,
  2387. Command: ICQLegacySrvMetaUser,
  2388. SeqNum1: session.NextServerSeqNum(),
  2389. SeqNum2: seqNum,
  2390. UIN: session.UIN,
  2391. Data: buf.Bytes(),
  2392. }
  2393. packetData := MarshalV5ServerPacket(pkt)
  2394. if result != nil {
  2395. h.logger.Info("sending META white search result",
  2396. "uin", session.UIN,
  2397. "sub_command", fmt.Sprintf("0x%04X", subCommand),
  2398. "result_uin", result.UIN,
  2399. "result_nickname", result.Nickname,
  2400. "is_last", isLast,
  2401. "more_available", moreAvailable,
  2402. "packet_len", len(packetData),
  2403. )
  2404. }
  2405. return h.sender.SendToSession(session, packetData)
  2406. }
  2407. // sendMetaWhiteSearchEnd sends an empty white pages search result to indicate end/no results
  2408. func (h *V5Handler) sendMetaWhiteSearchEnd(session *LegacySession, seqNum uint16, success bool) error {
  2409. if session == nil {
  2410. return nil
  2411. }
  2412. subCommand := ICQLegacySrvMetaWhiteLastFound // 0x01AE
  2413. buf := new(bytes.Buffer)
  2414. _ = binary.Write(buf, binary.LittleEndian, subCommand)
  2415. if success {
  2416. buf.WriteByte(0x0A) // success but no results
  2417. } else {
  2418. buf.WriteByte(0x32) // fail - no results
  2419. }
  2420. _ = binary.Write(buf, binary.LittleEndian, uint32(0)) // users_left
  2421. pkt := &V5ServerPacket{
  2422. Version: ICQLegacyVersionV5,
  2423. SessionID: session.SessionID,
  2424. Command: ICQLegacySrvMetaUser,
  2425. SeqNum1: session.NextServerSeqNum(),
  2426. SeqNum2: seqNum,
  2427. UIN: session.UIN,
  2428. Data: buf.Bytes(),
  2429. }
  2430. h.logger.Info("sending META white search 2 end",
  2431. "uin", session.UIN,
  2432. "success", success,
  2433. )
  2434. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2435. }
  2436. // Response helpers
  2437. // sendV5AckToAddr sends a V5 ACK to a specific address (for pre-login packets)
  2438. func (h *V5Handler) sendV5AckToAddr(addr *net.UDPAddr, sessionID uint32, uin uint32, seq1, seq2 uint16) error {
  2439. pkt := &V5ServerPacket{
  2440. Version: ICQLegacyVersionV5,
  2441. SessionID: sessionID,
  2442. Command: ICQLegacySrvAck,
  2443. SeqNum1: seq1,
  2444. SeqNum2: seq2,
  2445. UIN: uin,
  2446. }
  2447. // Server packets are NOT encrypted
  2448. data := MarshalV5ServerPacket(pkt)
  2449. return h.sender.SendPacket(addr, data)
  2450. }
  2451. // sendV5NotConnected sends a NOT_CONNECTED (0x00F0) response to a V5 client
  2452. // that has no session. This forces the client to reconnect/relogon.
  2453. // From licq.5 source: ICQ_CMDxRCV_ERROR (0x00F0) triggers icqRelogon()
  2454. // with message "Server says you are not logged on."
  2455. func (h *V5Handler) sendV5NotConnected(addr *net.UDPAddr, sessionID uint32, uin uint32, seq1, seq2 uint16) error {
  2456. pkt := &V5ServerPacket{
  2457. Version: ICQLegacyVersionV5,
  2458. SessionID: sessionID,
  2459. Command: ICQLegacySrvNotConnected,
  2460. SeqNum1: seq1,
  2461. SeqNum2: seq2,
  2462. UIN: uin,
  2463. }
  2464. return h.sender.SendPacket(addr, MarshalV5ServerPacket(pkt))
  2465. }
  2466. // sendV5FirstLoginReply sends the first login ACK response
  2467. // From iserverd v5_process_firstlog() - special ACK with session_id2
  2468. func (h *V5Handler) sendV5FirstLoginReply(addr *net.UDPAddr, sessionID uint32, uin uint32, seq1, seq2 uint16, sessionID2 uint32) error {
  2469. // Build data: 0x0A(1) + SESSION_ID2(4) + 0x0001(2) = 7 bytes
  2470. // Note: The JUNK(4) in iserverd is the checkcode placeholder in the header
  2471. data := make([]byte, 7)
  2472. data[0] = 0x0A
  2473. binary.LittleEndian.PutUint32(data[1:5], sessionID2)
  2474. binary.LittleEndian.PutUint16(data[5:7], 0x0001)
  2475. pkt := &V5ServerPacket{
  2476. Version: ICQLegacyVersionV5,
  2477. SessionID: sessionID,
  2478. Command: ICQLegacySrvAck,
  2479. SeqNum1: seq1,
  2480. SeqNum2: seq2,
  2481. UIN: uin,
  2482. Data: data,
  2483. }
  2484. packetData := MarshalV5ServerPacket(pkt)
  2485. return h.sender.SendPacket(addr, packetData)
  2486. }
  2487. func (h *V5Handler) sendV5Ack(session *LegacySession, seqNum uint16) error {
  2488. if session == nil {
  2489. return nil
  2490. }
  2491. // ACK echoes the client's seq1, and uses 0 for seq2 (as per iserverd)
  2492. pkt := &V5ServerPacket{
  2493. Version: ICQLegacyVersionV5,
  2494. SessionID: session.SessionID,
  2495. Command: ICQLegacySrvAck,
  2496. SeqNum1: seqNum,
  2497. SeqNum2: 0, // ACKs use 0 for seq2
  2498. UIN: session.UIN,
  2499. }
  2500. // Server packets are NOT encrypted
  2501. data := MarshalV5ServerPacket(pkt)
  2502. return h.sender.SendToSession(session, data)
  2503. }
  2504. // sendV5AckWithSeq2 sends an ACK echoing both seq1 and seq2 from the client
  2505. func (h *V5Handler) sendV5AckWithSeq2(session *LegacySession, seq1, seq2 uint16) error {
  2506. if session == nil {
  2507. return nil
  2508. }
  2509. pkt := &V5ServerPacket{
  2510. Version: ICQLegacyVersionV5,
  2511. SessionID: session.SessionID,
  2512. Command: ICQLegacySrvAck,
  2513. SeqNum1: seq1,
  2514. SeqNum2: seq2,
  2515. UIN: session.UIN,
  2516. }
  2517. data := MarshalV5ServerPacket(pkt)
  2518. return h.sender.SendToSession(session, data)
  2519. }
  2520. func (h *V5Handler) sendMetaAck(session *LegacySession, seq2 uint16, subCommand uint16) error {
  2521. if session == nil {
  2522. return nil
  2523. }
  2524. // Build META response
  2525. metaData := make([]byte, 3)
  2526. binary.LittleEndian.PutUint16(metaData[0:2], subCommand)
  2527. metaData[2] = 0x0A // Success
  2528. pkt := &V5ServerPacket{
  2529. Version: ICQLegacyVersionV5,
  2530. SessionID: session.SessionID,
  2531. Command: ICQLegacySrvMetaUser,
  2532. SeqNum1: session.NextServerSeqNum(),
  2533. SeqNum2: seq2,
  2534. UIN: session.UIN,
  2535. Data: metaData,
  2536. }
  2537. // Server packets are NOT encrypted
  2538. data := MarshalV5ServerPacket(pkt)
  2539. return h.sender.SendToSession(session, data)
  2540. }
  2541. // sendMetaUnregAck sends the unregister acknowledgment
  2542. // From iserverd v5_send_meta_set_ack() with SRV_META_UNREG_ACK
  2543. // Success byte: 0x0A for success, 0x32 for failure
  2544. func (h *V5Handler) sendMetaUnregAck(session *LegacySession, seq2 uint16, success bool) error {
  2545. if session == nil {
  2546. return nil
  2547. }
  2548. // Build META response
  2549. metaData := make([]byte, 3)
  2550. binary.LittleEndian.PutUint16(metaData[0:2], ICQLegacySrvMetaUnregAck)
  2551. if success {
  2552. metaData[2] = 0x0A // Success
  2553. } else {
  2554. metaData[2] = 0x32 // Failure
  2555. }
  2556. pkt := &V5ServerPacket{
  2557. Version: ICQLegacyVersionV5,
  2558. SessionID: session.SessionID,
  2559. Command: ICQLegacySrvMetaUser,
  2560. SeqNum1: session.NextServerSeqNum(),
  2561. SeqNum2: seq2,
  2562. UIN: session.UIN,
  2563. Data: metaData,
  2564. }
  2565. h.logger.Debug("sending META unregister ack",
  2566. "uin", session.UIN,
  2567. "success", success,
  2568. )
  2569. // Server packets are NOT encrypted
  2570. data := MarshalV5ServerPacket(pkt)
  2571. return h.sender.SendToSession(session, data)
  2572. }
  2573. // sendMetaLoginReply sends the login meta response
  2574. // From iserverd v5_send_lmeta(): sends 0x07D0 + 0x0000 + 0x0046
  2575. func (h *V5Handler) sendMetaLoginReply(session *LegacySession, seq2 uint16) error {
  2576. if session == nil {
  2577. return nil
  2578. }
  2579. // Build META login response: SUB_CMD(2) + 0x0000(2) + 0x0046(2)
  2580. metaData := make([]byte, 6)
  2581. binary.LittleEndian.PutUint16(metaData[0:2], 0x07D0) // sub-command echo
  2582. binary.LittleEndian.PutUint16(metaData[2:4], 0x0000) // unknown
  2583. binary.LittleEndian.PutUint16(metaData[4:6], 0x0046) // unknown (70 decimal)
  2584. pkt := &V5ServerPacket{
  2585. Version: ICQLegacyVersionV5,
  2586. SessionID: session.SessionID,
  2587. Command: ICQLegacySrvMetaUser,
  2588. SeqNum1: session.NextServerSeqNum(),
  2589. SeqNum2: seq2,
  2590. UIN: session.UIN,
  2591. Data: metaData,
  2592. }
  2593. h.logger.Debug("sending META login reply",
  2594. "uin", session.UIN,
  2595. "seq2", seq2,
  2596. )
  2597. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2598. }
  2599. // sendMetaFail sends a META fail response
  2600. func (h *V5Handler) sendMetaFail(session *LegacySession, seq2 uint16, subCommand uint16) error {
  2601. if session == nil {
  2602. return nil
  2603. }
  2604. buf := new(bytes.Buffer)
  2605. _ = binary.Write(buf, binary.LittleEndian, subCommand)
  2606. buf.WriteByte(0x32) // fail
  2607. pkt := &V5ServerPacket{
  2608. Version: ICQLegacyVersionV5,
  2609. SessionID: session.SessionID,
  2610. Command: ICQLegacySrvMetaUser,
  2611. SeqNum1: session.NextServerSeqNum(),
  2612. SeqNum2: seq2,
  2613. UIN: session.UIN,
  2614. Data: buf.Bytes(),
  2615. }
  2616. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2617. }
  2618. // sendMetaInfo3 sends basic user info (SRV_META_USER_INFO2 = 0x00C8)
  2619. // From iserverd v5_send_meta_info3()
  2620. func (h *V5Handler) sendMetaInfo3(session *LegacySession, seq2 uint16, user *state.User) error {
  2621. if session == nil || user == nil {
  2622. return nil
  2623. }
  2624. buf := new(bytes.Buffer)
  2625. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00C8)) // SRV_META_USER_INFO2
  2626. buf.WriteByte(0x0A) // success
  2627. writeLegacyString(buf, user.ICQInfo.Basic.Nickname)
  2628. writeLegacyString(buf, user.ICQInfo.Basic.FirstName)
  2629. writeLegacyString(buf, user.ICQInfo.Basic.LastName)
  2630. writeLegacyString(buf, user.ICQInfo.Basic.EmailAddress) // email1
  2631. writeLegacyString(buf, "") // email2 (secondary)
  2632. writeLegacyString(buf, "") // email3 (old)
  2633. writeLegacyString(buf, user.ICQInfo.Basic.City)
  2634. writeLegacyString(buf, user.ICQInfo.Basic.State)
  2635. writeLegacyString(buf, user.ICQInfo.Basic.Phone)
  2636. writeLegacyString(buf, user.ICQInfo.Basic.Fax)
  2637. writeLegacyString(buf, user.ICQInfo.Basic.Address)
  2638. writeLegacyString(buf, user.ICQInfo.Basic.CellPhone)
  2639. writeLegacyString(buf, user.ICQInfo.Basic.ZIPCode)
  2640. _ = binary.Write(buf, binary.LittleEndian, user.ICQInfo.Basic.CountryCode)
  2641. _ = binary.Write(buf, binary.LittleEndian, uint16(user.ICQInfo.Basic.GMTOffset))
  2642. authFlag := uint8(0)
  2643. if user.ICQInfo.Permissions.AuthRequired {
  2644. authFlag = 1
  2645. }
  2646. buf.WriteByte(authFlag)
  2647. publishFlag := uint8(0)
  2648. if !user.ICQInfo.Basic.PublishEmail {
  2649. publishFlag = 1
  2650. }
  2651. buf.WriteByte(publishFlag)
  2652. buf.WriteByte(0x00) // unknown
  2653. buf.WriteByte(0x00) // unknown
  2654. buf.WriteByte(0x00) // unknown
  2655. pkt := &V5ServerPacket{
  2656. Version: ICQLegacyVersionV5,
  2657. SessionID: session.SessionID,
  2658. Command: ICQLegacySrvMetaUser,
  2659. SeqNum1: session.NextServerSeqNum(),
  2660. SeqNum2: seq2,
  2661. UIN: session.UIN,
  2662. Data: buf.Bytes(),
  2663. }
  2664. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2665. }
  2666. // sendMetaMore sends more user info (SRV_META_INFO_MORE = 0x00DC)
  2667. // From iserverd v5_send_meta_more()
  2668. //
  2669. // This is the original format used by older ICQ clients (pre-99b).
  2670. // The key difference from sendMetaMore2() is the birth year field:
  2671. // - sendMetaMore(): birth year is 1 byte (year - 1900)
  2672. // - sendMetaMore2(): birth year is 2 bytes (full year)
  2673. //
  2674. // Packet data format:
  2675. // - SRV_META_INFO_MORE(2) = 0x00DC
  2676. // - success(1) = 0x0A
  2677. // - age(2)
  2678. // - gender(1)
  2679. // - homepage_len(2) + homepage(string)
  2680. // - byear(1) = year - 1900 (if year >= 1900, else raw year)
  2681. // - bmonth(1)
  2682. // - bday(1)
  2683. // - lang1(1)
  2684. // - lang2(1)
  2685. // - lang3(1)
  2686. func (h *V5Handler) sendMetaMore(session *LegacySession, seq2 uint16, user *state.User) error {
  2687. if session == nil || user == nil {
  2688. return nil
  2689. }
  2690. // Calculate birth year as single byte (year - 1900)
  2691. // From iserverd: if (tuser.byear < 1900) {temp_year = tuser.byear;} else {temp_year = tuser.byear - 1900;};
  2692. var tempYear uint8
  2693. if user.ICQInfo.More.BirthYear < 1900 {
  2694. tempYear = uint8(user.ICQInfo.More.BirthYear)
  2695. } else {
  2696. tempYear = uint8(user.ICQInfo.More.BirthYear - 1900)
  2697. }
  2698. buf := new(bytes.Buffer)
  2699. _ = binary.Write(buf, binary.LittleEndian, ICQLegacySrvMetaInfoMore) // SRV_META_INFO_MORE = 0x00DC
  2700. buf.WriteByte(0x0A) // success
  2701. _ = binary.Write(buf, binary.LittleEndian, user.Age(time.Now)) // age(2)
  2702. buf.WriteByte(uint8(user.ICQInfo.More.Gender)) // gender(1)
  2703. writeLegacyString(buf, user.ICQInfo.More.HomePageAddr) // homepage_len(2) + homepage
  2704. buf.WriteByte(tempYear) // byear(1) - year minus 1900
  2705. buf.WriteByte(user.ICQInfo.More.BirthMonth) // bmonth(1)
  2706. buf.WriteByte(user.ICQInfo.More.BirthDay) // bday(1)
  2707. buf.WriteByte(user.ICQInfo.More.Lang1) // lang1(1)
  2708. buf.WriteByte(user.ICQInfo.More.Lang2) // lang2(1)
  2709. buf.WriteByte(user.ICQInfo.More.Lang3) // lang3(1)
  2710. pkt := &V5ServerPacket{
  2711. Version: ICQLegacyVersionV5,
  2712. SessionID: session.SessionID,
  2713. Command: ICQLegacySrvMetaUser,
  2714. SeqNum1: session.NextServerSeqNum(),
  2715. SeqNum2: seq2,
  2716. UIN: session.UIN,
  2717. Data: buf.Bytes(),
  2718. }
  2719. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2720. }
  2721. // sendMetaMore2 sends more user info (SRV_META_INFO_MORE = 0x00DC)
  2722. // From iserverd v5_send_meta_more2()
  2723. //
  2724. // This is the newer format used by ICQ 99b and later clients.
  2725. // The key difference from sendMetaMore() is the birth year field:
  2726. // - sendMetaMore(): birth year is 1 byte (year - 1900)
  2727. // - sendMetaMore2(): birth year is 2 bytes (full year)
  2728. //
  2729. // Packet data format:
  2730. // - SRV_META_INFO_MORE(2) = 0x00DC
  2731. // - success(1) = 0x0A
  2732. // - age(2)
  2733. // - gender(1)
  2734. // - homepage_len(2) + homepage(string)
  2735. // - byear(2) = full year
  2736. // - bmonth(1)
  2737. // - bday(1)
  2738. // - lang1(1)
  2739. // - lang2(1)
  2740. // - lang3(1)
  2741. func (h *V5Handler) sendMetaMore2(session *LegacySession, seq2 uint16, user *state.User) error {
  2742. if session == nil || user == nil {
  2743. return nil
  2744. }
  2745. buf := new(bytes.Buffer)
  2746. _ = binary.Write(buf, binary.LittleEndian, ICQLegacySrvMetaInfoMore) // SRV_META_INFO_MORE = 0x00DC
  2747. buf.WriteByte(0x0A) // success
  2748. _ = binary.Write(buf, binary.LittleEndian, user.Age(time.Now)) // age(2)
  2749. buf.WriteByte(uint8(user.ICQInfo.More.Gender)) // gender(1)
  2750. writeLegacyString(buf, user.ICQInfo.More.HomePageAddr) // homepage_len(2) + homepage
  2751. _ = binary.Write(buf, binary.LittleEndian, user.ICQInfo.More.BirthYear) // byear(2) - full year
  2752. buf.WriteByte(user.ICQInfo.More.BirthMonth) // bmonth(1)
  2753. buf.WriteByte(user.ICQInfo.More.BirthDay) // bday(1)
  2754. buf.WriteByte(user.ICQInfo.More.Lang1) // lang1(1)
  2755. buf.WriteByte(user.ICQInfo.More.Lang2) // lang2(1)
  2756. buf.WriteByte(user.ICQInfo.More.Lang3) // lang3(1)
  2757. pkt := &V5ServerPacket{
  2758. Version: ICQLegacyVersionV5,
  2759. SessionID: session.SessionID,
  2760. Command: ICQLegacySrvMetaUser,
  2761. SeqNum1: session.NextServerSeqNum(),
  2762. SeqNum2: seq2,
  2763. UIN: session.UIN,
  2764. Data: buf.Bytes(),
  2765. }
  2766. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2767. }
  2768. // sendMetaHpageCat sends homepage category info (SRV_META_INFO_HPAGE_CAT = 0x010E)
  2769. // From iserverd v5_send_meta_hpage_cat()
  2770. func (h *V5Handler) sendMetaHpageCat(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2771. if session == nil || info == nil {
  2772. return nil
  2773. }
  2774. buf := new(bytes.Buffer)
  2775. _ = binary.Write(buf, binary.LittleEndian, uint16(0x010E)) // SRV_META_INFO_HPAGE_CAT
  2776. buf.WriteByte(0x0A) // success
  2777. buf.WriteByte(0x00) // hpage_cf (enabled)
  2778. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // hpage_cat
  2779. writeLegacyString(buf, "") // hpage_txt
  2780. buf.WriteByte(0x00) // unknown
  2781. pkt := &V5ServerPacket{
  2782. Version: ICQLegacyVersionV5,
  2783. SessionID: session.SessionID,
  2784. Command: ICQLegacySrvMetaUser,
  2785. SeqNum1: session.NextServerSeqNum(),
  2786. SeqNum2: seq2,
  2787. UIN: session.UIN,
  2788. Data: buf.Bytes(),
  2789. }
  2790. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2791. }
  2792. // sendMetaWork sends work info (SRV_META_INFO_WORK = 0x00D2)
  2793. // From iserverd v5_send_meta_work()
  2794. // This is the older format that uses uint32 for ZIP code (vs string in sendMetaWork2)
  2795. // Field order: wcity, wstate, wphone, wfax, waddr, wzip(uint32), wcountry, wcompany, wdepart, wtitle, wocup, wpage
  2796. func (h *V5Handler) sendMetaWork(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2797. if session == nil || info == nil {
  2798. return nil
  2799. }
  2800. buf := new(bytes.Buffer)
  2801. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00D2)) // SRV_META_INFO_WORK
  2802. buf.WriteByte(0x0A) // success
  2803. writeLegacyString(buf, "") // wcity
  2804. writeLegacyString(buf, "") // wstate
  2805. writeLegacyString(buf, "") // wphone
  2806. writeLegacyString(buf, "") // wfax
  2807. writeLegacyString(buf, "") // waddr
  2808. _ = binary.Write(buf, binary.LittleEndian, uint32(0)) // wzip (uint32 in work, string in work2)
  2809. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // wcountry
  2810. writeLegacyString(buf, "") // wcompany
  2811. writeLegacyString(buf, "") // wdepart
  2812. writeLegacyString(buf, "") // wtitle
  2813. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // wocup (occupation code)
  2814. writeLegacyString(buf, "") // wpage (work webpage)
  2815. pkt := &V5ServerPacket{
  2816. Version: ICQLegacyVersionV5,
  2817. SessionID: session.SessionID,
  2818. Command: ICQLegacySrvMetaUser,
  2819. SeqNum1: session.NextServerSeqNum(),
  2820. SeqNum2: seq2,
  2821. UIN: session.UIN,
  2822. Data: buf.Bytes(),
  2823. }
  2824. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2825. }
  2826. // sendMetaWork2 sends work info (SRV_META_INFO_WORK = 0x00D2)
  2827. // From iserverd v5_send_meta_work2() - used with ICQ99b
  2828. // This is the newer format that uses string for ZIP code (vs uint32 in sendMetaWork)
  2829. // Field order: wcity, wstate, wphone, wfax, waddr, wzip(string), wcountry, wcompany, wdepart, wtitle, wocup, wpage
  2830. func (h *V5Handler) sendMetaWork2(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2831. if session == nil || info == nil {
  2832. return nil
  2833. }
  2834. buf := new(bytes.Buffer)
  2835. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00D2)) // SRV_META_INFO_WORK
  2836. buf.WriteByte(0x0A) // success
  2837. writeLegacyString(buf, "") // wcity
  2838. writeLegacyString(buf, "") // wstate
  2839. writeLegacyString(buf, "") // wphone
  2840. writeLegacyString(buf, "") // wfax
  2841. writeLegacyString(buf, "") // waddr
  2842. writeLegacyString(buf, "") // wzip (string in work2, uint32 in work)
  2843. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // wcountry
  2844. writeLegacyString(buf, "") // wcompany
  2845. writeLegacyString(buf, "") // wdepart
  2846. writeLegacyString(buf, "") // wtitle
  2847. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // wocup (occupation code)
  2848. writeLegacyString(buf, "") // wpage (work webpage)
  2849. pkt := &V5ServerPacket{
  2850. Version: ICQLegacyVersionV5,
  2851. SessionID: session.SessionID,
  2852. Command: ICQLegacySrvMetaUser,
  2853. SeqNum1: session.NextServerSeqNum(),
  2854. SeqNum2: seq2,
  2855. UIN: session.UIN,
  2856. Data: buf.Bytes(),
  2857. }
  2858. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2859. }
  2860. // sendMetaAbout sends about/notes info (SRV_META_INFO_ABOUT = 0x00E6)
  2861. // From iserverd v5_send_meta_about()
  2862. func (h *V5Handler) sendMetaAbout(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2863. if session == nil || info == nil {
  2864. return nil
  2865. }
  2866. buf := new(bytes.Buffer)
  2867. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00E6)) // SRV_META_INFO_ABOUT
  2868. buf.WriteByte(0x0A) // success
  2869. writeLegacyString(buf, "") // notes
  2870. pkt := &V5ServerPacket{
  2871. Version: ICQLegacyVersionV5,
  2872. SessionID: session.SessionID,
  2873. Command: ICQLegacySrvMetaUser,
  2874. SeqNum1: session.NextServerSeqNum(),
  2875. SeqNum2: seq2,
  2876. UIN: session.UIN,
  2877. Data: buf.Bytes(),
  2878. }
  2879. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2880. }
  2881. // sendMetaInterests sends interests info (SRV_META_INFO_INTERESTS = 0x00F0)
  2882. // From iserverd v5_send_meta_interestsinfo()
  2883. func (h *V5Handler) sendMetaInterests(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2884. if session == nil || info == nil {
  2885. return nil
  2886. }
  2887. buf := new(bytes.Buffer)
  2888. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00F0)) // SRV_META_INFO_INTERESTS
  2889. buf.WriteByte(0x0A) // success
  2890. buf.WriteByte(0x00) // int_num (0 interests)
  2891. pkt := &V5ServerPacket{
  2892. Version: ICQLegacyVersionV5,
  2893. SessionID: session.SessionID,
  2894. Command: ICQLegacySrvMetaUser,
  2895. SeqNum1: session.NextServerSeqNum(),
  2896. SeqNum2: seq2,
  2897. UIN: session.UIN,
  2898. Data: buf.Bytes(),
  2899. }
  2900. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2901. }
  2902. // sendMetaAffiliations sends affiliations info (SRV_META_INFO_AFFILATIONS = 0x00FA)
  2903. // From iserverd v5_send_meta_affilationsinfo()
  2904. func (h *V5Handler) sendMetaAffiliations(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2905. if session == nil || info == nil {
  2906. return nil
  2907. }
  2908. buf := new(bytes.Buffer)
  2909. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00FA)) // SRV_META_INFO_AFFILATIONS
  2910. buf.WriteByte(0x0A) // success
  2911. // Past backgrounds (3 empty entries)
  2912. buf.WriteByte(0x03) // past_num
  2913. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // past_ind1
  2914. writeLegacyString(buf, "") // past_key1
  2915. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // past_ind2
  2916. writeLegacyString(buf, "") // past_key2
  2917. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // past_ind3
  2918. writeLegacyString(buf, "") // past_key3
  2919. // Affiliations (3 empty entries)
  2920. buf.WriteByte(0x03) // aff_num
  2921. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // aff_ind1
  2922. writeLegacyString(buf, "") // aff_key1
  2923. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // aff_ind2
  2924. writeLegacyString(buf, "") // aff_key2
  2925. _ = binary.Write(buf, binary.LittleEndian, uint16(0)) // aff_ind3
  2926. writeLegacyString(buf, "") // aff_key3
  2927. // Trailing bytes
  2928. _ = binary.Write(buf, binary.LittleEndian, uint16(0x0000))
  2929. _ = binary.Write(buf, binary.LittleEndian, uint16(0x0001))
  2930. buf.WriteByte(0x00)
  2931. pkt := &V5ServerPacket{
  2932. Version: ICQLegacyVersionV5,
  2933. SessionID: session.SessionID,
  2934. Command: ICQLegacySrvMetaUser,
  2935. SeqNum1: session.NextServerSeqNum(),
  2936. SeqNum2: seq2,
  2937. UIN: session.UIN,
  2938. Data: buf.Bytes(),
  2939. }
  2940. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2941. }
  2942. // sendMetaFullUserInfo sends full user info response (legacy, kept for compatibility)
  2943. // From iserverd v5_reply_metafullinfo_request2()
  2944. func (h *V5Handler) sendMetaFullUserInfo(session *LegacySession, seq2 uint16, info *LegacyUserSearchResult) error {
  2945. if session == nil || info == nil {
  2946. return nil
  2947. }
  2948. // Build basic info response (SRV_META_USER_INFO2 = 0x00C8)
  2949. // Format: SUB_CMD(2) + SUCCESS(1) + UIN(4) + NICK_LEN(2) + NICK + FIRST_LEN(2) + FIRST + LAST_LEN(2) + LAST + EMAIL_LEN(2) + EMAIL + AUTH(1)
  2950. buf := new(bytes.Buffer)
  2951. _ = binary.Write(buf, binary.LittleEndian, uint16(0x00C8)) // SRV_META_USER_INFO2
  2952. buf.WriteByte(0x0A) // success
  2953. _ = binary.Write(buf, binary.LittleEndian, info.UIN)
  2954. writeLegacyString(buf, info.Nickname)
  2955. writeLegacyString(buf, info.FirstName)
  2956. writeLegacyString(buf, info.LastName)
  2957. writeLegacyString(buf, info.Email)
  2958. buf.WriteByte(0) // auth
  2959. pkt := &V5ServerPacket{
  2960. Version: ICQLegacyVersionV5,
  2961. SessionID: session.SessionID,
  2962. Command: ICQLegacySrvMetaUser,
  2963. SeqNum1: session.NextServerSeqNum(),
  2964. SeqNum2: seq2,
  2965. UIN: session.UIN,
  2966. Data: buf.Bytes(),
  2967. }
  2968. h.logger.Debug("sending META full user info",
  2969. "uin", session.UIN,
  2970. "target", info.UIN,
  2971. )
  2972. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  2973. }
  2974. // sendMetaUserInfo sends a META user info response
  2975. // From iserverd v5_send_meta_info() in make_meta.cpp
  2976. //
  2977. // Packet format (success case):
  2978. // - SubCommand (2 bytes): SRV_META_USER_INFO (0x0104)
  2979. // - Success (1 byte): 0x0A for success
  2980. // - Nickname length (2 bytes) + Nickname (null-terminated string)
  2981. // - First name length (2 bytes) + First name (null-terminated string)
  2982. // - Last name length (2 bytes) + Last name (null-terminated string)
  2983. // - Email length (2 bytes) + Email (null-terminated string)
  2984. // - Auth required (1 byte): 0=no auth, 1=auth required
  2985. // - Gender (1 byte): 0=unspecified, 1=female, 2=male
  2986. // - Zero (1 byte): 0x00
  2987. func (h *V5Handler) sendMetaUserInfo(session *LegacySession, seqNum uint16, info *LegacyUserSearchResult) error {
  2988. if session == nil {
  2989. return nil
  2990. }
  2991. buf := new(bytes.Buffer)
  2992. // SubCommand: SRV_META_USER_INFO (0x0104)
  2993. _ = binary.Write(buf, binary.LittleEndian, ICQLegacySrvMetaUserInfo)
  2994. if info != nil {
  2995. // Success byte: 0x0A
  2996. buf.WriteByte(0x0A)
  2997. // Nickname (length-prefixed, null-terminated)
  2998. writeLegacyString(buf, info.Nickname)
  2999. // First name (length-prefixed, null-terminated)
  3000. writeLegacyString(buf, info.FirstName)
  3001. // Last name (length-prefixed, null-terminated)
  3002. writeLegacyString(buf, info.LastName)
  3003. // Email (length-prefixed, null-terminated) - iserverd uses email2 field
  3004. writeLegacyString(buf, info.Email)
  3005. // Auth required (1 byte)
  3006. buf.WriteByte(info.AuthRequired)
  3007. // Gender (1 byte)
  3008. buf.WriteByte(info.Gender)
  3009. // Trailing zero (1 byte) - as per iserverd
  3010. buf.WriteByte(0x00)
  3011. } else {
  3012. // Failure case: send meta fail
  3013. // Success byte: 0x32 (fail)
  3014. buf.WriteByte(0x32)
  3015. }
  3016. pkt := &V5ServerPacket{
  3017. Version: ICQLegacyVersionV5,
  3018. SessionID: session.SessionID,
  3019. Command: ICQLegacySrvMetaUser,
  3020. SeqNum1: session.NextServerSeqNum(),
  3021. SeqNum2: seqNum,
  3022. UIN: session.UIN,
  3023. Data: buf.Bytes(),
  3024. }
  3025. packetData := MarshalV5ServerPacket(pkt)
  3026. if info != nil {
  3027. h.logger.Info("sending META user info",
  3028. "uin", session.UIN,
  3029. "sub_command", fmt.Sprintf("0x%04X", ICQLegacySrvMetaUserInfo),
  3030. "target_uin", info.UIN,
  3031. "nickname", info.Nickname,
  3032. "firstname", info.FirstName,
  3033. "lastname", info.LastName,
  3034. "email", info.Email,
  3035. "auth", info.AuthRequired,
  3036. "gender", info.Gender,
  3037. "packet_len", len(packetData),
  3038. )
  3039. } else {
  3040. h.logger.Info("sending META user info not found",
  3041. "uin", session.UIN,
  3042. "sub_command", fmt.Sprintf("0x%04X", ICQLegacySrvMetaUserInfo),
  3043. "packet_len", len(packetData),
  3044. )
  3045. }
  3046. return h.sender.SendToSession(session, packetData)
  3047. }
  3048. // sendV5OldSearchFound sends an old-style search result
  3049. // From iserverd v5_send_old_search_found()
  3050. //
  3051. // Packet data format (after V5 header with JUNK(4) checkcode placeholder):
  3052. // - UIN(4): Target user's UIN (tuser.uin)
  3053. // - NICK_LEN(2) + NICK: Nickname (length-prefixed, null-terminated)
  3054. // - FIRST_LEN(2) + FIRST: First name (length-prefixed, null-terminated)
  3055. // - LAST_LEN(2) + LAST: Last name (length-prefixed, null-terminated)
  3056. // - EMAIL_LEN(2) + EMAIL: Email address (length-prefixed, null-terminated) - uses email2 in iserverd
  3057. // - AUTH(1): Authorization required flag (tuser.auth: 0=no, 1=yes)
  3058. // - 0x00(1): Unknown trailing byte
  3059. func (h *V5Handler) sendV5OldSearchFound(session *LegacySession, seq2 uint16, result *LegacyUserSearchResult) error {
  3060. if session == nil || result == nil {
  3061. return nil
  3062. }
  3063. // Build data: UIN(4) + NICK_LEN(2) + NICK + FIRST_LEN(2) + FIRST + LAST_LEN(2) + LAST + EMAIL_LEN(2) + EMAIL + AUTH(1) + 0x00(1)
  3064. // Note: The JUNK(4) in iserverd is the checkcode placeholder in the header, not part of data
  3065. buf := new(bytes.Buffer)
  3066. _ = binary.Write(buf, binary.LittleEndian, result.UIN)
  3067. writeLegacyString(buf, result.Nickname)
  3068. writeLegacyString(buf, result.FirstName)
  3069. writeLegacyString(buf, result.LastName)
  3070. writeLegacyString(buf, result.Email)
  3071. buf.WriteByte(result.AuthRequired) // auth - from iserverd tuser.auth
  3072. buf.WriteByte(0) // unknown trailing byte (as per iserverd)
  3073. pkt := &V5ServerPacket{
  3074. Version: ICQLegacyVersionV5,
  3075. SessionID: session.SessionID,
  3076. Command: ICQLegacySrvSearchFound,
  3077. SeqNum1: session.NextServerSeqNum(),
  3078. SeqNum2: seq2,
  3079. UIN: session.UIN,
  3080. Data: buf.Bytes(),
  3081. }
  3082. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3083. }
  3084. // sendV5OldSearchEnd sends old-style search end marker
  3085. // From iserverd v5_send_old_search_end()
  3086. //
  3087. // Packet format (after V5 header):
  3088. // - MORE(1): 0x01 if more results available, 0x00 if search complete
  3089. //
  3090. // Note: iserverd ALWAYS sends the more byte (0x00 or 0x01), not just when more=true
  3091. func (h *V5Handler) sendV5OldSearchEnd(session *LegacySession, seq2 uint16, more bool) error {
  3092. if session == nil {
  3093. return nil
  3094. }
  3095. // Build data: MORE(1) - always sent per iserverd v5_send_old_search_end()
  3096. // Note: The JUNK(4) in iserverd is the checkcode placeholder in the header, not part of data
  3097. var moreByte byte
  3098. if more {
  3099. moreByte = 0x01
  3100. } else {
  3101. moreByte = 0x00
  3102. }
  3103. pkt := &V5ServerPacket{
  3104. Version: ICQLegacyVersionV5,
  3105. SessionID: session.SessionID,
  3106. Command: ICQLegacySrvSearchDone,
  3107. SeqNum1: session.NextServerSeqNum(),
  3108. SeqNum2: seq2,
  3109. UIN: session.UIN,
  3110. Data: []byte{moreByte},
  3111. }
  3112. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3113. }
  3114. // sendV5OldStyleInfo sends old-style basic info response
  3115. // From iserverd v5_send_old_style_info()
  3116. //
  3117. // Packet format (after V5 header):
  3118. // - UIN(4): Target user's UIN
  3119. // - NICK_LEN(2) + NICK: Nickname (length-prefixed, null-terminated)
  3120. // - FIRST_LEN(2) + FIRST: First name (length-prefixed, null-terminated)
  3121. // - LAST_LEN(2) + LAST: Last name (length-prefixed, null-terminated)
  3122. // - EMAIL_LEN(2) + EMAIL: Email address (length-prefixed, null-terminated)
  3123. // - AUTH(1): Authorization required flag (0=no, 1=yes)
  3124. //
  3125. // Note: iserverd uses email2 field, we use primary Email field (functionally equivalent)
  3126. func (h *V5Handler) sendV5OldStyleInfo(session *LegacySession, info *LegacyUserSearchResult) error {
  3127. if session == nil || info == nil {
  3128. return nil
  3129. }
  3130. // Build data: UIN(4) + NICK_LEN(2) + NICK + FIRST_LEN(2) + FIRST + LAST_LEN(2) + LAST + EMAIL_LEN(2) + EMAIL + AUTH(1)
  3131. // Note: The JUNK(4) in iserverd is the checkcode placeholder in the header, not part of data
  3132. buf := new(bytes.Buffer)
  3133. _ = binary.Write(buf, binary.LittleEndian, info.UIN)
  3134. writeLegacyString(buf, info.Nickname)
  3135. writeLegacyString(buf, info.FirstName)
  3136. writeLegacyString(buf, info.LastName)
  3137. writeLegacyString(buf, info.Email)
  3138. buf.WriteByte(info.AuthRequired) // auth - from iserverd tuser.auth
  3139. seqNum := session.NextServerSeqNum()
  3140. pkt := &V5ServerPacket{
  3141. Version: ICQLegacyVersionV5,
  3142. SessionID: session.SessionID,
  3143. Command: ICQLegacySrvInfoReply,
  3144. SeqNum1: seqNum,
  3145. SeqNum2: 0,
  3146. UIN: session.UIN,
  3147. Data: buf.Bytes(),
  3148. }
  3149. packetData := MarshalV5ServerPacket(pkt)
  3150. h.logger.Debug("sending V5 old style info",
  3151. "uin", session.UIN,
  3152. "target_uin", info.UIN,
  3153. "seq1", seqNum,
  3154. "packet_len", len(packetData),
  3155. "packet_hex", fmt.Sprintf("%X", packetData),
  3156. )
  3157. return h.sender.SendToSession(session, packetData)
  3158. }
  3159. // sendV5OldStyleInfoExt sends old-style extended info response
  3160. // From iserverd v5_send_old_style_info_ext()
  3161. //
  3162. // Verified against licq.5 client (icqd-udp.cpp ICQ_CMDxRCV_USERxDETAILS):
  3163. // Client reads: UIN(4) + CITY(string) + COUNTRY(2) + TIMEZONE(1) + STATE(string) +
  3164. //
  3165. // AGE(2) + GENDER(1) + PHONE(string) + HOMEPAGE(string) + ABOUT(string) + ZIPCODE(4)
  3166. //
  3167. // Note: iserverd comments the byte after COUNTRY as "I don't know what is it" but
  3168. // the licq.5 client reads it as SetTimezone(packet.UnpackChar()). We send the user's
  3169. // timezone value here.
  3170. func (h *V5Handler) sendV5OldStyleInfoExt(session *LegacySession, targetUIN uint32, user *state.User) error {
  3171. if session == nil || user == nil {
  3172. return nil
  3173. }
  3174. // Extract fields from user struct (matching iserverd field names)
  3175. // From iserverd: tuser.hcity, tuser.hcountry, tuser.hstate, tuser.age, tuser.gender,
  3176. // tuser.hphone, tuser.hpage, notes.notes
  3177. hcity := user.ICQInfo.Basic.City
  3178. hcountry := user.ICQInfo.Basic.CountryCode
  3179. gmtOffset := user.ICQInfo.Basic.GMTOffset
  3180. hstate := user.ICQInfo.Basic.State
  3181. age := uint16(user.Age(func() time.Time { return time.Now() }))
  3182. gender := uint8(user.ICQInfo.More.Gender)
  3183. hphone := user.ICQInfo.Basic.Phone
  3184. hpage := user.ICQInfo.More.HomePageAddr
  3185. notes := user.ICQInfo.Notes.Notes
  3186. // Parse ZIP code string to uint32 for the old-style ext info format
  3187. // The licq.5 client reads this as UnpackUnsignedLong (4 bytes)
  3188. var zipCode uint32
  3189. if user.ICQInfo.Basic.ZIPCode != "" {
  3190. _, _ = fmt.Sscanf(user.ICQInfo.Basic.ZIPCode, "%d", &zipCode)
  3191. }
  3192. // Build data matching licq.5 client's USERxDETAILS parsing:
  3193. // UIN(4) + CITY(string) + COUNTRY(2) + TIMEZONE(1) + STATE(string) +
  3194. // AGE(2) + GENDER(1) + PHONE(string) + HOMEPAGE(string) + ABOUT(string) + ZIPCODE(4)
  3195. buf := new(bytes.Buffer)
  3196. _ = binary.Write(buf, binary.LittleEndian, targetUIN)
  3197. writeLegacyString(buf, hcity) // city (length-prefixed with null terminator)
  3198. _ = binary.Write(buf, binary.LittleEndian, hcountry) // country code
  3199. buf.WriteByte(gmtOffset) // timezone / GMT offset (client reads as SetTimezone)
  3200. writeLegacyString(buf, hstate) // state (length-prefixed with null terminator)
  3201. _ = binary.Write(buf, binary.LittleEndian, age) // age
  3202. buf.WriteByte(gender) // gender
  3203. writeLegacyString(buf, hphone) // phone (length-prefixed with null terminator)
  3204. writeLegacyString(buf, hpage) // homepage (length-prefixed with null terminator)
  3205. writeLegacyString(buf, notes) // about/notes (length-prefixed with null terminator)
  3206. _ = binary.Write(buf, binary.LittleEndian, zipCode) // zip code (uint32, client reads as UnpackUnsignedLong)
  3207. pkt := &V5ServerPacket{
  3208. Version: ICQLegacyVersionV5,
  3209. SessionID: session.SessionID,
  3210. Command: ICQLegacySrvExtInfoReply,
  3211. SeqNum1: session.NextServerSeqNum(),
  3212. SeqNum2: 0,
  3213. UIN: session.UIN,
  3214. Data: buf.Bytes(),
  3215. }
  3216. h.logger.Debug("sending V5 old-style extended info",
  3217. "to_uin", session.UIN,
  3218. "target_uin", targetUIN,
  3219. "city", hcity,
  3220. "country", hcountry,
  3221. "gmt_offset", gmtOffset,
  3222. "state", hstate,
  3223. "age", age,
  3224. "gender", gender,
  3225. "phone", hphone,
  3226. "homepage", hpage,
  3227. "notes_len", len(notes),
  3228. "zip_code", zipCode,
  3229. )
  3230. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3231. }
  3232. // sendV5InvalidUIN sends invalid UIN response
  3233. // From iserverd v5_send_invalid_uin()
  3234. func (h *V5Handler) sendV5InvalidUIN(session *LegacySession, uin uint32) error {
  3235. if session == nil {
  3236. return nil
  3237. }
  3238. // Build data: UIN(4)
  3239. // Note: The JUNK(4) in iserverd is the checkcode placeholder in the header, not part of data
  3240. data := make([]byte, 4)
  3241. binary.LittleEndian.PutUint32(data[0:4], uin)
  3242. pkt := &V5ServerPacket{
  3243. Version: ICQLegacyVersionV5,
  3244. SessionID: session.SessionID,
  3245. Command: ICQLegacySrvInvalidUIN,
  3246. SeqNum1: session.NextServerSeqNum(),
  3247. SeqNum2: 0,
  3248. UIN: session.UIN,
  3249. Data: data,
  3250. }
  3251. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3252. }
  3253. // writeLegacyString writes a length-prefixed string to a buffer
  3254. func writeLegacyString(buf *bytes.Buffer, s string) {
  3255. length := uint16(len(s) + 1)
  3256. _ = binary.Write(buf, binary.LittleEndian, length)
  3257. buf.WriteString(s)
  3258. buf.WriteByte(0) // null terminator
  3259. }
  3260. // readLPString reads a length-prefixed null-terminated string from data at offset.
  3261. // Returns the string (without null terminator) and the number of bytes consumed.
  3262. func readLPString(data []byte, offset int) (string, int) {
  3263. if offset+2 > len(data) {
  3264. return "", 0
  3265. }
  3266. strLen := int(binary.LittleEndian.Uint16(data[offset:]))
  3267. offset += 2
  3268. if strLen <= 0 || offset+strLen > len(data) {
  3269. return "", 2
  3270. }
  3271. // Strip null terminator if present
  3272. s := string(data[offset : offset+strLen])
  3273. if len(s) > 0 && s[len(s)-1] == 0 {
  3274. s = s[:len(s)-1]
  3275. }
  3276. return s, 2 + strLen
  3277. }
  3278. // handleDirectWhiteSearch handles white pages search sent directly (0x0532/0x0533)
  3279. // Some older clients send META search commands directly instead of wrapped in META_USER
  3280. func (h *V5Handler) handleDirectWhiteSearch(session *LegacySession, pkt *V5ClientPacket) error {
  3281. if session == nil {
  3282. return nil
  3283. }
  3284. _ = h.sendV5Ack(session, pkt.SeqNum1)
  3285. h.logger.Info("V5 direct white pages search", "uin", session.UIN, "data_len", len(pkt.Data))
  3286. // Delegate to the META handler - pkt.Data is the same as subData for direct commands
  3287. return h.handleMetaSearchWhite(session, pkt, pkt.Data)
  3288. }
  3289. // handleDirectNameSearch handles name search sent directly (0x0514/0x0515)
  3290. func (h *V5Handler) handleDirectNameSearch(session *LegacySession, pkt *V5ClientPacket) error {
  3291. if session == nil {
  3292. return nil
  3293. }
  3294. _ = h.sendV5Ack(session, pkt.SeqNum1)
  3295. // Parse three length-prefixed strings: nick, first, last
  3296. offset := 0
  3297. nick, n := readLPString(pkt.Data, offset)
  3298. offset += n
  3299. first, n := readLPString(pkt.Data, offset)
  3300. offset += n
  3301. last, _ := readLPString(pkt.Data, offset)
  3302. h.logger.Info("V5 direct name search",
  3303. "uin", session.UIN,
  3304. "nick", nick,
  3305. "first", first,
  3306. "last", last,
  3307. )
  3308. ctx := context.Background()
  3309. results, err := h.service.SearchByName(ctx, nick, first, last, "")
  3310. if err != nil {
  3311. h.logger.Info("V5 direct name search - error", "uin", session.UIN, "err", err)
  3312. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3313. }
  3314. if len(results) == 0 {
  3315. h.logger.Info("V5 direct name search - no results", "uin", session.UIN)
  3316. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3317. }
  3318. h.logger.Info("V5 direct name search - found", "uin", session.UIN, "count", len(results))
  3319. for _, r := range results {
  3320. _ = h.sendV5OldSearchFound(session, pkt.SeqNum2, &r)
  3321. }
  3322. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3323. }
  3324. // handleDirectUINSearch handles UIN search sent directly (0x051E/0x051F)
  3325. func (h *V5Handler) handleDirectUINSearch(session *LegacySession, pkt *V5ClientPacket) error {
  3326. if session == nil {
  3327. return nil
  3328. }
  3329. _ = h.sendV5Ack(session, pkt.SeqNum1)
  3330. // Parse target UIN
  3331. if len(pkt.Data) < 4 {
  3332. h.logger.Info("V5 direct UIN search - data too short", "uin", session.UIN)
  3333. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3334. }
  3335. ctx := context.Background()
  3336. targetUIN := binary.LittleEndian.Uint32(pkt.Data[0:4])
  3337. h.logger.Info("V5 direct UIN search",
  3338. "uin", session.UIN,
  3339. "target_uin", targetUIN,
  3340. )
  3341. result, err := h.service.SearchByUIN(ctx, targetUIN)
  3342. if err != nil {
  3343. h.logger.Info("V5 direct UIN search - error", "target_uin", targetUIN, "err", err)
  3344. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3345. }
  3346. if result == nil {
  3347. h.logger.Info("V5 direct UIN search - NOT FOUND", "target_uin", targetUIN)
  3348. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3349. }
  3350. h.logger.Info("V5 direct UIN search - FOUND",
  3351. "target_uin", targetUIN,
  3352. "nickname", result.Nickname,
  3353. )
  3354. _ = h.sendV5OldSearchFound(session, pkt.SeqNum2, result)
  3355. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3356. }
  3357. // handleDirectEmailSearch handles email search sent directly (0x0528/0x0529)
  3358. func (h *V5Handler) handleDirectEmailSearch(session *LegacySession, pkt *V5ClientPacket) error {
  3359. if session == nil {
  3360. return nil
  3361. }
  3362. _ = h.sendV5Ack(session, pkt.SeqNum1)
  3363. email, _ := readLPString(pkt.Data, 0)
  3364. h.logger.Info("V5 direct email search",
  3365. "uin", session.UIN,
  3366. "email", email,
  3367. )
  3368. ctx := context.Background()
  3369. results, err := h.service.SearchByName(ctx, "", "", "", email)
  3370. if err != nil {
  3371. h.logger.Info("V5 direct email search - error", "uin", session.UIN, "err", err)
  3372. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3373. }
  3374. if len(results) == 0 {
  3375. h.logger.Info("V5 direct email search - no results", "uin", session.UIN)
  3376. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3377. }
  3378. h.logger.Info("V5 direct email search - found", "uin", session.UIN, "count", len(results))
  3379. for _, r := range results {
  3380. _ = h.sendV5OldSearchFound(session, pkt.SeqNum2, &r)
  3381. }
  3382. return h.sendV5OldSearchEnd(session, pkt.SeqNum2, false)
  3383. }
  3384. // sendOnlineMessage sends an online system message to a V5 client
  3385. // Format: header + FROM_UIN(4) + MSG_TYPE(2) + MSG_LEN(2) + MESSAGE
  3386. func (h *V5Handler) sendOnlineMessage(session *LegacySession, fromUIN uint32, msgType uint16, message string) error {
  3387. msgBytes := []byte(message)
  3388. h.logger.Debug("V5 sending online message",
  3389. "to", session.UIN,
  3390. "from", fromUIN,
  3391. "type", fmt.Sprintf("0x%04X", msgType),
  3392. "msg_len", len(msgBytes),
  3393. )
  3394. // Send V5 format packet
  3395. data := make([]byte, 4+2+2+len(msgBytes)+1)
  3396. offset := 0
  3397. // From UIN
  3398. binary.LittleEndian.PutUint32(data[offset:], fromUIN)
  3399. offset += 4
  3400. // Message type (mask high byte for legacy clients)
  3401. binary.LittleEndian.PutUint16(data[offset:], msgType&0x00FF)
  3402. offset += 2
  3403. // Message length (including null terminator)
  3404. binary.LittleEndian.PutUint16(data[offset:], uint16(len(msgBytes)+1))
  3405. offset += 2
  3406. // Message content
  3407. copy(data[offset:], msgBytes)
  3408. offset += len(msgBytes)
  3409. data[offset] = 0 // null terminator
  3410. pkt := &V5ServerPacket{
  3411. Version: ICQLegacyVersionV5,
  3412. SessionID: session.SessionID,
  3413. Command: ICQLegacySrvSysMsgOnline, // 0x0104
  3414. SeqNum1: session.NextServerSeqNum(),
  3415. SeqNum2: 0,
  3416. UIN: session.UIN,
  3417. Data: data,
  3418. }
  3419. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3420. }
  3421. // sendV5UserOffline sends user offline notification
  3422. // From iserverd v5_send_user_offline()
  3423. func (h *V5Handler) sendV5UserOffline(session *LegacySession, uin uint32) error {
  3424. // V5 USER_OFFLINE format: UIN(4)
  3425. data := make([]byte, 4)
  3426. binary.LittleEndian.PutUint32(data[0:4], uin)
  3427. pkt := &V5ServerPacket{
  3428. Version: ICQLegacyVersionV5,
  3429. SessionID: session.SessionID,
  3430. Command: ICQLegacySrvUserOffline,
  3431. SeqNum1: session.NextServerSeqNum(),
  3432. SeqNum2: 0,
  3433. UIN: session.UIN,
  3434. Data: data,
  3435. }
  3436. h.logger.Debug("sending V5 user offline notification",
  3437. "to", session.UIN,
  3438. "offline_uin", uin,
  3439. )
  3440. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3441. }
  3442. // sendV5UserStatus sends user status change notification
  3443. // From iserverd v5_send_user_status() in make_packet.cpp
  3444. // This is used when a user changes status while already online
  3445. // (e.g., Away -> Online, Online -> DND)
  3446. // Format: UIN(4) + STATUS(2) + ESTAT(2)
  3447. func (h *V5Handler) sendV5UserStatus(session *LegacySession, uin uint32, status uint32) error {
  3448. // V5 USER_STATUS format from iserverd:
  3449. // UIN(4) + STATUS(2) + ESTAT(2)
  3450. data := make([]byte, 8)
  3451. offset := 0
  3452. // UIN of the user whose status changed
  3453. binary.LittleEndian.PutUint32(data[offset:], uin)
  3454. offset += 4
  3455. // Status (low word)
  3456. binary.LittleEndian.PutUint16(data[offset:], uint16(status&0xFFFF))
  3457. offset += 2
  3458. // Extended status (high word)
  3459. binary.LittleEndian.PutUint16(data[offset:], uint16(status>>16))
  3460. pkt := &V5ServerPacket{
  3461. Version: ICQLegacyVersionV5,
  3462. SessionID: session.SessionID,
  3463. Command: ICQLegacySrvUserStatus, // 0x01A4
  3464. SeqNum1: session.NextServerSeqNum(),
  3465. SeqNum2: 0,
  3466. UIN: session.UIN,
  3467. Data: data,
  3468. }
  3469. h.logger.Debug("sending V5 user status change notification",
  3470. "to", session.UIN,
  3471. "changed_uin", uin,
  3472. "status", fmt.Sprintf("0x%08X", status),
  3473. )
  3474. return h.sender.SendToSession(session, MarshalV5ServerPacket(pkt))
  3475. }