AJ_Status AJNS_Consumer_CreateSessionWithProducer(AJ_BusAttachment* busAttachment, const char* senderName, uint32_t* requestSerialNumber)
{
    AJ_Status status = AJ_OK;
    AJ_SessionOpts sessionOpts = {
        AJ_SESSION_TRAFFIC_MESSAGES,
        AJ_SESSION_PROXIMITY_ANY,
        AJ_TRANSPORT_ANY,
        FALSE
    };

    AJ_InfoPrintf(("Inside CreateSessionWithProducer()\n"));
    *requestSerialNumber = busAttachment->serial;
    AJ_InfoPrintf(("CreateSessionWithProducer(): Joining session with %s on port %u with serial number %u\n", senderName, AJNS_NotificationProducerPort, *requestSerialNumber));
    status = AJ_BusJoinSession(busAttachment, senderName, AJNS_NotificationProducerPort, &sessionOpts);
    AJ_InfoPrintf(("CreateSessionWithProducer(): AJ_BusJoinSession() returned with status %s\n", AJ_StatusText(status)));
    return status;
}
Esempio n. 2
0
static uint8_t OnAboutMatch(uint16_t version, uint16_t port, const char* peerName, const char* objPath)
{
    AJ_Status status;

    strncpy(serviceObjPath, objPath, sizeof(serviceObjPath));
    serviceObjPath[sizeof(serviceObjPath) - 1] = 0;

    strncpy(serviceName, peerName, sizeof(serviceName));
    serviceName[sizeof(serviceName) - 1] = 0;

    status = AJ_BusJoinSession(&bus, peerName, port, NULL);
    if (status != AJ_OK) {
        AJ_ErrPrintf(("JoinSession failed %s\n", AJ_StatusText(status)));
    }

    return TRUE;
}
AJSVC_ServiceStatus CPS_MessageProcessor(AJ_BusAttachment* bus, AJ_Message* msg, AJ_Status*msgStatus)
{
    AJSVC_ServiceStatus service_Status = AJSVC_SERVICE_STATUS_HANDLED;
    switch (msg->msgId) {
    case CONTROL_ANNOUNCE_SIGNAL_RECEIVED:
        AJ_InfoPrintf(("Received Announce Signal from %s.\n", msg->sender));
        if (CPSsessionId == 0) {
            if (!isControlPanelAnnounce(msg)) {
                break;
            }
            AJ_SessionOpts sessionOpts = {
                AJ_SESSION_TRAFFIC_MESSAGES,
                AJ_SESSION_PROXIMITY_ANY,
                AJ_TRANSPORT_ANY,
                TRUE
            };
            strcpy(announceSender, msg->sender);

            AJ_BusJoinSession(bus, msg->sender, ServicePort, &sessionOpts);
        }
        break;

        ALL_REPLY_CASES
            runningTestNum++;
        CPS_IdleConnectedHandler(bus);
        break;

    case AJ_SIGNAL_SESSION_LOST:
        CPSsessionId = 0;
        break;

    default:
        service_Status = AJSVC_SERVICE_STATUS_NOT_HANDLED;
        break;
    }
    return service_Status;
}
Esempio n. 4
0
AJ_Status AJ_StartClient2(AJ_BusAttachment* bus,
                          const char* daemonName,
                          uint32_t timeout,
                          uint8_t connected,
                          const char* name,
                          uint16_t port,
                          uint32_t* sessionId,
                          const AJ_SessionOpts* opts
                          )
{
    AJ_Status status = AJ_OK;
    AJ_Time timer;
    AJ_Time unmarshalTimer;
    uint8_t foundName = FALSE;
    uint8_t clientStarted = FALSE;
    uint8_t initial = TRUE;
    AJ_InitTimer(&timer);

    while (TRUE) {
        if (AJ_GetElapsedTime(&timer, TRUE) > timeout) {
            return AJ_ERR_TIMEOUT;
        }
        if (!initial || !connected) {
            initial = FALSE;
            AJ_InfoPrintf(("Attempting to connect to bus\n"));
            status = AJ_Connect(bus, daemonName, CONNECT_TIMEOUT);
            if (status != AJ_OK) {
                AJ_WarnPrintf(("Failed to connect to bus sleeping for %d seconds\n", CONNECT_PAUSE / 1000));
                AJ_Sleep(CONNECT_PAUSE);
                continue;
            }
            AJ_InfoPrintf(("AllJoyn client connected to bus\n"));
        }
        /*
         * Kick things off by finding the service names
         */
        status = AJ_BusFindAdvertisedName(bus, name, AJ_BUS_START_FINDING);
        if (status == AJ_OK) {
            break;
        }
        AJ_WarnPrintf(("FindAdvertisedName failed\n"));
        AJ_Disconnect(bus);
    }

    *sessionId = 0;

    while (!clientStarted && (status == AJ_OK)) {
        AJ_Message msg;

        if (AJ_GetElapsedTime(&timer, TRUE) > timeout) {
            return AJ_ERR_TIMEOUT;
        }
        status = AJ_UnmarshalMsg(bus, &msg, UNMARSHAL_TIMEOUT);
        /*
         * TODO This is a temporary hack to work around buggy select imlpementations
         */
        AJ_InitTimer(&unmarshalTimer);
        if (status == AJ_ERR_TIMEOUT && (AJ_GetElapsedTime(&unmarshalTimer, TRUE) < UNMARSHAL_TIMEOUT || !foundName)) {
            /*
             * Timeouts are expected until we find a name
             */
            status = AJ_OK;
            continue;
        }

        if (status != AJ_OK) {
            break;
        }
        switch (msg.msgId) {

        case AJ_REPLY_ID(AJ_METHOD_FIND_NAME):
        case AJ_REPLY_ID(AJ_METHOD_FIND_NAME_BY_TRANSPORT):
            if (msg.hdr->msgType == AJ_MSG_ERROR) {
                status = AJ_ERR_FAILURE;
            } else {
                uint32_t disposition;
                AJ_UnmarshalArgs(&msg, "u", &disposition);
                if ((disposition != AJ_FIND_NAME_STARTED) && (disposition != AJ_FIND_NAME_ALREADY)) {
                    status = AJ_ERR_FAILURE;
                }
            }
            break;


        case AJ_SIGNAL_FOUND_ADV_NAME:
            {
                AJ_Arg arg;
                AJ_UnmarshalArg(&msg, &arg);
                AJ_InfoPrintf(("FoundAdvertisedName(%s)\n", arg.val.v_string));
                foundName = TRUE;
                status = AJ_BusJoinSession(bus, arg.val.v_string, port, opts);
            }
            break;

        case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION):
            {
                uint32_t replyCode;

                if (msg.hdr->msgType == AJ_MSG_ERROR) {
                    status = AJ_ERR_FAILURE;
                } else {
                    status = AJ_UnmarshalArgs(&msg, "uu", &replyCode, sessionId);
                    if (replyCode == AJ_JOINSESSION_REPLY_SUCCESS) {
                        clientStarted = TRUE;
                        AJ_BusSetSignalRule2(bus, "NameOwnerChanged", "org.freedesktop.DBus", AJ_BUS_SIGNAL_ALLOW);
                    } else {
                        status = AJ_ERR_FAILURE;
                    }
                }
            }
            break;

        case AJ_SIGNAL_SESSION_LOST:
            /*
             * Force a disconnect
             */
            status = AJ_ERR_READ;
            break;

        default:
            /*
             * Pass to the built-in bus message handlers
             */
            status = AJ_BusHandleBusMessage(&msg);
            break;
        }
        AJ_CloseMsg(&msg);
    }
    if (status != AJ_OK) {
        AJ_WarnPrintf(("AllJoyn disconnect bus status=%s\n", AJ_StatusText(status)));
        AJ_Disconnect(bus);
    }
    return status;
}
Esempio n. 5
0
static
AJ_Status StartClient(AJ_BusAttachment* bus,
                      const char* daemonName,
                      uint32_t timeout,
                      uint8_t connected,
                      const char* name,
                      uint16_t port,
                      const char** interfaces,
                      uint32_t* sessionId,
                      char* serviceName,
                      const AJ_SessionOpts* opts)
{
    AJ_Status status = AJ_OK;
    AJ_Time timer;
    uint8_t found = FALSE;
    uint8_t clientStarted = FALSE;
    uint32_t elapsed = 0;
    char* rule;
    size_t ruleLen;
    const char* base = "interface='org.alljoyn.About',sessionless='t'";
    const char* impl = ",implements='";
    const char** ifaces;

    AJ_InfoPrintf(("AJ_StartClient(bus=0x%p, daemonName=\"%s\", timeout=%d., connected=%d., interface=\"%p\", sessionId=0x%p, serviceName=0x%p, opts=0x%p)\n",
                   bus, daemonName, timeout, connected, interfaces, sessionId, serviceName, opts));

    AJ_InitTimer(&timer);

    if ((name == NULL && interfaces == NULL) ||
        (name != NULL && interfaces != NULL)) {
        return AJ_ERR_INVALID;
    }

    while (elapsed < timeout) {
        if (!connected) {
            status = AJ_FindBusAndConnect(bus, daemonName, AJ_CONNECT_TIMEOUT);
            elapsed = AJ_GetElapsedTime(&timer, TRUE);
            if (status != AJ_OK) {
                elapsed += AJ_CONNECT_PAUSE;
                if (elapsed > timeout) {
                    break;
                }
                AJ_WarnPrintf(("AJ_StartClient(): Failed to connect to bus, sleeping for %d seconds\n", AJ_CONNECT_PAUSE / 1000));
                AJ_Sleep(AJ_CONNECT_PAUSE);
                continue;
            }
            AJ_InfoPrintf(("AJ_StartClient(): AllJoyn client connected to bus\n"));
        }
        if (name != NULL) {
            /*
             * Kick things off by finding the service names
             */
            status = AJ_BusFindAdvertisedName(bus, name, AJ_BUS_START_FINDING);
            AJ_InfoPrintf(("AJ_StartClient(): AJ_BusFindAdvertisedName()\n"));
        } else {
            /*
             * Kick things off by finding all services that implement the interface
             */
            ruleLen = strlen(base) + 1;
            ifaces = interfaces;
            while (*ifaces != NULL) {
                ruleLen += strlen(impl) + strlen(*ifaces) + 1;
                ifaces++;
            }
            rule = (char*) AJ_Malloc(ruleLen);
            if (rule == NULL) {
                status = AJ_ERR_RESOURCES;
                break;
            }
            strcpy(rule, base);
            ifaces = interfaces;
            while (*ifaces != NULL) {
                strcat(rule, impl);
                if ((*ifaces)[0] == '$') {
                    strcat(rule, &(*ifaces)[1]);
                } else {
                    strcat(rule, *ifaces);
                }
                strcat(rule, "'");
                ifaces++;
            }
            status = AJ_BusSetSignalRule(bus, rule, AJ_BUS_SIGNAL_ALLOW);
            AJ_InfoPrintf(("AJ_StartClient(): Client SetSignalRule: %s\n", rule));
            AJ_Free(rule);
        }
        if (status == AJ_OK) {
            break;
        }
        if (!connected) {
            AJ_WarnPrintf(("AJ_StartClient(): Client disconnecting from bus: status=%s.\n", AJ_StatusText(status)));
            AJ_Disconnect(bus);
        }
    }
    if (elapsed > timeout) {
        AJ_WarnPrintf(("AJ_StartClient(): Client timed-out trying to connect to bus: status=%s.\n", AJ_StatusText(status)));
        return AJ_ERR_TIMEOUT;
    }
    timeout -= elapsed;

    if (status != AJ_OK) {
        return status;
    }

    *sessionId = 0;
    if (serviceName != NULL) {
        *serviceName = '\0';
    }

    while (!clientStarted && (status == AJ_OK)) {
        AJ_Message msg;
        status = AJ_UnmarshalMsg(bus, &msg, AJ_UNMARSHAL_TIMEOUT);
        if ((status == AJ_ERR_TIMEOUT) && !found) {
            /*
             * Timeouts are expected until we find a name or service
             */
            if (timeout < AJ_UNMARSHAL_TIMEOUT) {
                return status;
            }
            timeout -= AJ_UNMARSHAL_TIMEOUT;
            status = AJ_OK;
            continue;
        }
        if (status == AJ_ERR_NO_MATCH) {
            // Ignore unknown messages
            status = AJ_OK;
            continue;
        }
        if (status != AJ_OK) {
            AJ_ErrPrintf(("AJ_StartClient(): status=%s\n", AJ_StatusText(status)));
            break;
        }
        switch (msg.msgId) {

        case AJ_REPLY_ID(AJ_METHOD_FIND_NAME):
        case AJ_REPLY_ID(AJ_METHOD_FIND_NAME_BY_TRANSPORT):
            if (msg.hdr->msgType == AJ_MSG_ERROR) {
                AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_FIND_NAME: %s\n", msg.error));
                status = AJ_ERR_FAILURE;
            } else {
                uint32_t disposition;
                AJ_UnmarshalArgs(&msg, "u", &disposition);
                if ((disposition != AJ_FIND_NAME_STARTED) && (disposition != AJ_FIND_NAME_ALREADY)) {
                    AJ_ErrPrintf(("AJ_StartClient(): AJ_ERR_FAILURE\n"));
                    status = AJ_ERR_FAILURE;
                }
            }
            break;

        case AJ_SIGNAL_FOUND_ADV_NAME:
            {
                AJ_Arg arg;
                AJ_UnmarshalArg(&msg, &arg);
                AJ_InfoPrintf(("FoundAdvertisedName(%s)\n", arg.val.v_string));
                found = TRUE;
                status = AJ_BusJoinSession(bus, arg.val.v_string, port, opts);
            }
            break;

        case AJ_SIGNAL_ABOUT_ANNOUNCE:
            {
                uint16_t version, port;
                AJ_InfoPrintf(("AJ_StartClient(): AboutAnnounce from (%s)\n", msg.sender));
                if (!found) {
                    found = TRUE;
                    AJ_UnmarshalArgs(&msg, "qq", &version, &port);
                    status = AJ_BusJoinSession(bus, msg.sender, port, opts);
                    if (serviceName != NULL) {
                        strncpy(serviceName, msg.sender, AJ_MAX_NAME_SIZE);
                        serviceName[AJ_MAX_NAME_SIZE] = '\0';
                    }
                    if (status != AJ_OK) {
                        AJ_ErrPrintf(("AJ_StartClient(): BusJoinSession failed (%s)\n", AJ_StatusText(status)));
                    }
                }
            }
            break;

        case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION):
            {
                uint32_t replyCode;

                if (msg.hdr->msgType == AJ_MSG_ERROR) {
                    AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_JOIN_SESSION: %s\n", msg.error));
                    status = AJ_ERR_FAILURE;
                } else {
                    status = AJ_UnmarshalArgs(&msg, "uu", &replyCode, sessionId);
                    if (replyCode == AJ_JOINSESSION_REPLY_SUCCESS) {
                        clientStarted = TRUE;
                    } else {
                        AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_JOIN_SESSION reply (%d)\n", replyCode));
                        status = AJ_ERR_FAILURE;
                    }
                }
            }
            break;

        case AJ_SIGNAL_SESSION_LOST_WITH_REASON:
            /*
             * Force a disconnect
             */
            {
                uint32_t id, reason;
                AJ_UnmarshalArgs(&msg, "uu", &id, &reason);
                AJ_InfoPrintf(("Session lost. ID = %u, reason = %u", id, reason));
            }
            AJ_ErrPrintf(("AJ_StartClient(): AJ_SIGNAL_SESSION_LOST_WITH_REASON: AJ_ERR_READ\n"));
            status = AJ_ERR_READ;
            break;

        default:
            /*
             * Pass to the built-in bus message handlers
             */
            AJ_InfoPrintf(("AJ_StartClient(): AJ_BusHandleBusMessage()\n"));
            status = AJ_BusHandleBusMessage(&msg);
            break;
        }
        AJ_CloseMsg(&msg);
    }
    if (status != AJ_OK && !connected) {
        AJ_WarnPrintf(("AJ_StartClient(): Client disconnecting from bus: status=%s\n", AJ_StatusText(status)));
        AJ_Disconnect(bus);
    }
    return status;
}
Esempio n. 6
0
AJ_Status AJ_StartClient(AJ_BusAttachment* bus,
                         const char* daemonName,
                         uint32_t timeout,
                         uint8_t connected,
                         const char* name,
                         uint16_t port,
                         uint32_t* sessionId,
                         const AJ_SessionOpts* opts)
{
    AJ_Status status = AJ_OK;
    AJ_Time timer;
    uint8_t foundName = FALSE;
    uint8_t clientStarted = FALSE;
    uint32_t elapsed = 0;

    AJ_InfoPrintf(("AJ_StartClient(bus=0x%p, daemonName=\"%s\", timeout=%d., connected=%d., name=\"%s\", port=%d., sessionId=0x%p, opts=0x%p)\n",
                   bus, daemonName, timeout, connected, name, port, sessionId, opts));

    AJ_InitTimer(&timer);

    while (elapsed < timeout) {
        if (!connected) {
            AJ_InfoPrintf(("AJ_StartClient(): AJ_FindBusAndConnect()\n"));
            status = AJ_FindBusAndConnect(bus, daemonName, AJ_CONNECT_TIMEOUT);
            elapsed = AJ_GetElapsedTime(&timer, TRUE);
            if (status != AJ_OK) {
                elapsed += AJ_CONNECT_PAUSE;
                if (elapsed > timeout) {
                    break;
                }
                AJ_WarnPrintf(("Failed to connect to bus sleeping for %d seconds\n", AJ_CONNECT_PAUSE / 1000));
                AJ_Sleep(AJ_CONNECT_PAUSE);
                continue;
            }
            AJ_InfoPrintf(("AllJoyn client connected to bus\n"));
        }
        /*
         * Kick things off by finding the service names
         */
        AJ_InfoPrintf(("AJ_StartClient(): AJ_BusFindAdvertisedName()\n"));
        status = AJ_BusFindAdvertisedName(bus, name, AJ_BUS_START_FINDING);
        if (status == AJ_OK) {
            break;
        }
        if (!connected) {
            AJ_WarnPrintf(("AjStartClient2(): AJ_Disconnect(): status=%s.\n", AJ_StatusText(status)));
            AJ_Disconnect(bus);
        }
    }
    if (elapsed > timeout) {
        return AJ_ERR_TIMEOUT;
    }
    timeout -= elapsed;

    *sessionId = 0;

    while (!clientStarted && (status == AJ_OK)) {
        AJ_Message msg;
        status = AJ_UnmarshalMsg(bus, &msg, AJ_UNMARSHAL_TIMEOUT);
        if ((status == AJ_ERR_TIMEOUT) && !foundName) {
            /*
             * Timeouts are expected until we find a name
             */
            if (timeout < AJ_UNMARSHAL_TIMEOUT) {
                return status;
            }
            timeout -= AJ_UNMARSHAL_TIMEOUT;
            status = AJ_OK;
            continue;
        }
        if (status != AJ_OK) {
            AJ_ErrPrintf(("AJ_StartClient(): status=%s\n", AJ_StatusText(status)));
            break;
        }
        switch (msg.msgId) {

        case AJ_REPLY_ID(AJ_METHOD_FIND_NAME):
        case AJ_REPLY_ID(AJ_METHOD_FIND_NAME_BY_TRANSPORT):
            if (msg.hdr->msgType == AJ_MSG_ERROR) {
                AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_FIND_NAME: %s\n", msg.error));
                status = AJ_ERR_FAILURE;
            } else {
                uint32_t disposition;
                AJ_UnmarshalArgs(&msg, "u", &disposition);
                if ((disposition != AJ_FIND_NAME_STARTED) && (disposition != AJ_FIND_NAME_ALREADY)) {
                    AJ_ErrPrintf(("AJ_StartClient(): AJ_ERR_FAILURE\n"));
                    status = AJ_ERR_FAILURE;
                }
            }
            break;


        case AJ_SIGNAL_FOUND_ADV_NAME:
            {
                AJ_Arg arg;
                AJ_UnmarshalArg(&msg, &arg);
                AJ_InfoPrintf(("FoundAdvertisedName(%s)\n", arg.val.v_string));
                foundName = TRUE;
                status = AJ_BusJoinSession(bus, arg.val.v_string, port, opts);
            }
            break;

        case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION):
            {
                uint32_t replyCode;

                if (msg.hdr->msgType == AJ_MSG_ERROR) {
                    AJ_ErrPrintf(("AJ_StartClient(): AJ_METHOD_JOIN_SESSION: %s\n", msg.error));
                    status = AJ_ERR_FAILURE;
                } else {
                    status = AJ_UnmarshalArgs(&msg, "uu", &replyCode, sessionId);
                    if (replyCode == AJ_JOINSESSION_REPLY_SUCCESS) {
                        clientStarted = TRUE;
                    } else {
                        AJ_ErrPrintf(("AJ_StartClient(): AJ_ERR_FAILURE\n"));
                        status = AJ_ERR_FAILURE;
                    }
                }
            }
            break;

        case AJ_SIGNAL_SESSION_LOST_WITH_REASON:
            /*
             * Force a disconnect
             */
            {
                uint32_t id, reason;
                AJ_UnmarshalArgs(&msg, "uu", &id, &reason);
                AJ_InfoPrintf(("Session lost. ID = %u, reason = %u", id, reason));
            }
            AJ_ErrPrintf(("AJ_StartClient(): AJ_SIGNAL_SESSION_LOST_WITH_REASON: AJ_ERR_READ\n"));
            status = AJ_ERR_READ;
            break;

        default:
            /*
             * Pass to the built-in bus message handlers
             */
            AJ_InfoPrintf(("AJ_StartClient(): AJ_BusHandleBusMessage()\n"));
            status = AJ_BusHandleBusMessage(&msg);
            break;
        }
        AJ_CloseMsg(&msg);
    }
    if (status != AJ_OK) {
        AJ_WarnPrintf(("AJ_StartClient(): AJ_Disconnect(): status=%s\n", AJ_StatusText(status)));
        AJ_Disconnect(bus);
    }
    return status;
}
Esempio n. 7
0
int AJ_Main()
{
    AJ_Status status;
    AJ_BusAttachment bus;
    int i;
    AJ_Initialize();
    AJ_PrintXML(AppObjects);
    AJ_RegisterObjects(AppObjects, NULL);

    Do_Connect(&bus);

    if (authenticate) {
        AJ_BusSetAuthListenerCallback(&bus, AuthListenerCallback);
    } else {
        authStatus = AJ_OK;
    }
    i = 0;
    while (commands[i] != NULL) {
        AJ_AlwaysPrintf(("%s\n", commands[i]));
        i++;
    }
    i = 0;
    while (TRUE) {
        // check for serial input and dispatch if needed.
        char buf[1024];
        AJ_Message msg;
        // read a line
        if (commands[i] != NULL) {
            char*command;
            strcpy(buf, commands[i]);
            AJ_AlwaysPrintf((">~~~%s\n", buf));
            command = aj_strtok(buf, " \r\n");
            i++;

            if (0 == strcmp("startservice", command)) {
                uint16_t port = 0;
                const char* name;
                AJ_SessionOpts opts;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    name = token;
                } else {
                    name = ServiceName;
                }
                token = aj_strtok(NULL, " \r\n");

                if (token) {
                    port = (uint16_t)atoi(token);
                }
                if (port == 0) {
                    port = ServicePort;
                }
                token = aj_strtok(NULL, " \r\n");

                if (token) {
                    opts.isMultipoint = (0 == strcmp("true", token));
                } else {
                    opts.isMultipoint = 0;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.traffic = atoi(token);
                } else {
                    opts.traffic = 0x1;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.proximity = atoi(token);
                } else {
                    opts.proximity = 0xFF;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.transports = atoi(token);
                } else {
                    opts.transports = 0xFFFF;
                }

                status = AJ_StartService(&bus, NULL, CONNECT_TIMEOUT, TRUE, port, name, AJ_NAME_REQ_DO_NOT_QUEUE, &opts);
                AJ_BusAddSignalRule(&bus, "Chat", InterfaceName, AJ_BUS_SIGNAL_ALLOW);
            } else if (0 == strcmp("find", command)) {
                char* namePrefix = aj_strtok(NULL, " \r\n");
                if (!namePrefix) {
                    AJ_AlwaysPrintf(("Usage: find <name_prefix>\n"));
                    continue;
                }
                status = AJ_BusFindAdvertisedName(&bus, namePrefix, AJ_BUS_START_FINDING);
            } else if (0 == strcmp("cancelfind", command)) {
                char* namePrefix = aj_strtok(NULL, " \r\n");
                if (!namePrefix) {
                    AJ_AlwaysPrintf(("Usage: cancelfind <name_prefix>\n"));
                    continue;
                }
                status = AJ_BusFindAdvertisedName(&bus, namePrefix, AJ_BUS_STOP_FINDING);
            } else if (0 == strcmp("find2", command)) {
                char* namePrefix = aj_strtok(NULL, " \r\n");
                uint16_t transport = 0;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    transport = (uint16_t)atoi(token);
                }
                if (!namePrefix || !transport) {
                    AJ_AlwaysPrintf(("Usage: find2 <name_prefix> <transport>\n"));
                    continue;
                }
                status = AJ_BusFindAdvertisedNameByTransport(&bus, namePrefix, transport, AJ_BUS_START_FINDING);
            } else if (0 == strcmp("cancelfind2", command)) {
                char* namePrefix = aj_strtok(NULL, " \r\n");
                uint16_t transport = 0;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    transport = (uint16_t)atoi(token);
                }
                if (!namePrefix || !transport) {
                    AJ_AlwaysPrintf(("Usage: cancelfind2 <name_prefix> <transport>\n"));
                    continue;
                }
                status = AJ_BusFindAdvertisedNameByTransport(&bus, namePrefix, transport, AJ_BUS_STOP_FINDING);
            } else if (0 == strcmp("requestname", command)) {
                char* name = aj_strtok(NULL, " \r\n");
                if (!name) {
                    AJ_AlwaysPrintf(("Usage: requestname <name>\n"));
                    continue;
                }
                status = AJ_BusRequestName(&bus, name, AJ_NAME_REQ_DO_NOT_QUEUE);
            } else if (0 == strcmp("releasename", command)) {
                char* name = aj_strtok(NULL, " \r\n");
                if (!name) {
                    AJ_AlwaysPrintf(("Usage: releasename <name>\n"));
                    continue;
                }
                status = AJ_BusReleaseName(&bus, name);
            } else if (0 == strcmp("advertise", command)) {
                uint16_t transport = 0xFFFF;
                char* token = NULL;
                char* name = aj_strtok(NULL, " \r\n");
                if (!name) {
                    AJ_AlwaysPrintf(("Usage: advertise <name> [transports]\n"));
                    continue;
                }
                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    transport = (uint16_t)atoi(token);
                }
                status = AJ_BusAdvertiseName(&bus, name, transport, AJ_BUS_START_ADVERTISING, 0);
            } else if (0 == strcmp("canceladvertise", command)) {
                uint16_t transport = 0xFFFF;
                char* token = NULL;
                char* name = aj_strtok(NULL, " \r\n");
                if (!name) {
                    AJ_AlwaysPrintf(("Usage: canceladvertise <name> [transports]\n"));
                    continue;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    transport = (uint16_t)atoi(token);
                }
                status = AJ_BusAdvertiseName(&bus, name, transport, AJ_BUS_STOP_ADVERTISING, 0);
            } else if (0 == strcmp("bind", command)) {
                AJ_SessionOpts opts;
                uint16_t port = 0;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    port = (uint16_t)atoi(token);
                }
                if (port == 0) {
                    AJ_AlwaysPrintf(("Usage: bind <port> [isMultipoint] [traffic] [proximity] [transports]\n"));
                    continue;
                }
                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.isMultipoint = (0 == strcmp("true", token));
                } else {
                    opts.isMultipoint = 0;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.traffic = atoi(token);
                } else {
                    opts.traffic = 0x1;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.proximity = atoi(token);
                } else {
                    opts.proximity = 0xFF;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.transports = atoi(token);
                } else {
                    opts.transports = 0xFFFF;
                }

                status = AJ_BusBindSessionPort(&bus, port, &opts, 0);
            } else if (0 == strcmp("unbind", command)) {
                uint16_t port = 0;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    port = (uint16_t) atoi(token);
                }

                if (port == 0) {
                    AJ_AlwaysPrintf(("Usage: unbind <port>\n"));
                    continue;
                }
                status = AJ_BusUnbindSession(&bus, port);
            } else if (0 == strcmp("join", command)) {
                AJ_SessionOpts opts;
                uint16_t port = 0;
                char* name = aj_strtok(NULL, " \r\n");
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    port = (uint16_t)atoi(token);
                } else {
                    port = 0;
                }
                if (!name || (port == 0)) {
                    AJ_AlwaysPrintf(("Usage: join <name> <port> [isMultipoint] [traffic] [proximity] [transports]\n"));
                    continue;
                }
                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.isMultipoint = (0 == strcmp("true", token));
                } else {
                    opts.isMultipoint = 0;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.traffic = (uint8_t)atoi(token);
                } else {
                    opts.traffic = 0x1;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.proximity = (uint8_t)atoi(token);
                } else {
                    opts.proximity = 0xFF;
                }

                token = aj_strtok(NULL, " \r\n");
                if (token) {
                    opts.transports = (uint16_t)atoi(token);
                } else {
                    opts.transports = 0xFFFF;
                }

                status = AJ_BusJoinSession(&bus, name, port, &opts);
            } else if (0 == strcmp("leave", command)) {
                uint32_t sessionId = (uint32_t)atoi(aj_strtok(NULL, "\r\n"));
                if (sessionId == 0) {
                    AJ_AlwaysPrintf(("Usage: leave <sessionId>\n"));
                    continue;
                }
                status = AJ_BusLeaveSession(&bus, sessionId);
            } else if (0 == strcmp("addmatch", command)) {
                char* ruleString = aj_strtok(NULL, "\r\n");
                if (!ruleString) {
                    AJ_AlwaysPrintf(("Usage: addmatch <rule>\n"));
                    continue;
                }
                status = AJ_BusSetSignalRule(&bus, ruleString, AJ_BUS_SIGNAL_ALLOW);
            } else if (0 == strcmp("removematch", command)) {
                char* ruleString = aj_strtok(NULL, "\r\n");
                if (!ruleString) {
                    AJ_AlwaysPrintf(("Usage: removematch <rule>\n"));
                    continue;
                }
                status = AJ_BusSetSignalRule(&bus, ruleString, AJ_BUS_SIGNAL_DENY);
            }  else if (0 == strcmp("sendttl", command)) {
                int32_t ttl = 0;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    ttl = atoi(token);
                }
                if (ttl < 0) {
                    AJ_AlwaysPrintf(("Usage: sendttl <ttl>\n"));
                    continue;
                }
                sendTTL = ttl;
            } else if (0 == strcmp("schat", command)) {
                char* chatMsg = aj_strtok(NULL, "\r\n");
                if (!chatMsg) {
                    AJ_AlwaysPrintf(("Usage: schat <msg>\n"));
                    continue;
                }
                status = AppSendChatSignal(&bus, 0, chatMsg, AJ_FLAG_SESSIONLESS, sendTTL);
            } else if (0 == strcmp("chat", command)) {
                char* sessionIdString = aj_strtok(NULL, " \r\n");
                char*chatMsg;

                uint32_t session = g_sessionId;
                if (sessionIdString != NULL) {
                    if (sessionIdString[0] != '#') {
                        session = (long)atoi(sessionIdString);
                    }
                }

                chatMsg = aj_strtok(NULL, "\r\n");
                status = AppSendChatSignal(&bus, session, chatMsg, 0, sendTTL);
            } else if (0 == strcmp("cancelsessionless", command)) {
                uint32_t serialId = 0;
                char* token = aj_strtok(NULL, " \r\n");
                if (token) {
                    serialId = (uint32_t)atoi(token);
                }
                if (serialId == 0) {
                    AJ_AlwaysPrintf(("Invalid serial number\n"));
                    AJ_AlwaysPrintf(("Usage: cancelsessionless <serialNum>\n"));
                    continue;
                }
                status = AJ_BusCancelSessionless(&bus, serialId);
            } else if (0 == strcmp("exit", command)) {
                break;
            } else if (0 == strcmp("help", command)) {
                //AJ_AlwaysPrintf(("debug <module_name> <level>                                   - Set debug level for a module\n"));
                AJ_AlwaysPrintf(("startservice [name] [port] [isMultipoint] [traffic] [proximity] [transports] - Startservice\n"));
                AJ_AlwaysPrintf(("requestname <name>                                            - Request a well-known name\n"));
                AJ_AlwaysPrintf(("releasename <name>                                            - Release a well-known name\n"));
                AJ_AlwaysPrintf(("bind <port> [isMultipoint] [traffic] [proximity] [transports] - Bind a session port\n"));
                AJ_AlwaysPrintf(("unbind <port>                                                 - Unbind a session port\n"));
                AJ_AlwaysPrintf(("advertise <name> [transports]                                 - Advertise a name\n"));
                AJ_AlwaysPrintf(("canceladvertise <name> [transports]                           - Cancel an advertisement\n"));
                AJ_AlwaysPrintf(("find <name_prefix>                                            - Discover names that begin with prefix\n"));
                AJ_AlwaysPrintf(("find2 <name_prefix> <transport>                               - Discover names that begin with prefix by specific transports\n"));
                AJ_AlwaysPrintf(("cancelfind <name_prefix>                                      - Cancel discovering names that begins with prefix\n"));
                AJ_AlwaysPrintf(("cancelfind2 <name_prefix> <transport>                         - Cancel discovering names that begins with prefix by specific transports\n"));
                AJ_AlwaysPrintf(("join <name> <port> [isMultipoint] [traffic] [proximity] [transports] - Join a session\n"));
                AJ_AlwaysPrintf(("leave <sessionId>                                             - Leave a session\n"));
                AJ_AlwaysPrintf(("chat <sessionId> <msg>                                        - Send a message over a given session\n"));
                AJ_AlwaysPrintf(("schat <msg>                                                   - Send a sessionless message\n"));
                AJ_AlwaysPrintf(("cancelsessionless <serialNum>                                 - Cancel a sessionless message\n"));
                AJ_AlwaysPrintf(("addmatch <rule>                                               - Add a DBUS rule\n"));
                AJ_AlwaysPrintf(("removematch <rule>                                            - Remove a DBUS rule\n"));
                AJ_AlwaysPrintf(("sendttl <ttl>                                                 - Set default ttl (in ms) for all chat messages (0 = infinite)\n"));
                AJ_AlwaysPrintf(("exit                                                          - Exit this program\n"));
                AJ_AlwaysPrintf(("\n"));
                continue;
            } else if (0 == strcmp("wait", command)) {
                char* token = aj_strtok(NULL, " \n\r");
                if (token) {
                    AJ_AlwaysPrintf(("Sleeping...\n"));
                    AJ_Sleep((uint16_t)atoi(token));
                    AJ_AlwaysPrintf(("Done\n"));
                }
            } else {
                AJ_AlwaysPrintf(("Unknown command: %s\n", command));
                continue;
            }
        }

        status = AJ_UnmarshalMsg(&bus, &msg, UNMARSHAL_TIMEOUT);
        if (status != AJ_OK) {
            if (status == AJ_ERR_TIMEOUT) {
                AppDoWork();
                continue;
            }
        }

        if (status == AJ_OK) {
            switch (msg.msgId) {

            case AJ_METHOD_ACCEPT_SESSION:
                {
                    uint16_t port;
                    char* joiner;
                    AJ_AlwaysPrintf(("Accepting...\n"));
                    AJ_UnmarshalArgs(&msg, "qus", &port, &g_sessionId, &joiner);
                    status = AJ_BusReplyAcceptSession(&msg, TRUE);
                    if (status == AJ_OK) {
                        AJ_InfoPrintf(("Accepted session session_id=%u joiner=%s\n", g_sessionId, joiner));
                    } else {
                        AJ_InfoPrintf(("AJ_BusReplyAcceptSession: error %d\n", status));
                    }
                }
                break;

            case AJ_REPLY_ID(AJ_METHOD_JOIN_SESSION):
                {
                    uint32_t replyCode;

                    if (msg.hdr->msgType == AJ_MSG_ERROR) {
                        status = AJ_ERR_FAILURE;
                    } else {
                        status = AJ_UnmarshalArgs(&msg, "uu", &replyCode, &g_sessionId);
                        if (replyCode == AJ_JOINSESSION_REPLY_SUCCESS) {
                            AJ_InfoPrintf(("Joined session session_id=%u\n", g_sessionId));
                            AJ_BusAddSignalRule(&bus, "Chat", InterfaceName, AJ_BUS_SIGNAL_ALLOW);
                        } else {
                            AJ_InfoPrintf(("Joined session failed\n"));
                        }
                    }
                }
                break;

            case APP_CHAT_SIGNAL:
                status = AppHandleChatSignal(&msg);
                break;

            case AJ_SIGNAL_SESSION_LOST_WITH_REASON:
                /*
                 * don't force a disconnect, be ready to accept another session
                 */
                {
                    uint32_t id, reason;
                    AJ_UnmarshalArgs(&msg, "uu", &id, &reason);
                    AJ_InfoPrintf(("Session lost. ID = %u, reason = %u", id, reason));
                }
                break;

            case AJ_SIGNAL_FOUND_ADV_NAME:
                {
                    char* name;
                    char* namePrefix;
                    uint16_t transport;
                    AJ_UnmarshalArgs(&msg, "sqs", &name, &transport, &namePrefix);
                    AJ_AlwaysPrintf(("FoundAdvertisedName name=%s, namePrefix=%s\n", name, namePrefix));
                }
                break;

            default:
                /*
                 * Pass to the built-in handlers
                 */
                status = AJ_BusHandleBusMessage(&msg);
                break;
            }
        }
        /*
         * Messages must be closed to free resources
         */
        AJ_CloseMsg(&msg);

        if ((status == AJ_ERR_READ) || (status == AJ_ERR_WRITE) || (status == AJ_ERR_LINK_DEAD)) {
            AJ_AlwaysPrintf(("AllJoyn disconnect\n"));
            AJ_AlwaysPrintf(("Disconnected from Daemon:%s\n", AJ_GetUniqueName(&bus)));
            AJ_Disconnect(&bus);
            connected = FALSE;
            /*
             * Sleep a little while before trying to reconnect
             */
            AJ_Sleep(10 * 1000);
            Do_Connect(&bus);
        }
    }

    return 0;
}
Esempio n. 8
0
/*
 * Announcements are processed as follows:
 *
 * 1) First check if there is an existing session for the announcement sender. If not create and
 *    initialize an empty session object. A session object has two properties "info" which is a buffer
 *    that holds state information about the session and an array "anno" which is used to accumulate
 *    announcements from the same sender.
 * 2) Unmarshal the announcement signal and if there is a callback registered for any of the
 *    interfaces add a service object to announcements array. The "interfaces" property on the
 *    service object is an array of all interfaces in the announcement.
 * 3) If there is already a session with the announcement sender make callbacks now, otherwise send
 *    a JOIN_SESSION method call to join the session with the announcement sender. The callbacks are
 *    reevaluated when the JOIN_SESSION reply is received.
 */
