/**
 * Network manager creates DHCPACK
 */
int NetworkManager::ack(const Client& client, uint32_t u32Xid,
                        uint8_t *pu8ReqList, int cReqList)
{
    RTNETADDRIPV4 address;

    prepareReplyPacket4Client(client, u32Xid);

    Lease l = client.lease();
    address = l.getAddress();
    m->BootPReplyMsg.BootPHeader.bp_ciaddr =  address;


    /* rfc2131 4.3.1 is about DHCPDISCOVER and this value is equal to ciaddr from
     * DHCPREQUEST or 0 ...
     * XXX: Using addressHint is not correct way to initialize [cy]iaddress...
     */
    m->BootPReplyMsg.BootPHeader.bp_ciaddr = address;
    m->BootPReplyMsg.BootPHeader.bp_yiaddr = address;

    Assert(m->BootPReplyMsg.BootPHeader.bp_yiaddr.u);

    /* options:
     * - IP address lease time (if DHCPREQUEST)
     * - message type
     * - server identifier
     */
    RawOption opt;
    RT_ZERO(opt);

    std::vector<RawOption> extra;
    opt.u8OptId = RTNET_DHCP_OPT_MSG_TYPE;
    opt.au8RawOpt[0] = RTNET_DHCP_MT_ACK;
    opt.cbRawOpt = 1;
    extra.push_back(opt);

    /*
     * XXX: lease time should be conditional. If on dhcprequest then tim should be provided,
     * else on dhcpinform it mustn't.
     */
    opt.u8OptId = RTNET_DHCP_OPT_LEASE_TIME;
    *(uint32_t *)opt.au8RawOpt = RT_H2N_U32(l.getExpiration());
    opt.cbRawOpt = sizeof(RTNETADDRIPV4);
    extra.push_back(opt);

    processParameterReqList(client, pu8ReqList, cReqList, extra);

    return doReply(client, extra);
}
static int vbglR3DnDHGProcessSendFileMessage(uint32_t  uClientId,
                                             char     *pszFilename,
                                             uint32_t  cbFilename,
                                             uint32_t *pcbFilenameRecv,
                                             void     *pvData,
                                             uint32_t  cbData,
                                             uint32_t *pcbDataRecv,
                                             uint32_t *pfMode)
{
    /* Validate input */
    AssertPtrReturn(pszFilename,     VERR_INVALID_POINTER);
    AssertReturn(cbFilename,         VERR_INVALID_PARAMETER);
    AssertPtrReturn(pcbFilenameRecv, VERR_INVALID_POINTER);
    AssertPtrReturn(pvData,          VERR_INVALID_POINTER);
    AssertReturn(cbData,             VERR_INVALID_PARAMETER);
    AssertPtrReturn(pcbDataRecv,     VERR_INVALID_POINTER);
    AssertPtrReturn(pfMode,          VERR_INVALID_POINTER);

    /* Initialize header */
    DragAndDropSvc::VBOXDNDHGSENDFILEMSG Msg;
    RT_ZERO(Msg);
    Msg.hdr.u32ClientID = uClientId;
    Msg.hdr.u32Function = DragAndDropSvc::HOST_DND_HG_SND_FILE;
    Msg.hdr.cParms      = 5;
    /* Initialize parameter */
    Msg.pvName.SetPtr(pszFilename, cbFilename);
    Msg.cName.SetUInt32(0);
    Msg.pvData.SetPtr(pvData, cbData);
    Msg.cData.SetUInt32(0);
    Msg.fMode.SetUInt32(0);
    /* Do request */
    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CALL(sizeof(Msg)), &Msg, sizeof(Msg));
    if (RT_SUCCESS(rc))
    {
        rc = Msg.hdr.result;
        if (RT_SUCCESS(rc))
        {
            /* Fetch results */
            rc = Msg.cName.GetUInt32(pcbFilenameRecv); AssertRC(rc);
            rc = Msg.cData.GetUInt32(pcbDataRecv);     AssertRC(rc);
            rc = Msg.fMode.GetUInt32(pfMode);          AssertRC(rc);
            /* A little bit paranoia */
            AssertReturn(cbFilename >= *pcbFilenameRecv, VERR_TOO_MUCH_DATA);
            AssertReturn(cbData     >= *pcbDataRecv,     VERR_TOO_MUCH_DATA);
        }
    }
    return rc;
}
Beispiel #3
0
/**
 * Create a session instance.
 *
 * @returns IPRT status code.
 *
 * @param   phClientSession         Where to store the session handle on success.
 * @param   hNmPipeSession          The named pipe handle. This will be consumed by this session, meaning on failure
 *                                  to create the session it will be closed.
 */
