// -*- c-basic-offset: 2 -*-
/* ----------------------------------------------------------------------------
 * Licq - A ICQ Client for Unix
 * Copyright (C) 1998 - 2003 Licq developers
 *
 * This program is licensed under the terms found in the LICENSE file.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>

#include <algorithm>

// Localization
#include "gettext.h"

#include "time-fix.h"

#include "licq_icqd.h"
#include "licq_translate.h"
#include "licq_packets.h"
#include "licq_socket.h"
#include "licq_user.h"
#include "licq_events.h"
#include "licq_log.h"
#include "licq_chat.h"
#include "licq_filetransfer.h"
#include "support.h"
#include "licq_message.h"
#include "licq_countrycodes.h"
#include "licq_protoplugind.h"

void CICQDaemon::ProtoAddUser(const char *_szId, unsigned long _nPPID,
                              bool _bAuthRequired)
{
  if (_nPPID == LICQ_PPID)
    icqAddUser(_szId, _bAuthRequired);
  else
    PushProtoSignal(new CAddUserSignal(_szId, _bAuthRequired), _nPPID);
}

//-----icqAddUser----------------------------------------------------------
void CICQDaemon::icqAddUser(const char *_szId, bool _bAuthRequired)
{
  CSrvPacketTcp *p = new CPU_GenericUinList(_szId, ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_ADDxTOxLIST);
  gLog.Info(tr("%sAlerting server to new user (#%lu)...\n"), L_SRVxSTR,
             p->Sequence());
  SendExpectEvent_Server(_szId, LICQ_PPID, p, NULL);

  // Server side list add, and update of group
  if (UseServerContactList())
  {
    icqAddUserServer(_szId, _bAuthRequired);
  }

  icqUserBasicInfo(_szId);
}

void CICQDaemon::icqAddUser(unsigned long _nUin, bool _bAuthRequired)
{
  char szUin[24];
  sprintf(szUin, "%lu", _nUin);

  icqAddUser(szUin, _bAuthRequired);
}


//-----icqAddUserServer---------------------------------------------------------
void CICQDaemon::icqAddUserServer(const char *_szId, bool _bAuthRequired)
{
  CSrvPacketTcp *pStart = 0;

  // Skip the authorization needed step
  // This has been reverted, it didn't work 100% of the time
  //if (_bAuthRequired)
  //  pStart = new CPU_ExportContactStart();
  //else
    pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
      ICQ_SNACxLIST_ROSTxEDITxSTART);
  SendEvent_Server(pStart);

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(_szId));
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CPU_AddToServerList *pAdd = new CPU_AddToServerList(_szId, ICQ_ROSTxNORMAL,
    0, _bAuthRequired);
  gLog.Info(tr("%sAdding %s to server list...\n"), L_SRVxSTR, _szId);
  SendExpectEvent_Server(0, pAdd, NULL);
}

void CICQDaemon::icqAddUserServer(unsigned long _nUin, bool _bAuthRequired)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", _nUin);
  szUin[12] = 0;

  icqAddUserServer(szUin, _bAuthRequired);
}

//-----CheckExport--------------------------------------------------------------
void CICQDaemon::CheckExport()
{
  // Export groups
  GroupList groups;
  GroupList *g = gUserManager.LockGroupList(LOCK_R);
  GroupIDList *gID = gUserManager.LockGroupIDList(LOCK_R);

  for (unsigned int i = 0; i < gID->size(); i++)
  {
    if ((*gID)[i] == 0)
    {
      groups.push_back((*g)[i]);

      pthread_mutex_lock(&mutex_modifyserverusers);
      m_lszModifyServerUsers.push_back( strdup((*g)[i]) );
      pthread_mutex_unlock(&mutex_modifyserverusers);
    }
  }

  gUserManager.UnlockGroupList();
  gUserManager.UnlockGroupIDList();

  if (groups.size())
    icqExportGroups(groups);

  // Export users on a per group basis for the update group packet to work
  UserStringList doneUsers;
  for (unsigned int j = 1; j <= g->size(); j++)
  {
    UserStringList users;
    FOR_EACH_PROTO_USER_START(LICQ_PPID, LOCK_R)
    {
      if (pUser->GetInGroup(GROUPS_USER, j) && pUser->GetSID() == 0 &&
          !pUser->IgnoreList())
      {
        UserStringList::const_iterator p = std::find(doneUsers.begin(), doneUsers.end(),
          pUser->IdString());

        if (p == doneUsers.end())
        {
          users.push_back(strdup(pUser->IdString()));
          doneUsers.push_back(strdup(pUser->IdString()));

          pthread_mutex_lock(&mutex_modifyserverusers);
          m_lszModifyServerUsers.push_back(strdup(pUser->IdString()));
          pthread_mutex_unlock(&mutex_modifyserverusers);
        }
      }
    }
    FOR_EACH_PROTO_USER_END

    if (users.size())
      icqExportUsers(users, ICQ_ROSTxNORMAL);
  }
  
  UserStringList::iterator it;
  for (it = doneUsers.begin(); it != doneUsers.end(); it++)
    free(*it);

  // Export visible/invisible/ignore list
  UserStringList visibleUsers, invisibleUsers, ignoredUsers;
  FOR_EACH_PROTO_USER_START(LICQ_PPID, LOCK_R)
  {
    if (pUser->IgnoreList() && pUser->GetSID() == 0)
    {
      ignoredUsers.push_back(strdup(pUser->IdString()));

      pthread_mutex_lock(&mutex_modifyserverusers);
      m_lszModifyServerUsers.push_back(strdup(pUser->IdString()));
      pthread_mutex_unlock(&mutex_modifyserverusers);
    }
    else
    {
      if (pUser->InvisibleList() && pUser->GetInvisibleSID() == 0)
      {
        invisibleUsers.push_back(strdup(pUser->IdString()));

        pthread_mutex_lock(&mutex_modifyserverusers);
        m_lszModifyServerUsers.push_back(strdup(pUser->IdString()));
        pthread_mutex_unlock(&mutex_modifyserverusers);
      }

      if (pUser->VisibleList() && pUser->GetVisibleSID() == 0)
      {
        visibleUsers.push_back(strdup(pUser->IdString()));

        pthread_mutex_lock(&mutex_modifyserverusers);
        m_lszModifyServerUsers.push_back(strdup(pUser->IdString()));
        pthread_mutex_unlock(&mutex_modifyserverusers);
      }
    }
  }
  FOR_EACH_PROTO_USER_END

  if (visibleUsers.size())
    icqExportUsers(visibleUsers, ICQ_ROSTxVISIBLE);

  if (invisibleUsers.size())
    icqExportUsers(invisibleUsers, ICQ_ROSTxINVISIBLE);

  if (ignoredUsers.size())
    icqExportUsers(ignoredUsers, ICQ_ROSTxIGNORE);
}

//-----icqExportUsers-----------------------------------------------------------
void CICQDaemon::icqExportUsers(UserStringList &users, unsigned short _nType)
{
  if (!UseServerContactList())  return;

  CSrvPacketTcp *pStart = new CPU_ExportContactStart();
  SendEvent_Server(pStart);

  CSrvPacketTcp *pExport = new CPU_ExportToServerList(users, _nType);
  gLog.Info(tr("%sExporting users to server contact list...\n"), L_SRVxSTR);
  SendExpectEvent_Server(0L, pExport, NULL);
}

//-----icqAddGroup--------------------------------------------------------------
void CICQDaemon::icqAddGroup(const char *_szName)
{
  if (!UseServerContactList())  return;

  CSrvPacketTcp *pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
    ICQ_SNACxLIST_ROSTxEDITxSTART);
  SendEvent_Server(pStart);

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(_szName));
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CPU_AddToServerList *pAdd = new CPU_AddToServerList(_szName, ICQ_ROSTxGROUP);
  int nGSID = pAdd->GetGSID();
  gLog.Info(tr("%sAdding group %s (%d) to server list ...\n"), L_SRVxSTR, _szName, nGSID);
  SendExpectEvent_Server(0L, pAdd, NULL);
}

//-----icqChangeGroup-----------------------------------------------------------
void CICQDaemon::icqChangeGroup(unsigned long _nUin, unsigned short _nNewGroup,
                                unsigned short _nOldGSID, unsigned short _nNewType,
                                unsigned short _nOldType)
{
  if (!UseServerContactList())  return;

  // Get their old SID
  ICQUser *u = gUserManager.FetchUser(_nUin, LOCK_R);
  int nSID = u->GetSID();
  gUserManager.DropUser(u);

  CSrvPacketTcp *pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
                                                ICQ_SNACxLIST_ROSTxEDITxSTART);
  SendEvent_Server(pStart);

  char szUin[13];
  snprintf(szUin, 12, "%lu", _nUin);
  szUin[12] = '\0';

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(szUin)); // add
  m_lszModifyServerUsers.push_back(strdup(szUin)); // remove
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CPU_AddToServerList *pAdd = new CPU_AddToServerList(szUin, _nNewType,
                                                      _nNewGroup);
  gLog.Info(tr("%sChanging group on server list for %s ...\n"), L_SRVxSTR, szUin);
  SendExpectEvent_Server(0, pAdd, NULL);

  CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(szUin, _nOldGSID,
                                                        nSID, _nOldType);
  SendExpectEvent_Server(0, pRemove, NULL);
}

void CICQDaemon::icqChangeGroup(const char *_szId, unsigned long _nPPID,
                                unsigned short _nNewGroup, unsigned short _nOldGSID,
                                unsigned short _nNewType, unsigned short _nOldType)
{
  if (!UseServerContactList())  return;

  // Get their old SID
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
  int nSID = u->GetSID();
  gUserManager.DropUser(u);

  CSrvPacketTcp *pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
                                                ICQ_SNACxLIST_ROSTxEDITxSTART);
  SendEvent_Server(pStart);

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(_szId)); // add
  m_lszModifyServerUsers.push_back(strdup(_szId)); // remove
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CPU_AddToServerList *pAdd = new CPU_AddToServerList(_szId, _nNewType,
                                                      _nNewGroup);
  gLog.Info(tr("%sChanging group on server list for %s ...\n"), L_SRVxSTR, _szId);
  SendExpectEvent_Server(0, pAdd, NULL);

  CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(_szId, _nOldGSID,
                                                        nSID, _nOldType);
  SendExpectEvent_Server(0, pRemove, NULL);
}

//-----icqExportGroups----------------------------------------------------------
void CICQDaemon::icqExportGroups(GroupList &groups)
{
  if (!UseServerContactList()) return;

  CSrvPacketTcp *pStart = new CPU_ExportContactStart();
  SendEvent_Server(pStart);

  CSrvPacketTcp *pExport = new CPU_ExportGroupsToServerList(groups);
  gLog.Info(tr("%sExporting groups to server contact list...\n"), L_SRVxSTR);
  SendExpectEvent_Server(0, pExport, NULL);
}

//-----icqRemoveUser-------------------------------------------------------
void CICQDaemon::ProtoRemoveUser(const char *_szId, unsigned long _nPPID)
{
  if (_nPPID == LICQ_PPID)
    icqRemoveUser(strtoul(_szId, (char **)NULL, 10));
  else
    PushProtoSignal(new CRemoveUserSignal(_szId), _nPPID);
}

void CICQDaemon::icqRemoveUser(const char *_szId)
{
  // Remove from the SSList and update groups
  if (UseServerContactList())
  {
    CSrvPacketTcp *pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
      ICQ_SNACxLIST_ROSTxEDITxSTART);
    SendEvent_Server(pStart);

    ICQUser *u = gUserManager.FetchUser(_szId, LICQ_PPID, LOCK_W);
    unsigned short nGSID = u->GetGSID();
    unsigned short nSID = u->GetSID();
    u->SetGSID(0);
    gUserManager.DropUser(u);

    pthread_mutex_lock(&mutex_modifyserverusers);
    m_lszModifyServerUsers.push_back(strdup(_szId));
    pthread_mutex_unlock(&mutex_modifyserverusers);

    CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(_szId, nGSID, nSID, ICQ_ROSTxNORMAL);
    SendExpectEvent_Server(0, pRemove, NULL);
  }

  // Tell server they are no longer with us.
  CSrvPacketTcp *p = new CPU_GenericUinList(_szId, ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_REMOVExFROMxLIST);
  gLog.Info(tr("%sAlerting server to remove user (#%ld)...\n"), L_SRVxSTR,
            p->Sequence());
  SendExpectEvent_Server(_szId, LICQ_PPID, p, NULL);
}

void CICQDaemon::icqRemoveUser(unsigned long _nUin)
{
  // Remove from the SSList and update groups
  if (UseServerContactList())
  {
    CSrvPacketTcp *pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
      ICQ_SNACxLIST_ROSTxEDITxSTART);
    SendEvent_Server(pStart);

    ICQUser *u = gUserManager.FetchUser(_nUin, LOCK_W);
    unsigned short nGSID = u->GetGSID();
    unsigned short nSID = u->GetSID();
    char szUin[13];
    snprintf(szUin, 12, "%lu", _nUin);
    szUin[12] = '\0';
    u->SetGSID(0);
    gUserManager.DropUser(u);

    pthread_mutex_lock(&mutex_modifyserverusers);
    m_lszModifyServerUsers.push_back(strdup(szUin));
    pthread_mutex_unlock(&mutex_modifyserverusers);

    CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(szUin, nGSID, nSID, ICQ_ROSTxNORMAL);
    SendExpectEvent_Server(0, pRemove, NULL);
  }

  // Tell server they are no longer with us.
  CSrvPacketTcp *p = new CPU_GenericUinList(_nUin, ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_REMOVExFROMxLIST);
  gLog.Info(tr("%sAlerting server to remove user (#%lu)...\n"), L_SRVxSTR,
            p->Sequence());
  SendExpectEvent_Server(_nUin, p, NULL);
}

//-----icqRemoveGroup----------------------------------------------------------
void CICQDaemon::icqRemoveGroup(const char *_szName)
{
  if (!UseServerContactList()) return;

  CSrvPacketTcp *pStart = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
    ICQ_SNACxLIST_ROSTxEDITxSTART);
  SendEvent_Server(pStart);

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(_szName));
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(_szName,
    gUserManager.GetIDFromGroup(_szName), 0, ICQ_ROSTxGROUP);
  gLog.Info(tr("%sRemoving group from server side list (%s)...\n"), L_SRVxSTR, _szName);
  SendExpectEvent_Server(0, pRemove, NULL);
}

//-----icqRenameGroup----------------------------------------------------------
void CICQDaemon::icqRenameGroup(const char *_szNewName, unsigned short _nGSID)
{
  if (!UseServerContactList() || !_nGSID || m_nTCPSrvSocketDesc == -1) return;

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(_szNewName));
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CSrvPacketTcp *pUpdate = new CPU_UpdateToServerList(_szNewName,
    ICQ_ROSTxGROUP, _nGSID);
  gLog.Info(tr("%sRenaming group with id %d to %s...\n"), L_SRVxSTR, _nGSID,
    _szNewName);
  SendExpectEvent_Server(0, pUpdate, NULL);
}

//-----icqRenameUser------------------------------------------------------------
void CICQDaemon::icqRenameUser(unsigned long _nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", _nUin);
  szUin[12] = '\0'; 

  icqRenameUser(szUin);
}

void CICQDaemon::ProtoRenameUser(const char *_szId, unsigned long _nPPID)
{
  if (_nPPID == LICQ_PPID)
    icqRenameUser(_szId);
  else
    PushProtoSignal(new CRenameUserSignal(_szId), _nPPID);
}

void CICQDaemon::icqRenameUser(const char *_szId)
{
  if (!UseServerContactList() || m_nTCPSrvSocketDesc == -1) return;

  ICQUser *u = gUserManager.FetchUser(_szId, LICQ_PPID, LOCK_R);
  if (u == NULL) return;
  char *szNewAlias = u->GetAlias();
  gUserManager.DropUser(u);

  pthread_mutex_lock(&mutex_modifyserverusers);
  m_lszModifyServerUsers.push_back(strdup(_szId));
  pthread_mutex_unlock(&mutex_modifyserverusers);

  CSrvPacketTcp *pUpdate = new CPU_UpdateToServerList(_szId, ICQ_ROSTxNORMAL);
  gLog.Info(tr("%sRenaming %s to %s...\n"), L_SRVxSTR, _szId, szNewAlias);
  SendExpectEvent_Server(0, pUpdate, NULL);
}

//-----icqAlertUser-------------------------------------------------------------
void CICQDaemon::icqAlertUser(unsigned long _nUin)
{
  ICQOwner *o = gUserManager.FetchOwner(LOCK_R);
  char sz[MAX_MESSAGE_SIZE];
  sprintf(sz, "%s%c%s%c%s%c%s%c%c%c", o->GetAlias(), 0xFE, o->GetFirstName(),
          0xFE, o->GetLastName(), 0xFE, o->GetEmailPrimary(), 0xFE,
          o->GetAuthorization() ? '0' : '1', 0xFE);
  gUserManager.DropOwner();
  CPU_ThroughServer *p = new CPU_ThroughServer(_nUin, ICQ_CMDxSUB_ADDEDxTOxLIST, sz);
  gLog.Info(tr("%sAlerting user they were added (#%lu)...\n"), L_SRVxSTR, p->Sequence());
  SendExpectEvent_Server(_nUin, p, NULL);
}

//-----icqFetchAutoResponseServer-----------------------------------------------
unsigned long CICQDaemon::ProtoFetchAutoResponseServer(const char *_szId, unsigned long _nPPID)
{
  unsigned long nRet = 0;

  if (_nPPID == LICQ_PPID)
    nRet = icqFetchAutoResponseServer(strtoul(_szId, (char **)NULL, 10));
  else
    ;

  return nRet;
}

unsigned long CICQDaemon::icqFetchAutoResponseServer(unsigned long _nUin)
{
  ICQUser *u = gUserManager.FetchUser(_nUin, LOCK_R);
  if (!u) return 0;

  int nCmd;
  switch (u->Status())
  {
  case ICQ_STATUS_AWAY:
    nCmd = ICQ_CMDxTCP_READxAWAYxMSG; break;
  case ICQ_STATUS_NA:
    nCmd = ICQ_CMDxTCP_READxNAxMSG; break;
  case ICQ_STATUS_DND:
    nCmd = ICQ_CMDxTCP_READxDNDxMSG; break;
  case ICQ_STATUS_OCCUPIED:
    nCmd = ICQ_CMDxTCP_READxOCCUPIEDxMSG; break;
  case ICQ_STATUS_FREEFORCHAT:
    nCmd = ICQ_CMDxTCP_READxFFCxMSG; break;
  default:
    nCmd = ICQ_CMDxTCP_READxAWAYxMSG; break;
  }

  CPU_ThroughServer *p = new CPU_ThroughServer(_nUin, nCmd, 0);
  gLog.Info(tr("%sRequesting auto response from %s (%lu).\n"), L_SRVxSTR,
  	u->GetAlias(), p->Sequence());
  gUserManager.DropUser(u);

  ICQEvent *result = SendExpectEvent_Server(_nUin, p, NULL);
  if (result != NULL)
    return result->EventId();
  return 0;
}

//-----icqSetRandomChatGroup----------------------------------------------------
unsigned long CICQDaemon::icqSetRandomChatGroup(unsigned long _nGroup)
{
  CPU_SetRandomChatGroup *p = new CPU_SetRandomChatGroup(_nGroup);
  gLog.Info(tr("%sSetting random chat group (#%lu)...\n"), L_SRVxSTR,
            p->Sequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqRandomChatSearch------------------------------------------------------
unsigned long CICQDaemon::icqRandomChatSearch(unsigned long _nGroup)
{
  CPU_RandomChatSearch *p = new CPU_RandomChatSearch(_nGroup);
  gLog.Info(tr("%sSearching for random chat user (#%lu)...\n"), L_SRVxSTR,
            p->Sequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

void CICQDaemon::icqRegister(const char *_szPasswd)
{
  m_szRegisterPasswd = strdup(_szPasswd);
  m_bRegistering = true;
//  CPU_RegisterFirst *p = new CPU_RegisterFirst();
//  gLog.Info("%sRegistering a new user (#%lu)...\n", L_SRVxSTR, p->Sequence());
// SendEvent_Server(p);
  ConnectToLoginServer();
}

//-----ICQ::icqRegisterFinish------------------------------------------------
void CICQDaemon::icqRegisterFinish()
{
  CPU_RegisterFirst *pFirst = new CPU_RegisterFirst();
  SendEvent_Server(pFirst);

  CPU_Register *p = new CPU_Register(m_szRegisterPasswd);
  gLog.Info(tr("%sRegistering a new user...\n"), L_SRVxSTR);
  SendExpectEvent_Server(0, p, NULL);
}

//-----ICQ::icqRelogon-------------------------------------------------------
void CICQDaemon::icqRelogon()
{
  unsigned long status;

  if (m_eStatus == STATUS_ONLINE)
  {
    ICQOwner *o = gUserManager.FetchOwner(LOCK_R);
    status = o->StatusFull();
    gUserManager.DropOwner();
  }
  else
  {
    status = m_nDesiredStatus;
  }

  icqLogoff();
  m_eStatus = STATUS_OFFLINE_MANUAL;

  icqLogon(status);

//  m_eStatus = STATUS_OFFLINE_FORCED;
}

//-----icqRequestMetaInfo----------------------------------------------------
unsigned long CICQDaemon::icqRequestMetaInfo(const char *_szId)
{
  CPU_Meta_RequestAllInfo *p = new CPU_Meta_RequestAllInfo(_szId);
  gLog.Info(tr("%sRequesting meta info for %s (#%lu/#%d)...\n"), L_SRVxSTR, _szId,
            p->Sequence(), p->SubSequence());
  //XXX not yet
  //ICQEvent *e = SendExpectEvent_Server(_szId, LICQ_PPID, p, NULL, true);
  ICQEvent *e = SendExpectEvent_Server(strtoul(_szId, (char **)NULL, 10), p, NULL, true);
  if (e != NULL)
    return e->EventId();
  return 0;
}

unsigned long CICQDaemon::icqRequestMetaInfo(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = 0;

  return icqRequestMetaInfo(szUin);
}

//-----icqSetStatus-------------------------------------------------------------
unsigned long CICQDaemon::ProtoSetStatus(unsigned long _nPPID,
                                         unsigned short _nNewStatus)
{
  unsigned long nRet = 0;

  if (_nPPID == LICQ_PPID)
    nRet = icqSetStatus(_nNewStatus);
  else
    PushProtoSignal(new CChangeStatusSignal(_nNewStatus), _nPPID);

  return nRet;
}

unsigned long CICQDaemon::icqSetStatus(unsigned short newStatus)
{
  if (newStatus & ICQ_STATUS_DND)
    newStatus |= ICQ_STATUS_OCCUPIED; // quick compat hack

  // icq go wants the mask set when we truly are away
  if (newStatus & ICQ_STATUS_DND || newStatus & ICQ_STATUS_OCCUPIED ||
      newStatus & ICQ_STATUS_NA)
    newStatus |= ICQ_STATUS_AWAY;

  // Set the status flags
  ICQOwner *o = gUserManager.FetchOwner(LOCK_R);
  unsigned long s = o->AddStatusFlags(newStatus);
  unsigned long pfm = o->PhoneFollowMeStatus();
  bool Invisible = o->StatusInvisible();
  bool goInvisible = (newStatus & ICQ_STATUS_FxPRIVATE);
  bool isLogon = o->StatusOffline();
  gUserManager.DropOwner();

  if (!Invisible && goInvisible)
    icqSendVisibleList();

  CSrvPacketTcp* p;
  if (isLogon)
    p = new CPU_SetLogonStatus(s);
  else
    p = new CPU_SetStatus(s);

  gLog.Info(tr("%sChanging status to %s (#%lu)...\n"), L_SRVxSTR,
            ICQUser::StatusToStatusStr(newStatus, goInvisible), p->Sequence());
  m_nDesiredStatus = s;

  SendEvent_Server(p);

  if (pfm)
  {
    p = new CPU_UpdateStatusTimestamp(PLUGIN_FOLLOWxME, pfm, s);
    SendEvent_Server(p);
  }

  if (Invisible && !goInvisible)
    icqSendInvisibleList();

  return 0;
}

//-----icqSetPassword--------------------------------------------------------
unsigned long CICQDaemon::icqSetPassword(const char *szPassword)
{
  CPU_SetPassword *p = new CPU_SetPassword(szPassword);
  gLog.Info(tr("%sUpdating password (#%lu/#%d)...\n"), L_SRVxSTR,
            p->Sequence(), p->SubSequence());
  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetGeneralInfo----------------------------------------------------
unsigned long CICQDaemon::icqSetGeneralInfo(
                          const char *szAlias, const char *szFirstName,
                          const char *szLastName, const char *szEmailPrimary,
                          const char *szCity,
                          const char *szState, const char *szPhoneNumber,
                          const char *szFaxNumber, const char *szAddress,
                          const char *szCellularNumber, const char *szZipCode,
                          unsigned short nCountryCode, bool bHideEmail)
{
  CPU_Meta_SetGeneralInfo *p =
    new CPU_Meta_SetGeneralInfo(szAlias, szFirstName,
                                szLastName, szEmailPrimary,
                                szCity,
                                szState, szPhoneNumber,
                                szFaxNumber, szAddress,
                                szCellularNumber, szZipCode,
                                nCountryCode, bHideEmail);

  gLog.Info(tr("%sUpdating general info (#%lu/#%d)...\n"), L_SRVxSTR, p->Sequence(), p->SubSequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetEmailInfo---------------------------------------------------------
unsigned long CICQDaemon::icqSetEmailInfo(
                          const char *szEmailSecondary, const char *szEmailOld)
{
  CPU_Meta_SetEmailInfo *p =
    new CPU_Meta_SetEmailInfo(szEmailSecondary, szEmailOld);

  gLog.Info(tr("%sUpdating additional E-Mail info (#%lu/#%d)...\n"), L_SRVxSTR, p->Sequence(), p->SubSequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetMoreInfo----------------------------------------------------
unsigned long CICQDaemon::icqSetMoreInfo(unsigned short nAge,
                              char nGender, const char *szHomepage,
                              unsigned short nBirthYear, char nBirthMonth,
                              char nBirthDay, char nLanguage1,
                              char nLanguage2, char nLanguage3)
{
  CPU_Meta_SetMoreInfo *p =
    new CPU_Meta_SetMoreInfo(nAge, nGender, szHomepage,
                             nBirthYear, nBirthMonth,
                             nBirthDay, nLanguage1,
                             nLanguage2, nLanguage3);

  gLog.Info(tr("%sUpdating more info (#%lu/#%d)...\n"), L_SRVxSTR, p->Sequence(), p->SubSequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetInterestsInfo------------------------------------------------------
unsigned long CICQDaemon::icqSetInterestsInfo(const ICQUserCategory* interests)
{
  CPU_Meta_SetInterestsInfo *p = new CPU_Meta_SetInterestsInfo(interests);
  gLog.Info("%sUpdating Interests info (#%lu/#%d)..\n", L_SRVxSTR,
    p->Sequence(), p->SubSequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetOrgBackInfo--------------------------------------------------------
unsigned long CICQDaemon::icqSetOrgBackInfo(const ICQUserCategory* orgs,
                                            const ICQUserCategory* background)
{
  CPU_Meta_SetOrgBackInfo *p =
    new CPU_Meta_SetOrgBackInfo(orgs, background);
  gLog.Info("%sUpdating Organizations/Backgrounds info (#%lu/#%d)..\n",
    L_SRVxSTR, p->Sequence(), p->SubSequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetWorkInfo--------------------------------------------------------
unsigned long CICQDaemon::icqSetWorkInfo(const char *_szCity, const char *_szState,
                                     const char *_szPhone,
                                     const char *_szFax, const char *_szAddress,
                                     const char *_szZip, unsigned short _nCompanyCountry,
                                     const char *_szName, const char *_szDepartment,
                                     const char *_szPosition, unsigned short _nCompanyOccupation,
                                     const char *_szHomepage)
{
  CPU_Meta_SetWorkInfo *p =
    new CPU_Meta_SetWorkInfo(_szCity, _szState, _szPhone, _szFax, _szAddress,
                             _szZip, _nCompanyCountry, _szName, _szDepartment,
                             _szPosition, _nCompanyOccupation, _szHomepage);

  gLog.Info(tr("%sUpdating work info (#%lu/#%d)...\n"), L_SRVxSTR, p->Sequence(), p->SubSequence());

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSetAbout-----------------------------------------------------------
unsigned long CICQDaemon::icqSetAbout(const char *_szAbout)
{
  char *szAbout = gTranslator.NToRN(_szAbout);

  CPU_Meta_SetAbout *p = new CPU_Meta_SetAbout(szAbout);

  gLog.Info(tr("%sUpdating about (#%lu/#%d)...\n"), L_SRVxSTR, p->Sequence(), p->SubSequence());

  delete [] szAbout;

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqAuthorizeGrant-------------------------------------------------------
unsigned long CICQDaemon::ProtoAuthorizeGrant(const char *szId,
  unsigned long nPPID, const char *szMessage)
{
  unsigned long nRet = 0;

  if (nPPID == LICQ_PPID)
    nRet = icqAuthorizeGrant(szId, szMessage);
  else
    PushProtoSignal(new CGrantAuthSignal(szId, szMessage), nPPID);
  return nRet;
}

unsigned long CICQDaemon::icqAuthorizeGrant(unsigned long nUin, const char *szMessage)
{
  char szUin[24];
  sprintf(szUin, "%lu", nUin);

  return icqAuthorizeGrant(szUin, szMessage);
}

unsigned long CICQDaemon::icqAuthorizeGrant(const char *szId,
  const char *szMessage)
{
  char *sz = NULL;
  if (szMessage != NULL)
  {
    sz = gTranslator.NToRN(szMessage);
    gTranslator.ClientToServer(sz);
  }
  CPU_ThroughServer *p = new CPU_ThroughServer(szId, ICQ_CMDxSUB_AUTHxGRANTED, sz);
  gLog.Info(tr("%sAuthorizing user %s (#%lu)...\n"), L_SRVxSTR, szId, p->Sequence());
  delete [] sz;

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqAuthorizeRefuse------------------------------------------------------
unsigned long CICQDaemon::ProtoAuthorizeRefuse(const char *szId,
  unsigned long nPPID, const char *szMessage)
{
  unsigned long nRet = 0;

  if (nPPID == LICQ_PPID)
    nRet = icqAuthorizeRefuse(szId, szMessage);
  else
    PushProtoSignal(new CRefuseAuthSignal(szId, szMessage), nPPID);

  return nRet;
}

unsigned long CICQDaemon::icqAuthorizeRefuse(unsigned long nUin, const char *szMessage)
{
  char szUin[24];
  sprintf(szUin, "%lu", nUin);
  return icqAuthorizeRefuse(szUin, szMessage);
}

unsigned long CICQDaemon::icqAuthorizeRefuse(const char *szId,
  const char *szMessage)
{
  char *sz = NULL;
  if (szMessage != NULL)
  {
    sz = gTranslator.NToRN(szMessage);
    gTranslator.ClientToServer(sz);
  }
  CPU_ThroughServer *p = new CPU_ThroughServer(szId, ICQ_CMDxSUB_AUTHxREFUSED, sz);
  gLog.Info(tr("%sRefusing authorization to user %s (#%lu)...\n"), L_SRVxSTR,
     szId, p->Sequence());
  delete [] sz;

  ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqRequestAuth--------------------------------------------------------
void CICQDaemon::icqRequestAuth(unsigned long _nUin, const char *_szMessage)
{
  CSrvPacketTcp *p = new CPU_RequestAuth(_nUin, _szMessage);
  SendEvent_Server(p);
}

//-----icqSetSecurityInfo----------------------------------------------------
unsigned long CICQDaemon::icqSetSecurityInfo(bool bAuthorize, bool bHideIp, bool bWebAware)
{
    CPU_Meta_SetSecurityInfo *p = new CPU_Meta_SetSecurityInfo(bAuthorize, bHideIp, bWebAware);
    gLog.Info(tr("%sUpdating security info (#%lu/#%d)...\n"), L_SRVxSTR, p->Sequence(), p->SubSequence());
    ICQEvent *e = SendExpectEvent_Server(0, p, NULL);
    if (e != NULL)
      return e->EventId();
    return 0;
}

//-----icqSearchWhitePages--------------------------------------------------
unsigned long CICQDaemon::icqSearchWhitePages(const char *szFirstName,
    const char *szLastName, const char *szAlias, const char *szEmail,
    unsigned short nMinAge, unsigned short nMaxAge, char nGender,
    char nLanguage, const char *szCity, const char *szState,
    unsigned short nCountryCode, const char *szCoName, const char *szCoDept,
    const char *szCoPos, const char *szKeyword, bool bOnlineOnly)
{
  // Yes, there are a lot of extra options that you can search by.. but I
  // don't see a point for the hundreds of items that I can add..  just
  // use their web page for that shit - Jon
  CPU_SearchWhitePages *p = new CPU_SearchWhitePages(szFirstName, szLastName,
    szAlias, szEmail, nMinAge, nMaxAge, nGender, nLanguage, szCity, szState,
    nCountryCode, szCoName, szCoDept, szCoPos, szKeyword, bOnlineOnly);
  gLog.Info(tr("%sStarting white pages search (#%lu/#%d)...\n"), L_SRVxSTR,
            p->Sequence(), p->SubSequence());
  ICQEvent *e = SendExpectEvent_Server(0, p, NULL, true);
  if (e != NULL)
    return e->EventId();
  return 0;
}

//-----icqSearchByUin----------------------------------------------------------
unsigned long CICQDaemon::icqSearchByUin(unsigned long nUin)
{
   CPU_SearchByUin *p = new CPU_SearchByUin(nUin);
   gLog.Info(tr("%sStarting search by UIN for user (#%lu/#%d)...\n"), L_SRVxSTR,
   	p->Sequence(), p->SubSequence());
   ICQEvent *e = SendExpectEvent_Server(0, p, NULL, true);
   if (e != NULL)
     return e->EventId();
   return 0;
}

//-----icqGetUserBasicInfo------------------------------------------------------
unsigned long CICQDaemon::icqUserBasicInfo(const char *_szId)
{
  //CPU_Meta_RequestBasicInfo *p = new CPU_Meta_RequestBasicInfo(_szId);
  CPU_Meta_RequestAllInfo *p = new CPU_Meta_RequestAllInfo(_szId);
  gLog.Info(tr("%sRequesting user info (#%lu/#%d)...\n"), L_SRVxSTR,
            p->Sequence(), p->SubSequence());
  //XXX not yet
  //ICQEvent *e = SendExpectEvent_Server(_szId, LICQ_PPID, p, NULL, true);
  ICQEvent *e = SendExpectEvent_Server(strtoul(_szId, (char **)NULL, 10), p, NULL, true);
  if (e != NULL)
    return e->EventId();
  return 0;
}

unsigned long CICQDaemon::icqUserBasicInfo(unsigned long _nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", _nUin);
  szUin[12] = 0;

  return icqUserBasicInfo(szUin);
}

//-----icqPing------------------------------------------------------------------
void CICQDaemon::icqPing()
{
  // pinging is necessary to avoid that masquerading
  // servers close the connection
   CPU_Ping *p = new CPU_Ping;
   SendEvent_Server(p);
}

//-----icqUpdateInfoTimestamp---------------------------------------------------
void CICQDaemon::icqUpdateInfoTimestamp(const char *GUID)
{
  CPU_UpdateInfoTimestamp *p = new CPU_UpdateInfoTimestamp(GUID);
  SendEvent_Server(p);
}

//-----icqUpdatePhoneBookTimestamp----------------------------------------------
void CICQDaemon::icqUpdatePhoneBookTimestamp()
{
  ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
  o->SetClientInfoTimestamp(time(NULL));
  bool bOffline = o->StatusOffline();
  gUserManager.DropOwner();

  if (!bOffline)
    icqUpdateInfoTimestamp(PLUGIN_PHONExBOOK);
}

//-----icqUpdatePictureTimestamp------------------------------------------------
void CICQDaemon::icqUpdatePictureTimestamp()
{
  ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
  o->SetClientInfoTimestamp(time(NULL));
  bool bOffline = o->StatusOffline();
  gUserManager.DropOwner();

  if (!bOffline)
    icqUpdateInfoTimestamp(PLUGIN_PICTURE);
}

//-----icqSetPhoneFollowMeStatus------------------------------------------------
void CICQDaemon::icqSetPhoneFollowMeStatus(unsigned long nNewStatus)
{
  ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
  o->SetClientStatusTimestamp(time(NULL));
  o->SetPhoneFollowMeStatus(nNewStatus);
  bool bOffline = o->StatusOffline();
  gUserManager.DropOwner();

  if (!bOffline)
  {
    CPU_UpdateStatusTimestamp *p =
      new CPU_UpdateStatusTimestamp(PLUGIN_FOLLOWxME, nNewStatus);
    SendEvent_Server(p);
  }
}

//-----icqUpdateContactList-----------------------------------------------------
void CICQDaemon::icqUpdateContactList()
{
  unsigned short n = 0;
  UserStringList users;
  FOR_EACH_PROTO_USER_START(LICQ_PPID, LOCK_W)
  {
    n++;
    users.push_back(strdup(pUser->IdString()));
    if (n == m_nMaxUsersPerPacket)
    {
      CSrvPacketTcp *p = new CPU_GenericUinList(users, ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_ADDxTOxLIST);
      gLog.Info(tr("%sUpdating contact list (#%lu)...\n"), L_SRVxSTR, p->Sequence());
      SendEvent_Server(p);
      users.erase(users.begin(), users.end());
      n = 0;
    }
    // Reset all users to offline
    if (!pUser->StatusOffline()) ChangeUserStatus(pUser, ICQ_STATUS_OFFLINE);
  }
  FOR_EACH_PROTO_USER_END
  if (n != 0)
  {
    CSrvPacketTcp *p = new CPU_GenericUinList(users, ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_ADDxTOxLIST);
    gLog.Info(tr("%sUpdating contact list (#%lu)...\n"), L_SRVxSTR, p->Sequence());
    SendEvent_Server(p);
  }
}
//-----icqTypingNotification---------------------------------------------------
void CICQDaemon::icqTypingNotification(const char *_szId, bool _bActive)
{
  CSrvPacketTcp *p = new CPU_TypingNotification(_szId, _bActive);
  SendEvent_Server(p);
}

//-----icqSendVisibleList-------------------------------------------------------
void CICQDaemon::icqSendVisibleList()
{
  // send user info packet
  // Go through the entire list of users, checking if each one is on
  // the visible list
  UserStringList users;
  FOR_EACH_PROTO_USER_START(LICQ_PPID, LOCK_R)
  {
    if (pUser->GetInGroup(GROUPS_SYSTEM, GROUP_VISIBLE_LIST) )
      users.push_back(strdup(pUser->IdString()));
  }
  FOR_EACH_PROTO_USER_END
  CSrvPacketTcp* p = new CPU_GenericUinList(users, ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_ADDxVISIBLExLIST);
  gLog.Info(tr("%sSending visible list (#%lu)...\n"), L_SRVxSTR, p->Sequence());
  SendEvent_Server(p);
}


//-----icqSendInvisibleList-----------------------------------------------------
void CICQDaemon::icqSendInvisibleList()
{
  UserStringList users;
  FOR_EACH_PROTO_USER_START(LICQ_PPID, LOCK_R)
  {
    if (pUser->GetInGroup(GROUPS_SYSTEM, GROUP_INVISIBLE_LIST) )
      users.push_back(strdup(pUser->IdString()));
  }
  FOR_EACH_PROTO_USER_END

  CSrvPacketTcp* p = new CPU_GenericUinList(users, ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_ADDxINVISIBxLIST);
  gLog.Info(tr("%sSending invisible list (#%lu)...\n"), L_SRVxSTR, p->Sequence());
  SendEvent_Server(p);
}

//----- icqToggleVisibleList (deprecated!) -------------------------------------
void CICQDaemon::icqToggleVisibleList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqToggleVisibleList(szUin, LICQ_PPID);
}

//-----icqToggleVisibleList--------------------------------------------------
void CICQDaemon::icqToggleVisibleList(const char* _szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
  if (u == NULL) return;
  bool b = u->VisibleList();
  gUserManager.DropUser(u);

  if (b)
    icqRemoveFromVisibleList(_szId, _nPPID);
  else
    icqAddToVisibleList(_szId, _nPPID);
}

//-----icqToggleInvisibleList (deprecated!)-------------------------------------
void CICQDaemon::icqToggleInvisibleList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqToggleInvisibleList(szUin, LICQ_PPID);
}

//-----icqToggleInvisibleList---------------------------------------------------
void CICQDaemon::icqToggleInvisibleList(const char *_szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
  if (u == NULL) return;
  bool b = u->InvisibleList();
  gUserManager.DropUser(u);

  if (b)
    icqRemoveFromInvisibleList(_szId, _nPPID);
  else
    icqAddToInvisibleList(_szId, _nPPID);
}

//-----icqToggleIgnoreList (deprecated!)----------------------------------------
void CICQDaemon::icqToggleIgnoreList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqToggleIgnoreList(szUin, LICQ_PPID);
}

//-----icqToggleIgnoreList------------------------------------------------------
void CICQDaemon::icqToggleIgnoreList(const char *_szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
  if (u == NULL) return;
  bool b = u->IgnoreList();
  gUserManager.DropUser(u);

  if (b)
    icqAddToIgnoreList(_szId, _nPPID);
  else
    icqRemoveFromIgnoreList(_szId, _nPPID);
}

//-----icqAddToVisibleList (deprecated!)----------------------------------------
void CICQDaemon::icqAddToVisibleList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqAddToVisibleList(szUin, LICQ_PPID);
}

//-----icqAddToVisibleList------------------------------------------------------
void CICQDaemon::icqAddToVisibleList(const char* _szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_W);
  if (u != NULL)
  {
    u->SetVisibleList(true);
    gUserManager.DropUser(u);
  }
  CSrvPacketTcp *p = new CPU_GenericUinList(_szId, ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_ADDxVISIBLExLIST);
  gLog.Info(tr("%sAdding user %s to visible list (#%lu)...\n"), L_SRVxSTR, _szId,
     p->Sequence());
  SendEvent_Server(p);

  if (UseServerContactList())
  {
    pthread_mutex_lock(&mutex_modifyserverusers);
    m_lszModifyServerUsers.push_back(strdup(_szId));
    pthread_mutex_unlock(&mutex_modifyserverusers);

    CSrvPacketTcp *pAdd = new CPU_AddToServerList(_szId, ICQ_ROSTxVISIBLE);
    SendExpectEvent_Server(0, pAdd, NULL);
  }
}

//-----icqRemoveFromVisibleList (deprecated!)-----------------------------------
void CICQDaemon::icqRemoveFromVisibleList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqRemoveFromVisibleList(szUin, LICQ_PPID);
}

//-----icqRemoveFromVisibleList-------------------------------------------------
void CICQDaemon::icqRemoveFromVisibleList(const char* _szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_W);
  if (u != NULL)
  {
    u->SetVisibleList(false);
    gUserManager.DropUser(u);
  }
  CSrvPacketTcp *p = new CPU_GenericUinList(_szId, ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_REMxVISIBLExLIST);
  gLog.Info(tr("%sRemoving user %s from visible list (#%lu)...\n"), L_SRVxSTR, _szId,
     p->Sequence());
  SendEvent_Server(p);

  if (UseServerContactList())
  {
    u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
    if (u != NULL)
    {
      pthread_mutex_lock(&mutex_modifyserverusers);
      m_lszModifyServerUsers.push_back(strdup(_szId));
      pthread_mutex_unlock(&mutex_modifyserverusers);

      CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(_szId, 0, u->GetVisibleSID(),
        ICQ_ROSTxVISIBLE);
      SendExpectEvent_Server(_szId, _nPPID, pRemove, NULL);
      gUserManager.DropUser(u);
    }
  }
}

//-----icqAddToInvisibleList (deprecated!)--------------------------------------
void CICQDaemon::icqAddToInvisibleList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqAddToInvisibleList(szUin, LICQ_PPID);
}

//-----icqAddToInvisibleList----------------------------------------------------
void CICQDaemon::icqAddToInvisibleList(const char* _szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_W);
  if (u != NULL)
  {
    u->SetInvisibleList(true);
    gUserManager.DropUser(u);
  }
  CSrvPacketTcp *p = new CPU_GenericUinList(_szId, ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_ADDxINVISIBxLIST);
  gLog.Info(tr("%sAdding user %s to invisible list (#%lu)...\n"), L_SRVxSTR, _szId,
     p->Sequence());
  SendEvent_Server(p);

  if (UseServerContactList())
  {
    pthread_mutex_lock(&mutex_modifyserverusers);
    m_lszModifyServerUsers.push_back(strdup(_szId));
    pthread_mutex_unlock(&mutex_modifyserverusers);

    CSrvPacketTcp *pAdd = new CPU_AddToServerList(_szId, ICQ_ROSTxINVISIBLE);
    SendExpectEvent_Server(0, pAdd, NULL);
  }
}

//-----icqRemoveFromInvisibleList (deprecated!)---------------------------------
void CICQDaemon::icqRemoveFromInvisibleList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqRemoveFromInvisibleList(szUin, LICQ_PPID);
}

//-----icqRemoveFromInvisibleList-----------------------------------------------
void CICQDaemon::icqRemoveFromInvisibleList(const char *_szId, unsigned long _nPPID)
{
  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_W);
  if (u != NULL)
  {
    u->SetInvisibleList(false);
    gUserManager.DropUser(u);
  }
  CSrvPacketTcp *p = new CPU_GenericUinList(_szId, ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_REMxINVISIBxLIST);
  gLog.Info(tr("%sRemoving user %s from invisible list (#%lu)...\n"), L_SRVxSTR, _szId,
     p->Sequence());
  SendEvent_Server(p);

  if (UseServerContactList())
  {
    u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
    if (u)
    {
      pthread_mutex_lock(&mutex_modifyserverusers);
      m_lszModifyServerUsers.push_back(strdup(_szId));
      pthread_mutex_unlock(&mutex_modifyserverusers);

      CSrvPacketTcp *pRemove = new CPU_RemoveFromServerList(_szId, 0, u->GetInvisibleSID(),
        ICQ_ROSTxINVISIBLE);
      SendExpectEvent_Server(_szId, _nPPID, pRemove, NULL);
      gUserManager.DropUser(u);
    }
  }
}

//-----icqAddToIgnoreList (deprecated!)-----------------------------------------
void CICQDaemon::icqAddToIgnoreList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqAddToIgnoreList(szUin, LICQ_PPID);
}

//-----icqAddToIgnoreList-------------------------------------------------------
void CICQDaemon::icqAddToIgnoreList(const char *_szId, unsigned long _nPPID)
{
  if (!UseServerContactList()) return;

  ICQUser *u = gUserManager.FetchUser(_szId, _nPPID, LOCK_R);
  int nGSID = u->GetGSID();
  gUserManager.DropUser(u);

  icqChangeGroup(_szId, _nPPID, 0, nGSID, ICQ_ROSTxIGNORE, ICQ_ROSTxNORMAL);
}

//-----icqRemoveFromIgnoreList (deprecated!)------------------------------------
void CICQDaemon::icqRemoveFromIgnoreList(unsigned long nUin)
{
  char szUin[13];
  snprintf(szUin, 12, "%lu", nUin);
  szUin[12] = '\0';
  icqRemoveFromIgnoreList(szUin, LICQ_PPID);
}

//-----icqRemoveFromIgnoreList--------------------------------------------------
void CICQDaemon::icqRemoveFromIgnoreList(const char *_szId, unsigned long _nPPID)
{
  if (!UseServerContactList()) return;

  icqChangeGroup(_szId, _nPPID, 0, 0, ICQ_ROSTxNORMAL, ICQ_ROSTxIGNORE);
}



//-----icqSendThroughServer-----------------------------------------------------
ICQEvent* CICQDaemon::icqSendThroughServer(const char *szId,
  unsigned char format, char *_sMessage, CUserEvent* ue)
{
  ICQEvent* result;

  CPU_ThroughServer *p = new CPU_ThroughServer(szId, format, _sMessage);

  switch (format)
  {
    case ICQ_CMDxSUB_MSG:
      gLog.Info(tr("%sSending message through server (#%lu).\n"), L_SRVxSTR, p->Sequence());
      break;
    case ICQ_CMDxSUB_URL:
      gLog.Info(tr("%sSending url through server (#%lu).\n"), L_SRVxSTR, p->Sequence());
      break;
    case ICQ_CMDxSUB_CONTACTxLIST:
      gLog.Info(tr("%sSending contact list through server (#%lu).\n"), L_SRVxSTR, p->Sequence());
      break;
    default:
      gLog.Info(tr("%sSending misc through server (#%lu).\n"), L_SRVxSTR, p->Sequence());
  }

  // If we are already shutting down, don't start any events
  if (m_bShuttingDown) return NULL;

  if (ue != NULL) ue->m_eDir = D_SENDER;
  ICQEvent *e = new ICQEvent(this, m_nTCPSrvSocketDesc, p, CONNECT_SERVER, szId,
    LICQ_PPID, ue);
  if (e == NULL) return 0;
  e->m_NoAck = true;

  result = SendExpectEvent(e, &ProcessRunningEvent_Server_tep);
  return result;
}

ICQEvent* CICQDaemon::icqSendThroughServer(unsigned long nUin, unsigned char format, char *_sMessage, CUserEvent* ue)
{
  char szUin[24];
  sprintf(szUin, "%lu", nUin);
  return icqSendThroughServer(szUin, format, _sMessage, ue);
}

//-----icqSendSms---------------------------------------------------------------
unsigned long CICQDaemon::icqSendSms(const char *szNumber, const char *szMessage,
				     unsigned long nUin)
{
  CEventSms *ue = new CEventSms(szNumber, szMessage, ICQ_CMDxSND_THRUxSERVER, TIME_NOW, INT_VERSION);
  CPU_SendSms *p = new CPU_SendSms(szNumber, szMessage);
  gLog.Info(tr("%sSending SMS through server (#%lu/#%d)...\n"), L_SRVxSTR,
	    p->Sequence(), p->SubSequence());
  ICQEvent *e = SendExpectEvent_Server(nUin, p, ue);
  if (e != NULL)
    return e->EventId();
  return 0;
}

/*------------------------------------------------------------------------------
 * ProcessDoneEvent
 *
 * Processes the given event possibly passes the result to the gui.
 *----------------------------------------------------------------------------*/