AJ_Status AJS_AboutAnnouncement(duk_context* ctx, AJ_Message* msg)
{
    AJ_BusAttachment* aj = msg->bus;
    AJ_Status status;
    uint16_t version;
    duk_idx_t anIdx;
    SessionInfo* sessionInfo;
    AJ_Arg objList;
    const char* sender;

    AJ_InfoPrintf(("AJS_AboutAnnouncement\n"));

    /*
     * Ignore our own announcements
     */
    if (strcmp(msg->sender, AJ_GetUniqueName(msg->bus)) == 0) {
        AJ_InfoPrintf(("Ignoring our own announcement\n"));
        return AJ_OK;
    }
    /*
     * Push the sender string on the stack to stabilize it.
     */
    sender = duk_push_string(ctx, msg->sender);
    /*
     * Announcements are accumulated in a global stash object indexed by peer name
     */
    AJS_GetGlobalStashObject(ctx, "sessions");
    sessionInfo = AllocSessionObject(ctx, sender);
    /*
     * Get the announcements array
     */
    duk_get_prop_string(ctx, -1, "anno");
    anIdx = duk_get_top_index(ctx);
    /*
     * Find out if there are JavaScript handlers for this announcement
     */
    AJ_UnmarshalArgs(msg, "qq", &version, &sessionInfo->port);
    status = AJ_UnmarshalContainer(msg, &objList, AJ_ARG_ARRAY);
    while (status == AJ_OK) {
        int ifcCount = 0;
        uint8_t hasCB = FALSE;
        AJ_Arg obj;
        AJ_Arg interfaces;
        const char* path;

        status = AJ_UnmarshalContainer(msg, &obj, AJ_ARG_STRUCT);
        if (status != AJ_OK) {
            break;
        }
        AJ_UnmarshalArgs(msg, "o", &path);
        /*
         * Array to accumulate interfaces
         */
        duk_push_array(ctx);
        status = AJ_UnmarshalContainer(msg, &interfaces, AJ_ARG_ARRAY);
        while (status == AJ_OK) {
            /*
             * Accumulate interfaces checking
             */
            const char* iface;
            status = AJ_UnmarshalArgs(msg, "s", &iface);
            if (status == AJ_OK) {
                duk_push_string(ctx, iface);
                duk_put_prop_index(ctx, -2, ifcCount++);
            }
            /*
             * We will disard the interface array if no callbacks are registered.
             */
            if (!hasCB && HasServiceCallback(ctx, iface)) {
                hasCB = TRUE;
            }
        }
        if (hasCB) {
            AddServiceObject(ctx, sessionInfo, path, sender);
            /*
             * Append service object to the announcements array for processing later
             */
            duk_put_prop_index(ctx, anIdx, duk_get_length(ctx, anIdx));
        } else {
            /* discard the interface array */
            duk_pop(ctx);
        }
        if (status == AJ_ERR_NO_MORE) {
            status = AJ_UnmarshalCloseContainer(msg, &interfaces);
        }
        if (status == AJ_OK) {
            status = AJ_UnmarshalCloseContainer(msg, &obj);
        }
    }
    if (status == AJ_ERR_NO_MORE) {
        status = AJ_UnmarshalCloseContainer(msg, &objList);
    }
    /*
     * All done with this message - we need to close it now to free up the output buffer before we
     * attempt to call AJ_BusJoinSession() below.
     */
    AJ_CloseMsg(msg);

    /* Pop "anno" and the session object */
    duk_pop_2(ctx);

    if (status != AJ_OK) {
        goto Exit;
    }
    /*
     * If we already have a session with this peer callback with the new service objects
     */
    if (sessionInfo->sessionId) {
        AnnouncementCallbacks(ctx, sender, sessionInfo);
        goto Exit;
    }
    /*
     * If there is a JOIN_SESSION in progress we have nothing more to do
     */
    if (sessionInfo->replySerial != 0) {
        goto Exit;
    }
    /*
     * If announcements were registered attempt to join the session
     */
    if (sessionInfo->refCount) {
        status = AJ_BusJoinSession(aj, sender, sessionInfo->port, NULL);
        if (status == AJ_OK) {
            sessionInfo->replySerial = aj->serial - 1;
        }
    }
    /*
     * At this point if we don't have a JOIN_SESSION in progress we must delete the session object
     */
    if (sessionInfo->replySerial == 0) {
        duk_del_prop_string(ctx, -2, sender);
    }

Exit:

    /* Pop "sessions" and sender string */
    duk_pop_2(ctx);
    return status;
}
Esempio n. 9
0
AJ_Status AJS_FoundAdvertisedName(duk_context* ctx, AJ_Message* msg)
{
    AJ_Status status;
    SessionInfo* sessionInfo;
    const char* name;
    const char* prefix;
    uint16_t port;
    uint16_t mask;
    duk_idx_t fnmeIdx;
    duk_idx_t sessIdx;

    AJ_UnmarshalArgs(msg, "sqs", &name, &mask, &prefix);

    AJ_InfoPrintf(("AJS_FoundAdvertisedName %s %s\n", prefix, name));

    AJS_GetGlobalStashObject(ctx, "sessions");
    sessIdx = duk_get_top_index(ctx);
    /*
     * If the name is already listed we can ignore this signal
     */
    if (duk_get_prop_string(ctx, -1, name)) {
        duk_pop_2(ctx);
        return AJ_OK;
    }
    /*
     * Check if there is a callback registered for this name (actually the prefix)
     */
    AJS_GetGlobalStashObject(ctx, "findName");
    duk_get_prop_string(ctx, -1, prefix);
    if (duk_is_undefined(ctx, -1)) {
        duk_pop_3(ctx);
        return AJ_OK;
    }
    fnmeIdx = duk_get_top_index(ctx);
    /*
     * From here on we make it look like we received an announcement
     */
    port = AJS_GetIntProp(ctx, fnmeIdx, "port");
    status = AJ_BusJoinSession(msg->bus, name, port, NULL);
    if (status == AJ_OK) {
        duk_idx_t anIdx;
        duk_idx_t svcIdx;
        /*
         * Create service object and add it to the sessions array
         */
        svcIdx = duk_push_object(ctx);
        /*
         * Set the "info" and "anno" properties on the service object
         */
        sessionInfo = duk_push_fixed_buffer(ctx, sizeof(SessionInfo));
        sessionInfo->port = port;
        duk_put_prop_string(ctx, svcIdx, "info");
        anIdx = duk_push_array(ctx);
        /*
         * Push array of interfaces
         */
        duk_get_prop_string(ctx, fnmeIdx, "interfaces");
        /*
         * Set the callback to be called when the JOIN_SESSION reply is received
         */
        AJS_GetGlobalStashObject(ctx, "serviceCB");
        duk_get_prop_index(ctx, -2, 0);           /* key - first interface in "interfaces" array */
        duk_get_prop_string(ctx, fnmeIdx, "cb");  /* val - callback function */
        duk_put_prop(ctx, -3);
        duk_pop(ctx);
        /* Interfaces array is at the top of the stack */
        AddServiceObject(ctx, sessionInfo, AJS_GetStringProp(ctx, fnmeIdx, "path"), name);
        /*
         * Append service object to the announcements array for processing later
         */
        duk_put_prop_index(ctx, anIdx, duk_get_length(ctx, anIdx));

        AJ_ASSERT(duk_get_top_index(ctx) == anIdx);
        duk_put_prop_string(ctx, svcIdx, "anno");
        AJ_ASSERT(duk_get_top_index(ctx) == svcIdx);
        duk_put_prop_string(ctx, sessIdx, name);
        /*
         * Store the reply serial number for the JOIN_SESSION reply
         */
        sessionInfo->replySerial = msg->bus->serial - 1;
    } else {
        duk_del_prop_string(ctx, sessIdx, prefix);
    }
    /* Clean up the stack */
    duk_pop_n(ctx, 4);
    return status;
}