static int rtLocalIpcWinCreateSession(PRTLOCALIPCSESSION phClientSession, HANDLE hNmPipeSession)
{
    AssertPtrReturn(phClientSession, VERR_INVALID_POINTER);
    AssertReturn(hNmPipeSession != INVALID_HANDLE_VALUE, VERR_INVALID_HANDLE);

    int rc;

    /*
     * Allocate and initialize the session instance data.
     */
    PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)RTMemAlloc(sizeof(*pThis));
    if (pThis)
    {
        pThis->u32Magic = RTLOCALIPCSESSION_MAGIC;
        pThis->cRefs = 1; /* our ref */
        pThis->fCancelled = false;
        pThis->fIOPending = false;
        pThis->fZeroByteRead = false;
        pThis->hNmPipe = hNmPipeSession;

        rc = RTCritSectInit(&pThis->CritSect);
        if (RT_SUCCESS(rc))
        {
            pThis->hEvent = CreateEvent(NULL /*lpEventAttributes*/, TRUE /*bManualReset*/,
                                        FALSE /*bInitialState*/, NULL /*lpName*/);
            if (pThis->hEvent != NULL)
            {
                RT_ZERO(pThis->OverlappedIO);
                pThis->OverlappedIO.Internal = STATUS_PENDING;
                pThis->OverlappedIO.hEvent = pThis->hEvent;

                *phClientSession = pThis;
                return VINF_SUCCESS;
            }

            /* bail out */
            rc = RTErrConvertFromWin32(GetLastError());
            RTCritSectDelete(&pThis->CritSect);
        }
        RTMemFree(pThis);
    }
    else
        rc = VERR_NO_MEMORY;

    BOOL fRc = CloseHandle(hNmPipeSession);
    AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
    return rc;
}
static void vboxTrayRemoveTrayIcon()
{
    if (gNotifyIconData.cbSize > 0)
    {
        /* Remove the system tray icon and refresh system tray. */
        Shell_NotifyIcon(NIM_DELETE, &gNotifyIconData);
        HWND hTrayWnd = FindWindow("Shell_TrayWnd", NULL); /* We assume we only have one tray atm. */
        if (hTrayWnd)
        {
            HWND hTrayNotifyWnd = FindWindowEx(hTrayWnd, 0, "TrayNotifyWnd", NULL);
            if (hTrayNotifyWnd)
                SendMessage(hTrayNotifyWnd, WM_PAINT, 0, NULL);
        }
        RT_ZERO(gNotifyIconData);
    }
}
/*
 * Worker for sobind() below.
 */
static int
sobindto(struct socket *so, uint32_t addr, uint16_t port)
{
    struct sockaddr_in self;
    int status;

    if (addr == INADDR_ANY && port == 0 && so->so_type != IPPROTO_UDP)
    {
        /* TCP sockets without constraints don't need to be bound */
        Log2(("NAT: sobind: %s guest %RTnaipv4:%d - nothing to do\n",
              so->so_type == IPPROTO_UDP ? "udp" : "tcp",
              so->so_laddr.s_addr, ntohs(so->so_lport)));
        return 0;
    }

    RT_ZERO(self);
#ifdef RT_OS_DARWIN
    self.sin_len = sizeof(self);
#endif
    self.sin_family = AF_INET;
    self.sin_addr.s_addr = addr;
    self.sin_port = port;

    status = bind(so->s, (struct sockaddr *)&self, sizeof(self));
    if (status == 0)
    {
        Log2(("NAT: sobind: %s guest %RTnaipv4:%d to host %RTnaipv4:%d\n",
              so->so_type == IPPROTO_UDP ? "udp" : "tcp",
              so->so_laddr.s_addr, ntohs(so->so_lport), addr, ntohs(port)));
        return 0;
    }

    Log2(("NAT: sobind: %s guest %RTnaipv4:%d to host %RTnaipv4:%d error %d%s\n",
          so->so_type == IPPROTO_UDP ? "udp" : "tcp",
          so->so_laddr.s_addr, ntohs(so->so_lport),
          addr, ntohs(port),
          errno, port ? " (will retry with random port)" : ""));

    if (port) /* retry without */
        status = sobindto(so, addr, 0);

    if (addr)
        return status;
    else
        return 0;
}
Beispiel #6
0
/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipTarFssBaseObj_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPTARBASEOBJ pThis = (PRTZIPTARBASEOBJ)pvThis;

    /*
     * Copy the desired data.
     */
    switch (enmAddAttr)
    {
        case RTFSOBJATTRADD_NOTHING:
        case RTFSOBJATTRADD_UNIX:
            *pObjInfo = pThis->ObjInfo;
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
            *pObjInfo = pThis->ObjInfo;
            pObjInfo->Attr.enmAdditional         = RTFSOBJATTRADD_UNIX_OWNER;
            pObjInfo->Attr.u.UnixOwner.uid       = pThis->ObjInfo.Attr.u.Unix.uid;
            pObjInfo->Attr.u.UnixOwner.szName[0] = '\0';
            if (rtZipTarReaderHasUserName(pThis->pTarReader))
                RTStrCopy(pObjInfo->Attr.u.UnixOwner.szName, sizeof(pObjInfo->Attr.u.UnixOwner.szName),
                          pThis->pTarReader->Hdr.Common.uname);
            break;

        case RTFSOBJATTRADD_UNIX_GROUP:
            *pObjInfo = pThis->ObjInfo;
            pObjInfo->Attr.enmAdditional         = RTFSOBJATTRADD_UNIX_GROUP;
            pObjInfo->Attr.u.UnixGroup.gid       = pThis->ObjInfo.Attr.u.Unix.gid;
            pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
            if (rtZipTarReaderHasGroupName(pThis->pTarReader))
                RTStrCopy(pObjInfo->Attr.u.UnixGroup.szName, sizeof(pObjInfo->Attr.u.UnixGroup.szName),
                          pThis->pTarReader->Hdr.Common.gname);
            break;

        case RTFSOBJATTRADD_EASIZE:
            *pObjInfo = pThis->ObjInfo;
            pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
            RT_ZERO(pObjInfo->Attr.u);
            break;

        default:
            return VERR_NOT_SUPPORTED;
    }

    return VINF_SUCCESS;
}
/**
 * Reports the Guest Additions status of a certain facility to the host.
 *
 * @returns IPRT status value
 * @param   enmFacility     The facility to report the status on.
 * @param   enmStatus       The new status of the facility.
 * @param   fReserved       Reserved for future use (what?).
 */
