static void on_cbs_put_token_complete_callback(void* context, CBS_OPERATION_RESULT operation_result, unsigned int status_code, const char* status_description)
{
#ifdef NO_LOGGING
    UNUSED(status_code);
    UNUSED(status_description);
#endif
    AUTHENTICATION_INSTANCE* instance = (AUTHENTICATION_INSTANCE*)context;

    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_095: [`instance->is_sas_token_refresh_in_progress` and `instance->is_cbs_put_token_in_progress` shall be set to FALSE]
    instance->is_cbs_put_token_in_progress = false;

    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_091: [If `result` is CBS_OPERATION_RESULT_OK `instance->state` shall be set to AUTHENTICATION_STATE_STARTED and `instance->on_state_changed_callback` invoked]
    if (operation_result == CBS_OPERATION_RESULT_OK)
    {
        update_state(instance, AUTHENTICATION_STATE_STARTED);
    }
    else
    {
        LogError("CBS reported status code %u, error: '%s' for put-token operation for device '%s'", status_code, status_description, instance->device_id);

        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_092: [If `result` is not CBS_OPERATION_RESULT_OK `instance->state` shall be set to AUTHENTICATION_STATE_ERROR and `instance->on_state_changed_callback` invoked]
        update_state(instance, AUTHENTICATION_STATE_ERROR);

        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_094: [If `result` is not CBS_OPERATION_RESULT_OK and `instance->is_sas_token_refresh_in_progress` is TRUE, `instance->on_error_callback`shall be invoked with AUTHENTICATION_ERROR_SAS_REFRESH_FAILED]
        if (instance->is_sas_token_refresh_in_progress)
        {
            notify_error(instance, AUTHENTICATION_ERROR_SAS_REFRESH_FAILED);
        }
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_093: [If `result` is not CBS_OPERATION_RESULT_OK and `instance->is_sas_token_refresh_in_progress` is FALSE, `instance->on_error_callback`shall be invoked with AUTHENTICATION_ERROR_AUTH_FAILED]
        else
        {
            notify_error(instance, AUTHENTICATION_ERROR_AUTH_FAILED);
        }
    }

    instance->is_sas_token_refresh_in_progress = false;
}
/**
 * @brief Creates a new entry in the language pairs dictionary
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param user Name of the user to create a new entry for
 * @param direction Direction to create a new entry in ("incoming" or "outgoing")
 * @param source Source language of the language pair
 * @param target Target language of the language pair
 * @return 1 on success, or 0 otherwise
 */