void CICQDaemon::ProcessDoneEvent(ICQEvent *e)
{
  // Write the event to the history file if appropriate
  if (e->m_pUserEvent != NULL &&
      (e->m_eResult == EVENT_ACKED || e->m_eResult == EVENT_SUCCESS) &&
      e->m_nSubResult != ICQ_TCPxACK_RETURN)
  {
    ICQUser *u = gUserManager.FetchUser(e->m_szId, e->m_nPPID, LOCK_R);
    if (u != NULL)
    {
      e->m_pUserEvent->AddToHistory(u, D_SENDER);
      u->SetLastSentEvent();
      m_xOnEventManager.Do(ON_EVENT_MSGSENT, u);
      gUserManager.DropUser(u);
    }
    m_sStats[STATS_EventsSent].Inc();
  }

  // Process the event, first by channel
  if (e->m_nChannel == ICQ_CHNxNEW || e->m_nChannel == ICQ_CHNxPING)
  {
    delete e;
  }
  else if (e->m_nChannel == ICQ_CHNxNONE || e->m_nChannel == ICQ_CHNxINFO ||
           e->m_nChannel == ICQ_CHNxSTATUS)
  {
    if (e->m_nCommand == ICQ_CMDxTCP_START)
      PushPluginEvent(e);
    else
      delete e;
  }
  else if (e->m_nChannel == ICQ_CHNxDATA)
  {
    // Now process by command
    switch (e->m_nSNAC)
    {
      case MAKESNAC(ICQ_SNACxFAM_MESSAGE, ICQ_SNACxMSG_SENDxSERVER):
      case MAKESNAC(ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_ADDxTOxLIST):
      case MAKESNAC(ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_REMOVExFROMxLIST):
        PushPluginEvent(e);
        break;

      // Other events
      case MAKESNAC(ICQ_SNACxFAM_VARIOUS, ICQ_SNACxMETA):
      {
        switch (e->m_eResult)
        {
          case EVENT_ERROR:
          case EVENT_TIMEDOUT:
          case EVENT_FAILED:
          case EVENT_SUCCESS:
          case EVENT_CANCELLED:
            PushPluginEvent(e);
            break;

          case EVENT_ACKED:
            PushExtendedEvent(e);
            break;

          default:
            gLog.Error("%sInternal error: ProcessDoneEvents(): Invalid result "
                       "for extended event (%d).\n", L_ERRORxSTR, e->m_eResult);
            delete e;
            return;
        }

        break;
      }

      default:
      {
        gLog.Warn("%sInternal error: ProcessDoneEvents(): Unknown SNAC (0x%08lX).\n",
                  L_ERRORxSTR, e->m_nSNAC);
        delete e;
        return;
      }
    } // switch
  }
  else
  {
  }
}