VBGLR3DECL(int) VbglR3ReportAdditionsStatus(VBoxGuestFacilityType enmFacility,
                                            VBoxGuestFacilityStatus enmStatusCurrent,
                                            uint32_t fReserved)
{
    VMMDevReportGuestStatus Report;
    RT_ZERO(Report);
    int rc = vmmdevInitRequest((VMMDevRequestHeader*)&Report, VMMDevReq_ReportGuestStatus);
    if (RT_SUCCESS(rc))
    {
        Report.guestStatus.facility = enmFacility;
        Report.guestStatus.status   = enmStatusCurrent;
        Report.guestStatus.flags    = fReserved;

        rc = vbglR3GRPerform(&Report.header);
    }
    return rc;
}
Beispiel #8
0
err_t VBoxNetLwipNAT::netifLinkoutput(netif *pNetif, pbuf *pPBuf)
{
    AssertPtrReturn(pNetif, ERR_ARG);
    AssertPtrReturn(pPBuf, ERR_ARG);

    VBoxNetLwipNAT *self = static_cast<VBoxNetLwipNAT *>(pNetif->state);
    AssertPtrReturn(self, ERR_IF);
    AssertReturn(self == g_pLwipNat, ERR_ARG);

    LogFlowFunc(("ENTER: pNetif[%c%c%d], pPbuf:%p\n",
                 pNetif->name[0],
                 pNetif->name[1],
                 pNetif->num,
                 pPBuf));

    RT_ZERO(VBoxNetLwipNAT::aXmitSeg);

    size_t idx = 0;
    for (struct pbuf *q = pPBuf; q != NULL; q = q->next, ++idx)
    {
        AssertReturn(idx < RT_ELEMENTS(VBoxNetLwipNAT::aXmitSeg), ERR_MEM);

#if ETH_PAD_SIZE
        if (q == pPBuf)
        {
            VBoxNetLwipNAT::aXmitSeg[idx].pv = (uint8_t *)q->payload + ETH_PAD_SIZE;
            VBoxNetLwipNAT::aXmitSeg[idx].cb = q->len - ETH_PAD_SIZE;
        }
        else
#endif
        {
            VBoxNetLwipNAT::aXmitSeg[idx].pv = q->payload;
            VBoxNetLwipNAT::aXmitSeg[idx].cb = q->len;
        }
    }

    int rc = self->sendBufferOnWire(VBoxNetLwipNAT::aXmitSeg, idx,
                                    pPBuf->tot_len - ETH_PAD_SIZE);
    AssertRCReturn(rc, ERR_IF);

    self->flushWire();

    LogFlowFunc(("LEAVE: %d\n", ERR_OK));
    return ERR_OK;
}
RTDECL(void) RTSha1Final(PRTSHA1CONTEXT pCtx, uint8_t pabDigest[RTSHA1_HASH_SIZE])
{
    Assert(pCtx->AltPrivate.cbMessage < UINT64_MAX / 2);

    /*
     * Complete the message by adding a single bit (0x80), padding till
     * the next 448-bit boundrary, the add the message length.
     */
    uint64_t const cMessageBits = pCtx->AltPrivate.cbMessage * 8;

    unsigned cbMissing = RTSHA1_BLOCK_SIZE - ((unsigned)pCtx->AltPrivate.cbMessage & (RTSHA1_BLOCK_SIZE - 1U));
    static uint8_t const s_abSingleBitAndSomePadding[12] =  { 0x80, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, };
    if (cbMissing < 1U + 8U)
        /* Less than 64+8 bits left in the current block, force a new block. */
        RTSha1Update(pCtx, &s_abSingleBitAndSomePadding, sizeof(s_abSingleBitAndSomePadding));
    else
        RTSha1Update(pCtx, &s_abSingleBitAndSomePadding, 1);

    unsigned cbBuffered = (unsigned)pCtx->AltPrivate.cbMessage & (RTSHA1_BLOCK_SIZE - 1U);
    cbMissing = RTSHA1_BLOCK_SIZE - cbBuffered;
    Assert(cbMissing >= 8);
    memset((uint8_t *)&pCtx->AltPrivate.auW[0] + cbBuffered, 0, cbMissing - 8);

    *(uint64_t *)&pCtx->AltPrivate.auW[14] = RT_H2BE_U64(cMessageBits);

    /*
     * Process the last buffered block constructed/completed above.
     */
    rtSha1BlockInitBuffered(pCtx);
    rtSha1BlockProcess(pCtx);

    /*
     * Convert the byte order of the hash words and we're done.
     */
    pCtx->AltPrivate.auH[0] = RT_H2BE_U32(pCtx->AltPrivate.auH[0]);
    pCtx->AltPrivate.auH[1] = RT_H2BE_U32(pCtx->AltPrivate.auH[1]);
    pCtx->AltPrivate.auH[2] = RT_H2BE_U32(pCtx->AltPrivate.auH[2]);
    pCtx->AltPrivate.auH[3] = RT_H2BE_U32(pCtx->AltPrivate.auH[3]);
    pCtx->AltPrivate.auH[4] = RT_H2BE_U32(pCtx->AltPrivate.auH[4]);

    memcpy(pabDigest, &pCtx->AltPrivate.auH[0], RTSHA1_HASH_SIZE);

    RT_ZERO(pCtx->AltPrivate);
    pCtx->AltPrivate.cbMessage = UINT64_MAX;
}
Beispiel #10
0
RTR3DECL(int) RTTarClose(RTTAR hTar)
{
    if (hTar == NIL_RTTAR)
        return VINF_SUCCESS;

    PRTTARINTERNAL pInt = hTar;
    RTTAR_VALID_RETURN(pInt);

    int rc = VINF_SUCCESS;

    /* gtar gives a warning, but the documentation says EOF is indicated by a
     * zero block. Disabled for now. */
#if 0
    {
        /* Append the EOF record which is filled all by zeros */
        RTTARRECORD record;
        RT_ZERO(record);
        rc = RTFileWrite(pInt->hTarFile, &record, sizeof(record), NULL);
    }
#endif

    if (pInt->hVfsFss != NIL_RTVFSFSSTREAM)
    {
        uint32_t cRefs = RTVfsFsStrmRelease(pInt->hVfsFss); Assert(cRefs != UINT32_MAX);
        pInt->hVfsFss  = NIL_RTVFSFSSTREAM;
    }

    if (pInt->hVfsFile != NIL_RTVFSFILE)
    {
        uint32_t cRefs = RTVfsFileRelease(pInt->hVfsFile); Assert(cRefs != UINT32_MAX);
        pInt->hVfsFile = NIL_RTVFSFILE;
    }

    if (pInt->hTarFile != NIL_RTFILE)
    {
        rc = RTFileClose(pInt->hTarFile);
        pInt->hTarFile = NIL_RTFILE;
    }

    pInt->u32Magic = RTTAR_MAGIC_DEAD;

    RTMemFree(pInt);

    return rc;
}
Beispiel #11
0
/**
 * Obtain the current state of the interface.
 *
 * @returns VBox status code.
 *
 * @param   pcszIfName  Interface name.
 * @param   penmState   Where to store the retrieved state.
 */
