Ejemplo n.º 1
0
int		create_interface(t_interface *in)
{
  if ((WIN(w_root) = initscr()) == NULL)
    return (error_str("initscr fail !"));
  if ((WIN(w_chans) = subwin(WIN(w_root), 3, 80, 0, 0)) == NULL)
    return (error_str("subwin chans fail !"));
  wborder(WIN(w_chans), 0, 0, 0, 0, 0, 0, 0, 0);
  if ((WIN(w_users) = subwin(WIN(w_root), 20, 20, 3, 60)) == NULL)
    return (error_str("subwin users fail !"));
  wborder(WIN(w_users), 0, 0, 0, 0, 0, 0, 0, 0);
  if ((WIN(w_mesgs) = subwin(WIN(w_root), 17, 60, 3, 0)) == NULL)
    return (error_str("subwin mesgs fail !"));
  wborder(WIN(w_mesgs), 0, 0, 0, 0, 0, 0, 0, 0);
  if ((WIN(w_input) = subwin(WIN(w_root), 3, 60, 20, 0)) == NULL)
    return (error_str("subwin input fail !"));
  wborder(WIN(w_input), 0, 0, 0, 0, 0, 0, 0, 0);
  curs_set(0);
  noecho();
  start_color();
  cbreak();
  keypad(WIN(w_root), TRUE);
  init_pair(1, COLOR_GREEN, COLOR_BLACK);
  init_pair(2, COLOR_RED, COLOR_BLACK);
  init_pair(3, COLOR_WHITE, COLOR_BLACK);
  init_pair(4, COLOR_BLUE, COLOR_BLACK);
  init_pair(5, COLOR_YELLOW, COLOR_BLACK);
  refresh_interface(in);
  return (1);
}
Ejemplo n.º 2
0
int checkscript() {
  char *prog[2];
  struct stat s;
  int pid, w;

  if (stat("check", &s) == -1) {
    if (errno == error_noent) return(1);
    outs2(WARN); outs2("unable to stat "); outs2(*service); outs2("/check: ");
    outs2(error_str(errno)); flush2("\n");
    return(0);
  }
  /* if (!(s.st_mode & S_IXUSR)) return(1); */
  if ((pid =fork()) == -1) {
    outs2(WARN); outs2("unable to fork for "); outs2(*service);
    outs2("/check: "); outs2(error_str(errno)); flush2("\n");
    return(0);
  }
  if (!pid) {
    prog[0] ="./check";
    prog[1] =0;
    close(1);
    execve("check", prog, environ);
    outs2(WARN); outs2("unable to run "); outs2(*service); outs2("/check: ");
    outs2(error_str(errno)); flush2("\n");
    _exit(0);
  }
  while (wait_pid(&w, pid) == -1) {
    if (errno == error_intr) continue;
    outs2(WARN); outs2("unable to wait for child "); outs2(*service);
    outs2("/check: "); outs2(error_str(errno)); flush2("\n");
    return(0);
  }
  return(!wait_exitcode(w));
}
Ejemplo n.º 3
0
int main()
{
  int ret = 0;
  struct dir_walk dw;

  dir_walk_init(&dw);

  dw.cb_dir = dirfile;
  dw.cb_reg = regfile;
  dw.cb_lnk = lnkfile;
  dw.cb_fifo = fifofile;

  dw.base = "testdata/dir_walk";

  if (mkfifo("testdata/dir_walk/fifo", 0644) == -1) {
    printf("fail: mkfifo: %s\n", error_str(errno));
    return 1;
  }

  if (!dir_walk(&dw)) {
    printf("fail: dir_walk_start() returned 0: %s\n", error_str(errno));
    ret = 1;
    goto END;
  }

  END:
  if (unlink("testdata/dir_walk/fifo") == -1)
    printf("error: unlink: %s\n", error_str(errno));
  return ret;
}
Ejemplo n.º 4
0
//luaGetError
std::string luaGetError(lua_State* plua_state, int err)
{
    std::string error_str("");
    if (0 == err)
        return error_str;

    std::string err_type;
    switch (err)
    {
        case LUA_ERRSYNTAX: //compile-time error
            err_type = "syntax error during pre-compilation";
            break;
        case LUA_ERRMEM: //memory error
            err_type = "memory allocation error";
            break;
        case LUA_ERRRUN: //runtime-time error
            err_type = "runtime error";
            break;
        case LUA_YIELD: //thread suspend error
            err_type = "thread has been suspended";
            break;
        case LUA_ERRERR: //error while running
            err_type = "error while running the error handler function";
            break;
        default:
            err_type = "unknown";
            break;
    }

    error_str = strFormat("error(%s) %s", err_type.c_str(), lua_tostring(plua_state, -1));
    luaPop(plua_state, 1);

    return error_str;
}
Ejemplo n.º 5
0
void strerr_sysinit()
{
  strerr_sys.who = 0;
  strerr_sys.x = error_str(errno);
  strerr_sys.y = "";
  strerr_sys.z = "";
}
Ejemplo n.º 6
0
/*
 * printerror
 *
 * format a nice and consistent error string using the errno to string
 * conversion utilities and the arguments supplied
 */