int dictionarySetUserEntry(const char* user, const char* direction, const char* source, const char* target){
    PyObject *pFunc, *pArgs, *result;

    if (files_module != NULL) {
        pFunc = PyObject_GetAttrString(files_module, "setLangPair");

        if (pFunc) {
            pArgs = PyTuple_New(4);

            PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(direction));

            PyTuple_SetItem(pArgs, 1, PyUnicode_FromString(user));

            PyTuple_SetItem(pArgs, 2, PyBytes_FromString(source));

            PyTuple_SetItem(pArgs, 3, PyBytes_FromString(target));

            result = PyObject_CallObject(pFunc, pArgs);

            if(result != NULL){
                if(result == Py_True){
                    Py_XDECREF(result);
                    Py_XDECREF(pFunc);
                    Py_XDECREF(pArgs);
                    return 1;
                }
                else{
                    Py_XDECREF(result);
                    Py_XDECREF(pFunc);
                    Py_XDECREF(pArgs);
                    return 0;
                }
            }
            else{
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                return 0;
            }
        }
        else{
            return 0;
        }
    }
    else {
        notify_error("Module: \'apertiumFiles\' is not loaded");
        return 0;
    }
}
void FileRequestBaton::file_stated(uv_fs_t *req) {
    FileRequestBaton *ptr = (FileRequestBaton *)req->data;
    assert(ptr->thread_id == std::this_thread::get_id());

    if (req->result != 0 || ptr->canceled || !ptr->request) {
        // Stating failed or was canceled. We already have an open file handle
        // though, which we'll have to close.
        notify_error(req);

        uv_fs_req_cleanup(req);
        uv_fs_close(req->loop, req, ptr->fd, file_closed);
    } else {
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
        const uv_statbuf_t *stat = static_cast<const uv_statbuf_t *>(req->ptr);
#else
        const uv_stat_t *stat = static_cast<const uv_stat_t *>(req->ptr);
#endif
        if (stat->st_size > std::numeric_limits<int>::max()) {
            // File is too large for us to open this way because uv_buf's only support unsigned
            // ints as maximum size.
            if (ptr->request) {
                ptr->request->response = util::make_unique<Response>();
                ptr->request->response->code = UV_EFBIG;
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
                ptr->request->response->message = uv_strerror(uv_err_t {UV_EFBIG, 0});
#else
                ptr->request->response->message = uv_strerror(UV_EFBIG);
#endif
                ptr->request->notify();
            }

            uv_fs_req_cleanup(req);
            uv_fs_close(req->loop, req, ptr->fd, file_closed);
        } else {
            const unsigned int size = (unsigned int)(stat->st_size);
            ptr->body.resize(size);
            ptr->buffer = uv_buf_init(const_cast<char *>(ptr->body.data()), size);
            uv_fs_req_cleanup(req);
#if UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10
            uv_fs_read(req->loop, req, ptr->fd, ptr->buffer.base, ptr->buffer.len, -1, file_read);
#else
            uv_fs_read(req->loop, req, ptr->fd, &ptr->buffer, 1, 0, file_read);
#endif
        }
    }
}
Exemplo n.º 4
0
void PurpleLine::reject_chat(GHashTable *components) {
    char *id_ptr = (char *)g_hash_table_lookup(components, "id");
    if (!id_ptr) {
        purple_debug_warning("line", "Tried to reject an invitation with no id.\n");
        return;
    }

    std::string id(id_ptr);

    c_out->send_rejectGroupInvitation(0, id);
    c_out->send([this]() {
        try {
            c_out->recv_rejectGroupInvitation();
        } catch (line::TalkException &err) {
            notify_error(err.reason);
        }
    });
}
/**
 * @brief Sets the Python dictionary containing the user-language_pair settings
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param item New dictionary to substitute the old one with
 */
void setDictionary(PyObject* item){
    PyObject *pFunc, *pArgs;

    if (files_module != NULL) {
        pFunc = PyObject_GetAttrString(files_module, "setDictionary");

        if (pFunc) {
            pArgs = PyTuple_New(1);

            PyTuple_SetItem(pArgs, 0, item);

            PyObject_CallObject(pFunc, pArgs);
        }
    }
    else {
        notify_error("Module: \'apertiumFiles\' is not loaded");
    }
}
/**
 * @brief Removes the specified entry from the dictionary related to the given user
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param user Name of the user whose entry will be removed
 * @param entry Name of the entry that will be removed. Must be either 'incoming' or 'outgoing'
 * @return 1 on success, or 0 otherwise
 */
int dictionaryRemoveUserEntry(const char* user, char* entry){
    PyObject *pFunc, *pArgs, *result;

    if (files_module != NULL) {
        pFunc = PyObject_GetAttrString(files_module, "unsetLangPair");

        if (pFunc) {
            pArgs = PyTuple_New(2);

            PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(entry));

            PyTuple_SetItem(pArgs, 1, PyUnicode_FromString(user));

            result = PyObject_CallObject(pFunc, pArgs);

            if(result != NULL){
                if(result == Py_True){
                    Py_XDECREF(result);
                    Py_XDECREF(pFunc);
                    Py_XDECREF(pArgs);
                    return 1;
                }
                else{
                    Py_XDECREF(result);
                    Py_XDECREF(pFunc);
                    Py_XDECREF(pArgs);
                    return 0;
                }
            }
            else{
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                return 0;
            }
        }
        else{
            return 0;
        }
    }
    else {
        notify_error("Module: \'apertiumFiles\' is not loaded");
        return 0;
    }
}
Exemplo n.º 7
0
static void devNI6254_AO_INTEGRAL_STIME(ST_execParam *pParam)
{
	ST_STD_device *pSTDdev = pParam->pSTDdev;
	int	nIonSrcNum;

	kLog (K_MON, "[devNI6254_AO_INTEGRAL_STIME] integral_stime(%f)\n", pParam->setValue);

	if (pSTDdev->StatusDev & TASK_ARM_ENABLED) {
		kLog (K_ERR, "[devNI6254_AO_INTEGRAL_STIME] %s: System is armed! \n", pSTDdev->taskName);
		notify_error (1, "System is armed!", pSTDdev->taskName );		
	}
	else {
		nIonSrcNum	= pParam->n32Arg0;
		gIonSourceSetup[nIonSrcNum].integral_stime	= pParam->setValue;

		kLog (K_MON, "[devNI6254_AO_INTEGRAL_STIME] task(%s) integral_stime(%.f) IS(%d)\n",
				pSTDdev->taskName, gIonSourceSetup[nIonSrcNum].integral_stime, nIonSrcNum);
	}
}
/**
 * @brief Returns the value for the display_mode stored in the preferences file
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @return The display_mode value on success or NULL otherwise
 */