int NetIfGetState(const char *pcszIfName, NETIFSTATUS *penmState)
{
    int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock < 0)
        return VERR_OUT_OF_RESOURCES;
    struct ifreq Req;
    RT_ZERO(Req);
    RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pcszIfName);
    if (ioctl(sock, SIOCGIFFLAGS, &Req) < 0)
    {
        Log(("NetIfGetState: ioctl(SIOCGIFFLAGS) -> %d\n", errno));
        *penmState = NETIF_S_UNKNOWN;
    }
    else
        *penmState = (Req.ifr_flags & IFF_UP) ? NETIF_S_UP : NETIF_S_DOWN;
    close(sock);
    return VINF_SUCCESS;
}
VBGLR3DECL(int) VbglR3VrdpGetChangeRequest(bool *pfActive, uint32_t *puExperienceLevel)
{
    VMMDevVRDPChangeRequest Req;
    RT_ZERO(Req); /* implicit padding */
    vmmdevInitRequest(&Req.header, VMMDevReq_GetVRDPChangeRequest); //VMMDEV_REQ_HDR_INIT(&Req.header, sizeof(Req), VMMDevReq_GetVRDPChangeRequest);
    int rc = vbglR3GRPerform(&Req.header);
    if (RT_SUCCESS(rc))
    {
        *pfActive          = Req.u8VRDPActive != 0;
        *puExperienceLevel = Req.u32VRDPExperienceLevel;
    }
    else
    {
        *pfActive          = false;
        *puExperienceLevel = 0;
    }
    return rc;
}
RTDECL(int) RTAsn1Time_Clone(PRTASN1TIME pThis, PCRTASN1TIME pSrc, PCRTASN1ALLOCATORVTABLE pAllocator)
{
    AssertPtr(pSrc); AssertPtr(pThis); AssertPtr(pAllocator);
    RT_ZERO(*pThis);
    if (RTAsn1Time_IsPresent(pSrc))
    {
        AssertReturn(pSrc->Asn1Core.pOps == &g_RTAsn1Time_Vtable, VERR_INTERNAL_ERROR_3);

        int rc = RTAsn1Core_CloneContent(&pThis->Asn1Core, &pSrc->Asn1Core, pAllocator);
        if (RT_SUCCESS(rc))
        {
            pThis->Time = pSrc->Time;
            return VINF_SUCCESS;
        }
        return rc;
    }
    return VINF_SUCCESS;
}
VBGLR3DECL(int) VbglR3DnDHGAcknowledgeOperation(uint32_t uAction)
{
    DO(("ACK: %u\n", uAction));
    /* Initialize header */
    DragAndDropSvc::VBOXDNDHGACKOPMSG Msg;
    RT_ZERO(Msg);
    Msg.hdr.result      = VERR_WRONG_ORDER;
    Msg.hdr.u32ClientID = g_clientId;
    Msg.hdr.u32Function = DragAndDropSvc::GUEST_DND_HG_ACK_OP;
    Msg.hdr.cParms      = 1;
    /* Initialize parameter */
    Msg.uAction.SetUInt32(uAction);
    /* Do request */
    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CALL(sizeof(Msg)), &Msg, sizeof(Msg));
    if (RT_SUCCESS(rc))
        rc = Msg.hdr.result;
    return rc;
}
extern int testRTFileSetTimes(RTFILE File, PCRTTIMESPEC pAccessTime,
                               PCRTTIMESPEC pModificationTime,
                               PCRTTIMESPEC pChangeTime,
                               PCRTTIMESPEC pBirthTime)
{
 /* RTPrintf("%s: pFile=%p, *pAccessTime=%lli, *pModificationTime=%lli, *pChangeTime=%lli, *pBirthTime=%lli\n",
             __PRETTY_FUNCTION__,
             pAccessTime ? (long long)RTTimeSpecGetNano(pAccessTime) : -1,
               pModificationTime
             ? (long long)RTTimeSpecGetNano(pModificationTime) : -1,
             pChangeTime ? (long long)RTTimeSpecGetNano(pChangeTime) : -1,
             pBirthTime ? (long long)RTTimeSpecGetNano(pBirthTime) : -1); */
    if (pAccessTime)
        testRTFileSetTimesATime = *pAccessTime;
    else
        RT_ZERO(testRTFileSetTimesATime);
    return VINF_SUCCESS;
}
RTDECL(bool) RTMpIsCpuOnline(RTCPUID idCpu)
{
    /*
     * FreeBSD doesn't support CPU hotplugging so every CPU which appears
     * in the tree is also online.
     */
    char    szName[40];
    RTStrPrintf(szName, sizeof(szName), "dev.cpu.%d.%%driver", (int)idCpu);

    char    szDriver[10];
    size_t  cbDriver = sizeof(szDriver);
    RT_ZERO(szDriver);                  /* this shouldn't be necessary. */
    int rcBsd = sysctlbyname(szName, szDriver, &cbDriver, NULL, NULL);
    if (rcBsd == 0)
        return true;

    return false;
}
/**
 * Connects to the shared folder service.
 *
 * @returns VBox status code
 * @param   pu32ClientId    Where to put the client id on success. The client id
 *                          must be passed to all the other calls to the service.
 */