//-----ICQ::Logon--------------------------------------------------------------
unsigned long CICQDaemon::ProtoLogon(unsigned long _nPPID, unsigned short _nLogonStatus)
{
  unsigned long nRet = 0;

  if (_nPPID == LICQ_PPID)
    nRet = icqLogon(_nLogonStatus);
  else
    PushProtoSignal(new CLogonSignal(_nLogonStatus), _nPPID);

  return nRet;
}

unsigned long CICQDaemon::icqLogon(unsigned short logonStatus)
{
  if (m_bLoggingOn)
  {
    gLog.Warn(tr(tr("%sAttempt to logon while already logged or logging on, logoff and try again.\n")), L_WARNxSTR);
    return 0;
  }
  ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_R);
  if (o->IdString() == 0)
  {
    gUserManager.DropOwner();
    gLog.Error("%sNo registered user, unable to process logon attempt.\n", L_ERRORxSTR);
    return 0;
  }
  if (o->Password()[0] == '\0')
  {
    gUserManager.DropOwner();
    gLog.Error(tr("%sNo password set.  Edit ~/.licq/owner.uin and fill in the password field.\n"), L_ERRORxSTR);
    return 0;
  }

  char *passwd = strdup(o->Password());
  char *user = strdup(o->IdString());
  unsigned long status = o->AddStatusFlags(logonStatus);
  gUserManager.DropOwner();
  CPU_Logon *p = new CPU_Logon(passwd, user, status);
  free(passwd);
  free(user);
  m_bOnlineNotifies = false;
  gLog.Info(tr("%sRequesting logon (#%lu)...\n"), L_SRVxSTR, p->Sequence());
  m_nServerSequence = 0;
  m_nDesiredStatus = status;
  m_bLoggingOn = true;
  m_tLogonTime = time(NULL);

  SendEvent_Server(p);

  return 0;
}

//-----ICQ::icqLogoff-----------------------------------------------------------
void CICQDaemon::ProtoLogoff(unsigned long _nPPID)
{
  if (_nPPID == LICQ_PPID)
    icqLogoff();
  else
    PushProtoSignal(new CLogoffSignal(), _nPPID);
}

void CICQDaemon::icqLogoff()
{
  // Kill the udp socket asap to avoid race conditions
  int nSD = m_nTCPSrvSocketDesc;
  m_nTCPSrvSocketDesc = -1;

  m_eStatus = STATUS_OFFLINE_MANUAL;

  if (nSD == -1 && !m_bLoggingOn)
  {
    gLog.Warn(tr("%sAttempt to logoff while not logged on.\n"), L_WARNxSTR);
    return;
  }

  m_bLoggingOn = false;

  gLog.Info(tr("%sLogging off.\n"), L_SRVxSTR);
  ICQEvent *cancelledEvent = NULL;

  if (nSD != -1)
  {
    CPU_Logoff p;
    cancelledEvent = new ICQEvent(this, nSD, &p, CONNECT_SERVER, 0, NULL);
    cancelledEvent->m_pPacket = NULL;
    cancelledEvent->m_bCancelled = true;
    SendEvent(nSD, p, true);
    gSocketManager.CloseSocket(nSD);
  }

  postLogoff(nSD, cancelledEvent);
}

void CICQDaemon::postLogoff(int nSD, ICQEvent *cancelledEvent)
{
  pthread_mutex_lock(&mutex_runningevents);
  pthread_mutex_lock(&mutex_sendqueue_server);
  pthread_mutex_lock(&mutex_extendedevents);
  pthread_mutex_lock(&mutex_cancelthread);
  pthread_mutex_lock(&mutex_reverseconnect);
  std::list<ICQEvent *>::iterator iter;

  // Cancel all events
  // Necessary since the end is always being modified
  unsigned long i = m_lxSendQueue_Server.size();
  for (iter = m_lxSendQueue_Server.begin(); i > 0; i--)
  {
    ICQEvent *e = *iter;
    gLog.Info("Event #%lu is still on the server queue!\n", e->Sequence());
    iter = m_lxSendQueue_Server.erase(iter);
    ICQEvent *cancelled = new ICQEvent(e);
    cancelled->m_bCancelled = true;
    m_lxSendQueue_Server.push_back(cancelled);
  }

  iter = m_lxRunningEvents.begin();
  while (iter != m_lxRunningEvents.end())
  {
    if ((*iter)->m_nSocketDesc == nSD || (*iter)->Channel() == ICQ_CHNxNEW)
    {
      ICQEvent *e = *iter;
      gLog.Info("Event #%lu is still on the running queue!\n", e->Sequence());
      iter = m_lxRunningEvents.erase(iter);
      if (e->thread_running && !pthread_equal(e->thread_send, pthread_self()))
      {
        pthread_cancel(e->thread_send);
        e->thread_running = false;
      }
      std::list<ICQEvent *>::iterator i;
      for (i = m_lxExtendedEvents.begin(); i != m_lxExtendedEvents.end(); i++)
      {
        if (*i == e)
        {
          m_lxExtendedEvents.erase(i);
          break;
        }
      }
      CancelEvent(e);
    }
    else
      iter++;
  }
  assert(m_lxExtendedEvents.empty());

  // Queue should be empty, might not be due to peer-to-peer events
  for (iter = m_lxRunningEvents.begin(); iter != m_lxRunningEvents.end(); iter++)
    gLog.Info(tr("Event #%lu is still on queue!\n"), (*iter)->Sequence());

  if (cancelledEvent != NULL)
    m_lxSendQueue_Server.push_back(cancelledEvent);

  std::list<CReverseConnectToUserData *>::iterator rciter;
  for (rciter = m_lReverseConnect.begin(); rciter != m_lReverseConnect.end();
                                           rciter++)
  {
    delete *rciter;
  }
  m_lReverseConnect.clear();

  pthread_mutex_unlock(&mutex_reverseconnect);    
  pthread_mutex_unlock(&mutex_cancelthread);
  pthread_mutex_unlock(&mutex_extendedevents);
  pthread_mutex_unlock(&mutex_sendqueue_server);
  pthread_mutex_unlock(&mutex_runningevents);

  // All extended event are a pointer that are also in the running events.
  // We do not need to clean these out.
#if 0
  // wipe out all extended events too...
  pthread_mutex_lock(&mutex_extendedevents);
  for (iter = m_lxExtendedEvents.begin(); iter != m_lxExtendedEvents.end(); iter++)
  {
    (*iter)->m_eResult = EVENT_CANCELLED;
    ProcessDoneEvent(*iter);
  }
  m_lxExtendedEvents.erase(m_lxExtendedEvents.begin(), m_lxExtendedEvents.end());
  pthread_mutex_unlock(&mutex_extendedevents);
#endif

  // Mark all users as offline, this also updates the last seen
  // online field
  FOR_EACH_PROTO_USER_START(LICQ_PPID, LOCK_W)
  {
    if (!pUser->StatusOffline())
      ChangeUserStatus(pUser, ICQ_STATUS_OFFLINE);
  }
  FOR_EACH_PROTO_USER_END

  ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
  if (o)
    ChangeUserStatus(o, ICQ_STATUS_OFFLINE);
  gUserManager.DropOwner();

  if (m_szRegisterPasswd)
  {
    free(m_szRegisterPasswd);
    m_szRegisterPasswd = 0;
  }

  PushPluginSignal(new CICQSignal(SIGNAL_LOGOFF, 0, 0));
}