const char* getDisplay(void){
    int mode;
    PyObject *pFunc, *pArgs, *result;

    if(files_module != NULL){
        pFunc = PyObject_GetAttrString(files_module, "getKey");

        if (pFunc) {
            pArgs = PyTuple_New(1);

            PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("displayMode"));

            result = PyObject_CallObject(pFunc, pArgs);

            Py_XDECREF(pArgs);

            if(result != NULL && result != Py_None){
                mode = (int)PyLong_AsLong(result);
                Py_XDECREF(result);
                switch(mode){
                    case 0:
                        return "compressed";
                    case 1:
                        return "both";
                    default:
                        return "translation";
                }
            }
            else{
                Py_XDECREF(pFunc);
                return NULL;
            }
        }
        else{
            return NULL;
        }
    }
    else{
        notify_error("Module: \'apertiumFiles\' is not loaded");
        return NULL;
    }
}
Exemplo n.º 9
0
void PurpleLine::send_message(
    line::Message &msg,
    std::function<void(line::Message &)> callback)
{
    std::string to(msg.to);

    c_out->send_sendMessage(0, msg);
    c_out->send([this, to, callback]() {
        line::Message msg_back;

        try {
            c_out->recv_sendMessage(msg_back);
        } catch (line::TalkException &err) {
            std::string msg = "Failed to send message: " + err.reason;

            PurpleConversation *conv = purple_find_conversation_with_account(
                PURPLE_CONV_TYPE_ANY,
                to.c_str(),
                acct);

            if (conv) {
                purple_conversation_write(
                    conv,
                    "",
                    msg.c_str(),
                    (PurpleMessageFlags)PURPLE_MESSAGE_ERROR,
                    time(NULL));
            } else {
                notify_error(msg);
            }

            return;
        }

        // Kludge >_>
        if (to[0] == 'u')
            push_recent_message(msg_back.id);

        if (callback)
            callback(msg_back);
    });
}
/**
 * @brief Sets the display_mode value in the dictionary so that it is store in the preferences file
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param display_mode The display_mode. Must be 'both', 'translation' or 'compressed'
 * @return 1 on success or 0 otherwise
 */
int setDisplay(const char* display_mode){
    int mode;
    PyObject *pFunc, *pArgs;

    if(!strcmp("compressed",display_mode)){
        mode = 0;
    }
    else{
        if(!strcmp("both",display_mode)){
            mode = 1;
        }
        else{
            mode = 2;
        }
    }

    if(files_module != NULL){
        pFunc = PyObject_GetAttrString(files_module, "setKey");

        if (pFunc) {
            pArgs = PyTuple_New(2);

            PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("displayMode"));

            PyTuple_SetItem(pArgs, 1, PyLong_FromLong((long)mode));

            PyObject_CallObject(pFunc, pArgs);

            Py_XDECREF(pArgs);
        }
        else{
            return 0;
        }
        Py_XDECREF(pFunc);
        return 1;
    }
    else{
        notify_error("Module: \'apertiumFiles\' is not loaded");
        return 0;
    }
}
Exemplo n.º 11
0
void FileRequestBaton::file_read(uv_fs_t *req) {
    FileRequestBaton *ptr = (FileRequestBaton *)req->data;
    assert(ptr->thread_id == std::this_thread::get_id());

    if (req->result < 0 || ptr->canceled || !ptr->request) {
        // Stating failed or was canceled. We already have an open file handle
        // though, which we'll have to close.
        notify_error(req);
    } else {
        // File was successfully read.
        if (ptr->request) {
            ptr->request->response = util::make_unique<Response>();
            ptr->request->response->code = 200;
            ptr->request->response->data = std::move(ptr->body);
            ptr->request->notify();
        }
    }

    uv_fs_req_cleanup(req);
    uv_fs_close(req->loop, req, ptr->fd, file_closed);
}
/**
 * @brief Removes the APY address at the given position in the APY list
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param position Position in the list of the address to be removed
 * @return 1 on success, or 0 otherwise
 */