VBGLR3DECL(int) VbglR3SharedFolderConnect(uint32_t *pu32ClientId)
{
    VBoxGuestHGCMConnectInfo Info;
    Info.result = VERR_WRONG_ORDER;
    Info.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
    RT_ZERO(Info.Loc.u);
    strcpy(Info.Loc.u.host.achName, "VBoxSharedFolders");
    Info.u32ClientID = UINT32_MAX;  /* try make valgrind shut up. */

    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CONNECT, &Info, sizeof(Info));
    if (RT_SUCCESS(rc))
    {
        rc = Info.result;
        if (RT_SUCCESS(rc))
            *pu32ClientId = Info.u32ClientID;
    }
    return rc;
}
/** Reports our current status to the SCM. */
static BOOL vboxServiceWinSetStatus(DWORD dwStatus, DWORD dwCheckPoint)
{
    if (g_hWinServiceStatus == NULL) /* Program could be in testing mode, so no service environment available. */
        return FALSE;

    VBoxServiceVerbose(2, "Setting service status to: %ld\n", dwStatus);
    g_dwWinServiceLastStatus = dwStatus;

    SERVICE_STATUS ss;
    RT_ZERO(ss);

    ss.dwServiceType              = SERVICE_WIN32_OWN_PROCESS;
    ss.dwCurrentState             = dwStatus;
    /* Don't accept controls when in start pending state. */
    if (ss.dwCurrentState != SERVICE_START_PENDING)
    {
        ss.dwControlsAccepted     = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
#ifndef TARGET_NT4
        /* Don't use SERVICE_ACCEPT_SESSIONCHANGE on Windows 2000.
         * This makes SCM angry. */
        char szOSVersion[32];
        int rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE,
                                     szOSVersion, sizeof(szOSVersion));
        if (RT_SUCCESS(rc))
        {
            if (RTStrVersionCompare(szOSVersion, "5.1") >= 0)
                ss.dwControlsAccepted |= SERVICE_ACCEPT_SESSIONCHANGE;
        }
        else
            VBoxServiceError("Error determining OS version, rc=%Rrc\n", rc);
#endif
    }

    ss.dwWin32ExitCode            = NO_ERROR;
    ss.dwServiceSpecificExitCode  = 0; /* Not used */
    ss.dwCheckPoint               = dwCheckPoint;
    ss.dwWaitHint                 = 3000;

    BOOL fStatusSet = SetServiceStatus(g_hWinServiceStatus, &ss);
    if (!fStatusSet)
        VBoxServiceError("Error reporting service status=%ld (controls=%x, checkpoint=%ld) to SCM: %ld\n",
                         dwStatus, ss.dwControlsAccepted, dwCheckPoint, GetLastError());
    return fStatusSet;
}
Beispiel #19
0
RTR3DECL(int) RTFsQuerySizes(const char *pszFsPath, RTFOFF *pcbTotal, RTFOFF *pcbFree,
                             uint32_t *pcbBlock, uint32_t *pcbSector)
{
    /*
     * Validate input.
     */
    AssertMsgReturn(VALID_PTR(pszFsPath) && *pszFsPath, ("%p", pszFsPath), VERR_INVALID_PARAMETER);

    /*
     * Convert the path and query the information.
     */
    char const *pszNativeFsPath;
    int rc = rtPathToNative(&pszNativeFsPath, pszFsPath, NULL);
    if (RT_SUCCESS(rc))
    {
        /** @todo I'm not quite sure if statvfs was properly specified by SuS, I have to check my own
         * implementation and FreeBSD before this can eventually be promoted to posix. */
        struct statvfs StatVFS;
        RT_ZERO(StatVFS);
        if (!statvfs(pszNativeFsPath, &StatVFS))
        {
            /*
             * Calc the returned values.
             */
            if (pcbTotal)
                *pcbTotal = (RTFOFF)StatVFS.f_blocks * StatVFS.f_frsize;
            if (pcbFree)
                *pcbFree = (RTFOFF)StatVFS.f_bavail * StatVFS.f_frsize;
            if (pcbBlock)
                *pcbBlock = StatVFS.f_frsize;
            /* no idea how to get the sector... */
            if (pcbSector)
                *pcbSector = 512;
        }
        else
            rc = RTErrConvertFromErrno(errno);
        rtPathFreeNative(pszNativeFsPath, pszFsPath);
    }

    LogFlow(("RTFsQuerySizes(%p:{%s}, %p:{%RTfoff}, %p:{%RTfoff}, %p:{%RX32}, %p:{%RX32}): returns %Rrc\n",
             pszFsPath, pszFsPath, pcbTotal, pcbTotal ? *pcbTotal : 0, pcbFree, pcbFree ? *pcbFree : 0,
             pcbBlock, pcbBlock ? *pcbBlock : 0, pcbSector, pcbSector ? *pcbSector : 0, rc));
    return rc;
}
Beispiel #20
0
RTDECL(int) RTAsn1GeneralizedTime_DecodeAsn1(PRTASN1CURSOR pCursor, uint32_t fFlags, PRTASN1TIME pThis, const char *pszErrorTag)
{
    int rc = RTAsn1CursorReadHdr(pCursor, &pThis->Asn1Core, pszErrorTag);
    if (RT_SUCCESS(rc))
    {
        rc = RTAsn1CursorMatchTagClassFlags(pCursor, &pThis->Asn1Core, ASN1_TAG_GENERALIZED_TIME,
                                            ASN1_TAGCLASS_UNIVERSAL | ASN1_TAGFLAG_PRIMITIVE,
                                            fFlags, pszErrorTag, "GENERALIZED TIME");
        if (RT_SUCCESS(rc))
        {
            RTAsn1CursorSkip(pCursor, pThis->Asn1Core.cb);
            pThis->Asn1Core.pOps    = &g_RTAsn1Time_Vtable;
            pThis->Asn1Core.fFlags |= RTASN1CORE_F_PRIMITE_TAG_STRUCT;
            return rtAsn1Time_ConvertGeneralizedTime(pCursor, pThis, pszErrorTag);
        }
    }
    RT_ZERO(*pThis);
    return rc;
}
Beispiel #21
0
RTR3DECL(int) RTFsQueryProperties(const char *pszFsPath, PRTFSPROPERTIES pProperties)
{
    /*
     * Validate.
     */
    AssertMsgReturn(VALID_PTR(pszFsPath) && *pszFsPath, ("%p", pszFsPath), VERR_INVALID_PARAMETER);
    AssertMsgReturn(VALID_PTR(pProperties), ("%p", pProperties), VERR_INVALID_PARAMETER);

    /*
     * Convert the path and query the information.
     */
    char const *pszNativeFsPath;
    int rc = rtPathToNative(&pszNativeFsPath, pszFsPath, NULL);
    if (RT_SUCCESS(rc))
    {
        struct statvfs StatVFS;
        RT_ZERO(StatVFS);
        if (!statvfs(pszNativeFsPath, &StatVFS))
        {
            /*
             * Calc/fake the returned values.
             */
            pProperties->cbMaxComponent = StatVFS.f_namemax;
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
            pProperties->fCaseSensitive = false;
#else
            pProperties->fCaseSensitive = true;
#endif
            pProperties->fCompressed = false;
            pProperties->fFileCompression = false;
            pProperties->fReadOnly = !!(StatVFS.f_flag & ST_RDONLY);
            pProperties->fRemote = false;
            pProperties->fSupportsUnicode = true;
        }
        else
            rc = RTErrConvertFromErrno(errno);
        rtPathFreeNative(pszNativeFsPath, pszFsPath);
    }

    LogFlow(("RTFsQueryProperties(%p:{%s}, %p:{.cbMaxComponent=%u, .fReadOnly=%RTbool}): returns %Rrc\n",
             pszFsPath, pszFsPath, pProperties, pProperties->cbMaxComponent, pProperties->fReadOnly, rc));
    return rc;
}
Beispiel #22
0
int localMappings(const ComNatPtr& nat, AddressToOffsetMapping& mapping)
{
    mapping.clear();

    ComBstrArray strs;
    size_t cStrs;
    HRESULT hrc = nat->COMGETTER(LocalMappings)(ComSafeArrayAsOutParam(strs));
    if (   SUCCEEDED(hrc)
            && (cStrs = strs.size()))
    {
        for (size_t i = 0; i < cStrs; ++i)
        {
            char szAddr[17];
            RTNETADDRIPV4 ip4addr;
            char *pszTerm;
            uint32_t u32Off;
            com::Utf8Str strLo2Off(strs[i]);
            const char *pszLo2Off = strLo2Off.c_str();

            RT_ZERO(szAddr);

            pszTerm = RTStrStr(pszLo2Off, "=");

            if (   pszTerm
                    && (pszTerm - pszLo2Off) <= INET_ADDRSTRLEN)
            {
                memcpy(szAddr, pszLo2Off, (pszTerm - pszLo2Off));
                int rc = RTNetStrToIPv4Addr(szAddr, &ip4addr);
                if (RT_SUCCESS(rc))
                {
                    u32Off = RTStrToUInt32(pszTerm + 1);
                    if (u32Off != 0)
                        mapping.insert(
                            AddressToOffsetMapping::value_type(ip4addr, u32Off));
                }
            }
        }
    }
    else
        return VERR_NOT_FOUND;

    return VINF_SUCCESS;
}
VBGLR3DECL(int) VbglR3DnDGHErrorEvent(int rcOp)
{
    DO(("GH_ERROR\n"));

    /* Initialize header */
    DragAndDropSvc::VBOXDNDGHEVTERRORMSG Msg;
    RT_ZERO(Msg);
    Msg.hdr.result      = VERR_WRONG_ORDER;
    Msg.hdr.u32ClientID = g_clientId;
    Msg.hdr.u32Function = DragAndDropSvc::GUEST_DND_GH_EVT_ERROR;
    Msg.hdr.cParms      = 1;
    /* Initialize parameter */
    Msg.uRC.SetUInt32(rcOp);
    /* Do request */
    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CALL(sizeof(Msg)), &Msg, sizeof(Msg));
    if (RT_SUCCESS(rc))
        rc = Msg.hdr.result;
    return rc;
}
/* Initialize the memory buffer including its checksum.
 * No changes alloed to the header and the tail after that.
 */