//-----ProtoTypingNotification-------------------------------------------------
void CICQDaemon::ProtoTypingNotification(const char *_szId,
  unsigned long _nPPID, bool _bActive)
{
  if (_nPPID == LICQ_PPID)
    icqTypingNotification(_szId, _bActive);
  else
    PushProtoSignal(new CTypingNotificationSignal(_szId, _bActive), _nPPID);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----ConnectToServer---------------------------------------------------------

int CICQDaemon::ConnectToLoginServer()
{
  if (m_bProxyEnabled)
    InitProxy();

  // Which protocol plugin?
  int r = ConnectToServer(m_szICQServer, m_nICQServerPort);

  write(pipe_newsocket[PIPE_WRITE], "S", 1);

  return r;
}

int CICQDaemon::ConnectToServer(const char* server, unsigned short port)
{
  SrvSocket *s = new SrvSocket(gUserManager.OwnerUin());

  if (m_bProxyEnabled)
  {
    if (m_xProxy == NULL)
    {
      gLog.Warn(tr("%sProxy server not properly configured.\n"), L_ERRORxSTR);
      delete s;
      return (-1);
    }
    s->SetProxy(m_xProxy);
  }
  else if (m_xProxy != NULL)
  {
    delete m_xProxy;
    m_xProxy = NULL;
  }
  
  char ipbuf[32];

  if (m_xProxy == NULL)
  {
    gLog.Info(tr("%sResolving %s port %d...\n"), L_SRVxSTR, server, port);
    if (!s->SetRemoteAddr(server, port)) {
      char buf[128];
      gLog.Warn(tr("%sUnable to resolve %s:\n%s%s.\n"), L_ERRORxSTR,
                server, L_BLANKxSTR, s->ErrorStr(buf, 128));
      delete s;
      return (-1); // no route to host (not connected)
    }
    gLog.Info(tr("%sICQ server found at %s:%d.\n"), L_SRVxSTR,
	      s->RemoteIpStr(ipbuf), s->RemotePort());
  }
  else
  {
    // It doesn't matter if it resolves or not, the proxy should do it then
    s->SetRemoteAddr(server, port);
  }

  if (m_xProxy == NULL)
    gLog.Info(tr("%sOpening socket to server.\n"), L_SRVxSTR);
  else
    gLog.Info("%sOpening socket to server via proxy.\n", L_SRVxSTR);
  if (!s->OpenConnection())
  {
    char buf[128];
    gLog.Warn(tr("%sUnable to connect to %s:%d:\n%s%s.\n"), L_ERRORxSTR,
              s->RemoteIpStr(ipbuf), s->RemotePort(), L_BLANKxSTR,
              s->ErrorStr(buf, 128));
    delete s;
    return -1;
  }

  static pthread_mutex_t connect_mutex = PTHREAD_MUTEX_INITIALIZER;
  pthread_mutex_lock(&connect_mutex);
  int nSocket;
  if (m_nTCPSrvSocketDesc != -1)
  {
    gLog.Warn(tr("%sConnection to server already exists, aborting.\n"), L_WARNxSTR);
    delete s;
    nSocket = -1;
  }
  else
  {
    // Now get the internal ip from this socket
    CPacket::SetLocalIp(  NetworkIpToPacketIp(s->LocalIp() ));
    ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
    if (o)
      o->SetIntIp(s->LocalIp());
    gUserManager.DropOwner();

    gSocketManager.AddSocket(s);
    nSocket = m_nTCPSrvSocketDesc = s->Descriptor();
    gSocketManager.DropSocket(s);
  }

  pthread_mutex_unlock(&connect_mutex);

  return nSocket;
}

//-----FindUserForInfoUpdate-------------------------------------------------
ICQUser *CICQDaemon::FindUserForInfoUpdate(unsigned long nUin, ICQEvent *e,
   const char *t)
{
  ICQUser *u = gUserManager.FetchUser(nUin, LOCK_W);
  if (u == NULL)
  {
    // If the event is NULL as well then nothing we can do
    if (e == NULL)
    {
      gLog.Warn(tr("%sResponse to unknown %s info request for unknown user (%lu).\n"),
                L_WARNxSTR, t, nUin);
      return NULL;
    }
    // Check if we need to create the user
    if (e->m_pUnknownUser == NULL)
    {
      e->m_pUnknownUser = new ICQUser(nUin);
    }
    // If not, validate the uin
    else if (e->m_pUnknownUser->Uin() != nUin)
    {
      gLog.Error("%sInternal Error: Event contains wrong user.\n", L_ERRORxSTR);
      return NULL;
    }

    u = e->m_pUnknownUser;
    u->Lock(LOCK_W);
  }
  gLog.Info(tr("%sReceived %s information for %s (%lu).\n"), L_SRVxSTR, t,
            u->GetAlias(), nUin);
  return u;
}

//-----FindUinByCellular-------------------------------------------------------
unsigned long CICQDaemon::FindUinByCellular(const char *szCellular)
{
  char szParsedNumber1[16], szParsedNumber2[16];
  unsigned long nUin = 0;
  
  FOR_EACH_USER_START(LOCK_R)
  {
    ParseDigits(szParsedNumber1, pUser->GetCellularNumber(), 15);
    ParseDigits(szParsedNumber2, szCellular, 15);
    if (!strcmp(szParsedNumber1, szParsedNumber2))
      nUin = pUser->Uin();
  }
  FOR_EACH_USER_END

  return nUin;
}

//-----ProcessSrvPacket---------------------------------------------------------
bool CICQDaemon::ProcessSrvPacket(CBuffer& packet)
{
  unsigned short nLen;
  unsigned short  nSequence;
  char startCode, nChannel;

  // read in the standard server TCP header info
  packet >> startCode;

  if (startCode != 0x2a)
  {
    gLog.Warn("%sProcessSrvPacket bad start code: %d.\n", L_WARNxSTR, startCode);
    char *buf;
    gLog.Unknown(tr("%sUnknown server response:\n%s\n"), L_UNKNOWNxSTR,
                 packet.print(buf));
    delete [] buf;
    return false;
  }

  packet >> nChannel
         >> nSequence
         >> nLen;

  // Eww
  rev_e_short(nSequence);
  rev_e_short(nLen);

  switch (nChannel)
  {
  case ICQ_CHNxNEW:
    if (m_bRegistering)
    {
      icqRegisterFinish();
      m_bRegistering = false;
    }
    break;

  case ICQ_CHNxDATA:
    ProcessDataChannel(packet);
    break;

  case ICQ_CHNxERROR:
    gLog.Warn(tr("%sPacket on unhandled Channel 'Error' received!\n"), L_SRVxSTR);
    break;

  case ICQ_CHNxCLOSE:
    return ProcessCloseChannel(packet);
    break;

  default:
    gLog.Warn(tr("%sServer send unknown channel: %02x\n"), L_SRVxSTR, nChannel);
    break;
  }

  return true;
}

//--------ProcessServiceFam----------------------------------------------------

void CICQDaemon::ProcessServiceFam(CBuffer &packet, unsigned short nSubtype)
{
  packet.UnpackUnsignedShortBE(); // flags
  packet.UnpackUnsignedLongBE(); // sequence

  switch (nSubtype)
  {
  case ICQ_SNACxSUB_READYxSERVER:
    {
      CSrvPacketTcp* p;

      gLog.Info(tr("%sServer says he's ready.\n"), L_SRVxSTR);

      gLog.Info(tr("%sSending our channel capability list...\n"), L_SRVxSTR);
      p = new CPU_ImICQ();
      SendEvent_Server(p);

      gLog.Info(tr("%sRequesting rate info...\n"), L_SRVxSTR);
      p = new CPU_GenericFamily(ICQ_SNACxFAM_SERVICE, ICQ_SNACxSUB_REQ_RATE_INFO);
      SendEvent_Server(p);

      // ask the user who we are (yeah we know already though)
      p = new CPU_GenericFamily(ICQ_SNACxFAM_SERVICE, ICQ_SNACxSRV_GETxUSERxINFO);
      SendEvent_Server(p);

      break;
    }

  case ICQ_SNACxSRV_ACKxIMxICQ:
    {
      CSrvPacketTcp* p;
      gLog.Info(tr("%sServer sent us channel capability list (ignoring).\n"), L_SRVxSTR);

      gLog.Info(tr("%sRequesting location rights.\n"), L_SRVxSTR);
      p = new CPU_GenericFamily(ICQ_SNACxFAM_LOCATION, ICQ_SNACxLOC_REQUESTxRIGHTS);
      SendEvent_Server(p);

      gLog.Info(tr("%sRequesting contact list rights.\n"), L_SRVxSTR);
      p = new CPU_GenericFamily(ICQ_SNACxFAM_BUDDY, ICQ_SNACxBDY_REQUESTxRIGHTS);
      SendEvent_Server(p);

      gLog.Info(tr("%sRequesting server contact list rights.\n"), L_SRVxSTR);
      p = new CPU_GenericFamily(ICQ_SNACxFAM_LIST, ICQ_SNACxLIST_REQUESTxRIGHTS);
      SendEvent_Server(p);

      gLog.Info(tr("%sRequesting Instant Messaging rights.\n"), L_SRVxSTR);
      p = new CPU_GenericFamily(ICQ_SNACxFAM_MESSAGE, ICQ_SNACxMSG_REQUESTxRIGHTS);
      SendEvent_Server(p);

      gLog.Info(tr("%sRequesting BOS rights.\n"), L_SRVxSTR);
      p = new CPU_GenericFamily(ICQ_SNACxFAM_BOS, ICQ_SNACxBOS_REQUESTxRIGHTS);
      SendEvent_Server(p);

      break;
    }
  case ICQ_SNACxSUB_RATE_INFO:
  {
      gLog.Info(tr("%sServer sent us rate information.\n"), L_SRVxSTR);
      CSrvPacketTcp *p = new CPU_RateAck();
      SendEvent_Server(p);

      gLog.Info(tr("%sSetting ICQ Instant Messaging Mode.\n"), L_SRVxSTR);
      p = new CPU_ICQMode(1, 11); // enable typing notifications
      SendEvent_Server(p);
      p = new CPU_ICQMode(0, 3); // set default flags for all channels
      SendEvent_Server(p);

      gLog.Info(tr("%sSending capability settings (?)\n"),L_SRVxSTR);
      p = new CPU_CapabilitySettings();
      SendEvent_Server(p);

      icqSetStatus(m_nDesiredStatus);

      gLog.Info(tr("%sSending client ready...\n"), L_SRVxSTR);
      p = new CPU_ClientReady();
      SendEvent_Server(p);

      gLog.Info(tr("%sSending offline message request...\n"), L_SRVxSTR);
      p = new CPU_RequestSysMsg;
      SendEvent_Server(p);

      m_eStatus = STATUS_ONLINE;
      m_bLoggingOn = false;
      // ### FIX subsequence !!
      ICQEvent *e = DoneExtendedServerEvent(0, EVENT_SUCCESS);
      if (e != NULL) ProcessDoneEvent(e);
      PushPluginSignal(new CICQSignal(SIGNAL_LOGON, 0, 0));

      break;
    }

  case ICQ_SNACxRCV_NAMExINFO:
  {
    unsigned short nUserClass, nLevel;
    unsigned long nUin, realIP;
    time_t nOnlineSince = 0;

    gLog.Info(tr("%sGot Name Info from Server\n"), L_SRVxSTR);

    nUin = packet.UnpackUinString();
    nLevel = packet.UnpackUnsignedShortBE();
    nUserClass = packet.UnpackUnsignedShortBE();

    gLog.Info(tr("%sUIN: %lu level: %04hx Class: %04hx\n"), L_SRVxSTR,
              nUin, nLevel, nUserClass );

    if (!packet.readTLV()) {
      char *buf;
      gLog.Unknown(tr("%sUnknown server response:\n%s\n"), L_UNKNOWNxSTR,
         packet.print(buf));
      delete [] buf;
      break;
    }

    // T(1) unknown
    // T(2) member since
    // T(3) online since
    // T(4) idle time
    // T(6) status code
    // T(A) IP
    // T(C) direct connection info
    if (packet.getTLVLen(0x0006) == 4)
      m_nDesiredStatus = packet.UnpackUnsignedLongTLV(0x0006);
    if (packet.getTLVLen(0x000a) == 4) {
      realIP = packet.UnpackUnsignedLongTLV(0x000a);
      rev_e_long(realIP);
      realIP = PacketIpToNetworkIp(realIP);
      CPacket::SetRealIp(NetworkIpToPacketIp(realIP));
      ICQOwner *owner = gUserManager.FetchOwner(LOCK_W);
      owner->SetIp(realIP);
      gUserManager.DropOwner();

      char buf[32];
      gLog.Info(tr("%sServer says we are at %s.\n"), L_SRVxSTR, ip_ntoa(realIP, buf));
      //icqSetStatus(m_nDesiredStatus);
    }
    if (packet.getTLVLen(0x0003) == 4)
      nOnlineSince = packet.UnpackUnsignedLongTLV(0x0003);

    ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
    unsigned long nPFM = o->PhoneFollowMeStatus();
    // Workaround for the ICQ4.0 problem of it not liking the PFM flags
    if (nPFM != ICQ_PLUGIN_STATUSxINACTIVE)
      m_nDesiredStatus |= ICQ_STATUS_FxPFM;
    if (nPFM == ICQ_PLUGIN_STATUSxACTIVE)
      m_nDesiredStatus |= ICQ_STATUS_FxPFMxAVAILABLE;
    ChangeUserStatus(o, m_nDesiredStatus);
    o->SetOnlineSince(nOnlineSince);
    gLog.Info(tr("%sServer says we're now: %s\n"), L_SRVxSTR, ICQUser::StatusToStatusStr(o->Status(), o->StatusInvisible()));

    gUserManager.DropOwner();

    break;
  }

  case ICQ_SNACxSUB_RATE_WARNING:
  {
    // TODO: Inform the user:
    // we are sending fast, if we keep it up we will be kicked off
    break;
  }

  case ICQ_SNACxSUB_PAUSE:
  {
    // Server is going to disconnect/pause (maintainance?)
    // lets change servers and reconnect.
    gLog.Info(tr("%sServer is going to disconnect/pause. Lets reconnect to another one.\n"), L_SRVxSTR);
    icqRelogon();
    break;
  }

  default:
    gLog.Warn(tr("%sUnknown Service Family Subtype: %04hx\n"), L_SRVxSTR, nSubtype);
    break;
  }
}

//--------ProcessLocationFam-----------------------------------------------
void CICQDaemon::ProcessLocationFam(const CBuffer &packet, unsigned short nSubtype)
{
  switch (nSubtype)
  {
  case ICQ_SNAXxLOC_RIGHTSxGRANTED:
    gLog.Info(tr("%sReceived rights for Location Services\n"), L_SRVxSTR);
    break;

  default:
    gLog.Warn(tr("%sUnknown Location Family Subtype: %04hx\n"), L_SRVxSTR, nSubtype);
    break;
  }
}

//--------ProcessBuddyFam--------------------------------------------------
void CICQDaemon::ProcessBuddyFam(CBuffer &packet, unsigned short nSubtype)
{
  switch (nSubtype)
  {
  case ICQ_SNACxSUB_ONLINExLIST:
  {
    unsigned long junk1, intIP, userPort, nInfoTimestamp = 0,
                  nStatusPluginTimestamp = 0, nInfoPluginTimestamp = 0, nCookie,
                  nUserIP;
    unsigned short junk2;
    unsigned char mode;
    char *szId;

    junk1 = packet.UnpackUnsignedLongBE();
    junk2 = packet.UnpackUnsignedShortBE();
    szId = packet.UnpackUserString();

    junk1 = packet.UnpackUnsignedLongBE(); // tlvcount

    if (!packet.readTLV()) {
      gLog.Error("%sfuck\n", L_ERRORxSTR);
      return;
    }

//     userIP = packet.UnpackUnsignedLongTLV(0x0a, 1);
//     rev_e_long(userIP);
    ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
    if (u == NULL)
    {
      gLog.Warn(tr("%sUnknown user (%s) changed status.\n"), L_WARNxSTR,
                szId);
      delete [] szId;
      break;
    }
    delete [] szId;

    // 0 if not set -> Online
    unsigned long nNewStatus = 0;
    unsigned long nOldStatus = u->StatusFull();
    nUserIP = 0;

    // AIM status
    if (packet.getTLVLen(0x0001) == 2)
    {
      unsigned short nStatus = packet.UnpackUnsignedShortTLV(0x0001);
      if (nStatus & 0x0020)
        nNewStatus = ICQ_STATUS_AWAY;
      else
        nNewStatus = ICQ_STATUS_ONLINE;
    }

    // ICQ status
    if (packet.getTLVLen(0x0006))
      nNewStatus = packet.UnpackUnsignedLongTLV(0x0006);

    if (packet.getTLVLen(0x000a) == 4) {
      nUserIP = packet.UnpackUnsignedLongTLV(0x000a);
      if (nUserIP) {
        rev_e_long(nUserIP);
        nUserIP = PacketIpToNetworkIp(nUserIP);
      }
    }
    if( u->StatusOffline() || nUserIP )
      u->SetIp(nUserIP);

    if (packet.getTLVLen(0x0003) == 4) {
      time_t nOnlineSince = packet.UnpackUnsignedLongTLV(0x0003);
      u->SetOnlineSince(nOnlineSince);
    }

    if (packet.getTLVLen(0x0004) == 2)
    {
      unsigned short nIdleTime = packet.UnpackUnsignedShortTLV(0x0004);
      u->SetIdleSince(time(NULL) - (nIdleTime * 60));
    }
    else
      u->SetIdleSince(0);

    if (packet.getTLVLen(0x000c) == 0x25)
    {
      CBuffer msg = packet.UnpackTLV(0x000c);

      intIP = msg.UnpackUnsignedLong();
      userPort = msg.UnpackUnsignedLongBE();
      mode = msg.UnpackChar();
      unsigned short tcpVersion = msg.UnpackUnsignedShortBE();
      nCookie = msg.UnpackUnsignedLongBE();
      msg.UnpackUnsignedLongBE();
      unsigned long tcount = msg.UnpackUnsignedLongBE();
      nInfoTimestamp = msg.UnpackUnsignedLongBE();  // will be licq version
      nStatusPluginTimestamp = msg.UnpackUnsignedLongBE();
      nInfoPluginTimestamp = msg.UnpackUnsignedLongBE();
      if (tcount == 0)
        nInfoTimestamp = nStatusPluginTimestamp = nInfoPluginTimestamp = 0;
      else if (tcount == 1)
        nStatusPluginTimestamp = nInfoPluginTimestamp = 0;
      else if (tcount == 2)
        nInfoPluginTimestamp = 0;
        
      junk2 = msg.UnpackUnsignedShortBE();

      char szExtraInfo[28] = { 0 };
      if ((nInfoTimestamp & 0xFFFF0000) == LICQ_WITHSSL)
        snprintf(szExtraInfo, 27, "Licq %s/SSL",
                 CUserEvent::LicqVersionToString(nInfoTimestamp & 0xFFFF));
      else if ((nInfoTimestamp & 0xFFFF0000) == LICQ_WITHOUTSSL)
        snprintf(szExtraInfo, 27, "Licq %s",
                 CUserEvent::LicqVersionToString(nInfoTimestamp & 0xFFFF));
      else if (nInfoTimestamp == 0xffffffff)
        strcpy(szExtraInfo, "MIRANDA");
      else if (nInfoTimestamp == 0xFFFFFF8F)
        strcpy(szExtraInfo, "StrICQ");
      else if (nInfoTimestamp == 0xFFFFFF42)
        strcpy(szExtraInfo, "mICQ");
      else if (nInfoTimestamp == 0xFFFFFF7F)
        strcpy(szExtraInfo, "&RQ");
      else if (nInfoTimestamp == 0xFFFFFFAB)
        strcpy(szExtraInfo, "YSM");
      else
        szExtraInfo[0]=0;
      szExtraInfo[27] = '\0';

      u->SetClientInfo(szExtraInfo[0] ? szExtraInfo : NULL);
      u->SetVersion(tcpVersion);
      
      if (nOldStatus != nNewStatus)
      {
        char *szClient = new char[strlen(szExtraInfo)+6];
        if (szExtraInfo[0])
          sprintf(szClient, " [%s].\n", szExtraInfo);
        else
          sprintf(szClient, ".\n");

        ChangeUserStatus(u, nNewStatus);
        gLog.Info(tr("%s%s (%s) changed status: %s (v%01x)%s"),
                   L_SRVxSTR, u->GetAlias(), u->IdString(), u->StatusStr(),
                   tcpVersion & 0x0F, szClient);
        if ( (nNewStatus & ICQ_STATUS_FxUNKNOWNxFLAGS) )
          gLog.Unknown("%sUnknown status flag for %s (%s): 0x%08lX\n",
                       L_UNKNOWNxSTR, u->GetAlias(), u->IdString(),
                       (nNewStatus & ICQ_STATUS_FxUNKNOWNxFLAGS));
        nNewStatus &= ICQ_STATUS_FxUNKNOWNxFLAGS;
        u->SetAutoResponse(NULL);
        u->SetShowAwayMsg(false);

        delete [] szClient;
      }

      if (intIP)
      {
        intIP = PacketIpToNetworkIp(intIP);
        u->SetIntIp(intIP);
      }

      if (userPort)
        u->SetPort(userPort);

      u->SetCookie(nCookie);

      /* Mode 0 is used improperly by too many clients,
         don't bother warning, just set it to be indirect */
      if (mode == MODE_DENIED || mode == 6 || mode == 0 ||
          (nNewStatus & ICQ_STATUS_FxDIRECTxLISTED) ||
          (nNewStatus & ICQ_STATUS_FxDIRECTxAUTH)
        ) mode = MODE_INDIRECT;
      if (mode != MODE_DIRECT && mode != MODE_INDIRECT)
      {
        gLog.Unknown("%sUnknown peer-to-peer mode for %s (%s): %d\n", L_UNKNOWNxSTR,
                     u->GetAlias(), u->IdString(), mode);
        u->SetMode(MODE_DIRECT);
        u->SetSendServer(false);
      }
      else
      {
        u->SetMode(mode);
        u->SetSendServer(mode == MODE_INDIRECT);
      }
    }
    else // for AIM users
    {
      if (nOldStatus != nNewStatus)
      {
        ChangeUserStatus(u, nNewStatus);
        gLog.Info(tr("%s%s changed status: %s (AIM).\n"), L_SRVxSTR, u->GetAlias(),
                  u->StatusStr());
        if ( (nNewStatus & ICQ_STATUS_FxUNKNOWNxFLAGS) )
          gLog.Unknown("%sUnknown status flag for %s: 0x%08lX\n",
                       L_UNKNOWNxSTR, u->GetAlias(),
                       nNewStatus & ICQ_STATUS_FxUNKNOWNxFLAGS);
        u->SetAutoResponse(NULL);
        u->SetShowAwayMsg(false);
      }
    }

    if (u->OurClientStatusTimestamp() != nStatusPluginTimestamp &&
        nOldStatus == ICQ_STATUS_OFFLINE)
    {
      //we don't know what the new values are yet, so don't show anything
      u->SetPhoneFollowMeStatus(ICQ_PLUGIN_STATUSxINACTIVE);
      u->SetICQphoneStatus(ICQ_PLUGIN_STATUSxINACTIVE);
      u->SetSharedFilesStatus(ICQ_PLUGIN_STATUSxINACTIVE);
    }
    
    if (packet.hasTLV(0x0011))
    {
      CBuffer msg = packet.UnpackTLV(0x0011);
      char index = msg.UnpackChar();
      unsigned long nTime = msg.UnpackUnsignedLong(); //Timestamp

      char plugin[GUID_LENGTH];
      switch (index)
      {
      case 0x01: //Updated user info
        gLog.Info("%s%s updated info.\n", L_SRVxSTR, u->GetAlias());
        u->SetUserUpdated(false);
        break;

      case 0x02: //Updated info plugin settings
        msg.incDataPosRead(6); /* 02 00 01 00 01 00
                                  Don't know what those mean */
        for (unsigned int i = 0; i < sizeof(plugin); i ++)
          plugin[i] = msg.UnpackChar();

        if (memcmp(plugin, PLUGIN_PHONExBOOK, GUID_LENGTH) == 0)
          gLog.Info("%s%s updated phonebook\n", L_SRVxSTR, u->GetAlias());
        else if (memcmp(plugin, PLUGIN_PICTURE, GUID_LENGTH) == 0)
          gLog.Info("%s%s updated picture\n", L_SRVxSTR, u->GetAlias());
        else if (memcmp(plugin, PLUGIN_QUERYxINFO, GUID_LENGTH) == 0)
          gLog.Info("%s%s updated info plugin list\n", L_SRVxSTR,
                    u->GetAlias());
        else
          gLog.Warn("%sUnknown info plugin update from %s\n", L_WARNxSTR,
                    u->GetAlias());

        u->SetUserUpdated(false);

        break;

      case 0x03: //Updated status plugin settings
      {
        msg.incDataPosRead(6); /* 00 00 01 00 01 00 */
        for (unsigned int i = 0; i < sizeof(plugin); i ++)
          plugin[i] = msg.UnpackChar();

        msg.incDataPosRead(1);  /* 01 */

        unsigned long nPluginStatus = msg.UnpackUnsignedLong();
        char *state;
        switch (nPluginStatus)
        {
          case ICQ_PLUGIN_STATUSxINACTIVE: state = "inactive"; break;
          case ICQ_PLUGIN_STATUSxACTIVE:   state = "active";   break;
          case ICQ_PLUGIN_STATUSxBUSY:     state = "busy";     break;
          default:                         state = "unknown";  break;
        }

        if (memcmp(plugin, PLUGIN_FOLLOWxME, GUID_LENGTH) == 0)
        {
            gLog.Info(tr("%s%s changed Phone \"Follow Me\" status to %s.\n"),
                                              L_SRVxSTR, u->GetAlias(), state);
            u->SetPhoneFollowMeStatus(nPluginStatus);
        }
        else if (memcmp(plugin, PLUGIN_FILExSERVER, GUID_LENGTH) == 0)
        {
            gLog.Info(tr("%s%s changed Shared Files Directory status to %s.\n"),
              L_SRVxSTR, u->GetAlias(), state);
            u->SetSharedFilesStatus(nPluginStatus);
        }
        else if (memcmp(plugin, PLUGIN_ICQxPHONE, GUID_LENGTH) == 0)
        {
            gLog.Info(tr("%s%s changed ICQphone status to %s.\n"), L_SRVxSTR,
              u->GetAlias(), state);
            u->SetICQphoneStatus(nPluginStatus);
        }

        // if status was up to date then we don't need to reask the user
        if (u->OurClientStatusTimestamp() == u->ClientStatusTimestamp() &&
            nOldStatus != ICQ_STATUS_OFFLINE)
          u->SetOurClientStatusTimestamp(nTime);


        PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER,
                                         USER_STATUS, u->IdString(), u->PPID(), 0));

        break;
      }

      default:
        gLog.Warn(tr("%sUnknown index %d from %s.\n"), L_WARNxSTR, index,
        u->GetAlias());
      }
    }

    // maybe use this for auto update info later
    u->SetClientTimestamp(nInfoTimestamp);
    u->SetClientInfoTimestamp(nInfoPluginTimestamp);
    u->SetClientStatusTimestamp(nStatusPluginTimestamp);

    // We are no longer able to differentiate oncoming users from the
    // users that are on when we sign on.. so try the online since flag
    if ((m_bAlwaysOnlineNotify || (u->OnlineSince()+60 >= time(NULL))) &&
        nOldStatus == ICQ_STATUS_OFFLINE && u->OnlineNotify())
      m_xOnEventManager.Do(ON_EVENT_NOTIFY, u);
    gUserManager.DropUser(u);
    break;
  }
  case ICQ_SNACxSUB_OFFLINExLIST:
  {
    unsigned long junk1;
    unsigned short junk2;
    char *szId;

    junk1 = packet.UnpackUnsignedLongBE();
    junk2 = packet.UnpackUnsignedShortBE();
    szId = packet.UnpackUserString();

    ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
    if (u == NULL)
    {
      gLog.Warn(tr("%sUnknown user (%s) has gone offline.\n"), L_WARNxSTR, szId);
      delete [] szId;
      break;
    }
    delete [] szId;

    gLog.Info(tr("%s%s went offline.\n"), L_SRVxSTR, u->GetAlias());
    u->SetClientTimestamp(0);
    ChangeUserStatus(u, ICQ_STATUS_OFFLINE);
    gUserManager.DropUser(u);
    break;
  }
  case ICQ_SNACxBDY_RIGHTSxGRANTED:
  {
    gLog.Info(tr("%sReceived rights for Contact List..\n"), L_SRVxSTR);

    icqUpdateContactList();
    break;
  }

  default:
    gLog.Warn("%sUnknown Buddy Family Subtype: %04hx\n", L_SRVxSTR, nSubtype);
    break;
  }
}