int removeAPYAddress(int position){
    PyObject *pFunc, *pArgs, *result;

    if(iface_module != NULL){
        pFunc = PyObject_GetAttrString(iface_module, "removeAPYAddress");

        if (pFunc) {
            pArgs = PyTuple_New(1);

            PyTuple_SetItem(pArgs, 0, PyLong_FromLong((long)position));

            result = PyObject_CallObject(pFunc, pArgs);

            Py_XDECREF(pArgs);

            if(result != NULL && result != Py_False){
                Py_XDECREF(result);
                Py_XDECREF(pFunc);

                if(updateFileAddresses()){
                    return 1;
                }
                else{
                    return 0;
                }
            }
            else{
                Py_XDECREF(pFunc);
                return 0;
            }
        }
        else{
            return 0;
        }
    }
    else{
        notify_error("Module: \'apertiumInterfaceAPY\' is not loaded");
        return 0;
    }
}
/**
 * @brief Retrieves a list with all the APYs
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param list References to a 2-level char array where the apy list will be stored
 * The list parameter must be freed after its use
 * @return The number of addresses returned or -1 if an error occured
 */
int getAPYAddress(char ***list){
    int i,size;
    PyObject *pFunc, *pArgs, *result;

    if (iface_module != NULL) {
        pFunc = PyObject_GetAttrString(iface_module, "getAPYList");

        if (pFunc) {
            pArgs = PyTuple_New(0);

            result = PyObject_CallObject(pFunc, pArgs);

            if (result != NULL) {

                size = PyList_GET_SIZE(result);

                *list = malloc(sizeof(char*)*size);
                for(i=0; i<size; i++){
                    (*list)[i] = PyBytes_AsString(PyList_GetItem(result,i));
                }

                Py_XDECREF(pFunc);
                Py_XDECREF(result);
                return size;
            }
            else {
                Py_XDECREF(pFunc);
                return -1;
            }
        }
        else {
            return -1;
        }
        Py_XDECREF(pFunc);
    }
    else {
        notify_error("Module: \'apertiumInterfaceAPY\' is not loaded");
        return -1;
    }
}
Exemplo n.º 14
0
static void devNI6123_AO_DAQ_SAMPLEING_TIME(ST_execParam *pParam)
{
        ST_MASTER *pMaster = get_master();
        ST_STD_device *pSTDdev = (ST_STD_device*) ellFirst(pMaster->pList_DeviceTask);
        ST_NI6123 *pNI6123 = NULL;

        kLog (K_DATA,"[devNI6123_AO_DAQ_SAMPLEING_TIME] sampleTime(%f)\n", pParam->setValue);
#if 0
		char strBuf[24];
		float stopT1;
	/*	remove this function because ECH has not LTU, so We donot use the DBproc_get function */
		if (!(pSTDdev->StatusDev & TASK_ARM_ENABLED)) {
			/* Change T0 value form LUT when Remote Mode TG */
			if( pSTDdev->ST_Base.opMode == OPMODE_REMOTE ){
			/*	DBproc_get (PV_LTU_TIG_T0_STR, strBuf);   Get T0 from LTU - ECH Not yet ready LTU*/
				DBproc_put (PV_START_TIG_T0_STR, strBuf);   //Set T0 from LTU 
				sscanf(strBuf, "%f", &stopT1);
				stopT1 = pParam->setValue - stopT1;
				sprintf(strBuf,"%f",stopT1);
				DBproc_put (PV_STOP_TIG_T1_STR, strBuf);   //Set T0 from LTU
			}
		}
#endif
        while(pSTDdev) {
                if (pSTDdev->StatusDev & TASK_ARM_ENABLED) {
                        kLog (K_DATA,"[devNI6123_AO_DAQ_SAMPLEING_TIME] %s: System is armed! \n", pSTDdev->taskName);
                        notify_error (1, "System is armed!", pSTDdev->taskName );
                }
                else {
                        pNI6123 = pSTDdev->pUser;
                        pNI6123->sample_time = pParam->setValue;
                        scanIoRequest(pSTDdev->ioScanPvt_userCall);

                        kLog (K_DATA,"[devNI6123_AO_DAQ_SAMPLEING_TIME] task(%s) sampleTime(%.f)\n",
                                        pSTDdev->taskName, pNI6123->sample_rate);
                }
                pSTDdev = (ST_STD_device*) ellNext(&pSTDdev->node);
        }
}
/**
 * @brief Saves the Python dictionary containing the user-language_pair settings to a file
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 */
void saveDictionary(void){
    PyObject *pFunc, *pArgs;

    if(getDictionary() != Py_None && getDictionary() != NULL){
        if (files_module != NULL) {
            pFunc = PyObject_GetAttrString(files_module, "save");

            if (pFunc) {
                pArgs = PyTuple_New(0);

                PyObject_CallObject(pFunc, pArgs);
            }
            else {
                return;
            }
            Py_XDECREF(pFunc);
        }
        else {
            notify_error("Module: \'apertiumFiles\' is not loaded");
            return;
        }
    }
}
/**
 * @brief Writes to the preferences files the latest changes to the APY address list
 *
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @return 1 on success, or 0 otherwise
 */