void printerror(const int ecode, char *(*error_itoa)(int),
		const char *func, const char *format, ...)
{
  char     message[512];
  char     err[128];
  char     ts[16];
  char     fs[64];
  va_list  ap;

  va_start(ap, format);
  vsnprintf(message, sizeof(message), format, ap);
  va_end(ap);

  error_str(ecode, error_itoa, err, sizeof(err));
  timestamp_str(ts, sizeof(ts));

  if(func != NULL) snprintf(fs, sizeof(fs), "%s: ", func);
  else             fs[0] = '\0';

  fprintf(stderr, "%s%s%s%s\n", ts, fs, message, err);
  fflush(stderr);

#ifndef WITHOUT_DEBUGFILE
  if(debugfile != NULL)
    {
      fprintf(debugfile, "%s%s%s%s\n", ts, fs, message, err);
      fflush(debugfile);
    }
#endif

  return;
}
Ejemplo n.º 7
0
 autobroadcast_incompatible_shapes::autobroadcast_incompatible_shapes(
     const ngraph::Shape& shape1, const ngraph::Shape& shape2)
     : ngraph::ngraph_error(error_str(shape1, shape2))
     , m_shape1(shape1)
     , m_shape2(shape2)
 {
 }
Ejemplo n.º 8
0
Archivo: main.c Proyecto: DmitryKuk/ls
int main(int argc, char **argv)
{
	arguments args;
	int status = arguments_init(&args, &argc, &argv);
	switch (status) {
	case STATUS_OK:	// Всё задано корректно
		break;
	case STATUS_INCORRECT_ARGUMENT:
		usage();
		exit(STATUS_INCORRECT_ARGUMENT);	// Неизвестный аргумент
	default:	// Этого не случится
		error_str("Unknown error!");
		exit(STATUS_ERROR);
	}
	
	status = 0;
	if (argc == 0) {
		status = ls(&args, "./");
	} else {
		for ( ; argc > 0; --argc, ++argv) {
			int tmp = ls(&args, *argv);
			if (status == 0) status = tmp;
		}
	}
	
	exit(status);
}
Ejemplo n.º 9
0
std::pair<size_t, bool> socket_engine::io_read(char *buf, size_t size) {
    int n = ::recv(socket_, buf, size, 0);
    if (n > 0) return std::make_pair(n, true);
    if (n == 0) return std::make_pair(0, false);
    if (n == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
        return std::make_pair(0, true);
    throw connection_engine::io_error("read: " + error_str());
}
Ejemplo n.º 10
0
static void
warn_cb (const char *name, int err)
{
    aa_put_warn (cur_name, name, 0);
    aa_bs_noflush (AA_ERR, ": ");
    aa_bs_noflush (AA_ERR, error_str (err));
    aa_end_warn ();
}
	void http_tracker_connection::on_response(error_code const& ec
		, http_parser const& parser, char const* data, int size)
	{
		// keep this alive
		boost::intrusive_ptr<http_tracker_connection> me(this);

		if (ec && ec != asio::error::eof)
		{
			fail(-1, ec.message().c_str());
			return;
		}
		
		if (!parser.header_finished())
		{
			fail(-1, "premature end of file");
			return;
		}

		if (parser.status_code() != 200)
		{
			fail(parser.status_code(), parser.message().c_str());
			return;
		}
	
		if (ec && ec != asio::error::eof)
		{
			fail(parser.status_code(), ec.message().c_str());
			return;
		}
		
		received_bytes(size + parser.body_start());

		// handle tracker response
		lazy_entry e;
		int res = lazy_bdecode(data, data + size, e);

		if (res == 0 && e.type() == lazy_entry::dict_t)
		{
			parse(parser.status_code(), e);
		}
		else
		{
			std::string error_str("invalid encoding of tracker response: \"");
			for (char const* i = data, *end(data + size); i != end; ++i)
			{
				if (*i >= ' ' && *i <= '~') error_str += *i;
				else
				{
					char val[30];
					snprintf(val, sizeof(val), "0x%02x ", *i);
					error_str += val;
				}
			}
			error_str += "\"";
			fail(parser.status_code(), error_str.c_str());
		}
		close();
	}
Ejemplo n.º 12
0
static int get_status(struct shinkos2145_ctx *ctx)
{
	struct s2145_cmd_hdr cmd;
	struct s2145_status_resp *resp = (struct s2145_status_resp *) rdbuf;
	int ret, num = 0;

	cmd.cmd = cpu_to_le16(S2145_CMD_STATUS);
	cmd.len = cpu_to_le16(0);

	if ((ret = s2145_do_cmd(ctx,
				(uint8_t*)&cmd, sizeof(cmd),
				sizeof(*resp),
				&num)) < 0) {
		ERROR("Failed to execute %s command\n", cmd_names(cmd.cmd));
		return ret;
	}

	INFO("Printer Status:  0x%02x (%s)\n", resp->hdr.status,
	     status_str(resp->hdr.status));
	if (resp->hdr.status == ERROR_PRINTER) {
		if(resp->hdr.error == ERROR_NONE)
			resp->hdr.error = resp->hdr.status;
		INFO(" Error 0x%02x (%s) 0x%02x/0x%02x (%s)\n",
		     resp->hdr.error,
		     error_str(resp->hdr.error),
		     resp->hdr.printer_major,
		     resp->hdr.printer_minor, error_codes(resp->hdr.printer_major, resp->hdr.printer_minor));
	}
	if (le16_to_cpu(resp->hdr.payload_len) != (sizeof(struct s2145_status_resp) - sizeof(struct s2145_status_hdr)))
		return 0;

	INFO(" Print Counts:\n");
	INFO("\tSince Paper Changed:\t%08u\n", le32_to_cpu(resp->count_paper));
	INFO("\tLifetime:\t\t%08u\n", le32_to_cpu(resp->count_lifetime));
	INFO("\tMaintainence:\t\t%08u\n", le32_to_cpu(resp->count_maint));
	INFO("\tPrint Head:\t\t%08u\n", le32_to_cpu(resp->count_head));
	INFO(" Cutter Actuations:\t%08u\n", le32_to_cpu(resp->count_cutter));
	INFO(" Ribbon Remaining:\t%08u\n", le32_to_cpu(resp->count_ribbon_left));
	INFO("Bank 1: 0x%02x (%s) Job %03u @ %03u/%03u (%03u remaining)\n",
	     resp->bank1_status, bank_statuses(resp->bank1_status),
	     resp->bank1_printid,
	     le16_to_cpu(resp->bank1_finished),
	     le16_to_cpu(resp->bank1_specified),
	     le16_to_cpu(resp->bank1_remaining));

	INFO("Bank 2: 0x%02x (%s) Job %03d @ %03d/%03d (%03d remaining)\n",
	     resp->bank2_status, bank_statuses(resp->bank1_status),
	     resp->bank2_printid,
	     le16_to_cpu(resp->bank2_finished),
	     le16_to_cpu(resp->bank2_specified),
	     le16_to_cpu(resp->bank2_remaining));

	INFO("Tonecurve Status: 0x%02x (%s)\n", resp->tonecurve_status, tonecurve_statuses(resp->tonecurve_status));

	return 0;
}
Ejemplo n.º 13
0
void errout(int i)
{
  int j;

  if (!stralloc_copys(&x[i].middle,":")) nomem();
  if (!stralloc_cats(&x[i].middle,error_str(errno))) nomem();
  for (j = 0;j < x[i].middle.len;++j)
    if (x[i].middle.s[j] == ' ')
      x[i].middle.s[j] = '-';
}
Ejemplo n.º 14
0
    void istreambuf::raise_error(int err){
        std::string what = error_str(err);

        LOG("bz::istreambuf::raise_error (" << err << ") = " << what);

        if (what.size() > 0) {
            throw decompress_error(this, what);
        } else {
            throw decompress_error(this);
        }
    }
Ejemplo n.º 15
0
void out(char *p, char *m1) {
  buffer_puts(buffer_1, p);
  buffer_puts(buffer_1, *service);
  buffer_puts(buffer_1, ": ");
  buffer_puts(buffer_1, m1);
  if (errno) {
    buffer_puts(buffer_1, ": ");
    buffer_puts(buffer_1, error_str(errno));
  }
  buffer_puts(buffer_1, "\n");
  buffer_flush(buffer_1);
}
	void http_tracker_connection::on_response(error_code const& ec
		, http_parser const& parser, char const* data, int size)
	{
		// keep this alive
		boost::intrusive_ptr<http_tracker_connection> me(this);

		if (ec && ec != asio::error::eof)
		{
			fail(-1, ec.message().c_str());
			return;
		}
		
		if (!parser.header_finished())
		{
			fail(-1, "premature end of file");
			return;
		}

		if (parser.status_code() != 200)
		{
			fail(parser.status_code(), parser.message().c_str());
			return;
		}
	
		if (ec && ec != asio::error::eof)
		{
			fail(parser.status_code(), ec.message().c_str());
			return;
		}
		
		// handle tracker response
		entry e;
		e = bdecode(data, data + size);

		if (e.type() == entry::dictionary_t)
		{
			parse(parser.status_code(), e);
		}
		else
		{
			std::string error_str("invalid bencoding of tracker response: \"");
			for (char const* i = data, *end(data + size); i != end; ++i)
			{
				if (*i >= ' ' && *i <= '~') error_str += *i;
				else error_str += "0x" + boost::lexical_cast<std::string>((unsigned int)*i) + " ";
			}
			error_str += "\"";
			fail(parser.status_code(), error_str.c_str());
		}
		close();
	}
Ejemplo n.º 17
0
void dump_config_fcs(fcs_float *pos,fcs_float *chg,int n,int step,int myid) {
  FILE *out=NULL;
  str255 fname;
  int i;
  sprintf(fname,"%s.%05d.xyzq.%u", outfilename, step, myid);
  out = fopen(fname,"w");
  if (NULL == out) error_str("Cannot open output file %s",fname);
  fprintf(out, "%d\n", n);
  for (i=0; i<n; i++) {
    fprintf(out, "%g %g %g %g\n", pos[3*i], pos[3*i+1], pos[3*i+2], chg[i] );
  }
  fclose(out);
  MPI_Barrier(cpugrid);
}
Ejemplo n.º 18
0
Archivo: imd_neb.c Proyecto: CBegau/imd
/******************************************************************************
*
*  write file with total fnorm, for monitoring convergence
*
******************************************************************************/
void write_neb_eng_file(int steps)
{
  static int flush_count=0;
  str255 fname;
  int i;

  /* write header */
  if (steps==0) {
    sprintf(fname, "%s.eng", neb_outfilename);
    neb_eng_file = fopen(fname,"a");
    if (NULL == neb_eng_file) 
      error_str("Cannot open properties file %s", fname);
    fprintf(neb_eng_file, "# nfc fnorm neb_k Epot_0 Epot_1 ... Epot_nrep\n");
  }

  /* open .eng file if not yet open */
  if (NULL == neb_eng_file) {
    sprintf(fname, "%s.eng", neb_outfilename);
    neb_eng_file = fopen(fname,"a");
    if (NULL == neb_eng_file) 
      error_str("Cannot open properties file %s.eng", outfilename);
  }

  fprintf(neb_eng_file, "%d %e %e   ", nfc, neb_fnorm, neb_k);
  for(i=0;i<neb_nrep;i++)
	{
	  fprintf(neb_eng_file,"%lf ", neb_epot_im[i]);
	}
  fprintf(neb_eng_file,"\n ");

  /* flush .eng file every flush_int writes */
  if (flush_count++ > flush_int) {
    fflush(neb_eng_file);
    flush_count=0;
  }
}
Ejemplo n.º 19
0
Archivo: sdp.c Proyecto: ghent360/bluez
static void error_rsp(const struct l2cap_frame *frame, struct tid_data *tid)
{
	uint16_t error;

	clear_tid(tid);

	if (frame->size < 2) {
		print_text(COLOR_ERROR, "invalid size");
		packet_hexdump(frame->data, frame->size);
		return;
	}

	error = get_be16(frame->data);

	print_field("Error code: %s (0x%4.4x)", error_str(error), error);
}
Ejemplo n.º 20
0
rcp_packet* rcp_command(rcp_packet* req)
{
	int res = rcp_send(req);
	if (res == -1)
		goto error;

	sem_wait(&resp_available[req->request_id]);

	if (resp[req->request_id].action == RCP_PACKET_ACTION_ERROR)
	{
		TL_ERROR("%s", error_str(resp[req->request_id].payload[0]));
		return NULL;
	}

	return &resp[req->request_id];

error:
	TL_ERROR("rcp_command()");
	return NULL;
}
Ejemplo n.º 21
0
void PionPlugin::openPlugin(const std::string& plugin_file,
							PionPluginData& plugin_data)
{
	// get the name of the plugin (for create/destroy symbol names)
	plugin_data.m_plugin_name = getPluginName(plugin_file);
	
	// attempt to open the plugin; note that this tries all search paths
	// and also tries a variety of platform-specific extensions
	plugin_data.m_lib_handle = loadDynamicLibrary(plugin_file.c_str());
	if (plugin_data.m_lib_handle == NULL) {
#ifndef PION_WIN32
		char *error_msg = dlerror();
		if (error_msg != NULL) {
			std::string error_str(plugin_file);
			error_str += " (";
			error_str += error_msg;
			error_str += ')';
			throw OpenPluginException(error_str);
		} else
#endif
		throw OpenPluginException(plugin_file);
	}
	
	// find the function used to create new plugin objects
	plugin_data.m_create_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_CREATE + plugin_data.m_plugin_name);
	if (plugin_data.m_create_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingCreateException(plugin_file);
	}

	// find the function used to destroy existing plugin objects
	plugin_data.m_destroy_func =
		getLibrarySymbol(plugin_data.m_lib_handle,
						 PION_PLUGIN_DESTROY + plugin_data.m_plugin_name);
	if (plugin_data.m_destroy_func == NULL) {
		closeDynamicLibrary(plugin_data.m_lib_handle);
		throw PluginMissingDestroyException(plugin_file);
	}
}
Ejemplo n.º 22
0
int status(char *unused) {
  int rc;

  rc =svstatus_get();
  switch(r) { case -1: if (lsb) done(4); case 0: return(0); }
  rc =svstatus_print(*service);
  if (chdir("log") == -1) {
    if (errno != error_noent) {
      outs("; log: "); outs(WARN);
      outs("unable to change to log service directory: ");
      outs(error_str(errno));
    }
  }
  else
    if (svstatus_get()) {
      outs("; "); svstatus_print("log");
    }
  flush("\n");
  if (lsb) switch(rc) { case 1: done(0); case 2: done(3); case 0: done(4); }
  return(rc);
}
Ejemplo n.º 23
0
unsigned int svstatus_print(char *m) {
  int pid;
  int normallyup =0;
  struct stat s;
 
  if (stat("down", &s) == -1) {
    if (errno != error_noent) {
      outs2(WARN); outs2("unable to stat "); outs2(*service); outs2("/down: ");
      outs2(error_str(errno)); flush2("\n");
      return(0);
    }
    normallyup =1;
  }
  pid =(unsigned char) svstatus[15];
  pid <<=8; pid +=(unsigned char)svstatus[14];
  pid <<=8; pid +=(unsigned char)svstatus[13];
  pid <<=8; pid +=(unsigned char)svstatus[12];
  tai_unpack(svstatus, &tstatus);
  switch (svstatus[19]) {
  case 0: outs(DOWN); break;
  case 1: outs(RUN); break;
  case 2: outs(FINISH); break;
  }
  outs(m); outs(": ");
  if (svstatus[19]) {
    outs("(pid "); sulong[fmt_ulong(sulong, pid)] =0;
    outs(sulong); outs(") ");
  }
  buffer_put(buffer_1, sulong,
    fmt_ulong(sulong, tnow.sec.x < tstatus.x ? 0 : tnow.sec.x -tstatus.x));
  outs("s");
  if (pid && !normallyup) outs(", normally down");
  if (!pid && normallyup) outs(", normally up");
  if (pid && svstatus[16]) outs(", paused");
  if (!pid && (svstatus[17] == 'u')) outs(", want up");
  if (pid && (svstatus[17] == 'd')) outs(", want down");
  if (pid && svstatus[18]) outs(", got TERM");
  return(pid ? 1 : 2);
}
Ejemplo n.º 24
0
int main(int argc,char **argv)
{
  uint16 u16;

  dns_random_init(seed);

  if (!*argv) usage();
  if (!*++argv) usage();
  if (!parsetype(*argv,type)) usage();

  if (!*++argv) usage();
  if (!dns_domain_fromdot(&q,*argv,str_len(*argv))) oops();

  if (!*++argv) usage();
  if (!stralloc_copys(&out,*argv)) oops();
  if (dns_ip6_qualify(&ip,&fqdn,&out) == -1) oops();
  if (ip.len >= 256) ip.len = 256;
  byte_zero(servers,256);
  byte_copy(servers,ip.len,ip.s);

  if (!stralloc_copys(&out,"")) oops();
  uint16_unpack_big(type,&u16);
  if (!stralloc_catulong0(&out,u16,0)) oops();
  if (!stralloc_cats(&out," ")) oops();
  if (!dns_domain_todot_cat(&out,q)) oops();
  if (!stralloc_cats(&out,":\n")) oops();

  if (resolve(q,type,servers) == -1) {
    if (!stralloc_cats(&out,error_str(errno))) oops();
    if (!stralloc_cats(&out,"\n")) oops();
  }
  else {
    if (!printpacket_cat(&out,tx.packet,tx.packetlen)) oops();
  }

  buffer_putflush(buffer_1,out.s,out.len);
  _exit(0);
}
Ejemplo n.º 25
0
bool CMySQLQuery::Execute(MYSQL *mysql_connection)
{
    bool ret_val = false;
    char log_funcname[64];
    if (Unthreaded)
        sprintf(log_funcname, "CMySQLQuery::Execute");
    else
        sprintf(log_funcname, "CMySQLQuery::Execute[%s]", Callback.Name.c_str());

    CLog::Get()->LogFunction(LOG_DEBUG, log_funcname, "starting query execution");

    chrono::steady_clock::time_point query_exec = chrono::steady_clock::now();
    int query_error = mysql_real_query(mysql_connection, Query.c_str(), Query.length());
    chrono::steady_clock::duration query_exec_duration = chrono::steady_clock::now() - query_exec;

    if (query_error == 0)
    {
        unsigned int
        query_exec_time_milli = static_cast<unsigned int>(chrono::duration_cast<chrono::milliseconds>(query_exec_duration).count()),
        query_exec_time_micro = static_cast<unsigned int>(chrono::duration_cast<chrono::microseconds>(query_exec_duration).count());

        CLog::Get()->LogFunction(LOG_DEBUG, log_funcname, "query was successfully executed within %d.%d milliseconds", query_exec_time_milli, query_exec_time_micro-(query_exec_time_milli*1000));

        MYSQL_RES *mysql_result = mysql_store_result(mysql_connection); //this has to be here

        //why should we process the result if it won't and can't be used?
        if (Unthreaded || Callback.Name.length() > 0)
        {
            if (StoreResult(mysql_connection, mysql_result) == false)
                CLog::Get()->LogFunction(LOG_ERROR, log_funcname, "an error occured while storing the result: (error #%d) \"%s\"", mysql_errno(mysql_connection), mysql_error(mysql_connection));
            else
            {
                Result->m_Query = Query;
                Result->m_ExecTime[UNIT_MILLISECONDS] = query_exec_time_milli;
                Result->m_ExecTime[UNIT_MICROSECONDS] = query_exec_time_micro;
            }
        }
        else  //no callback was specified
            CLog::Get()->LogFunction(LOG_DEBUG, log_funcname, "no callback specified, skipping result saving");

        if (mysql_result != NULL)
            mysql_free_result(mysql_result);

        ret_val = true;
    }
    else  //mysql_real_query failed
    {
        int error_id = mysql_errno(mysql_connection);
        string error_str(mysql_error(mysql_connection));

        CLog::Get()->LogFunction(LOG_ERROR, log_funcname, "(error #%d) %s", error_id, error_str.c_str());

        if (!Unthreaded)
        {
            //forward OnQueryError(error_id, error[], callback[], query[], connectionHandle);
            //recycle these structures, change some data

            Orm.Object = NULL;
            Orm.Type = 0;

            while (Callback.Params.size() > 0)
                Callback.Params.pop();


            Callback.Params.push(static_cast<cell>(error_id));
            Callback.Params.push(error_str);
            Callback.Params.push(Callback.Name);
            Callback.Params.push(Query);
            Callback.Params.push(static_cast<cell>(Handle->GetID()));

            Callback.Name = "OnQueryError";

            CLog::Get()->LogFunction(LOG_DEBUG, log_funcname, "error will be triggered in OnQueryError");
        }
        ret_val = false;
    }

    if(Unthreaded == false) //decrease counter only if threaded query
        Handle->DecreaseQueryCounter();
    return ret_val;
}
Ejemplo n.º 26
0
template <class T> T check(T result) {
    if (result < 0)
        throw decode_error("" + error_str(result));
    return result;
}
Ejemplo n.º 27
0
template <class T> T check(T result) {
    if (result < 0)
        throw conversion_error(error_str(result));
    return result;
}
Ejemplo n.º 28
0
static int shinkos2145_main_loop(void *vctx, int copies) {
	struct shinkos2145_ctx *ctx = vctx;

	int ret, num;
	uint8_t cmdbuf[CMDBUF_LEN];
	uint8_t rdbuf2[READBACK_LEN];

	int i, last_state = -1, state = S_IDLE;

	struct s2145_cmd_hdr *cmd = (struct s2145_cmd_hdr *) cmdbuf;;
	struct s2145_print_cmd *print = (struct s2145_print_cmd *) cmdbuf;
	struct s2145_status_resp *sts = (struct s2145_status_resp *) rdbuf; 
	struct s2145_mediainfo_resp *media = (struct s2145_mediainfo_resp *) rdbuf;

	/* Send Media Query */
	memset(cmdbuf, 0, CMDBUF_LEN);
	cmd->cmd = cpu_to_le16(S2145_CMD_MEDIAINFO);
	cmd->len = cpu_to_le16(0);

	if ((ret = s2145_do_cmd(ctx,
				cmdbuf, sizeof(*cmd),
				sizeof(*media),
				&num)) < 0) {
		ERROR("Failed to execute %s command\n", cmd_names(cmd->cmd));
		return CUPS_BACKEND_FAILED;
	}
	
	if (le16_to_cpu(media->hdr.payload_len) != (sizeof(struct s2145_mediainfo_resp) - sizeof(struct s2145_status_hdr)))
		return CUPS_BACKEND_FAILED;

	/* Validate print sizes */
	for (i = 0; i < media->count ; i++) {
		/* Look for matching media */
		if (le16_to_cpu(media->items[i].columns) == cpu_to_le16(le32_to_cpu(ctx->hdr.columns)) &&
		    le16_to_cpu(media->items[i].rows) == cpu_to_le16(le32_to_cpu(ctx->hdr.rows)) &&
		    media->items[i].print_type == le32_to_cpu(ctx->hdr.method))
			break;
	}
	if (i == media->count) {
		ERROR("Incorrect media loaded for print!\n");
		return CUPS_BACKEND_HOLD;
	}

	// XXX check copies against remaining media!

top:
	if (state != last_state) {
		if (dyesub_debug)
			DEBUG("last_state %d new %d\n", last_state, state);
	}

	/* Send Status Query */
	memset(cmdbuf, 0, CMDBUF_LEN);
	cmd->cmd = cpu_to_le16(S2145_CMD_STATUS);
	cmd->len = cpu_to_le16(0);

	if ((ret = s2145_do_cmd(ctx,
				cmdbuf, sizeof(*cmd),
				sizeof(struct s2145_status_hdr),
				&num)) < 0) {
		ERROR("Failed to execute %s command\n", cmd_names(cmd->cmd));
		return CUPS_BACKEND_FAILED;
	}

	if (memcmp(rdbuf, rdbuf2, READBACK_LEN)) {
		memcpy(rdbuf2, rdbuf, READBACK_LEN);

		INFO("Printer Status: 0x%02x (%s)\n", 
		     sts->hdr.status, status_str(sts->hdr.status));
		if (sts->hdr.result != RESULT_SUCCESS)
			goto printer_error;		
		if (sts->hdr.error == ERROR_PRINTER)
			goto printer_error;
	} else if (state == last_state) {
		sleep(1);
		goto top;
	}
	last_state = state;

	fflush(stderr);       

	switch (state) {
	case S_IDLE:
		INFO("Waiting for printer idle\n");
		/* If either bank is free, continue */
		if (sts->bank1_status == BANK_STATUS_FREE || 
		    sts->bank2_status == BANK_STATUS_FREE) 
			state = S_PRINTER_READY_CMD;

		break;
	case S_PRINTER_READY_CMD:
		INFO("Initiating print job (internal id %d)\n", ctx->jobid);

		memset(cmdbuf, 0, CMDBUF_LEN);
		print->hdr.cmd = cpu_to_le16(S2145_CMD_PRINTJOB);
		print->hdr.len = cpu_to_le16(sizeof (*print) - sizeof(*cmd));

		print->id = ctx->jobid;
		print->count = cpu_to_le16(copies);
		print->columns = cpu_to_le16(le32_to_cpu(ctx->hdr.columns));
		print->rows = cpu_to_le16(le32_to_cpu(ctx->hdr.rows));
		print->media = le32_to_cpu(ctx->hdr.media);
		print->mode = le32_to_cpu(ctx->hdr.mode);
		print->method = le32_to_cpu(ctx->hdr.method);

		if ((ret = s2145_do_cmd(ctx,
					cmdbuf, sizeof(*print),
					sizeof(struct s2145_status_hdr),
					&num)) < 0) {
			ERROR("Failed to execute %s command\n", cmd_names(print->hdr.cmd));
			return ret;
		}

		if (sts->hdr.result != RESULT_SUCCESS) {
			if (sts->hdr.error == ERROR_BUFFER_FULL) {
				INFO("Printer Buffers full, retrying\n");
				break;
			} else if ((sts->hdr.status & 0xf0) == 0x30 || sts->hdr.status == 0x21) {
				INFO("Printer busy (%s), retrying\n", status_str(sts->hdr.status));
				break;
			} else if (sts->hdr.status != ERROR_NONE)
				goto printer_error;
		}

		INFO("Sending image data to printer\n");
		if ((ret = send_data(ctx->dev, ctx->endp_down,
				     ctx->databuf, ctx->datalen)))
			return CUPS_BACKEND_FAILED;

		INFO("Waiting for printer to acknowledge completion\n");
		sleep(1);
		state = S_PRINTER_SENT_DATA;
		break;
	case S_PRINTER_SENT_DATA:
		if (fast_return) {
			INFO("Fast return mode enabled.\n");
			state = S_FINISHED;
		} else if (sts->hdr.status == STATUS_READY ||
			   sts->hdr.status == STATUS_FINISHED) {
			state = S_FINISHED;
		}
		break;
	default:
		break;
	};

	if (state != S_FINISHED)
		goto top;
	
	INFO("Print complete\n");

	return CUPS_BACKEND_OK;

printer_error:
	ERROR("Printer reported error: %#x (%s) status: %#x (%s) -> %#x.%#x (%s)\n",
	      sts->hdr.error, 
	      error_str(sts->hdr.error),
	      sts->hdr.status, 
	      status_str(sts->hdr.status),
	      sts->hdr.printer_major, sts->hdr.printer_minor,
	      error_codes(sts->hdr.printer_major, sts->hdr.printer_minor));
	return CUPS_BACKEND_FAILED;
}
Ejemplo n.º 29
0
static void
reset_service (const char *name, intptr_t mode)
{
    aa_service *s;
    int si;
    int r;
    int old_event;
    int event;

    r = aa_get_service (name, &si, 1);
    if (r < 0)
    {
        aa_put_err (name, errmsg[-r], 1);
        return;
    }

    r = aa_preload_service (si);
    if (r < 0)
    {
        aa_put_err (name, errmsg[-r], 1);
        return;
    }

    s = aa_service (si);
    if (aa_service_status_read (&s->st, aa_service_name (s)) < 0 && errno != ENOENT)
    {
        int e = errno;

        aa_put_err (name, "Failed to read service status file: ", 0);
        aa_bs_noflush (AA_ERR, error_str (e));
        aa_end_err ();
        return;
    }

    if (s->st.type == AA_TYPE_LONGRUN)
    {
        aa_put_err (name, "Can only reset ont-shot services", 1);
        return;
    }

    /* Starting/Stopping cannot be reset */
    if (s->st.event == AA_EVT_STARTING || s->st.event == AA_EVT_STOPPING)
        return;

    if (mode == MODE_AUTO)
    {
        if (s->st.event == AA_EVT_STARTING_FAILED || s->st.event == AA_EVT_START_FAILED)
            event = AA_EVT_STARTED;
        else if (s->st.event == AA_EVT_STOPPING_FAILED || s->st.event == AA_EVT_STOP_FAILED)
            event = AA_EVT_STOPPED;
        else
            return;
    }
    else
        event = (mode == MODE_STARTED) ? AA_EVT_STARTED : AA_EVT_STOPPED;

    if (s->st.event == event)
        return;

    tain_now_g ();
    old_event = s->st.event;
    s->st.event = event;
    s->st.stamp = STAMP;
    aa_service_status_set_msg (&s->st, "");
    if (aa_service_status_write (&s->st, aa_service_name (s)) < 0)
    {
        int e = errno;

        aa_put_err (name, "Failed to write service status file: ", 0);
        aa_bs_noflush (AA_ERR, error_str (e));
        aa_end_err ();
    }
    else
    {
        aa_put_title (1, name, "", 0);
        aa_is_noflush (AA_OUT, ANSI_HIGHLIGHT_OFF);
        aa_bs_noflush (AA_OUT, eventmsg[old_event]);
        aa_is_noflush (AA_OUT, ANSI_HIGHLIGHT_ON);
        aa_bs_noflush (AA_OUT, " -> ");
        aa_bs_noflush (AA_OUT, eventmsg[event]);
        aa_end_title ();
    }
}
Ejemplo n.º 30
0
/*
	- result data is sent as a string which ends with "\n\r"
	- the Teamspeak3 server can send multiple strings
	- the end of a result set is always an error result string
*/
void CNetwork::OnRead(const boost::system::error_code &error_code)
{
	if (error_code.value() == 0)
	{
		static vector<string> captured_data;
		std::istream tmp_stream(&m_ReadStreamBuf);
		string read_data;
		std::getline(tmp_stream, read_data, '\r');

#ifdef _DEBUG
		string dbg_read_data(read_data);
		bool first_line = true;
		do
		{
			logprintf("%s> %s", 
				first_line == true ? ">>>" : "   ",
				dbg_read_data.substr(0, 512).c_str());
			dbg_read_data.erase(0, 512);
			first_line = false;
		} while (dbg_read_data.empty() == false);
#endif

		//regex: parse error
		//if this is an error message, it means that no other result data will come
		static const boost::regex error_rx("error id=([0-9]+) msg=([^ \n]+)");
		boost::smatch error_rx_result;
		if (boost::regex_search(read_data, error_rx_result, error_rx))
		{
			if (error_rx_result[1].str() == "0")
			{
				for (auto i = captured_data.begin(); i != captured_data.end(); ++i)
				{
					string &data = *i;
					if (data.find('|') == string::npos) 
						continue;

					//we have multiple data rows with '|' as delimiter here,
					//split them up and re-insert every single row
					vector<string> result_set;
					size_t delim_pos = 0;
					do
					{
						size_t old_delim_pos = delim_pos;
						delim_pos = data.find('|', delim_pos);
						string row = data.substr(old_delim_pos, delim_pos - old_delim_pos);
						result_set.push_back(row);
					} while (delim_pos != string::npos && ++delim_pos);

					i = captured_data.erase(i);
					for (auto j = result_set.begin(), jend = result_set.end(); j != jend; ++j)
						i = captured_data.insert(i, *j);
				}
				
				//call callback and send next command
				m_CmdQueueMutex.lock();
				if (m_CmdQueue.empty() == false)
				{
					ReadCallback_t &callback = m_CmdQueue.front().get<1>();
					if (callback)
					{
						m_CmdQueueMutex.unlock();
						callback(captured_data); //calls the callback
						m_CmdQueueMutex.lock();
					}
					m_CmdQueue.pop();

					if (m_CmdQueue.empty() == false)
						AsyncWrite(m_CmdQueue.front().get<0>());
				}
				m_CmdQueueMutex.unlock();
			}
			else
			{
				string error_str(error_rx_result[2].str());
				unsigned int error_id = 0;

				CUtils::Get()->UnEscapeString(error_str);
				CUtils::Get()->ConvertStringToInt(error_rx_result[1].str(), error_id);

				m_CmdQueueMutex.lock();

				CCallbackHandler::Get()->ForwardError(
					EErrorType::TEAMSPEAK_ERROR, error_id,
					fmt::format("error while executing \"{}\": {}", m_CmdQueue.front().get<0>(), error_str));

				m_CmdQueue.pop();

				if (m_CmdQueue.empty() == false)
					AsyncWrite(m_CmdQueue.front().get<0>());

				m_CmdQueueMutex.unlock();
			}

			captured_data.clear();
		}
		else if (read_data.find("notify") == 0)
		{
			//check if notify is duplicate
			static string last_notify_data;
			static const vector<string> duplicate_notifies{ 
				"notifyclientmoved", 
				"notifycliententerview", 
				"notifyclientleftview" 
			};
			bool is_duplicate = false;
			
			for (auto &s : duplicate_notifies)
			{
				if (read_data.find(s) == 0)
				{
					if (last_notify_data == read_data)
						is_duplicate = true;
					
					break;
				}
			}
			
			if (is_duplicate == false)
			{
				//notify event
				boost::smatch event_result;
				for (auto &event : m_EventList)
				{
					if (boost::regex_search(read_data, event_result, event.get<0>()))
					{
						event.get<1>()(event_result);
						break;
					}
				}
			}

			last_notify_data = read_data;
		}
		else
		{
			//stack the result data if it is not an error or notification message
			captured_data.push_back(read_data);
		}

		AsyncRead();
	}
	else //error
	{
		CCallbackHandler::Get()->ForwardError(
			EErrorType::CONNECTION_ERROR, error_code.value(),
			fmt::format("error while reading: {}", error_code.message()));

		//"disable" the plugin, since calling Disconnect() or
		//destroying CNetwork here is not very smart
		CServer::CSingleton::Destroy();
		m_Connected = false; //we're not _really_ connected, are we?
	}
}