HGSMIOFFSET HGSMIBufferInitializeSingle(const HGSMIAREA *pArea,
                                        HGSMIBUFFERHEADER *pHeader,
                                        HGSMISIZE cbBuffer,
                                        uint8_t u8Channel,
                                        uint16_t u16ChannelInfo)
{
    if (   !pArea
        || !pHeader
        || cbBuffer < HGSMIBufferMinimumSize())
    {
        return HGSMIOFFSET_VOID;
    }

    /* Buffer must be within the area:
     *   * header data size do not exceed the maximum data size;
     *   * buffer address is greater than the area base address;
     *   * buffer address is lower than the maximum allowed for the given data size.
     */
    HGSMISIZE cbMaximumDataSize = pArea->offLast - pArea->offBase;
    uint32_t u32DataSize = cbBuffer - HGSMIBufferMinimumSize();

    if (   u32DataSize > cbMaximumDataSize
        || (uint8_t *)pHeader < pArea->pu8Base
        || (uint8_t *)pHeader > pArea->pu8Base + cbMaximumDataSize - u32DataSize)
    {
        return HGSMIOFFSET_VOID;
    }

    HGSMIOFFSET offBuffer = HGSMIPointerToOffset(pArea, pHeader);

    pHeader->u8Flags        = HGSMI_BUFFER_HEADER_F_SEQ_SINGLE;
    pHeader->u32DataSize    = u32DataSize;
    pHeader->u8Channel      = u8Channel;
    pHeader->u16ChannelInfo = u16ChannelInfo;
    RT_ZERO(pHeader->u.au8Union);

    HGSMIBUFFERTAIL *pTail = HGSMIBufferTailFromPtr(pHeader, u32DataSize);
    pTail->u32Reserved = 0;
    pTail->u32Checksum = HGSMIChecksum(offBuffer, pHeader, pTail);

    return offBuffer;
}
VBGLR3DECL(int) VbglR3DnDHGRequestData(const char* pcszFormat)
{
    DO(("DATA_REQ: '%s'\n", pcszFormat));
    /* Validate input */
    AssertPtrReturn(pcszFormat, VERR_INVALID_PARAMETER);

    /* Initialize header */
    DragAndDropSvc::VBOXDNDHGREQDATAMSG Msg;
    RT_ZERO(Msg);
    Msg.hdr.result      = VERR_WRONG_ORDER;
    Msg.hdr.u32ClientID = g_clientId;
    Msg.hdr.u32Function = DragAndDropSvc::GUEST_DND_HG_REQ_DATA;
    Msg.hdr.cParms      = 1;
    /* Do request */
    Msg.pFormat.SetPtr((void*)pcszFormat, (uint32_t)strlen(pcszFormat) + 1);
    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CALL(sizeof(Msg)), &Msg, sizeof(Msg));
    if (RT_SUCCESS(rc))
        rc = Msg.hdr.result;
    return rc;
}
Beispiel #26
0
/**
 * Connects to an HGCM service.
 *
 * @returns VBox status code
 * @returns VERR_NOT_SUPPORTED if pass-through is not available on the host.
 * @param   pszServiceName  Name of the host service.
 * @param   pidClient       Where to put the client ID on success. The client ID
 *                          must be passed to all the other calls to the service.
 */