int updateFileAddresses(void){
    PyObject *pFunc, *pArgs, *list;

    if(iface_module != NULL){
        pFunc = PyObject_GetAttrString(iface_module, "getAPYList");

        if (pFunc) {
            pArgs = PyTuple_New(0);

            list = PyObject_CallObject(pFunc, pArgs);

            Py_XDECREF(pArgs);
            Py_XDECREF(pFunc);

            if(list != NULL){

                if(setFileAPYList(list)){
                    return 1;
                }
                else{
                    return 0;
                }
            }
            else{
                return 0;
            }
        }
        else{
            return 0;
        }
    }
    else{
        notify_error("Module: \'apertiumInterfaceAPY\' is not loaded");
        return 0;
    }
}
Exemplo n.º 17
0
void FileRequestBaton::file_opened(uv_fs_t *req) {
    FileRequestBaton *ptr = (FileRequestBaton *)req->data;
    assert(ptr->thread_id == std::this_thread::get_id());

    if (req->result < 0) {
        // Opening failed or was canceled. There isn't much left we can do.
        notify_error(req);
        cleanup(req);
    } else {
        const uv_file fd = uv_file(req->result);

        // We're going to reuse this handle, so we need to cleanup first.
        uv_fs_req_cleanup(req);

        if (ptr->canceled || !ptr->request) {
            // Either the FileRequest object has been destructed, or the
            // request was canceled.
            uv_fs_close(req->loop, req, fd, file_closed);
        } else {
            ptr->fd = fd;
            uv_fs_fstat(req->loop, req, fd, file_stated);
        }
    }
}
Exemplo n.º 18
0
PurpleCmdRet PurpleLine::cmd_open(PurpleConversation *conv,
    const gchar *, gchar **args, gchar **error, void *)
{
    static std::map<line::ContentType::type, std::string> attachment_extensions = {
        { line::ContentType::IMAGE, ".jpg" },
        { line::ContentType::VIDEO, ".mp4" },
        { line::ContentType::AUDIO, ".mp3" },
    };

    std::string token(args[0]);

    Attachment *att = conv_attachment_get(conv, token);
    if (!att) {
        *error = g_strdup("No such attachment.");
        return PURPLE_CMD_RET_FAILED;
    }

    if (att->path != "" && g_file_test(att->path.c_str(), G_FILE_TEST_EXISTS)) {
        purple_notify_uri(conn, att->path.c_str());
        return PURPLE_CMD_RET_OK;
    }

    // Ensure there's nothing funny about the id as we're going to use it as a path element
    try {
        std::stoll(att->id);
    } catch (...) {
        *error = g_strdup("Failed to download attachment.");
        return PURPLE_CMD_RET_FAILED;
    }

    std::string ext = ".jpg";
    if (attachment_extensions.count(att->type))
        ext = attachment_extensions[att->type];

    std::string dir = get_tmp_dir(true);

    gchar *path_p = g_build_filename(
        dir.c_str(),
        (att->id + ext).c_str(),
        nullptr);

    std::string path(path_p);

    g_free(path_p);

    purple_conversation_write(
        conv,
        "",
        "Downloading attachment...",
        (PurpleMessageFlags)PURPLE_MESSAGE_SYSTEM,
        time(NULL));

    std::string url = std::string(LINE_OS_URL) + "os/m/"+ att->id;

    PurpleConversationType ctype = purple_conversation_get_type(conv);
    std::string cname = std::string(purple_conversation_get_name(conv));

    http.request(url, HTTPFlag::AUTH | HTTPFlag::LARGE,
        [this, path, token, ctype, cname]
        (int status, const guchar *data, gsize len)
        {
            if (status == 200 && data && len > 0) {
                g_file_set_contents(path.c_str(), (const char *)data, len, nullptr);

                temp_files.push_back(path);

                PurpleConversation *conv = purple_find_conversation_with_account(
                    ctype, cname.c_str(), acct);

                if (conv) {
                    Attachment *att = conv_attachment_get(conv, token);
                    if (att)
                        att->path = path;
                }

                purple_notify_uri(conn, path.c_str());
            } else {
                notify_error("Failed to download attachment.");
            }
        });

    return PURPLE_CMD_RET_OK;
}
Exemplo n.º 19
0
void Connection::consume(char* input, size_t size) {
  char* buffer = input;
  size_t remaining = size;

  // A successful read means the connection is still responsive
  restart_terminate_timer();

  while (remaining != 0) {
    ssize_t consumed = response_->decode(buffer, remaining);
    if (consumed <= 0) {
      notify_error("Error consuming message");
      remaining = 0;
      continue;
    }

    if (response_->is_body_ready()) {
      ScopedPtr<ResponseMessage> response(response_.release());
      response_.reset(new ResponseMessage());

      LOG_TRACE("Consumed message type %s with stream %d, input %u, remaining %u on host %s",
                opcode_to_string(response->opcode()).c_str(),
                static_cast<int>(response->stream()),
                static_cast<unsigned int>(size),
                static_cast<unsigned int>(remaining),
                host_->address_string().c_str());

      if (response->stream() < 0) {
        if (response->opcode() == CQL_OPCODE_EVENT) {
          listener_->on_event(static_cast<EventResponse*>(response->response_body().get()));
        } else {
          notify_error("Invalid response opcode for event stream: " +
                       opcode_to_string(response->opcode()));
        }
      } else {
        Handler* handler = NULL;
        if (stream_manager_.get_pending_and_release(response->stream(), handler)) {
          switch (handler->state()) {
            case Handler::REQUEST_STATE_READING:
              maybe_set_keyspace(response.get());
              pending_reads_.remove(handler);
              handler->stop_timer();
              handler->set_state(Handler::REQUEST_STATE_DONE);
              handler->on_set(response.get());
              handler->dec_ref();
              break;

            case Handler::REQUEST_STATE_WRITING:
              // There are cases when the read callback will happen
              // before the write callback. If this happens we have
              // to allow the write callback to cleanup.
              maybe_set_keyspace(response.get());
              handler->set_state(Handler::REQUEST_STATE_READ_BEFORE_WRITE);
              handler->on_set(response.get());
              break;

            case Handler::REQUEST_STATE_TIMEOUT:
              pending_reads_.remove(handler);
              handler->set_state(Handler::REQUEST_STATE_DONE);
              handler->dec_ref();
              break;

            case Handler::REQUEST_STATE_TIMEOUT_WRITE_OUTSTANDING:
              // We must wait for the write callback before we can do the cleanup
              handler->set_state(Handler::REQUEST_STATE_READ_BEFORE_WRITE);
              break;

            default:
              assert(false && "Invalid request state after receiving response");
              break;
          }
        } else {
          notify_error("Invalid stream ID");
        }
      }
    }
    remaining -= consumed;
    buffer += consumed;
  }
}
Exemplo n.º 20
0
void Connection::notify_error_ssl(const std::string& error) {
  ssl_error_code_ = ssl_session_->error_code();
  ssl_error_ = error;
  notify_error(error);
}
Exemplo n.º 21
0
void RecordSet::set_last_error(const _com_error& e) {
    set_last_error(e.Error());
    notify_error(e);
}
void authentication_do_work(AUTHENTICATION_HANDLE authentication_handle)
{
    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_036: [If authentication_handle is NULL, authentication_do_work() shall fail and return]
    if (authentication_handle == NULL)
    {
        LogError("authentication_do_work failed (authentication_handle is NULL)");
    }
    else
    {
        AUTHENTICATION_INSTANCE* instance = (AUTHENTICATION_INSTANCE*)authentication_handle;
        
        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_038: [If `instance->is_cbs_put_token_in_progress` is TRUE, authentication_do_work() shall only verify the authentication timeout]
        if (instance->is_cbs_put_token_in_progress)
        {
            // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_084: [If no timeout has occurred, authentication_do_work() shall return]

            bool is_timed_out;
            if (verify_cbs_put_token_timeout(instance, &is_timed_out) == RESULT_OK && is_timed_out)
            {
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_085: [`instance->is_cbs_put_token_in_progress` shall be set to FALSE]
                instance->is_cbs_put_token_in_progress = false;
            
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_086: [`instance->state` shall be updated to AUTHENTICATION_STATE_ERROR and `instance->on_state_changed_callback` invoked]
                update_state(instance, AUTHENTICATION_STATE_ERROR);

                if (instance->is_sas_token_refresh_in_progress)
                {
                    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_087: [If `instance->is_sas_token_refresh_in_progress` is TRUE, `instance->on_error_callback` shall be invoked with AUTHENTICATION_ERROR_SAS_REFRESH_TIMEOUT]
                    notify_error(instance, AUTHENTICATION_ERROR_SAS_REFRESH_TIMEOUT);
                }
                else
                {
                    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_088: [If `instance->is_sas_token_refresh_in_progress` is FALSE, `instance->on_error_callback` shall be invoked with AUTHENTICATION_ERROR_AUTH_TIMEOUT]
                    notify_error(instance, AUTHENTICATION_ERROR_AUTH_TIMEOUT);
                }

                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_089: [`instance->is_sas_token_refresh_in_progress` shall be set to FALSE]
                instance->is_sas_token_refresh_in_progress = false;
            }
        }
        else if (instance->state == AUTHENTICATION_STATE_STARTED)
        {
            // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_040: [If `instance->state` is AUTHENTICATION_STATE_STARTED and user-provided SAS token was used, authentication_do_work() shall return]
            if (IoTHubClient_Auth_Get_Credential_Type(instance->authorization_module) == IOTHUB_CREDENTIAL_TYPE_DEVICE_KEY)
            {
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_039: [If `instance->state` is AUTHENTICATION_STATE_STARTED and device keys were used, authentication_do_work() shall only verify the SAS token refresh time]
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_065: [The SAS token shall be refreshed if the current time minus `instance->current_sas_token_put_time` equals or exceeds `instance->sas_token_refresh_time_secs`]
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_066: [If SAS token does not need to be refreshed, authentication_do_work() shall return]
                bool is_timed_out;
                if (verify_sas_token_refresh_timeout(instance, &is_timed_out) == RESULT_OK && is_timed_out)
                {
                    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_119: [authentication_do_work() shall set `instance->is_sas_token_refresh_in_progress` to TRUE]
                    instance->is_sas_token_refresh_in_progress = true;

                    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_067: [authentication_do_work() shall create a SAS token using `instance->device_primary_key`, unless it has failed previously]
                    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_069: [If using `instance->device_primary_key` has failed previously, a SAS token shall be created using `instance->device_secondary_key`]
                    // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_068: [If using `instance->device_primary_key` has failed previously and `instance->device_secondary_key` is not provided,  authentication_do_work() shall fail and return]
                    if (create_and_put_SAS_token_to_cbs(instance) != RESULT_OK)
                    {
                        LogError("Failed refreshing SAS token '%'", instance->device_id);
                    }

                    if (!instance->is_cbs_put_token_in_progress)
                    {
                        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_120: [If cbs_put_token() fails, `instance->is_sas_token_refresh_in_progress` shall be set to FALSE]
                        instance->is_sas_token_refresh_in_progress = false;

                        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_079: [If cbs_put_token() fails, `instance->state` shall be updated to AUTHENTICATION_STATE_ERROR and `instance->on_state_changed_callback` invoked]
                        update_state(instance, AUTHENTICATION_STATE_ERROR);

                        // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_080: [If cbs_put_token() fails, `instance->on_error_callback` shall be invoked with AUTHENTICATION_ERROR_SAS_REFRESH_FAILED]
                        notify_error(instance, AUTHENTICATION_ERROR_SAS_REFRESH_FAILED);
                    }
                }
            }
        }
        else if (instance->state == AUTHENTICATION_STATE_STARTING)
        {
            if (create_and_put_SAS_token_to_cbs(instance) != RESULT_OK)
            {
                LogError("Failed authenticating device '%s' using device keys", instance->device_id);
            }

            if (!instance->is_cbs_put_token_in_progress)
            {
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_061: [If cbs_put_token() fails, `instance->state` shall be updated to AUTHENTICATION_STATE_ERROR and `instance->on_state_changed_callback` invoked]
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_121: [If cbs_put_token() fails, `instance->state` shall be updated to AUTHENTICATION_STATE_ERROR and `instance->on_state_changed_callback` invoked]
                update_state(instance, AUTHENTICATION_STATE_ERROR);

                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_062: [If cbs_put_token() fails, `instance->on_error_callback` shall be invoked with AUTHENTICATION_ERROR_AUTH_FAILED]
                // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_122: [If cbs_put_token() fails, `instance->on_error_callback` shall be invoked with AUTHENTICATION_ERROR_AUTH_FAILED]
                notify_error(instance, AUTHENTICATION_ERROR_AUTH_FAILED);
            }
        }
        else
        {
            // Codes_SRS_IOTHUBTRANSPORT_AMQP_AUTH_09_037: [If `instance->state` is not AUTHENTICATION_STATE_STARTING or AUTHENTICATION_STATE_STARTED, authentication_do_work() shall fail and return]
            // Nothing to be done.
        }
    }
}
/**
 * @brief Sets the address where the request for the Apertium-APY will be sent
 *
 * The address will not be set if there is no response from an APY server <br>
 * pythonInit() must have been called before or an error will occur (the module is not loaded)
 * @param address Pointer to a string with the new address
 * @param port Pointer to a string with the new port. NULL if no port is needed
 * @param order Position this address will take in the list. Negative value to append at the end
 * @param force Any number that is not 0 indicates the function to forcefully change the address,
 * despite not receiving an answer from the server
 * @return 1 if the call was successful and the address was set, or 0 otherwise
 */