//--------ProcessMessageFam------------------------------------------------
void CICQDaemon::ProcessMessageFam(CBuffer &packet, unsigned short nSubtype)
{
  /*unsigned short Flags =*/ packet.UnpackUnsignedShortBE();
  unsigned long nSubSequence = packet.UnpackUnsignedLongBE();

  switch (nSubtype)
  {
  case ICQ_SNACxMSG_ICBMxERROR:
  {
    unsigned short err = packet.UnpackUnsignedShortBE();
    switch (err)
    {
    case 0x0004:
      gLog.Warn(tr("%sUser is offline.\n"), L_WARNxSTR);
      break;
    case 0x0009:
      gLog.Warn(tr("%sClient does not understand type-2 messages.\n"), L_WARNxSTR);
      break;
    case 0x000e:
      gLog.Warn(tr("%sPacket was malformed.\n"), L_WARNxSTR);
      break;
    case 0x0015:
      gLog.Info(tr("%sList overflow.\n"), L_WARNxSTR);
      break;
    default:
      gLog.Unknown(tr("%sUnknown ICBM error: 0x%04x.\n"), L_UNKNOWNxSTR, err);
    }

    ICQEvent *e = DoneServerEvent(nSubSequence, EVENT_ERROR);
    
    if (e)
      ProcessDoneEvent(e);
    else
    {
      pthread_mutex_lock(&mutex_reverseconnect);
      bool bFound = false;
      std::list<CReverseConnectToUserData *>::iterator iter;
      for (iter = m_lReverseConnect.begin(); iter != m_lReverseConnect.end();
                                             iter++)
      {
        if ((*iter)->nId == nSubSequence)
        {
          ICQUser *u = gUserManager.FetchUser((*iter)->nUin, LOCK_R);
          if (u == NULL)
            gLog.Warn("%sReverse connection from %lu failed.\n", L_WARNxSTR,
                      (*iter)->nUin);
          else
          {
            gLog.Warn("%sReverse connection from %s failed.\n", L_WARNxSTR,
                      u->GetAlias());
            gUserManager.DropUser(u);
          }

          (*iter)->bSuccess = false;
          (*iter)->bFinished = true;
          pthread_cond_broadcast(&cond_reverseconnect_done);
          bFound = true;
          break;
        }
      }
      pthread_mutex_unlock(&mutex_reverseconnect);

      if (!bFound)
        gLog.Warn("%sICBM error for unknown event.\n", L_WARNxSTR);
    }

    break;
  }
  case ICQ_SNACxMSG_SERVERxMESSAGE:
  {
    unsigned long nMsgID[2], nUin;
    unsigned long nTimeSent;
    unsigned short mFormat, nMsgLen, nTLVs;
    char *szId;

    nMsgID[0] = packet.UnpackUnsignedLongBE();
    nMsgID[1] = packet.UnpackUnsignedLongBE();
    nTimeSent   = time(0L);
    mFormat    = packet.UnpackUnsignedShortBE();
    szId       = packet.UnpackUserString();

    //TODO Check this again with new protocol plugin support
    //if (nUin < 10000 && nUin != ICQ_UINxPAGER && nUin != ICQ_UINxSMS)
    //{
    //  gLog.Warn("%sMessage through server with strange Uin: %04lx\n", L_WARNxSTR, nUin);
    //  break;
    //}

    packet.UnpackUnsignedShortBE();  // warning level ?
    nTLVs = packet.UnpackUnsignedShortBE() + 1;
    if (nTLVs && !packet.readTLV())
    {
      gLog.Error("%sIvalid packet format in message through server\n", L_ERRORxSTR);
      return;
    }

    switch (mFormat)
    {
    case 1:
    {
      CBuffer msg = packet.UnpackTLV(0x0002);

      // TLVs in TLV
      // type: 05 01: ???
      //       01 01: 4 bytes flags? + message text
      msg.readTLV();
      CBuffer msgTxt = msg.UnpackTLV(0x0101);
      nMsgLen = msgTxt.getDataSize();

      unsigned short nEncoding = msgTxt.UnpackUnsignedShort();
      unsigned short nSubEncoding = msgTxt.UnpackUnsignedShort();
      
      nMsgLen -= 4;

      char* szMessage = new char[nMsgLen+1];
      for (int i = 0; i < nMsgLen; ++i)
        szMessage[i] = msgTxt.UnpackChar();

      szMessage[nMsgLen] = '\0';
      char* szMsg = 0;
      if (nEncoding == 2) // utf-8 or utf-16?
      {
        char *szTmpMsg = 0;
        szTmpMsg = gTranslator.FromUnicode(szMessage);
        szMsg = gTranslator.RNToN(szTmpMsg);
        delete [] szTmpMsg;
      }
      else
        szMsg = gTranslator.RNToN(szMessage);
      delete [] szMessage;

      // now send the message to the user
      CEventMsg *e = CEventMsg::Parse(szMsg, ICQ_CMDxRCV_SYSxMSGxONLINE, nTimeSent, 0);
      delete [] szMsg;

      // Lock the user to add the message to their queue
      ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
      if (u == NULL)
      {
        if (Ignore(IGNORE_NEWUSERS))
        {
          gLog.Info(tr("%sMessage from new user (%s), ignoring.\n"), L_SBLANKxSTR, szId);
          //TODO
          RejectEvent(strtoul(szId, (char **)NULL, 10), e);
          break;
        }

        gLog.Info(tr("%sMessage from new user (%s).\n"),
                  L_SBLANKxSTR, szId);

        AddUserToList(szId, LICQ_PPID);
        u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
      }
      else
        gLog.Info(tr("%sMessage through server from %s (%s).\n"), L_SRVxSTR,
          u->GetAlias(), szId);
    
      u->SetTyping(ICQ_TYPING_INACTIVEx0);
      
      if (AddUserEvent(u, e))
        m_xOnEventManager.Do(ON_EVENT_MSG, u);
      gUserManager.DropUser(u);
      PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_TYPING, szId,
                                      LICQ_PPID));
      break;
    }
    case 2: // OSCAR's "Add ICBM parameter" message
    {
      //I must admit, any server that does anything like this is a pile of shit
      CBuffer msgTxt = packet.UnpackTLV(5);
      if (msgTxt.getDataSize() == 0)  break;

      unsigned short nCancel = msgTxt.UnpackUnsignedShort();

      if (nCancel == 1)  break;

      msgTxt.incDataPosRead(8); // message ids again
      
      char cap[CAP_LENGTH];
      for (unsigned short i = 0; i < CAP_LENGTH; i++)
        msgTxt >> cap[i];

      msgTxt.readTLV();

      CBuffer ackMsg = msgTxt.UnpackTLV(0x000A);
      if (ackMsg.getDataSize() == 0)  break;
      bool bIsAck = (ackMsg.UnpackUnsignedShortBE() == 2 ? true : false);

      CBuffer advMsg = msgTxt.UnpackTLV(0x2711);
      if (advMsg.getDataSize() == 0)  break;
      
      if (memcmp(cap, ICQ_CAPABILITY_DIRECT, CAP_LENGTH) == 0)
      {
        // reverse connect request
        if (advMsg.getDataSize() != 27) break;

        unsigned long nUin, nIp, nPort, nFailedPort, nPort2, nId;
        unsigned short nVersion;
        char nMode;
        advMsg >> nUin >> nIp >> nPort >> nMode >> nFailedPort >> nPort2
               >> nVersion >> nId;

        /* nPort seems to always contain the port to connect to, nPort2 is a
           duplicate of nPort. But check anyway */
        if (nPort == 0)
          nPort = nPort2;

        pthread_t t;
        CReverseConnectToUserData *data = new CReverseConnectToUserData(
                               nUin, nId, ICQ_CHNxUNKNOWN, nIp, nPort,
                               nVersion, nFailedPort, nMsgID[0], nMsgID[1]);
        pthread_create(&t, NULL, &ReverseConnectToUser_tep, data);
        break;
      }
      else if (memcmp(cap, ICQ_CAPABILITY_SRVxRELAY, CAP_LENGTH) != 0) break;

      unsigned short nLen;
      unsigned short nMsgType, nStatus, nMsgFlags;

      nLen = advMsg.UnpackUnsignedShort();
      advMsg.UnpackUnsignedShort(); // tcp version
      
      char GUID[GUID_LENGTH];
      for (unsigned short i = 0; i < GUID_LENGTH; i++) // channel
        advMsg >> GUID[i];
        
      advMsg.incDataPosRead(nLen - 2 - GUID_LENGTH - 2);
      
      unsigned short nSequence = advMsg.UnpackUnsignedShort();

      nLen = advMsg.UnpackUnsignedShort();
      advMsg.incDataPosRead(nLen);

      // Get the message type, status, and flags
      unsigned long nMask = 0;
      advMsg >> nMsgType;

      if (memcmp(GUID, PLUGIN_NORMAL, GUID_LENGTH) != 0)
      {
        unsigned char nChannel = ICQ_CHNxUNKNOWN;

        if (memcmp(GUID, PLUGIN_INFOxMANAGER, GUID_LENGTH) == 0)
          nChannel = ICQ_CHNxINFO;
        else if (memcmp(GUID, PLUGIN_STATUSxMANAGER, GUID_LENGTH) == 0)
          nChannel = ICQ_CHNxSTATUS;

        bool bNewUser = false;
        ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
        if (u == NULL)
        {
          u = new ICQUser(szId, LICQ_PPID);
          bNewUser = true;
        }

        ProcessPluginMessage(advMsg, u, nChannel, bIsAck, nMsgID[0], nMsgID[1],
                             nSequence, NULL);

        if (bNewUser)
          delete u;
        else
          gUserManager.DropUser(u);

        break;
      }
 
      advMsg >> nStatus >> nMsgFlags;

      if (nMsgType & ICQ_CMDxSUB_FxMULTIREC)
      {
        nMask |= ICQ_CMDxSUB_FxMULTIREC;
        nMsgType &= ~ICQ_CMDxSUB_FxMULTIREC;
      }

      if (nMsgFlags == ICQ_TCPxMSG_URGENT2)
        nMask |= ICQ_TCPxMSG_URGENT;
      if (nMsgFlags == ICQ_TCPxMSG_LIST2)
        nMask |= ICQ_TCPxMSG_LIST;

      nLen = advMsg.UnpackUnsignedShort();

      // read the message in, except for DOS \r's
      char junkChar;
      char *message = new char[nLen+1];
      unsigned short j = 0;
      for (unsigned short i = 0; i < nLen; i++)
      {
        advMsg >> junkChar;
        if (junkChar != 0x0D)  message[j++] = junkChar;
      }
      message[j] = '\0'; // ensure null terminated

      char *szMsg = gTranslator.RNToN(message);
      delete [] message;

      gTranslator.ServerToClient(szMsg);

      bool bNewUser = false;
      ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
      if (u == NULL)
      {
        u = new ICQUser(szId, LICQ_PPID);
        bNewUser = true;
      }

      u->SetTyping(ICQ_TYPING_INACTIVEx0);
      
      if (msgTxt.getTLVLen(0x0004) == 4)
      {
        unsigned long Ip = msgTxt.UnpackUnsignedLongTLV(0x0004);
        rev_e_long(Ip);
        u->SetIp(PacketIpToNetworkIp(Ip));
      }

      // Special status to us?
      if (!bIsAck && !bNewUser && nStatus != ICQ_STATUS_OFFLINE &&
          !(nStatus == ICQ_STATUS_ONLINE && u->Status() == ICQ_STATUS_FREEFORCHAT) &&
          nStatus != u->Status() | (u->StatusInvisible() ? ICQ_STATUS_FxPRIVATE : 0))
      {
        bool r = u->OfflineOnDisconnect() || u->StatusOffline();
        ChangeUserStatus(u, (u->StatusFull() & ICQ_STATUS_FxFLAGS) | nStatus);
        gLog.Info(tr("%s%s (%s) is %s to us.\n"), L_TCPxSTR, u->GetAlias(),
          u->IdString(), u->StatusStr());
        if (r) u->SetOfflineOnDisconnect(true);
      }

      // Handle it
      ProcessMessage(u, advMsg, szMsg, nMsgType, nMask, nMsgID,
                     nSequence, bIsAck, bNewUser);

      delete [] szMsg;
      if (bNewUser) // can be changed in ProcessMessage
      {
        delete u;
        break;
      }

      gUserManager.DropUser(u);
      PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_TYPING, szId,
                                      LICQ_PPID));
      break;
    }
    case 4:
    //Version 5 (V5) protocol messages incapsulated in v7 packet.
    {
      CBuffer msgTxt = packet.UnpackTLV(0x0005);
      msgTxt.UnpackUnsignedLongBE();
      unsigned short nTypeMsg = msgTxt.UnpackUnsignedShort();
      unsigned long nMask = ((nTypeMsg & ICQ_CMDxSUB_FxMULTIREC) ? E_MULTIxREC : 0);
      nTypeMsg &= ~ICQ_CMDxSUB_FxMULTIREC;

      char *szMessage = NULL;

      if (nTypeMsg == ICQ_CMDxSUB_SMS)
      {
        msgTxt.incDataPosRead(21);

        unsigned short nTypeSMS = msgTxt.UnpackUnsignedShort();
        switch (nTypeSMS)
        {
          case 0x0000:
	          // SMS
	          break;
          case 0x0002:
            // SMS Receipt: Success (meanwhile, we handle it in a rather lame way)
            gLog.Unknown(tr("%sReceived SMS receipt indicating success.\n"), L_UNKNOWNxSTR);
            return;
          case 0x0003:
            // SMS Receipt : Failure
            gLog.Unknown(tr("%sReceived SMS receipt indicating failure.\n"), L_UNKNOWNxSTR);
            return;
          default:
          {
            char *buf;
            gLog.Unknown("%sUnknown SMS subtype (0x%04x):\n%s\n", L_UNKNOWNxSTR,
              nTypeSMS, packet.print(buf));
            delete [] buf;
            return;
          }
        }

        unsigned long nTagLength = msgTxt.UnpackUnsignedLong();
        // Refuse irreasonable tag sizes
        if (nTagLength > 255)
        {
          gLog.Unknown(tr("%sInvalid tag in SMS message."), L_UNKNOWNxSTR);
          return;
        }

        char* szTag = new char[nTagLength + 1];
        for (unsigned long i = 0; i < nTagLength; ++i)
          szTag[i] = msgTxt.UnpackChar();
        szTag[nTagLength] = '\0';

        if (strcmp(szTag, "ICQSMS") != 0)
        {
          gLog.Unknown(tr("%sUnknown tag in SMS message:\n%s\n"), L_UNKNOWNxSTR,
            szTag);
          delete [] szTag;
          return;
        }
        delete [] szTag;

        msgTxt.incDataPosRead(3);

        msgTxt.UnpackUnsignedLong(); // length till end of the message (useless)
        unsigned long nSMSLength = msgTxt.UnpackUnsignedLong();
        // Refuse irreasonable SMS sizes (something must've went wrong)
        if (nSMSLength > 0x7fff)
        {
          gLog.Unknown(tr("%sSMS message packet was too large (claimed size: %lu bytes)\n"),
            L_UNKNOWNxSTR, nSMSLength);
          return;
        }
        szMessage = new char[nSMSLength+1];
        for (unsigned long i = 0; i < nSMSLength; ++i)
          szMessage[i] = msgTxt.UnpackChar();
        szMessage[nSMSLength] = '\0';
      }
      else
      {
        // new unpack the message
        nMsgLen = msgTxt.UnpackUnsignedShort();
        char* szMsg = new char[nMsgLen+1];
        for (int i = 0; i < nMsgLen; ++i)
          szMsg[i] = msgTxt.UnpackChar();
        szMsg[nMsgLen] = '\0';

        szMessage = gTranslator.RNToN(szMsg);
        delete [] szMsg;
      }

      char *szType = NULL;
      unsigned short nTypeEvent = 0;
      CUserEvent *eEvent = NULL;

      switch(nTypeMsg)
      {
        case ICQ_CMDxSUB_MSG:
        {
          CEventMsg *e = CEventMsg::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxONLINE, nTimeSent, nMask);
          szType = strdup(tr("Message"));
          nTypeEvent = ON_EVENT_MSG;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_URL:
        {
          CEventUrl *e = CEventUrl::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxONLINE, nTimeSent, nMask);
          if (e == NULL)
          {
            char *buf;
            gLog.Warn(tr("%sInvalid URL message:\n%s\n"), L_WARNxSTR, packet.print(buf));
            delete [] buf;
            break;
          }
          szType = strdup(tr("URL"));
          nTypeEvent = ON_EVENT_URL;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_AUTHxREQUEST:
        {
          gLog.Info(tr("%sAuthorization request from %s.\n"), L_SBLANKxSTR, szId);
          char **szFields = new char *[6];  // alias, first name, last name, email, auth, comment

          if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;
            gLog.Warn(tr("%sInvalid authorization request system message:\n%s\n"), L_WARNxSTR,
              packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient (szFields[0]);  // alias
          gTranslator.ServerToClient (szFields[1]);  // first name
          gTranslator.ServerToClient (szFields[2]);  // last name
          gTranslator.ServerToClient (szFields[5]);  // comment

          CEventAuthRequest *e = new CEventAuthRequest(szId, LICQ_PPID,
                                                       szFields[0], szFields[1],
                                                       szFields[2], szFields[3],
                                                       szFields[5],
                                                       ICQ_CMDxRCV_SYSxMSGxONLINE,
                                                       nTimeSent, 0);

          delete [] szFields;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_AUTHxREFUSED:  // system message: authorization refused
        {
          gLog.Info(tr("%sAuthorization refused by %s.\n"), L_SBLANKxSTR, szId);

          // Translating string with Translation Table
          gTranslator.ServerToClient(szMessage);

          CEventAuthRefused *e = new CEventAuthRefused(szId, LICQ_PPID, szMessage,
                                                       ICQ_CMDxRCV_SYSxMSGxONLINE, 
                                                       nTimeSent, 0);
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_AUTHxGRANTED:  // system message: authorized
        {
          gLog.Info(tr("%sAuthorization granted by %s.\n"), L_SBLANKxSTR, szId);

          // translating string with Translation Table
          gTranslator.ServerToClient (szMessage);

          ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
          if (u)
          {
            u->SetAwaitingAuth(false);
            gUserManager.DropUser(u);
          }

          CEventAuthGranted *e = new CEventAuthGranted(szId, LICQ_PPID,
            szMessage, ICQ_CMDxRCV_SYSxMSGxONLINE, nTimeSent, 0);
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_MSGxSERVER:
        {
          gLog.Info(tr("%sServer message.\n"), L_BLANKxSTR);

          CEventServerMessage *e = CEventServerMessage::Parse(szMessage,
            ICQ_CMDxSUB_MSGxSERVER, nTimeSent, nMask);
          if (e == NULL)
          {
            char *buf;

            gLog.Warn(tr("%sInvalid Server Message:\n%s\n"), L_WARNxSTR,
              packet.print(buf));
            delete [] buf;
            break;
          }
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_ADDEDxTOxLIST: // system message: added to a contact list
        {
          gLog.Info(tr("%sUser %s added you to their contact list.\n"), L_SBLANKxSTR, szId);

          char **szFields = new char*[6]; // alias, first name, last name, email, auth, comment

          if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;
            gLog.Warn(tr("%sInvalid added to list system message:\n%s\n"), L_WARNxSTR,
                      packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient (szFields[0]);  // alias
          gTranslator.ServerToClient (szFields[1]);  // first name
          gTranslator.ServerToClient (szFields[2]);  // last name

          CEventAdded *e = new CEventAdded(szId, LICQ_PPID, szFields[0],
            szFields[1], szFields[2], szFields[3], ICQ_CMDxRCV_SYSxMSGxONLINE,
            nTimeSent, 0);
          delete [] szFields;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_WEBxPANEL:
        {
          gLog.Info(tr("%sMessage through web panel.\n"), L_SBLANKxSTR);

          char **szFields = new char *[6];	// name, ?, ?, email, ?, message

          if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;
            gLog.Warn(tr("%sInvalid web panel system message:\n%s\n"), L_WARNxSTR,
              packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient(szFields[0]);  // name
          gTranslator.ServerToClient(szFields[3]);  // email
          gTranslator.ServerToClient(szFields[5]);  // message

          gLog.Info(tr("%sFrom %s (%s).\n"), L_SBLANKxSTR, szFields[0], szFields[3]);
          CEventWebPanel *e = new CEventWebPanel(szFields[0], szFields[3],
                                                 szFields[5], ICQ_CMDxRCV_SYSxMSGxONLINE,
                                                 nTimeSent, 0);
          delete [] szFields;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_EMAILxPAGER:
        {
          gLog.Info(tr("%sEmail pager message.\n"), L_SBLANKxSTR);

          char **szFields = new char *[6];	// name, ?, ?, email, ?, message

          if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;
            gLog.Warn(tr("%sInvalid email pager system message:\n%s\n"), L_WARNxSTR,
                      packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient(szFields[0]);  // name
          gTranslator.ServerToClient(szFields[3]);  // email
          gTranslator.ServerToClient(szFields[5]);  // message

          gLog.Info(tr("%sFrom %s (%s).\n"), L_SBLANKxSTR, szFields[0], szFields[3]);
          CEventEmailPager *e = new CEventEmailPager(szFields[0], szFields[3],
                                                     szFields[5], ICQ_CMDxRCV_SYSxMSGxONLINE,
                                                     nTimeSent, 0);
          delete [] szFields;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_CONTACTxLIST:
        {
          CEventContactList *e = CEventContactList::Parse(szMessage,
            ICQ_CMDxRCV_SYSxMSGxONLINE,nTimeSent, nMask);
          if (e == NULL)
          {
            char *buf;
            gLog.Warn(tr("%sInvalid Contact List message:\n%s\n"), L_WARNxSTR,
              packet.print(buf));
            delete [] buf;
            break;
          }

          szType = strdup(tr("Contacts"));
          nTypeEvent = ON_EVENT_MSG;
          eEvent = e;
          break;
        }
        case ICQ_CMDxSUB_SMS:
        {
          CEventSms *e = CEventSms::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxONLINE,
            nTimeSent, nMask);
          if (e == NULL)
          {
            char *buf;
            gLog.Warn(tr("%sInvalid SMS message:\n%s\n"), L_WARNxSTR,
              packet.print(buf));
            delete [] buf;
            break;
          }
          eEvent = e;
          break;
        }
        default:
        {
          char *szFE, *buf;
          
          while ((szFE = strchr(szMessage, 0xFE)) != NULL) *szFE = '\n';

          gLog.Unknown(tr("%sUnknown system message (0x%04x):\n%s\n"), L_UNKNOWNxSTR,
                       nTypeMsg, packet.print(buf));
          delete [] buf;
          //TODO
          CEventUnknownSysMsg *e = new CEventUnknownSysMsg(nTypeMsg, ICQ_CMDxRCV_SYSxMSGxONLINE,
                                                           strtoul(szId, (char **)NULL, 10), 
                                                           szMessage, nTimeSent, 0);

          ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
          AddUserEvent(o, e);
          gUserManager.DropOwner();
        }
      }

      if (eEvent)
	switch(nTypeMsg)
	{
	  case ICQ_CMDxSUB_MSG:
	  case ICQ_CMDxSUB_URL:
	  case ICQ_CMDxSUB_CONTACTxLIST:
	  {
	    // Lock the user to add the message to their queue
	    ICQUser* u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
	    if (u == NULL)
	    {
	      if (Ignore(IGNORE_NEWUSERS))
	      {
          gLog.Info(tr("%s%s from new user (%s), ignoring.\n"), L_SBLANKxSTR, szType, szId);

          if (szType) free(szType);

          //TODO
          RejectEvent(strtoul(szId, (char **)NULL, 10), eEvent);
          break;
        }

	      gLog.Info(tr("%s%s from new user (%s).\n"), L_SBLANKxSTR, szType, szId);
	      AddUserToList(szId, LICQ_PPID);
	      u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
	    }
	    else
	      gLog.Info(tr("%s%s through server from %s (%s).\n"), L_SBLANKxSTR,
	    					szType, u->GetAlias(), u->IdString());

            u->SetTyping(ICQ_TYPING_INACTIVEx0);
            
	    if (szType) free(szType);
	    if (AddUserEvent(u, eEvent))
	      m_xOnEventManager.Do(nTypeEvent, u);
	    gUserManager.DropUser(u);
	    PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_TYPING, szId,
                                            LICQ_PPID));
            break;
	  }
	  case ICQ_CMDxSUB_AUTHxREQUEST:
	  case ICQ_CMDxSUB_AUTHxREFUSED:
	  case ICQ_CMDxSUB_AUTHxGRANTED:
	  case ICQ_CMDxSUB_MSGxSERVER:
	  case ICQ_CMDxSUB_ADDEDxTOxLIST:
	  case ICQ_CMDxSUB_WEBxPANEL:
	  case ICQ_CMDxSUB_EMAILxPAGER:
	  {
	    ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
	    if (AddUserEvent(o, eEvent))
	    {
	      gUserManager.DropOwner();
	      eEvent->AddToHistory(NULL, D_RECEIVER);
	      m_xOnEventManager.Do(ON_EVENT_SYSMSG, NULL);
	    }
	    else
	      gUserManager.DropOwner();
	    break;
	  }
	  case ICQ_CMDxSUB_SMS:
	  {
	    CEventSms *eSms = (CEventSms *)eEvent;
      //TODO
	    unsigned long nUinSms = FindUinByCellular(eSms->Number());

	    if (nUinSms != 0)
	    {
        //TODO
	      ICQUser* u = gUserManager.FetchUser(nUinSms, LOCK_W);
	      gLog.Info(tr("%sSMS from %s - %s (%lu).\n"), L_SBLANKxSTR, eSms->Number(), 
                  u->GetAlias(), nUinSms);
	      if (AddUserEvent(u, eEvent))
	        m_xOnEventManager.Do(ON_EVENT_SMS, u);
	      gUserManager.DropUser(u);
	    }
	    else
	    {
	      ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
	      gLog.Info(tr("%sSMS from %s.\n"), L_BLANKxSTR, eSms->Number());
	      if (AddUserEvent(o, eEvent))
	      {
	        gUserManager.DropOwner();
	        eEvent->AddToHistory(NULL, D_RECEIVER);
	        m_xOnEventManager.Do(ON_EVENT_SMS, NULL);
	      }
	      else
	        gUserManager.DropOwner();
	    }
	    break;
	  }
	}

      delete [] szMessage;
      break;
    }

    default:
      char *buf;

      gLog.Unknown(tr("%sMessage through server with unknown format: %04hx\n%s\n"),
				    L_ERRORxSTR, mFormat, packet.print(buf));
      delete [] buf;
      break;
    }
    delete [] szId;
    break;
  }
  case ICQ_SNACxMSG_SERVERxREPLYxMSG:
  {
		unsigned short nFormat, nLen, nSequence, nMsgType, nAckFlags, nMsgFlags;
		unsigned long nUin, nMsgID;
                CExtendedAck *pExtendedAck = 0;
		ICQUser *u = NULL;

	 	packet.incDataPosRead(4); // msg id
		nMsgID = packet.UnpackUnsignedLongBE(); // lower bits, what licq uses
		nFormat = packet.UnpackUnsignedShortBE();
		nUin = packet.UnpackUinString();

		u = gUserManager.FetchUser(nUin, LOCK_W);
		if (u == NULL)
		{
			gLog.Warn(tr("%sUnexpected new user in subtype 0x%04x.\n"), L_SRVxSTR,
								nSubtype);
			break;
		}

    pthread_mutex_lock(&mutex_reverseconnect);
    std::list<CReverseConnectToUserData *>::iterator iter;
    bool bFound = false;
    for (iter = m_lReverseConnect.begin(); iter != m_lReverseConnect.end();
                                           iter++)
    {
      if ((*iter)->nId == nMsgID && (*iter)->nUin == nUin)
      {
        gLog.Warn("%sReverse connection from %s failed.\n", L_WARNxSTR,
                  u->GetAlias());
        (*iter)->bSuccess = false;
        (*iter)->bFinished = true;
        bFound = true;
        break;
      }
    }
    pthread_mutex_unlock(&mutex_reverseconnect);
    
    int nSubResult;
    if (bFound)
    {
      nSubResult = ICQ_TCPxACK_REFUSE;
      pExtendedAck = NULL;
      pthread_cond_broadcast(&cond_reverseconnect_done);
      gUserManager.DropUser(u);
      return;
    }

    packet.incDataPosRead(2);
    packet >> nLen;
    if (nLen == 0x0200)
    {
      gLog.Warn(tr("%s%s doesn't have a manager for this event.\n"), L_WARNxSTR,
        u->GetAlias());
      gUserManager.DropUser(u);  
      
      ICQEvent *e = DoneServerEvent(nMsgID, EVENT_ERROR);
      if (e)
      {
        ProcessDoneEvent(e);
        return;
      }
      else
      {
        gLog.Warn(tr("%sAck for unknown event.\n"), L_SRVxSTR);
        break;
      }
    }
    
    packet.UnpackUnsignedShort(); //tcp version
    
    char GUID[GUID_LENGTH];
    for (unsigned short i = 0; i < GUID_LENGTH; i++)
      packet >> GUID[i];
    
    packet.incDataPosRead(nLen - GUID_LENGTH - 2);
    packet >> nLen;
    nSequence = packet.UnpackUnsignedShortBE();
    packet.incDataPosRead(nLen - 2);
    packet >> nMsgType;
    
    if (memcmp(GUID, PLUGIN_NORMAL, GUID_LENGTH) != 0)
    {
      unsigned char nChannel = ICQ_CHNxUNKNOWN;
      if (memcmp(GUID, PLUGIN_INFOxMANAGER, GUID_LENGTH) == 0)
        nChannel = ICQ_CHNxINFO;
      else if (memcmp(GUID, PLUGIN_STATUSxMANAGER, GUID_LENGTH) == 0)
        nChannel = ICQ_CHNxSTATUS;
        
      ProcessPluginMessage(packet, u, nChannel, true, 0, nMsgID, nSequence, 0);
      
      gUserManager.DropUser(u);
      break;
    }
    
    packet >> nAckFlags >> nMsgFlags >> nLen;
    
    char szMessage[nLen + 1];
    for (unsigned short i = 0; i < nLen; i++)
      packet >> szMessage[i];
    szMessage[nLen] = '\0';
    gTranslator.ServerToClient(szMessage);
    
    if (nAckFlags == ICQ_TCPxACK_REFUSE)
    {
      pExtendedAck = new CExtendedAck(false, 0, szMessage);
      nSubResult = ICQ_TCPxACK_REFUSE;
      gLog.Info(tr("%sRefusal from %s (#%lu).\n"), L_SRVxSTR, u->GetAlias(),
        nMsgID);
    }
    else
    {
      // Update the away message if it's changed
      if (strcmp(u->AutoResponse(), szMessage))
      {
        u->SetAutoResponse(szMessage);
        u->SetShowAwayMsg(*szMessage);
        gLog.Info(tr("%sAuto response from %s (#%lu).\n"), L_SRVxSTR,
          u->GetAlias(), nMsgID);
      }

      if (nMsgType != ICQ_CMDxTCP_READxAWAYxMSG &&
          nMsgType != ICQ_CMDxTCP_READxOCCUPIEDxMSG &&
          nMsgType != ICQ_CMDxTCP_READxNAxMSG &&
          nMsgType != ICQ_CMDxTCP_READxDNDxMSG &&
          nMsgType != ICQ_CMDxTCP_READxFFCxMSG &&
          nAckFlags != ICQ_TCPxACK_ACCEPT &&
          nAckFlags != ICQ_TCPxACK_OCCUPIED &&
          nAckFlags != ICQ_TCPxACK_DND)
      {
        nSubResult = ICQ_TCPxACK_REFUSE;
      }
      else
      {
        nSubResult = ICQ_TCPxACK_RETURN;
      }

      pExtendedAck = new CExtendedAck(nSubResult == ICQ_TCPxACK_RETURN, 0,
                                      szMessage);
    }
    gUserManager.DropUser(u);
    
    ICQEvent *e = DoneServerEvent(nMsgID, EVENT_ACKED);
    if (e)
    {
      e->m_pExtendedAck = pExtendedAck;
      e->m_nSubResult = nSubResult;
      ProcessDoneEvent(e);
      return;
    }
    else
    {
      gLog.Warn(tr("%sAck for unknown event.\n"), L_SRVxSTR);
      break;
    }

		break;
	}
	case ICQ_SNACxMSG_RIGHTSxGRANTED:
	{
		gLog.Info(tr("%sReceived rights for Instant Messaging..\n"), L_SRVxSTR);
		break;
	}
  case ICQ_SNACxMSG_SERVERxACK:
  {
    ICQEvent *e = DoneServerEvent(nSubSequence, EVENT_ACKED);
    if (e)
    {
	      e->m_nSubResult = ICQ_TCPxACK_ACCEPT;
      ProcessDoneEvent(e);
    }
      
    gLog.Info(tr("%sMessage was sent to an offline user. It will be delivered"
                " when the user logs on.\n"), L_SRVxSTR);

    break;
  }
  case ICQ_SNACxMSG_TYPING:
  {
    packet.UnpackUnsignedLongBE(); // timestamp
    packet.UnpackUnsignedLongBE(); // message id
    packet.UnpackUnsignedShortBE(); // format (only seen 1)
    const char *szId = packet.UnpackUserString();
    unsigned short nTyping = packet.UnpackUnsignedShortBE();

    ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
    if (u == NULL)
    {
      gLog.Warn(tr("%sTyping status received for unknown user (%s).\n"),
        L_WARNxSTR, szId);
      break;
    }
    u->SetTyping(nTyping);
    gUserManager.DropUser(u);
    PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_TYPING, szId,
                                    LICQ_PPID));
    break;
  }
	default:
	{
		gLog.Warn(tr("%sUnknown Message Family Subtype: %04hx\n"), L_SRVxSTR, nSubtype);
		break;
	}
	}
}

//--------ProcessListFam--------------------------------------------
void CICQDaemon::ProcessListFam(CBuffer &packet, unsigned short nSubtype)
{
  /*unsigned short nFlags = */packet.UnpackUnsignedShortBE();
  unsigned long nSubSequence = packet.UnpackUnsignedLongBE();

  switch (nSubtype)
  {
    case ICQ_SNACxLIST_RIGHTSxGRANTED:
    {
      gLog.Info(tr("%sServer granted Server Contact List.\n"), L_SRVxSTR);
      if (UseServerContactList())
      {
        gLog.Info(tr("%sRequesting Server Contact List.\n"), L_SRVxSTR);

        CSrvPacketTcp *p = new CPU_RequestList();
        SendEvent_Server(p);
      }
      break;
    }

    case ICQ_SNACxLIST_ROSTxREPLY:
    {
      static unsigned short nCount;
      unsigned short nPacketCount;
      unsigned long nTime;

      gLog.Info(tr("%sReceived contact list.\n"), L_SRVxSTR);

      m_bOnlineNotifies = true;

      packet.UnpackChar();  // unknown
      nPacketCount = packet.UnpackUnsignedShortBE();
      nCount += nPacketCount;

      for (unsigned short i = 0; i < nPacketCount; i++)
      {
        char *szId;
        unsigned short nTag, nID, nType, nByteLen;

        // Can't use UnpackUserString because this may be a group name
        szId = packet.UnpackStringBE();
        nTag = packet.UnpackUnsignedShortBE();
        nID = packet.UnpackUnsignedShortBE();
        nType = packet.UnpackUnsignedShortBE();
        nByteLen = packet.UnpackUnsignedShortBE();

        char *szUnicodeName = gTranslator.FromUnicode(szId);

        if (nByteLen)
        {
          if (!packet.readTLV(-1, nByteLen))
          {
            gLog.Error("%sUnable to parse contact list TLV, aborting!\n",
											 L_ERRORxSTR);
            delete[] szId;
            return;
          }
        }

        switch (nType)
        {
          case ICQ_ROSTxNORMAL:
          case ICQ_ROSTxVISIBLE:
          case ICQ_ROSTxINVISIBLE:
          case ICQ_ROSTxIGNORE:
          {
            char *szNewName = packet.UnpackStringTLV(0x0131);
            char *szSMSNumber = packet.UnpackStringTLV(0x013A);
            bool bAwaitingAuth = packet.hasTLV(0x0066);

            //unsigned long nUin = atoi(szName);
            unsigned short nInGroup = gUserManager.GetGroupFromID(nTag);
            bool isOnList = true;
            if (szId && !gUserManager.IsOnList(szId, LICQ_PPID))
            {
              isOnList = false;
              AddUserToList(szId, LICQ_PPID, false); // Don't notify server
            }

            char *szUnicodeAlias = gTranslator.FromUnicode(szNewName);

            ICQUser *u = gUserManager.FetchUser(szId, LICQ_PPID, LOCK_W);
            if (u)
            {
              u->SetGSID(nTag);

              if (szNewName)
              {
                if (szUnicodeName)
                {
                  u->SetAlias(szUnicodeAlias);
                }
              }

              if (szSMSNumber)
              {
                char *szUnicodeSMS = gTranslator.FromUnicode(szSMSNumber);
                if (szUnicodeSMS)
                {
                  u->SetCellularNumber(szUnicodeSMS);
                  delete [] szUnicodeSMS;
                }
              }

              u->SetAwaitingAuth(bAwaitingAuth);

              if (nType == ICQ_ROSTxINVISIBLE)
              {
                u->SetInvisibleList(true);
                u->SetInvisibleSID(nID);
              }
              else if (nType == ICQ_ROSTxVISIBLE)
              {
                u->SetVisibleList(true);
                u->SetVisibleSID(nID);
              }
              else if (nType == ICQ_ROSTxIGNORE)
              {
                u->SetSID(nID);
                u->SetIgnoreList(true);
              }
              else
              {
                u->SetSID(nID);
                u->AddToGroup(GROUPS_USER, nInGroup);
              }

              if (!isOnList)
              {
                // They aren't a new user if we added them to a server list
                u->SetNewUser(false);
              }

              gUserManager.DropUser(u);
            }

            if (!isOnList)
            {
              gLog.Info(tr("%sAdded %s (%s) to list from server.\n"), L_SRVxSTR,
                (szUnicodeAlias ? szUnicodeAlias : ""), szId);
            }

            if (szUnicodeAlias)
              delete [] szUnicodeAlias;
            if (szNewName)
              delete [] szNewName;
            if (szSMSNumber)
              delete [] szSMSNumber;

            break;
          }

          case ICQ_ROSTxGROUP:
          {
            if (szId[0] != '\0')
            {
              // Rename the group if we have it already or else add it
              unsigned short nGroup = gUserManager.GetGroupFromID(nTag);
              if (nGroup == gUserManager.NumGroups())
              {
                if (!gUserManager.AddGroup(szUnicodeName, nTag))
                  gUserManager.ModifyGroupID(szUnicodeName, nTag);
              }
              else
              {
                gUserManager.RenameGroup(nGroup, szUnicodeName, false);
              }
            }
            break;
          }
        }  // switch (nType)

        if (szUnicodeName)
          delete [] szUnicodeName;

        packet.cleanupTLV();
        delete[] szId;
      } // for count

      // Update local info about contact list
      nTime = packet.UnpackUnsignedLongBE();
      ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
      o->SetSSTime(nTime);
      o->SetSSCount(nCount);
      gUserManager.DropOwner();

      // Let's update server with local info!
      CheckExport();
      
      break;
    } // case rost reply

    case ICQ_SNACxLIST_ROSTxSYNCED:
    {
      // The server says we are up to date, let's double check
      CheckExport();
      break;
    }

    case ICQ_SNACxLIST_UPDxACK:
    {
      ICQEvent *e = DoneServerEvent(nSubSequence, EVENT_SUCCESS);

      if (e == NULL)
      {
        gLog.Warn(tr("%sServer list update ack without request.\n"), L_SRVxSTR);
        break;
      }

      CSrvPacketTcp *pReply = 0;
      bool bHandled = false;
      unsigned short nError = 0;

      do
      {
        pthread_mutex_lock(&mutex_modifyserverusers);
        char *szPending = m_lszModifyServerUsers.front();
        m_lszModifyServerUsers.pop_front();
        pthread_mutex_unlock(&mutex_modifyserverusers);

       unsigned long nUin = 0;
        if (szPending)
          nUin = atol(szPending);

        nError = packet.UnpackUnsignedShortBE();

        switch (nError)
        {
          case 0: break; // No error

          case 0x0E:
            gLog.Info(tr("%s%s added to awaiting authorization group on server list.\n"),
                       L_SRVxSTR, szPending);
            break;

          case 0x02:
            gLog.Warn(tr("%sUser/Group %s not found on server list.\n"),
                       L_WARNxSTR,szPending);
            break;

          default:
            gLog.Error(tr("%sUnknown error modifying server list: 0x%02X\n"),
                       L_ERRORxSTR, nError & 0xFF);
        }

        if (nError && nError != 0x0E)
          break;

        switch (e->SubType())
        {
          case ICQ_SNACxLIST_ROSTxADD:
          case ICQ_SNACxLIST_ROSTxREM:
          {
            if (nError == 0x0E && e->SubType() == ICQ_SNACxLIST_ROSTxADD)
            {
              // If we don't send this, we can still add them
              // without any known side effects
              // This has been put back, it didn't work 100%
              pReply = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
                ICQ_SNACxLIST_ROSTxEDITxEND);
              SendEvent_Server(pReply);
              if (szPending)
                icqAddUserServer(szPending, true);
              break;
            }

            bool bTopLevelUpdated = false;

            if (bHandled == false)
            {
              bHandled = true;
              int n = gUserManager.GetGroupFromID(e->ExtraInfo());
              if (n < 1 && e->ExtraInfo() != 0)
                break;


              GroupList *g = gUserManager.LockGroupList(LOCK_R);
              pthread_mutex_lock(&mutex_modifyserverusers);
              char *szGroupName = 0;
              if (e->ExtraInfo() == 0)
                szGroupName = strdup(tr("top level"));
              else
                szGroupName = strdup((*g)[n-1]);
              m_lszModifyServerUsers.push_back(szGroupName);
              pthread_mutex_unlock(&mutex_modifyserverusers);
              gUserManager.UnlockGroupList();

              if (e->ExtraInfo() == 0)
              {
                bTopLevelUpdated = true;
                pReply = new CPU_UpdateToServerList("", ICQ_ROSTxGROUP, 0);
                gLog.Info(tr("%sUpdating top level group.\n"), L_SRVxSTR);
              }
              else
              {
                pReply = new CPU_UpdateToServerList(szGroupName, ICQ_ROSTxGROUP,
                                                    e->ExtraInfo());
                gLog.Info(tr("%sUpdating group %s.\n"), L_SRVxSTR, szGroupName);
              }
              SendExpectEvent_Server(0, pReply, NULL);
            }


            // Skip the call to gUserManager.AddUserToGroup because
            // that will send a message out to the server AGAIN
            if (e->SubType() == ICQ_SNACxLIST_ROSTxADD && !bTopLevelUpdated)
            {
              ICQUser *u = gUserManager.FetchUser(szPending, LICQ_PPID, LOCK_R);
              if (u)
              {
                u->AddToGroup(GROUPS_USER, gUserManager.GetGroupFromID(
                              e->ExtraInfo()));
                gUserManager.DropUser(u);
                PushPluginSignal(new CICQSignal(SIGNAL_ADDxSERVERxLIST, 0,
                                                szPending, LICQ_PPID));
              }
            }

            break;
          }

          case ICQ_SNACxLIST_ROSTxUPD_GROUP:
          {
            if (bHandled == false)
            {
              bHandled = true;
              gLog.Info(tr("%sUpdated %s successfully.\n"), L_SRVxSTR,
                        szPending);
                
              if (nError == 0x0E)
              {
                pReply = new CPU_UpdateToServerList(szPending,
                  ICQ_ROSTxNORMAL, 0, true);
                pthread_mutex_lock(&mutex_modifyserverusers);
                m_lszModifyServerUsers.push_back(strdup(szPending));
                pthread_mutex_unlock(&mutex_modifyserverusers);
                SendExpectEvent_Server(0, pReply, NULL);
              }
            }

            break;
          }
        }
        free(szPending);
      } while (!packet.End());

      if (nError == 0)
      {
        pReply = new CPU_GenericFamily(ICQ_SNACxFAM_LIST,
                                       ICQ_SNACxLIST_ROSTxEDITxEND);
        SendEvent_Server(pReply);
      }

      break;
    }

    default:
      gLog.Warn(tr("%sUnknown List Family Subtype: %04hx\n"), L_SRVxSTR, nSubtype);
      break;
  } // switch subtype
}

//--------ProcessBosFam---------------------------------------------
void CICQDaemon::ProcessBOSFam(CBuffer &packet, unsigned short nSubtype)
{
  switch (nSubtype)
  {
  case ICQ_SNACxBOS_RIGHTSxGRANTED:
    gLog.Info(tr("%sReceived BOS rights.\n"), L_SRVxSTR);
    //icqSetStatus(m_nDesiredStatus);
    break;

  default:
    gLog.Warn(tr("%sUnknown BOS Family Subtype: %04hx\n"), L_SRVxSTR, nSubtype);
    break;
  }
}

//--------ProcessVariousFam-----------------------------------------
void CICQDaemon::ProcessVariousFam(CBuffer &packet, unsigned short nSubtype)
{
  /*unsigned long Flags =*/ packet.UnpackUnsignedLongBE();
  unsigned short nSubSequence = packet.UnpackUnsignedShortBE();
  char *tmp;

  switch (nSubtype)
  {
  case 0x0003: // multi-purpose sub-type
  {
    unsigned short nLen, nType, nId;

    if (!packet.readTLV()) {
      char *buf;
      gLog.Unknown(tr("%sUnknown server response:\n%s\n"), L_UNKNOWNxSTR,
         packet.print(buf));
      delete [] buf;
      break;
    }

    CBuffer msg = packet.UnpackTLV(0x0001);

    if (msg.Empty()) {
      char *buf;
      gLog.Unknown(tr("%sUnknown server response:\n%s\n"), L_UNKNOWNxSTR,
         packet.print(buf));
      delete [] buf;
      break;
    }

    nLen = msg.UnpackUnsignedShortBE();
    msg.UnpackUnsignedLong(); // own UIN
    nType = msg.UnpackUnsignedShort();
    nId = msg.UnpackUnsignedShortBE(); // req-id, which we use to match requests for info and replies

    switch(nType) {
    case 0x0041:
    {
      struct tm sendTM;
      unsigned long nUin;
      unsigned long nTimeSent;
      
      nUin = msg.UnpackUnsignedLong();

      sendTM.tm_year = msg.UnpackUnsignedShort() - 1900;
      sendTM.tm_mon = msg.UnpackChar() - 1;
      sendTM.tm_mday = msg.UnpackChar();
      sendTM.tm_hour = msg.UnpackChar();
      sendTM.tm_min = msg.UnpackChar();
      sendTM.tm_sec = 0;
      sendTM.tm_isdst = -1;

      ICQOwner *o = gUserManager.FetchOwner(LOCK_R);
      nTimeSent = mktime(&sendTM) - o->SystemTimeGMTOffset();
      gUserManager.DropOwner();
      
      // Msg type & flags
      unsigned short nTypeMsg = msg.UnpackUnsignedShort();
      unsigned long nMask = ((nTypeMsg & ICQ_CMDxSUB_FxMULTIREC) ? E_MULTIxREC : 0);
      nTypeMsg &= ~ICQ_CMDxSUB_FxMULTIREC;
      
      char* szMessage = new char[msg.getDataMaxSize()];
      // 2 byte length little endian + string
      msg.UnpackString(szMessage, msg.getDataMaxSize());      
      char *szType = NULL;
      unsigned short nTypeEvent = 0;
      CUserEvent *eEvent = NULL;
            
      switch(nTypeMsg)
      {
        case ICQ_CMDxSUB_MSG:
	{
          CEventMsg *e = CEventMsg::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, nMask);
	  szType = strdup(tr("Message"));
	  nTypeEvent = ON_EVENT_MSG;
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_URL:
	{
          CEventUrl *e = CEventUrl::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, nMask);
	  if (e == NULL)
	  {
	    char *buf;
	    
	    gLog.Warn(tr("%sInvalid offline URL message:\n%s\n"), L_WARNxSTR, packet.print(buf));
	    delete [] buf;
	    break;
	  }
	  szType = strdup(tr("URL"));
	  nTypeEvent = ON_EVENT_URL;
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_AUTHxREQUEST:
	{
	  gLog.Info(tr("%sOffline authorization request from %lu.\n"), L_SBLANKxSTR, nUin);
	  
	  char **szFields = new char *[6];  // alias, first name, last name, email, auth, comment
          
	  if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;
	    
            gLog.Warn(tr("%sInvalid offline authorization request system message:\n%s\n"), L_WARNxSTR,
		      packet.print(buf));
	    delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient (szFields[0]);  // alias
          gTranslator.ServerToClient (szFields[1]);  // first name
          gTranslator.ServerToClient (szFields[2]);  // last name
          gTranslator.ServerToClient (szFields[5]);  // comment

          CEventAuthRequest *e = new CEventAuthRequest(nUin, szFields[0], szFields[1],
                                                       szFields[2], szFields[3], szFields[5],
                                            	       ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, 0);
	  delete [] szFields;	
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_AUTHxREFUSED:  // system message: authorization refused
        {
          gLog.Info(tr("%sOffline authorization refused by %lu.\n"), L_SBLANKxSTR, nUin);

          // Translating string with Translation Table
          gTranslator.ServerToClient(szMessage);

          CEventAuthRefused *e = new CEventAuthRefused(nUin, szMessage, ICQ_CMDxRCV_SYSxMSGxOFFLINE,
						       nTimeSent, 0);
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_AUTHxGRANTED:  // system message: authorized
        {
          gLog.Info(tr("%sOffline authorization granted by %lu.\n"), L_SBLANKxSTR, nUin);

          // translating string with Translation Table
          gTranslator.ServerToClient (szMessage);

          ICQUser *u = gUserManager.FetchUser(nUin, LOCK_W);
          if (u)
          {
            u->SetAwaitingAuth(false);
            gUserManager.DropUser(u);
          }

          CEventAuthGranted *e = new CEventAuthGranted(nUin, szMessage, ICQ_CMDxRCV_SYSxMSGxOFFLINE,
                                                       nTimeSent, 0);
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_MSGxSERVER:
	{
	  gLog.Info(tr("%sOffline server message.\n"), L_BLANKxSTR);
	  
	  CEventServerMessage *e = CEventServerMessage::Parse(szMessage, ICQ_CMDxSUB_MSGxSERVER, nTimeSent, nMask);
	  if (e == NULL)
	  {
	    char *buf;

	    gLog.Warn(tr("%sInvalid Server Message:\n%s\n"), L_WARNxSTR, packet.print(buf));
	    delete [] buf;
	    break;
	  }
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_ADDEDxTOxLIST:  // system message: added to a contact list
        {
          gLog.Info(tr("%sUser %lu added you to their contact list (offline).\n"), L_SBLANKxSTR, nUin);

          char **szFields = new char *[6]; // alias, first name, last name, email, auth, comment
          
	  if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;
	    
            gLog.Warn(tr("%sInvalid offline added to list system message:\n%s\n"), L_WARNxSTR,
                      packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient (szFields[0]);  // alias
          gTranslator.ServerToClient (szFields[1]);  // first name
          gTranslator.ServerToClient (szFields[2]);  // last name

          CEventAdded *e = new CEventAdded(nUin, szFields[0], szFields[1],
                                           szFields[2], szFields[3],
                                           ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, 0);
	  delete [] szFields;	
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_WEBxPANEL:
        {
          gLog.Info(tr("%sOffline message through web panel.\n"), L_SBLANKxSTR);

          char **szFields = new char *[6];	// name, ?, ?, email, ?, message
        
	  if (!ParseFE(szMessage, &szFields, 6))
          {
    	    char *buf;
	    
            gLog.Warn(tr("%sInvalid offline web panel system message:\n%s\n"), L_WARNxSTR,
                      packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

          // translating string with Translation Table
          gTranslator.ServerToClient(szFields[0]);  // name
          gTranslator.ServerToClient(szFields[3]);  // email
          gTranslator.ServerToClient(szFields[5]);  // message

          gLog.Info(tr("%sFrom %s (%s).\n"), L_SBLANKxSTR, szFields[0], szFields[3]);
          CEventWebPanel *e = new CEventWebPanel(szFields[0], szFields[3], szFields[5],
                                                 ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, 0);
          delete [] szFields;	
          eEvent = e;
          break;
    }
	case ICQ_CMDxSUB_EMAILxPAGER:
        {
          gLog.Info(tr("%sEmail pager offline message.\n"), L_SBLANKxSTR);

          char **szFields = new char *[6];	// name, ?, ?, email, ?, message
        
	  if (!ParseFE(szMessage, &szFields, 6))
          {
            char *buf;

            gLog.Warn(tr("%sInvalid offline email pager system message:\n%s\n"), L_WARNxSTR,
		      packet.print(buf));
            delete [] buf;
            delete [] szFields;
            break;
          }

	  // translating string with Translation Table
          gTranslator.ServerToClient(szFields[0]);  // name
          gTranslator.ServerToClient(szFields[3]);  // email
          gTranslator.ServerToClient(szFields[5]);  // message

          gLog.Info(tr("%sFrom %s (%s).\n"), L_SBLANKxSTR, szFields[0], szFields[3]);
          CEventEmailPager *e = new CEventEmailPager(szFields[0], szFields[3], szFields[5],
                                                     ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, 0);
	  delete [] szFields;	
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_CONTACTxLIST:
        {
	  CEventContactList *e = CEventContactList::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxOFFLINE, nTimeSent, nMask);
          if (e == NULL)
          {
            char *buf;
 
            gLog.Warn(tr("%sInvalid offline Contact List message:\n%s\n"), L_WARNxSTR,
		      packet.print(buf));
            delete [] buf;
            break;
          }
	  szType = strdup(tr("Contacts"));
	  nTypeEvent = ON_EVENT_MSG;
	  eEvent = e;
	  break;
	}
	case ICQ_CMDxSUB_SMS:
	{
	  CEventSms *e = CEventSms::Parse(szMessage, ICQ_CMDxRCV_SYSxMSGxONLINE, nTimeSent, nMask);
	  if (e == NULL)
          {
	    char *buf;

	    gLog.Warn(tr("%sInvalid SMS message:\n%s\n"), L_WARNxSTR, packet.print(buf));
	    delete [] buf;
	    break;
	  }
	  eEvent = e;
	  break;
	}
	default:
	{
	  char *szFE, *buf;

	  while ((szFE = strchr(szMessage, 0xFE)) != NULL) *szFE = '\n';
	  
          gLog.Unknown("%sUnknown offline system message (0x%04x):\n%s\n", L_UNKNOWNxSTR,
                       nTypeMsg, packet.print(buf));
          delete [] buf;
          CEventUnknownSysMsg *e = new CEventUnknownSysMsg(nTypeMsg, ICQ_CMDxRCV_SYSxMSGxOFFLINE,
                                                           nUin, szMessage, nTimeSent, 0);
          
	  ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          AddUserEvent(o, e);
          gUserManager.DropOwner();
	}
      }

      if (eEvent)
        switch(nTypeMsg)
        {
	  case ICQ_CMDxSUB_MSG:
	  case ICQ_CMDxSUB_URL:
	  case ICQ_CMDxSUB_CONTACTxLIST:
	  {
    	    // Lock the user to add the message to their queue
    	    ICQUser* u = gUserManager.FetchUser(nUin, LOCK_W);
    	    if (u == NULL)
    	    {
    	      if (Ignore(IGNORE_NEWUSERS))
    	      {
        	gLog.Info(tr("%sOffline %s from new user (%lu), ignoring.\n"), L_SBLANKxSTR, szType, nUin);
		if (szType) free(szType);
        	RejectEvent(nUin, eEvent);
        	break;
    	      }
    	      gLog.Info(tr("%sOffline %s from new user (%lu).\n"), L_SBLANKxSTR, szType, nUin);
    	      AddUserToList(nUin);
    	      u = gUserManager.FetchUser(nUin, LOCK_W);
    	    }
    	    else
    	      gLog.Info(tr("%sOffline %s through server from %s (%lu).\n"), L_SBLANKxSTR,
                        szType, u->GetAlias(), nUin);

            if (szType) free(szType);
    	    if (AddUserEvent(u, eEvent))
    	      m_xOnEventManager.Do(nTypeEvent, u);
    	    gUserManager.DropUser(u);
	    break;
	  }
	  case ICQ_CMDxSUB_AUTHxREQUEST:
	  case ICQ_CMDxSUB_AUTHxREFUSED:
	  case ICQ_CMDxSUB_AUTHxGRANTED:
	  case ICQ_CMDxSUB_MSGxSERVER:
	  case ICQ_CMDxSUB_ADDEDxTOxLIST:
	  case ICQ_CMDxSUB_WEBxPANEL:
	  case ICQ_CMDxSUB_EMAILxPAGER:
	  {
	    ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
            if (AddUserEvent(o, eEvent))
	    {
              gUserManager.DropOwner();
              eEvent->AddToHistory(NULL, D_RECEIVER);
              m_xOnEventManager.Do(ON_EVENT_SYSMSG, NULL);
	    }
	    else
	      gUserManager.DropOwner();
            break;
	  }
	  case ICQ_CMDxSUB_SMS:
	  {
	    CEventSms *eSms = (CEventSms *)eEvent; 
	    unsigned long nUinSms = FindUinByCellular(eSms->Number());
	    
	    if (nUinSms != 0)
	    {
	      ICQUser* u = gUserManager.FetchUser(nUinSms, LOCK_W);
	      gLog.Info(tr("%sOffline SMS from %s - %s (%lu).\n"), L_SBLANKxSTR, eSms->Number(), u->GetAlias(), nUin);
	      if (AddUserEvent(u, eEvent))
	        m_xOnEventManager.Do(ON_EVENT_SMS, u);
	      gUserManager.DropUser(u);
	    }
	    else
	    {  
	      ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
	      gLog.Info(tr("%sOffline SMS from %s.\n"), L_BLANKxSTR, eSms->Number());
	      if (AddUserEvent(o, eEvent))
	      {
	        gUserManager.DropOwner();
	        eEvent->AddToHistory(NULL, D_RECEIVER);
	        m_xOnEventManager.Do(ON_EVENT_SMS, NULL);
	      }
	      else
	        gUserManager.DropOwner();
	    }
	    break;
	  }
	}

      delete [] szMessage;
      break;
    }
    case 0x0042:
    {
      gLog.Info(tr("%sEnd of Offline messages (nId: %04hx).\n"), L_SRVxSTR, nId);
      CSrvPacketTcp* p = new CPU_SysMsgDoneAck(nId);
      SendEvent_Server(p);

      break;
    }
    case 0x07DA:
    {
      unsigned short nSubtype;
      unsigned char nResult;
      ICQEvent *pEvent = NULL;
      nSubtype = msg.UnpackUnsignedShort();
      nResult = msg.UnpackChar();
      char *szType = NULL;

      if (nSubtype == ICQ_CMDxMETA_PASSWORDxRSP)
      {
        szType = strdup(tr("Password change"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);
        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          o->SetPassword(((CPU_SetPassword *)pEvent->m_pPacket)->m_szPassword);
          o->SetEnableSave(true);
          o->SaveLicqInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_SECURITYxRSP)
      {
        szType = strdup(tr("Security info"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetSecurityInfo *p = (CPU_Meta_SetSecurityInfo *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          o->SetAuthorization(p->Authorization());
          o->SetWebAware(p->WebAware());
          o->SetHideIp(p->HideIp());
          o->SetEnableSave(true);
          o->SaveLicqInfo();
          unsigned short s = o->StatusFull();
          gUserManager.DropOwner();

          // Set status to ensure the status flags are set
          icqSetStatus(s);
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_GENERALxINFOxRSP)
      {
        szType = strdup(tr("General info"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetGeneralInfo *p = (CPU_Meta_SetGeneralInfo *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          o->SetAlias(p->m_szAlias);
          o->SetFirstName(p->m_szFirstName);
          o->SetLastName(p->m_szLastName);
          o->SetEmailPrimary(p->m_szEmailPrimary);
          o->SetCity(p->m_szCity);
          o->SetState(p->m_szState);
          o->SetPhoneNumber(p->m_szPhoneNumber);
          o->SetFaxNumber(p->m_szFaxNumber);
          o->SetAddress(p->m_szAddress);
          o->SetCellularNumber(p->m_szCellularNumber);
          o->SetZipCode(p->m_szZipCode);
          o->SetCountryCode(p->m_nCountryCode);
          o->SetTimezone(p->m_nTimezone);
          o->SetHideEmail(p->m_nHideEmail); // 0 = no, 1 = yes

          // translating string with Translation Table
          gTranslator.ServerToClient(o->GetAlias());
          gTranslator.ServerToClient(o->GetFirstName());
          gTranslator.ServerToClient(o->GetLastName());
          gTranslator.ServerToClient(o->GetEmailPrimary());
          gTranslator.ServerToClient(o->GetCity());
          gTranslator.ServerToClient(o->GetState());
          gTranslator.ServerToClient(o->GetPhoneNumber());
          gTranslator.ServerToClient(o->GetFaxNumber());
          gTranslator.ServerToClient(o->GetAddress());
          gTranslator.ServerToClient(o->GetCellularNumber());
          gTranslator.ServerToClient(o->GetZipCode());

          // save the user infomation
          o->SetEnableSave(true);
          o->SaveGeneralInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_EMAILxINFOxRSP)
      {
        szType = strdup(tr("E-mail info"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetEmailInfo *p = (CPU_Meta_SetEmailInfo *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          o->SetEmailSecondary(p->m_szEmailSecondary);
          o->SetEmailOld(p->m_szEmailOld);

          // translating string with Translation Table
          gTranslator.ServerToClient(o->GetEmailSecondary());
          gTranslator.ServerToClient(o->GetEmailOld());

          // save the user infomation
          o->SetEnableSave(true);
          o->SaveGeneralInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_MORExINFOxRSP)
      {
        szType = strdup(tr("More info"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetMoreInfo *p = (CPU_Meta_SetMoreInfo *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          o->SetAge(p->m_nAge);
          o->SetGender(p->m_nGender);
          o->SetHomepage(p->m_szHomepage);
          o->SetBirthYear(p->m_nBirthYear);
          o->SetBirthMonth(p->m_nBirthMonth);
          o->SetBirthDay (p->m_nBirthDay);
          o->SetLanguage1(p->m_nLanguage1);
          o->SetLanguage2(p->m_nLanguage2);
          o->SetLanguage3(p->m_nLanguage3);

          // translating string with Translation Table
          gTranslator.ServerToClient(o->GetHomepage());

          // save the user infomation
          o->SetEnableSave(true);
          o->SaveMoreInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_INTERESTSxINFOxRSP)
      {
        szType = strdup("Interests info");
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetInterestsInfo *p =
                           (CPU_Meta_SetInterestsInfo *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          unsigned short cat;
          const char *descr;
          o->m_Interests->Clean();
          for (int i = 0; p->m_Interests->Get(i, &cat, &descr); i++)
          {
            char *tmp = strdup(descr);
            gTranslator.ServerToClient(tmp);
            o->m_Interests->AddCategory(cat, tmp);
            free(tmp);
          }
          o->SetEnableSave(true);
          o->SaveInterestsInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_WORKxINFOxRSP)
      {
        szType = strdup(tr("Work info"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetWorkInfo *p = (CPU_Meta_SetWorkInfo *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetEnableSave(false);
          o->SetCompanyCity(p->m_szCity);
          o->SetCompanyState(p->m_szState);
          o->SetCompanyPhoneNumber(p->m_szPhoneNumber);
          o->SetCompanyFaxNumber(p->m_szFaxNumber);
          o->SetCompanyAddress(p->m_szAddress);
          o->SetCompanyZip(p->m_szZip);
          o->SetCompanyCountry(p->m_nCompanyCountry);
          o->SetCompanyName(p->m_szName);
          o->SetCompanyDepartment(p->m_szDepartment);
          o->SetCompanyPosition(p->m_szPosition);
          o->SetCompanyOccupation(p->m_nCompanyOccupation);
          o->SetCompanyHomepage(p->m_szHomepage);

          // translating string with Translation Table
          gTranslator.ServerToClient(o->GetCompanyCity());
          gTranslator.ServerToClient(o->GetCompanyState());
          gTranslator.ServerToClient(o->GetCompanyPhoneNumber());
          gTranslator.ServerToClient(o->GetCompanyFaxNumber());
          gTranslator.ServerToClient(o->GetCompanyAddress());
          gTranslator.ServerToClient(o->GetCompanyZip());
          gTranslator.ServerToClient(o->GetCompanyName());
          gTranslator.ServerToClient(o->GetCompanyDepartment());
          gTranslator.ServerToClient(o->GetCompanyPosition());
          gTranslator.ServerToClient(o->GetCompanyHomepage());

          // save the user infomation
          o->SetEnableSave(true);
          o->SaveWorkInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_ABOUTxRSP)
      {
        szType = strdup(tr("About"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          CPU_Meta_SetAbout *p = (CPU_Meta_SetAbout *)pEvent->m_pPacket;
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          char* msg = gTranslator.RNToN(p->m_szAbout);
          o->SetEnableSave(false);
          o->SetAbout(msg);
          delete [] msg;

          // translating string with Translation Table
          gTranslator.ServerToClient(o->GetAbout());

          // save the user infomation
          o->SetEnableSave(true);
          o->SaveAboutInfo();
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_SENDxSMSxRSP)
      {
        // this one sucks, it could be sms or organization response
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL &&
            pEvent->m_pPacket->SubCommand() == ICQ_CMDxMETA_ORGBACKxINFOxSET)
        {
          szType = strdup("Organizations/Background info");

          if (nResult == META_SUCCESS)
          {
            CPU_Meta_SetOrgBackInfo *p =
                             (CPU_Meta_SetOrgBackInfo *)pEvent->m_pPacket;
            ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
            o->SetEnableSave(false);
            unsigned short cat;
            const char *descr;
            o->m_Organizations->Clean();
            for (int i = 0; p->m_Orgs->Get(i, &cat, &descr); i++)
            {
              char *tmp = strdup(descr);
              gTranslator.ServerToClient(tmp);
              o->m_Organizations->AddCategory(cat, tmp);
              free(tmp);
            }
            o->SetEnableSave(true);
            o->SaveOrganizationsInfo();

            o->m_Backgrounds->Clean();
            for (int i = 0; p->m_Background->Get(i, &cat, &descr); i++)
            {
              char *tmp = strdup(descr);
              gTranslator.ServerToClient(tmp);
              o->m_Backgrounds->AddCategory(cat, tmp);
              free(tmp);
            }
            o->SetEnableSave(true);
            o->SaveBackgroundsInfo();
            gUserManager.DropOwner();
          }
        }
        else if (pEvent != NULL &&
                pEvent->m_pPacket->SubCommand() == ICQ_CMDxMETA_SENDxSMS)
        {
          char *szTag, *szXml, *szSmsResponse;
  
          msg.UnpackUnsignedShortBE();
          msg.UnpackUnsignedShortBE();
          msg.UnpackUnsignedShortBE();
  
          szTag = msg.UnpackStringBE();
          szXml = msg.UnpackStringBE();
          szSmsResponse = GetXmlTag(szXml, "sms_response");
  
          if (szSmsResponse != NULL)
          {
            char *szDeliverable;
            szDeliverable = GetXmlTag(szSmsResponse, "deliverable");
  
            if (szDeliverable != NULL)
            {
              if (!strcmp(szDeliverable, "Yes"))
              {
                gLog.Info(tr("%sSMS delivered.\n"), L_SRVxSTR);
                if (pEvent)
                {
                  pEvent->m_eResult = EVENT_SUCCESS;
                  ProcessDoneEvent(pEvent);
                }
              }
              else if (!strcmp(szDeliverable, "No"))
              {
                char *szId, *szParam;
  
                szId = GetXmlTag(szSmsResponse, "id");
                szParam = GetXmlTag(szSmsResponse, "param");
                gLog.Warn(tr("%sSMS not delivered, error #%s, param: %s\n"),
                  L_SRVxSTR, szId, szParam);
  
                if (szId != NULL) free(szId);
                if (szParam != NULL) free(szParam);
                if (pEvent)
                {
                  pEvent->m_eResult = EVENT_FAILED;
                  ProcessDoneEvent(pEvent);
                }
              }
              else if (!strcmp(szDeliverable, "SMTP"))
              {
                char *szFrom, *szTo, *szSubject;
  
                szFrom = GetXmlTag(szSmsResponse, "from");
                szTo = GetXmlTag(szSmsResponse, "to");
                szSubject = GetXmlTag(szSmsResponse, "subject");
                gLog.Info(tr("%sSending SMS via SMTP not supported yet.\n"),
                  L_SRVxSTR);
  
                if (szFrom != NULL)
                {
                  gLog.Info(tr("%sFrom: %s\n"), L_SRVxSTR, szFrom);
                  free(szFrom);
                }
  
                if (szTo != NULL)
                {
                  gLog.Info(tr("%sTo: %s\n"), L_SRVxSTR, szTo);
                  free(szTo);
                }
  
                if (szSubject != NULL)
                {
                  gLog.Info(tr("%sSubject: %s\n"), L_SRVxSTR, szSubject);
                  free(szSubject);
                }
  
                if (pEvent)
                {
                  pEvent->m_eResult = EVENT_FAILED;
                  ProcessDoneEvent(pEvent);
                }
              }
              else
              {
                char *buf;
                gLog.Info(tr("%sUnknown SMS response:\n%s"), L_UNKNOWNxSTR,
                          packet.print(buf));
  
                delete [] buf;
  
                if (pEvent)
                {
                  pEvent->m_eResult = EVENT_FAILED;
                  ProcessDoneEvent(pEvent);
                }
              }
  
              free(szDeliverable);
            }
            else
            {
              gLog.Info(tr("%sUndeliverable SMS.\n"), L_SRVxSTR);
              if (pEvent)
              {
                pEvent->m_eResult = EVENT_FAILED;
                ProcessDoneEvent(pEvent);
              }
            }
  
            free(szSmsResponse);
          }
  
          delete [] szTag;
          delete [] szXml;
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_SETxRANDxCHATxRSP)
      {
        szType = strdup(tr("Random chat group"));
        pEvent = DoneServerEvent(nSubSequence,
          nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (pEvent != NULL && nResult == META_SUCCESS)
        {
          ICQOwner *o = gUserManager.FetchOwner(LOCK_W);
          o->SetRandomChatGroup(((CPU_SetRandomChatGroup *)pEvent->m_pPacket)->Group());
          gUserManager.DropOwner();
        }
      }
      else if (nSubtype == ICQ_CMDxMETA_RANDOMxUSERxRSP)
      {
        ICQEvent *e = DoneServerEvent(nSubSequence,
                        nResult == META_SUCCESS ? EVENT_SUCCESS : EVENT_FAILED);

        if (e != NULL && nResult == META_SUCCESS)
        {
          unsigned long nUin, nIp;
          char nMode;
          msg >> nUin;
          gLog.Info(tr("%sRandom chat user found (%lu).\n"), L_SRVxSTR, nUin);
          ICQUser *u = gUserManager.FetchUser(nUin, LOCK_W);
          bool bNewUser = false;
          if (u == NULL)
          {
             u = new ICQUser(nUin);
             bNewUser = true;
          }

          msg.UnpackUnsignedShort(); // chat group

          nIp = msg.UnpackUnsignedLongBE();
          nIp = PacketIpToNetworkIp(nIp);
          u->SetIpPort(nIp, msg.UnpackUnsignedLong());

          nIp = msg.UnpackUnsignedLongBE();
          nIp = PacketIpToNetworkIp(nIp);
          u->SetIntIp(nIp);

          msg >> nMode;
          u->SetMode(nMode);
          if (nMode != MODE_DIRECT)
            u->SetSendServer(true);

          u->SetVersion(msg.UnpackUnsignedShort());

          gUserManager.DropUser(u);

          if (bNewUser)
          {
            AddUserToList(nUin);
            icqRequestMetaInfo(nUin);
          }

          e->m_pSearchAck = new CSearchAck(nUin);
        }
        else
          gLog.Info(tr("%sNo random chat user found.\n"), L_SRVxSTR);
        ProcessDoneEvent(e);
      }
      else if (nSubtype == 0x0001)
      {
        ICQEvent *e = DoneServerEvent(nSubSequence, EVENT_FAILED);
        gLog.Info(tr("%sSMS failed to send.\n"), L_SRVxSTR);
        if (e != NULL)
        ProcessDoneEvent(e);
      }
      // Search results need to be processed differently
      else if (nSubtype == 0x0190 || nSubtype == 0x019a ||
               nSubtype == 0x01a4 || nSubtype == 0x01ae)
      {
        ICQEvent *e = NULL;

        if (nResult == 0x32) // No results found
        {
          gLog.Info(tr("%sWhitePages search found no users.\n"), L_SRVxSTR);
          e = DoneExtendedServerEvent(nSubSequence, EVENT_SUCCESS);
          ICQEvent *e2 = new ICQEvent(e);
          e2->m_pSearchAck = NULL; // Search ack is null lets plugins know no results found
          e2->m_nCommand = ICQ_CMDxSND_META;
          e2->m_nSubCommand = ICQ_CMDxMETA_SEARCHxWPxLAST_USER;
          PushPluginEvent(e2);
          DoneEvent(e, EVENT_SUCCESS);break;
        }

        e = DoneExtendedServerEvent(nSubSequence, EVENT_ACKED);
        if (e == NULL)
        {
          gLog.Warn("%sUnmatched extended event (%d)!\n", L_WARNxSTR, nSubSequence);
          break;
        }

        unsigned long nFoundUin;
        char szTemp[64];

        msg.UnpackUnsignedShort(); // length of the rest of the packet.
        nFoundUin = msg.UnpackUnsignedLong();
        CSearchAck *s = new CSearchAck(nFoundUin);;

        s->m_szAlias = strdup(msg.UnpackString(szTemp, sizeof(szTemp)));
        s->m_szFirstName = strdup(msg.UnpackString(szTemp, sizeof(szTemp)));
        s->m_szLastName = strdup(msg.UnpackString(szTemp, sizeof(szTemp)));
        s->m_szEmail = strdup(msg.UnpackString(szTemp, sizeof(szTemp)));
        s->m_nAuth = msg.UnpackChar(); // authorization required
        s->m_nStatus = msg.UnpackChar();
        msg.UnpackChar(); // unknown
        s->m_nGender = msg.UnpackChar(); // gender
        s->m_nAge = msg.UnpackChar(); // age
        msg.UnpackChar(); // unknown

        // translating string with Translation Table
        gTranslator.ServerToClient(s->m_szAlias);
        gTranslator.ServerToClient(s->m_szFirstName);
        gTranslator.ServerToClient(s->m_szLastName);

        gLog.Info("%s%s (%lu) <%s %s, %s>\n", L_SBLANKxSTR, s->m_szAlias, nFoundUin,
                  s->m_szFirstName, s->m_szLastName, s->m_szEmail);

        ICQEvent *e2 = new ICQEvent(e);
        // JON: Hack it so it is backwards compatible with plugins for now.
        e2->m_nCommand = ICQ_CMDxSND_META;
        e2->m_pSearchAck = s;
        if (nSubtype & 0x0008)
        {
          unsigned long nMore = 0;
          e2->m_nSubCommand = ICQ_CMDxMETA_SEARCHxWPxLAST_USER;
          nMore = msg.UnpackUnsignedLong();
          e2->m_pSearchAck->m_nMore = nMore;
          e2->m_eResult = EVENT_SUCCESS;
        }
        else
        {
          e2->m_nSubCommand = ICQ_CMDxMETA_SEARCHxWPxFOUND;
          e2->m_pSearchAck->m_nMore = 0;
        }

        PushPluginEvent(e2);

        if (nSubtype & 0x0008)
          DoneEvent(e, EVENT_SUCCESS); // Remove it from the running event list
        else
          PushExtendedEvent(e);
      }
      else
      {
        ICQEvent *e = NULL;
        ICQUser *u = NULL;
        unsigned long nUin = 0;
        bool multipart = false;

        if ((nResult == 0x32) || (nResult == 0x14) || (nResult == 0x1e))
        {
          // error: empty result or nonexistent user (1E =  readonly???)
          gLog.Warn(tr("%sFailed to update user info: %x.\n"), L_WARNxSTR, nResult);
          e = DoneExtendedServerEvent(nSubSequence, EVENT_FAILED);
          if (e)
          {
            DoneEvent(e, EVENT_FAILED);
            ProcessDoneEvent(e);
          }
          e = NULL;
          break;
        }
        else
        {
          // Find the relevant event
          e = DoneExtendedServerEvent(nSubSequence, EVENT_SUCCESS);
          if (e == NULL)
          {
            gLog.Warn("%sUnmatched extended event (%d)!\n", L_WARNxSTR, nSubSequence);
              break;
          }
          nUin = e->Uin();

          u = FindUserForInfoUpdate( nUin, e, "extended");
          if (u == NULL)
          {
            gLog.Warn(tr("%scan't find user for updating!\n"), L_WARNxSTR);
            break;
          }
        }

        switch (nSubtype)
        {
        case ICQ_CMDxMETA_GENERALxINFO:
        {   
          gLog.Info(tr("%sGeneral info on %s (%lu).\n"), L_SRVxSTR, u->GetAlias(), u->Uin());

          // main home info
          u->SetEnableSave(false);
          if (u->m_bKeepAliasOnUpdate)
            tmp = msg.UnpackString(); // Skip the alias, user wants to keep his own.
          else
            u->SetAlias( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetFirstName( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetLastName( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetEmailPrimary( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCity( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetState( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetPhoneNumber( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetFaxNumber( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetAddress( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCellularNumber( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetZipCode( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCountryCode( msg.UnpackUnsignedShort() );
          u->SetTimezone( msg.UnpackChar() );
          u->SetAuthorization( !msg.UnpackChar() );
          unsigned char nStatus = msg.UnpackChar(); // Web aware status

          if (u->Uin() == gUserManager.OwnerUin())
          {
            static_cast<ICQOwner *>(u)->SetWebAware(nStatus);
            /* this unpack is inside the if statement since it appears only
               for the owner request */
            u->SetHideEmail( msg.UnpackChar() );
          }
          else
          {
          /* TODO maybe implement web aware (could be useful for viewing info of
             users not on contact list) */
          }

/*
          unsigned short tmp = msg.UnpackChar();
          if (tmp)
            gLog.Error("%sConnection flags??? %x\n", L_ERRORxSTR, cf); */
 
          // translating string with Translation Table
          gTranslator.ServerToClient(u->GetAlias());
          gTranslator.ServerToClient(u->GetFirstName());
          gTranslator.ServerToClient(u->GetLastName());
          gTranslator.ServerToClient(u->GetEmailPrimary());
          gTranslator.ServerToClient(u->GetCity());
          gTranslator.ServerToClient(u->GetState());
          gTranslator.ServerToClient(u->GetPhoneNumber());
          gTranslator.ServerToClient(u->GetFaxNumber());
          gTranslator.ServerToClient(u->GetAddress());
          gTranslator.ServerToClient(u->GetCellularNumber());
          gTranslator.ServerToClient(u->GetZipCode());

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveGeneralInfo();

          PushExtendedEvent(e);
          multipart = true;

          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_GENERAL, u->Uin()));
          break;
        }
        case ICQ_CMDxMETA_MORExINFO:
        {
          gLog.Info(tr("%sMore info on %s (%lu).\n"), L_SRVxSTR, u->GetAlias(), u->Uin());

          u->SetEnableSave(false);
          u->SetAge( msg.UnpackUnsignedShort() );
          u->SetGender( msg.UnpackChar() );
          u->SetHomepage( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetBirthYear( msg.UnpackUnsignedShort() );
          u->SetBirthMonth( msg.UnpackChar() );
          u->SetBirthDay (msg.UnpackChar() );
          u->SetLanguage1( msg.UnpackChar() );
          u->SetLanguage2( msg.UnpackChar() );
          u->SetLanguage3( msg.UnpackChar() );

          //TODO
/*
          if (unsigned short tmp = msg.UnpackUnsignedShort()) //??
            gLog.Error("Unknown value %x\n", tmp);
          char *city = msg.UnpackString();        //Originally from city
          char *state = msg.UnpackString();        //Originally from state
          const struct SCountry *sc = GetCountryByCode(msg.UnpackUnsignedShort()); //Originally from country
          char *country = "unknown";
          if (sc)
            country = sc->szName;
          char *mstatus = "unknown";
          switch (msg.UnpackChar())          // marital status: 
          {
            case 0:  mstatus = "unspecified"; break;
            case 10: mstatus = "Single"; break;
            case 11: mstatus = "In a long-term relationship"; break;
            case 12: mstatus = "Engaged"; break;
            case 20: mstatus = "Married"; break;
            case 30: mstatus = "Divorced"; break;
            case 31: mstatus = "Separated"; break;
            case 40: mstatus = "Widowed"; break;
          }
          gLog.Info("%s%s status is %s, originally from: %s, %s, %s\n",
                    L_WARNxSTR, u->GetAlias(), mstatus, city, state, country);
          */
          
          // translating string with Translation Table
          gTranslator.ServerToClient(u->GetHomepage());

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveMoreInfo();

          PushExtendedEvent(e);
          multipart = true;

          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_MORE, u->Uin()));
          break;
        }
        case ICQ_CMDxMETA_EMAILxINFO:
        {

          gLog.Info(tr("%sEmail info on %s (%lu).\n"), L_SRVxSTR, u->GetAlias(), u->Uin());

          u->SetEnableSave(false);
          int nEmail = (int)msg.UnpackChar();
          for(int i = 0; i < 2; i++)
          {
            if (i < nEmail)
            {
              msg.UnpackChar(); // publish email, not yet implemented
              tmp = msg.UnpackString();
            }
            else
            {
              tmp = new char[1];
              tmp[0] = '\0';
            }
              
            if(i == 0)
            {
              u->SetEmailSecondary(tmp);
              gTranslator.ServerToClient(u->GetEmailSecondary());
            }
            else if(i == 1)
            {
              u->SetEmailOld(tmp);
              gTranslator.ServerToClient(u->GetEmailOld());
            }
            delete[] tmp;
          }
          
          // save the user infomation
          u->SetEnableSave(true);
          u->SaveGeneralInfo();

          PushExtendedEvent(e);
          multipart = true;
          
          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_EXT, u->Uin()));
          break;
        }

        case ICQ_CMDxMETA_HOMEPAGExINFO:
        {
          gLog.Info("%sHomepage info on %s (%lu).\n", L_SRVxSTR, u->GetAlias(),
            u->Uin());          
          
          u->SetEnableSave(false);
          
          unsigned char categoryPresent = msg.UnpackChar();
          u->SetHomepageCatPresent(categoryPresent);
          
          if (categoryPresent)
          {
            u->SetHomepageCatCode(msg.UnpackUnsignedShort());

            char *rawmsg = msg.UnpackString();
            char *msg = gTranslator.RNToN(rawmsg);
            delete [] rawmsg;

            u->SetHomepageDesc(msg);
            delete [] msg;

            gTranslator.ServerToClient(u->GetHomepageDesc());
          }
          
          u->SetICQHomepagePresent(msg.UnpackChar());

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveHomepageInfo();

          PushExtendedEvent(e);
          multipart = true;
          
          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_HP, u->Uin()));
          break;
        }

        case ICQ_CMDxMETA_WORKxINFO:
        
          gLog.Info(tr("%sWork info on %s (%lu).\n"), L_SRVxSTR, u->GetAlias(), u->Uin());
          
          u->SetEnableSave(false);
          u->SetCompanyCity( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyState( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyPhoneNumber( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyFaxNumber( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyAddress( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyZip( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyCountry( msg.UnpackUnsignedShort() );
          u->SetCompanyName( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyDepartment( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyPosition( tmp = msg.UnpackString() );
          delete[] tmp;
          u->SetCompanyOccupation(msg.UnpackUnsignedShort());
          u->SetCompanyHomepage( tmp = msg.UnpackString() );
          delete[] tmp;

          // translating string with Translation Table
          gTranslator.ServerToClient(u->GetCompanyCity());
          gTranslator.ServerToClient(u->GetCompanyState());
          gTranslator.ServerToClient(u->GetCompanyPhoneNumber());
          gTranslator.ServerToClient(u->GetCompanyFaxNumber());
          gTranslator.ServerToClient(u->GetCompanyAddress());
          gTranslator.ServerToClient(u->GetCompanyZip());
          gTranslator.ServerToClient(u->GetCompanyName());
          gTranslator.ServerToClient(u->GetCompanyDepartment());
          gTranslator.ServerToClient(u->GetCompanyPosition());
          gTranslator.ServerToClient(u->GetCompanyHomepage());

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveWorkInfo();

          PushExtendedEvent(e);
          multipart = true;

          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_WORK, u->Uin()));

          break;

        case ICQ_CMDxMETA_ABOUT:
        {
          gLog.Info(tr("%sAbout info on %s (%lu).\n"), L_SRVxSTR, u->GetAlias(), u->Uin());

          char* rawmsg = msg.UnpackString();
          char* msg = gTranslator.RNToN(rawmsg);
          delete [] rawmsg;

          u->SetEnableSave(false);
          u->SetAbout( msg );
          delete [] msg;

          // translating string with Translation Table
          gTranslator.ServerToClient(u->GetAbout());

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveAboutInfo();

          PushExtendedEvent(e);
          multipart = true;

          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_ABOUT, u->Uin()));

          break;
        }

        case ICQ_CMDxMETA_INTERESTSxINFO:
        {
          unsigned i, n;
          bool nRet = true;

          gLog.Info("%sPersonal Interests info on %s (%lu).\n", L_SRVxSTR,
                    u->GetAlias(), u ->Uin());

          u->SetEnableSave(false);
          u->m_Interests->Clean();
          n = msg.UnpackChar();

          for (i = 0; nRet && i < n; i++)
          { 
            unsigned short cat = msg.UnpackUnsignedShort();
            tmp = msg.UnpackString();
            gTranslator.ServerToClient(tmp);
            nRet = u->m_Interests->AddCategory(cat, tmp);
            delete [] tmp;
          }

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveInterestsInfo();
          
          PushExtendedEvent(e);
          multipart = true;
          
          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_MORE2,
                           u->Uin()));
          break;
        }

        case ICQ_CMDxMETA_PASTxINFO:
        {
          // past background info - last one received
          unsigned i, n;
          bool nRet = true;

          gLog.Info("%sOrganizations/Past Background info on %s (%lu).\n",
                    L_SRVxSTR, u->GetAlias(), u ->Uin());

          u->SetEnableSave(false);

          u->m_Backgrounds->Clean();
 
          n = msg.UnpackChar();

          for (i = 0; nRet && i < n; i++)
          {
            unsigned short cat = msg.UnpackUnsignedShort();
            tmp = msg.UnpackString();
            gTranslator.ServerToClient(tmp);
            nRet = u->m_Backgrounds->AddCategory(cat, tmp);
            delete [] tmp;
          }

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveBackgroundsInfo();

          //---- Organizations
          u->SetEnableSave(false);
          u->m_Organizations->Clean();
          nRet = true;
          n = msg.UnpackChar();

          for(i = 0; nRet && i < n; i++)
          {
            unsigned short cat = msg.UnpackUnsignedShort();
            tmp = msg.UnpackString();
            gTranslator.ServerToClient(tmp);
            nRet = u->m_Organizations->AddCategory(cat, tmp);
            delete [] tmp;
          }

          // our user info is now up to date
          u->SetOurClientTimestamp(u->ClientTimestamp());

          // save the user infomation
          u->SetEnableSave(true);
          u->SaveOrganizationsInfo();
          u->SaveLicqInfo();

          PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_MORE2,
                           u->Uin()));

          break;
        }

        default:
        {
          char* buf;

          gLog.Unknown(tr("%sunknown info: %04hx\n%s\n"), L_UNKNOWNxSTR,
                       nSubtype, packet.print(buf));
          delete [] buf;
        }
        }

        if (!multipart) {
          if (e) {
            DoneEvent(e, EVENT_SUCCESS);
            ProcessDoneEvent(e);
          } else {
            gLog.Warn(tr("%sResponse to unknown extended info request for %s (%lu).\n"),
                      L_WARNxSTR, u->GetAlias(), nUin);
          }
        }

        PushPluginSignal(new CICQSignal(SIGNAL_UPDATExUSER, USER_EXT, u->Uin()));
        gUserManager.DropUser(u);
      }

      if (szType)
      {
        if (pEvent)
        {
          if (pEvent->Result() == EVENT_SUCCESS)
            gLog.Info(tr("%s%s updated.\n"), L_SRVxSTR, szType);
          else
            gLog.Info(tr("%s%s update failed.\n"), L_SRVxSTR, szType);
          ProcessDoneEvent(pEvent);
        }
        else
          gLog.Info(tr("%sUnexpected result for %s.\n"), L_SRVxSTR, szType);

        free(szType);
      }
      break;
    }
    default: {
      char *buf;
      gLog.Unknown("%sUnknown SNAC 15,03 response type: %04hx\n%s\n", L_UNKNOWNxSTR,
                   nType, packet.print(buf));
      delete [] buf;
      break;
    }
    }
    break;
  }
  default:
    char *buf;
    gLog.Unknown(tr("%sUnknown Various Family Subtype: %04hx\n%s\n"), L_UNKNOWNxSTR,
                 nSubtype, packet.print(buf));
    delete [] buf;
    break;
  }
}

//--------ProcessNewUINFam-----------------------------------------------------
void CICQDaemon::ProcessNewUINFam(CBuffer &packet, unsigned short nSubtype)
{
  switch (nSubtype)
  {
    case ICQ_SNACxNEW_UIN_ERROR:
    {
      gLog.Warn(tr("%sRegistration error.\n"), L_WARNxSTR);
      break;
    }
    case ICQ_SNACxNEW_UIN:
    {
      packet.UnpackUnsignedShort(); // flags
      packet.UnpackUnsignedLong();  // id

      // 46 bytes of shit
      for (int x = 0; x < 11; x++)
        packet.UnpackUnsignedLong();
      packet.UnpackUnsignedShort();

      unsigned long nNewUin = packet.UnpackUnsignedLong();

      if (gUserManager.OwnerUin() != 0)
      {
        gLog.Warn(tr("%sReceived new uin (%lu) when already have a uin (%lu).\n"), L_WARNxSTR,
          nNewUin, gUserManager.OwnerUin());
        return;
      }

      gLog.Info(tr("%sReceived new uin: %lu\n"), L_SRVxSTR, nNewUin);
      char szUin[14];
      snprintf(szUin, sizeof(szUin), "%lu", nNewUin);
      gUserManager.AddOwner(szUin, LICQ_PPID);

      ICQOwner *o = gUserManager.FetchOwner(LICQ_PPID, LOCK_W);
      if (o)
      {
        o->SetPassword(m_szRegisterPasswd);
        gUserManager.DropOwner(LICQ_PPID);
        free(m_szRegisterPasswd);
        m_szRegisterPasswd = 0;
      }

      // Reconnect now
      int nSD = m_nTCPSrvSocketDesc;
      m_nTCPSrvSocketDesc = -1;
      m_eStatus = STATUS_OFFLINE_MANUAL;
      m_bLoggingOn = false; 
      gSocketManager.CloseSocket(nSD);
      postLogoff(nSD, NULL);
      icqLogon(ICQ_STATUS_ONLINE);
      break;
    }
    default:
    {
      char *buf;
      gLog.Unknown("%sUnknown New UIN Family Subtype: %04hx\n%s\n", L_UNKNOWNxSTR,
          nSubtype, packet.print(buf));
      delete [] buf;
      break;
    }
  }
}

//--------ProcessDataChannel---------------------------------------------------

void CICQDaemon::ProcessDataChannel(CBuffer &packet)
{
  unsigned short nFamily, nSubtype;

  packet >> nFamily >> nSubtype;
  rev_e_short(nFamily);
  rev_e_short(nSubtype);

  switch (nFamily)
  {
  case ICQ_SNACxFAM_SERVICE:
    ProcessServiceFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_LOCATION:
    ProcessLocationFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_BUDDY:
    ProcessBuddyFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_MESSAGE:
    ProcessMessageFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_LIST:
    ProcessListFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_BOS:
    ProcessBOSFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_VARIOUS:
    ProcessVariousFam(packet, nSubtype);
    break;

  case ICQ_SNACxFAM_NEWUIN:
    ProcessNewUINFam(packet, nSubtype);
    break;
    
  default:
    gLog.Warn("%sUnknown Family on data channel: %04hx\n", L_SRVxSTR, nFamily);
    break;
  }
}

//--------ProcessCloseChannel--------------------------------------------------

bool CICQDaemon::ProcessCloseChannel(CBuffer &packet)
{
  int nSD = m_nTCPSrvSocketDesc;
  if (nSD < 0) {
    fprintf(stderr, "nsd <0 !\n");
  }
  else {
    m_nTCPSrvSocketDesc = -1;
    gSocketManager.CloseSocket(nSD);
    postLogoff(nSD, NULL);
  }

  if (packet.getDataSize() == 0) {
    gLog.Info(tr("%sWe're logging off..\n"), L_SRVxSTR);
    m_eStatus = STATUS_OFFLINE_FORCED;
    m_bLoggingOn = false;
    return true;
  }

  if (!packet.readTLV()) {
    gLog.Error("%sError during parsing packet!\n", L_ERRORxSTR);
    return false;
  }

  unsigned short nError = packet.UnpackUnsignedShortTLV(0x0008);
  switch (nError) {
  case 0x1D:
  case 0x18:
    gLog.Error(tr("%sRate limit exceeded.\n"), L_ERRORxSTR);
    PushPluginSignal(new CICQSignal(SIGNAL_LOGOFF, LOGOFF_RATE, 0));
    break;

  case 0x04:
  case 0x05:
    gLog.Error(tr("%sInvalid UIN and password combination.\n"), L_ERRORxSTR);
    PushPluginSignal(new CICQSignal(SIGNAL_LOGOFF, LOGOFF_PASSWORD, 0));
    break;
    
  case 0x0C:
  case 0x0D:
  case 0x12:
  case 0x13:
  case 0x14:
  case 0x15:
  case 0x1A:
  case 0x1F:
    gLog.Error(tr("%sThe requested network service is temporarily unavailable.\n"
                  "Please try again later.\n"), L_ERRORxSTR);
    break;  

  case 0:
    break;

  default:
    gLog.Error("%sUnknown sign on error: 0x%02X.\n", L_ERRORxSTR, nError);
  }

  if (nError)
  {
    packet.cleanupTLV();
    m_eStatus = STATUS_OFFLINE_FORCED;
    m_bLoggingOn = false;
    return false;
  }

  nError = packet.UnpackUnsignedShortTLV(0x0009);
  switch (nError)
  {
  case 0x0001:
    if (ReconnectAfterUinClash())
    {
      gLog.Error(tr("%sYour ICQ number is used from another location.\n"), L_ERRORxSTR);
      m_eStatus = STATUS_OFFLINE_FORCED; // will try to reconnect
    }
    else 
    {
      gLog.Error(tr("%sYour ICQ number is used from another location.\n"
                    "Automatic reconnect is disabled.\n"), L_ERRORxSTR);
      m_eStatus = STATUS_OFFLINE_MANUAL; // don't reconnect
    }
    break;

  case 0:
    break;

  default:
    gLog.Error("%sUnknown runtime error form server: 0x%02X.\n", L_ERRORxSTR, nError);
    m_eStatus = STATUS_OFFLINE_FORCED;
  }

  if (nError)
  {
    packet.cleanupTLV();
    m_bLoggingOn = false;
    return false;
  }

  char *szNewServer = packet.UnpackStringTLV(0x0005);
  char *szCookie = packet.UnpackStringTLV(0x0006);
  int nCookieLen = packet.getTLVLen(0x0006);

  if (!szNewServer || !szCookie)
  {
    gLog.Error("%sUnable to sign on: NewServer: %s, cookie: %s.\n", L_ERRORxSTR,
               szNewServer ? szNewServer : "(null)", szCookie ? szCookie : "(null)");
    if (szNewServer) delete [] szNewServer;
    if (szCookie) delete [] szCookie;
    m_eStatus = STATUS_OFFLINE_FORCED;
    m_bLoggingOn = false;
    return false;
  }

  packet.cleanupTLV();

  char* ptr;
  if ( (ptr = strchr(szNewServer, ':')))
    *ptr++ = '\0';

  gLog.Info(tr("%sAuthenticated. Connecting to %s port %s.\n"), L_SRVxSTR, szNewServer, ptr);

  // Connect to the new server here and send our cookie
  ConnectToServer(szNewServer, ptr ? atoi(ptr) : 5190);

  // Send our cookie
  CPU_SendCookie *p = new CPU_SendCookie(szCookie, nCookieLen);
  SendEvent_Server(p);

  delete [] szNewServer;
  delete [] szCookie;

  return true;
}

int CICQDaemon::RequestReverseConnection(unsigned long nUin,
                                         unsigned long nData,
                                         unsigned long nLocalIP,
                                         unsigned short nLocalPort,
                                         unsigned short nRemotePort)
{
  if (nUin == gUserManager.OwnerUin()) return -1;

  ICQUser *u = gUserManager.FetchUser(nUin, LOCK_W);
  if (u == NULL) return -1;


  CPU_ReverseConnect *p = new CPU_ReverseConnect(u, nLocalIP, nLocalPort,
                                                 nRemotePort);
  int nId = p->SubSequence();

  pthread_mutex_lock(&mutex_reverseconnect);

  m_lReverseConnect.push_back(
            new CReverseConnectToUserData(nUin, nId, nData, nLocalIP,
                                          nLocalPort, ICQ_VERSION_TCP,
                                          nRemotePort, 0, nId));
  pthread_mutex_unlock(&mutex_reverseconnect);

  gLog.Info("%sRequesting reverse connection from %s.\n", L_TCPxSTR,
            u->GetAlias());
  SendEvent_Server(p);
  
  gUserManager.DropUser(u);

  return nId;
}
 