VBGLR3DECL(int) VbglR3HGCMConnect(const char *pszServiceName, HGCMCLIENTID *pidClient)
{
    VBoxGuestHGCMConnectInfo Info;
    Info.result = VERR_WRONG_ORDER;
    Info.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
    RT_ZERO(Info.Loc.u);
    strcpy(Info.Loc.u.host.achName, pszServiceName);
    Info.u32ClientID = UINT32_MAX;  /* try make valgrind shut up. */

    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CONNECT, &Info, sizeof(Info));
    if (RT_SUCCESS(rc))
    {
        rc = Info.result;
        if (RT_SUCCESS(rc))
            *pidClient = Info.u32ClientID;
        if (rc == VERR_NOT_IMPLEMENTED || rc == VERR_HGCM_SERVICE_NOT_FOUND)
            rc = VERR_NOT_SUPPORTED;
    }
    return rc;
}
/**
 * Connects to the clipboard service.
 *
 * @returns VBox status code
 * @param   pu32ClientId    Where to put the client id on success. The client id
 *                          must be passed to all the other clipboard calls.
 */
VBGLR3DECL(int) VbglR3ClipboardConnect(uint32_t *pu32ClientId)
{
    VBoxGuestHGCMConnectInfo Info;
    Info.result = VERR_WRONG_ORDER;
    Info.Loc.type = VMMDevHGCMLoc_LocalHost_Existing;
    RT_ZERO(Info.Loc.u);
    strcpy(Info.Loc.u.host.achName, "VBoxSharedClipboard");
    Info.u32ClientID = UINT32_MAX;  /* try make valgrind shut up. */

    int rc = vbglR3DoIOCtl(VBOXGUEST_IOCTL_HGCM_CONNECT, &Info, sizeof(Info));
    if (RT_SUCCESS(rc))
    {
        rc = Info.result;
        if (RT_SUCCESS(rc))
            *pu32ClientId = Info.u32ClientID;
    }
    if (rc == VERR_HGCM_SERVICE_NOT_FOUND)
        rc = VINF_PERMISSION_DENIED;
    return rc;
}
Beispiel #28
0
/**
 * Initializes remaining bits of the Minimal provider.
 * This is called after initializing HM and almost all other VMM components.
 *
 * @returns VBox status code.
 * @param   pVM     Pointer to the VM.
 */