int setAPYAddress(char* address, char* port, int order, int force){
    char* msg;
    PyObject *pFunc, *pArg, *pArgs, *new_address;

    if (iface_module != NULL) {
        pFunc = PyObject_GetAttrString(iface_module, "setAPYAddress");

        if (pFunc) {
            pArgs = PyTuple_New(4);

            pArg = PyBytes_FromString(address);
            PyTuple_SetItem(pArgs, 0, pArg);

            pArg = port == NULL ? Py_None : PyBytes_FromString(port);
            PyTuple_SetItem(pArgs, 1, pArg);

            PyTuple_SetItem(pArgs, 2, order > -1 ? PyLong_FromLong(order) : Py_None);

            PyTuple_SetItem(pArgs, 3, force == 0 ? Py_False : Py_True);

            new_address = PyObject_CallObject(pFunc, pArgs);
            Py_XDECREF(pArgs);
            Py_XDECREF(pFunc);

            if (new_address != NULL){
                if(new_address != Py_None){
                    if(files_module != NULL){
                        pFunc = PyObject_GetAttrString(files_module, "setKey");

                        if (pFunc) {
                            pArgs = PyTuple_New(2);

                            PyTuple_SetItem(pArgs, 0, PyUnicode_FromString("apyAddress"));

                            PyTuple_SetItem(pArgs, 1, new_address);

                            PyObject_CallObject(pFunc, pArgs);

                            Py_XDECREF(new_address);
                        }
                        else{
                            Py_XDECREF(new_address);
                            return 0;
                        }
                    }
                    else{
                        notify_error("Module: \'apertiumFiles\' is not loaded");
                        return 0;
                    }
                    return 1;
                }
                else{
                    msg = malloc(sizeof(char)*(strlen(address)+(port == NULL ? 0 : strlen(port))+100));
                    if(port != NULL){
                        sprintf(msg,"No response from server at %s:%s",address,port);
                    }
                    else{
                        sprintf(msg,"No response from server at %s",address);
                    }
                    notify_error(msg);
                    free(msg);
                    return 0;
                }
            }
            else {
                return 0;
            }
        }
        else {
            return 0;
        }
        Py_XDECREF(pFunc);
    }
    else {
        notify_error("Module: \'apertiumInterfaceAPY\' is not loaded");
        return 0;
    }
}