VMMR3_INT_DECL(int) GIMR3MinimalInitCompleted(PVM pVM)
{
    /*
     * Expose a generic hypervisor-agnostic leaf (originally defined VMware).
     * The leaves range from  0x40000010 to 0x400000FF.
     *
     * This is done in the init. completed routine as we need PDM to be
     * initialized (otherwise PDMApicGetTimerFreq() would fail).
     */
    CPUMCPUIDLEAF HyperLeaf;
    int rc = CPUMR3CpuIdGetLeaf(pVM, &HyperLeaf, 0x40000000, 0 /* uSubLeaf */);
    if (RT_SUCCESS(rc))
    {
        HyperLeaf.uEax         = UINT32_C(0x40000010);  /* Maximum leaf we implement. */
        rc = CPUMR3CpuIdInsert(pVM, &HyperLeaf);
        AssertLogRelRCReturn(rc, rc);

        /*
         * Add the timing information hypervisor leaf.
         * MacOS X uses this to determine the TSC, bus frequency. See @bugref{7270}.
         *
         * EAX - TSC frequency in KHz.
         * EBX - APIC frequency in KHz.
         * ECX, EDX - Reserved.
         */
        uint64_t uApicFreq;
        rc = PDMApicGetTimerFreq(pVM, &uApicFreq);
        AssertLogRelRCReturn(rc, rc);

        RT_ZERO(HyperLeaf);
        HyperLeaf.uLeaf        = UINT32_C(0x40000010);
        HyperLeaf.uEax         = TMCpuTicksPerSecond(pVM) / UINT64_C(1000);
        HyperLeaf.uEbx         = (uApicFreq + 500) / UINT64_C(1000);
        rc = CPUMR3CpuIdInsert(pVM, &HyperLeaf);
        AssertLogRelRCReturn(rc, rc);
    }
    else
        LogRel(("GIM: Minimal: failed to get hypervisor leaf 0x40000000.\n"));

    return VINF_SUCCESS;
}
/**
 * The client is requesting an offer.
 *
 * @returns true.
 *
 * @param   pDhcpMsg    The message.
 * @param   cb          The message size.
 */
bool NetworkManager::handleDhcpReqRequest(PCRTNETBOOTP pDhcpMsg, size_t cb)
{
    ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();

    /* 1. find client */
    Client client = confManager->getClientByDhcpPacket(pDhcpMsg, cb);

    /* 2. find bound lease */
    Lease l = client.lease();
    if (l != Lease::NullLease)
    {

        if (l.isExpired())
        {
            /* send client to INIT state */
            Client c(client);
            nak(client, pDhcpMsg->bp_xid);
            confManager->expireLease4Client(c);
            return true;
        }
        else {
            /* XXX: Validate request */
            RawOption opt;
            RT_ZERO(opt);

            Client c(client);
            int rc = confManager->commitLease4Client(c);
            AssertRCReturn(rc, false);

            rc = ConfigurationManager::extractRequestList(pDhcpMsg, cb, opt);
            AssertRCReturn(rc, false);

            ack(client, pDhcpMsg->bp_xid, opt.au8RawOpt, opt.cbRawOpt);
        }
    }
    else
    {
        nak(client, pDhcpMsg->bp_xid);
    }
    return true;
}
RemoteUSBBackend::RemoteUSBBackend(Console *console, ConsoleVRDPServer *server, uint32_t u32ClientId)
    :
    mConsole(console),
    mServer(server),
    cRefs(0),
    mu32ClientId(u32ClientId),
    mfHasDeviceList(false),
    mpvDeviceList(NULL),
    mcbDeviceList(0),
    menmPollRemoteDevicesStatus(PollRemoteDevicesStatus_Negotiate),
    mfPollURB(true),
    mpDevices(NULL),
    mfWillBeDeleted(false),
    mClientVersion(0),                   /* VRDE_USB_VERSION_2: the client version. */
    mfDescExt(false)                     /* VRDE_USB_VERSION_3: VRDE_USB_REQ_DEVICE_LIST_EXT_RET. */
{
    Assert(console);
    Assert(server);

    int rc = RTCritSectInit(&mCritsect);

    if (RT_FAILURE(rc))
    {
        AssertFailed();
        RT_ZERO(mCritsect);
    }

    mCallback.pInstance           = (PREMOTEUSBBACKEND)this;
    mCallback.pfnOpen             = iface_Open;
    mCallback.pfnClose            = iface_Close;
    mCallback.pfnReset            = iface_Reset;
    mCallback.pfnSetConfig        = iface_SetConfig;
    mCallback.pfnClaimInterface   = iface_ClaimInterface;
    mCallback.pfnReleaseInterface = iface_ReleaseInterface;
    mCallback.pfnInterfaceSetting = iface_InterfaceSetting;
    mCallback.pfnQueueURB         = iface_QueueURB;
    mCallback.pfnReapURB          = iface_ReapURB;
    mCallback.pfnClearHaltedEP    = iface_ClearHaltedEP;
    mCallback.pfnCancelURB        = iface_CancelURB;
    mCallback.pfnWakeup           = iface_Wakeup;
}