/* LQR_PUBLIC */ LqrRetVal lqr_carver_bias_add_area(LqrCarver *r, gdouble *buffer, gint bias_factor, gint width, gint height, gint x_off, gint y_off) { gint x, y; gint xt, yt; gint wt, ht; gint x0, y0, x1, y1, x2, y2; gfloat bias; LQR_CATCH_CANC(r); if (bias_factor == 0) { return LQR_OK; } if ((r->w != r->w0) || (r->w_start != r->w0) || (r->h != r->h0) || (r->h_start != r->h0)) { LQR_CATCH(lqr_carver_flatten(r)); } if (r->nrg_active == FALSE) { LQR_CATCH(lqr_carver_init_energy_related(r)); } if (r->bias == NULL) { LQR_CATCH_MEM(r->bias = g_try_new0(gfloat, r->w * r->h)); } wt = r->transposed ? r->h : r->w; ht = r->transposed ? r->w : r->h; x0 = MIN(0, x_off); y0 = MIN(0, y_off); x1 = MAX(0, x_off); y1 = MAX(0, y_off); x2 = MIN(wt, width + x_off); y2 = MIN(ht, height + y_off); for (y = 0; y < y2 - y1; y++) { for (x = 0; x < x2 - x1; x++) { bias = (gfloat) ((gdouble) bias_factor * buffer[(y - y0) * width + (x - x0)] / 2); xt = r->transposed ? y : x; yt = r->transposed ? x : y; r->bias[(yt + y1) * r->w0 + (xt + x1)] += bias; } } r->nrg_uptodate = FALSE; return LQR_OK; }
GAtHDLC *g_at_hdlc_new_from_io(GAtIO *io) { GAtHDLC *hdlc; unsigned char *buf; if (io == NULL) return NULL; hdlc = g_try_new0(GAtHDLC, 1); if (hdlc == NULL) return NULL; hdlc->ref_count = 1; hdlc->decode_fcs = HDLC_INITFCS; hdlc->decode_offset = 0; hdlc->decode_escape = FALSE; hdlc->xmit_accm[0] = ~0U; hdlc->xmit_accm[3] = 0x60000000; /* 0x7d, 0x7e */ hdlc->recv_accm = ~0U; hdlc->write_buffer = ring_buffer_new(BUFFER_SIZE * 2); if (!hdlc->write_buffer) goto error; /* Write an initial 0x7e as wakeup character */ buf = ring_buffer_write_ptr(hdlc->write_buffer, 0); *buf = HDLC_FLAG; ring_buffer_write_advance(hdlc->write_buffer, 1); hdlc->decode_buffer = g_try_malloc(BUFFER_SIZE * 2); if (!hdlc->decode_buffer) goto error; hdlc->record_fd = -1; hdlc->io = g_at_io_ref(io); g_at_io_set_read_handler(hdlc->io, new_bytes, hdlc); return hdlc; error: if (hdlc->write_buffer) ring_buffer_free(hdlc->write_buffer); if (hdlc->decode_buffer) g_free(hdlc->decode_buffer); g_free(hdlc); return NULL; }
int tty_try_alloc_color_pair2 (const char *fg, const char *bg, const char *attrs, gboolean is_temp_color) { gchar *color_pair; tty_color_pair_t *mc_color_pair; int ifg, ibg, attr; if (fg == NULL || !strcmp (fg, "base")) fg = tty_color_defaults__fg; if (bg == NULL || !strcmp (bg, "base")) bg = tty_color_defaults__bg; if (attrs == NULL || !strcmp (attrs, "base")) attrs = tty_color_defaults__attrs; ifg = tty_color_get_index_by_name (fg); ibg = tty_color_get_index_by_name (bg); attr = tty_attr_get_bits (attrs); color_pair = g_strdup_printf ("%d.%d.%d", ifg, ibg, attr); if (color_pair == NULL) return 0; mc_color_pair = (tty_color_pair_t *) g_hash_table_lookup (mc_tty_color__hashtable, (gpointer) color_pair); if (mc_color_pair != NULL) { g_free (color_pair); return mc_color_pair->pair_index; } mc_color_pair = g_try_new0 (tty_color_pair_t, 1); if (mc_color_pair == NULL) { g_free (color_pair); return 0; } mc_color_pair->is_temp = is_temp_color; mc_color_pair->ifg = ifg; mc_color_pair->ibg = ibg; mc_color_pair->attr = attr; mc_color_pair->pair_index = tty_color_get_next__color_pair_number (); tty_color_try_alloc_pair_lib (mc_color_pair); g_hash_table_insert (mc_tty_color__hashtable, (gpointer) color_pair, (gpointer) mc_color_pair); return mc_color_pair->pair_index; }
static int sqlfs_open(const char *path, struct fuse_file_info *fi) { int err = 0; GError *terr = NULL; struct sqlfs_object *object = find_object(path, &terr); if (terr != NULL && terr->code == EENOTFOUND) { err = -ENOENT; } if ((fi->flags & O_ACCMODE) == O_RDONLY) { if (fi->flags & O_CREAT) { err = sqlfs_mknod(path, 07777 | S_IFREG, 0); } } else { if ((fi->flags & O_ACCMODE) == O_RDWR || (fi->flags & O_ACCMODE) == O_WRONLY) { if ((fi->flags & O_EXCL) && object->object_id) err = -EACCES; } else { err = -EIO; } } if (!err) { // FIXME: Не надёжная генерация уникальных значений fi->fh = object->object_id + g_get_monotonic_time(); char *def = fetch_object_text(path, &terr); if (def != NULL) { sqlfs_file_t *fsfile = g_try_new0(sqlfs_file_t, 1); uint64_t *pfh = g_malloc0(sizeof(uint64_t)); *pfh = fi->fh; if (def) { fsfile->buffer = g_strdup(def); } g_hash_table_insert(cache.open_table, pfh, fsfile); } if (object != NULL) free_sqlfs_object(object); } if (terr != NULL) g_error_free(terr); return err; }
ut_Timer* ut_Timer_new(void* userdata, ut_TimerCallback* cb, GError** error) { ut_Timer* self = g_try_new0(ut_Timer, 1); if (G_UNLIKELY(!self)) { if (error) *error = gx_error_no_memory; return NULL; } self->timer = new_nothrow MyTimer(userdata, cb); if (G_UNLIKELY(!(self->timer))) { g_free(self); if (error) *error = gx_error_no_memory; return NULL; } return self; }
EXTERN_C sa_Sensor_mark* sa_Sensor_mark_new(LogDb* log, GError** error) { sa_Sensor_mark* self = g_try_new0(sa_Sensor_mark, 1); if (G_UNLIKELY(!self)) { if (error) *error = gx_error_no_memory; return NULL; } self->log = log; self->timer = ut_Timer_new(self, &timerCallback, error); if (!self->timer) { sa_Sensor_mark_destroy(self); return NULL; } return self; }
static void mc_skin_color_set_default_for_terminal (mc_skin_t * mc_skin) { mc_skin_color_t *mc_skin_color; mc_skin_color = g_try_new0 (mc_skin_color_t, 1); if (mc_skin_color != NULL) { mc_skin_color->fgcolor = g_strdup ("default"); mc_skin_color->bgcolor = g_strdup ("default"); mc_skin_color->attrs = NULL; mc_skin_color->pair_index = tty_try_alloc_color_pair2 (mc_skin_color->fgcolor, mc_skin_color->bgcolor, mc_skin_color->attrs, FALSE); mc_skin_color_add_to_hash (mc_skin, "skin", "terminal_default_color", mc_skin_color); } }
mongo_sync_connection * test_make_fake_sync_conn (gint fd, gboolean slaveok) { mongo_sync_connection *c; c = g_try_new0 (mongo_sync_connection, 1); if (!c) return NULL; c->super.fd = fd; c->slaveok = slaveok; c->safe_mode = FALSE; c->auto_reconnect = FALSE; c->max_insert_size = MONGO_SYNC_DEFAULT_MAX_INSERT_SIZE; return c; }
GAtRawIP *g_at_rawip_new_from_io(GAtIO *io) { GAtRawIP *rawip; rawip = g_try_new0(GAtRawIP, 1); if (rawip == NULL) return NULL; rawip->ref_count = 1; rawip->write_buffer = NULL; rawip->tun_write_buffer = NULL; rawip->io = g_at_io_ref(io); return rawip; }
static GRilIO *create_io(GIOChannel *channel, GIOFlags flags) { GRilIO *io; if (channel == NULL) return NULL; io = g_try_new0(GRilIO, 1); if (io == NULL) return io; io->ref_count = 1; io->debugf = NULL; if (flags & G_IO_FLAG_NONBLOCK) { io->max_read_attempts = 3; io->use_write_watch = TRUE; } else { io->max_read_attempts = 1; io->use_write_watch = FALSE; } io->buf = ring_buffer_new(8192); if (!io->buf) goto error; if (!g_ril_util_setup_io(channel, flags)) goto error; io->channel = channel; io->read_watch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, received_data, io, read_watcher_destroy_notify); return io; error: if (io->buf) ring_buffer_free(io->buf); g_free(io); return NULL; }
/** * Create a QEMUSizedBuffer * This type of buffer uses scatter-gather lists internally and * can grow to any size. Any data array in the scatter-gather list * can hold different amount of bytes. * * @buffer: Optional buffer to copy into the QSB * @len: size of initial buffer; if @buffer is given, buffer must * hold at least len bytes * * Returns a pointer to a QEMUSizedBuffer or NULL on allocation failure */ QEMUSizedBuffer *qsb_create(const uint8_t *buffer, size_t len) { QEMUSizedBuffer *qsb; size_t alloc_len, num_chunks, i, to_copy; size_t chunk_size = (len > QSB_MAX_CHUNK_SIZE) ? QSB_MAX_CHUNK_SIZE : QSB_CHUNK_SIZE; num_chunks = DIV_ROUND_UP(len ? len : QSB_CHUNK_SIZE, chunk_size); alloc_len = num_chunks * chunk_size; qsb = g_try_new0(QEMUSizedBuffer, 1); if (!qsb) { return NULL; } qsb->iov = g_try_new0(struct iovec, num_chunks); if (!qsb->iov) { g_free(qsb); return NULL; } qsb->n_iov = num_chunks; for (i = 0; i < num_chunks; i++) { qsb->iov[i].iov_base = g_try_malloc0(chunk_size); if (!qsb->iov[i].iov_base) { /* qsb_free is safe since g_free can cope with NULL */ qsb_free(qsb); return NULL; } qsb->iov[i].iov_len = chunk_size; if (buffer) { to_copy = (len - qsb->used) > chunk_size ? chunk_size : (len - qsb->used); memcpy(qsb->iov[i].iov_base, &buffer[qsb->used], to_copy); qsb->used += to_copy; } } qsb->size = alloc_len; return qsb; }
/** * Check the correctness of a layout string. * @param layout The layout string as stored in the config files * "type1;left1;right1;top1;bottom1;type2; ... " * @return LAYOUT_GOOD if the layout is valid, LAYOUT_BAD if the layout is invalid. * * A layout is invalid if it refers to a non-existent view type or if there is something wrong * with the coordinates (e.g. left > right). */ gboolean sat_pref_layout_check(const gchar * layout) { gchar **buffv; guint length, nviews; gint *grid; guint i; gboolean error = FALSE; /* split layout string into an array of strings */ buffv = g_strsplit(layout, ";", 0); length = g_strv_length(buffv); /* check correct number of entries */ if ((length == 0) || (length % 5 != 0)) { error |= TRUE; } nviews = length / 5; grid = g_try_new0(gint, length); /* convert string to array of integers */ for (i = 0; i < length; i++) { grid[i] = (gint) g_ascii_strtoll(buffv[i], NULL, 0); } /* check each view record */ for (i = 0; i < nviews; i++) { if ((grid[5 * i] >= GTK_SAT_MOD_VIEW_NUM) || /* view type within range */ (grid[5 * i + 1] >= grid[5 * i + 2]) || /* left < right */ (grid[5 * i + 3] >= grid[5 * i + 4])) { /* top < bottom */ error |= TRUE; } } g_free(grid); g_strfreev(buffv); return (error ? LAYOUT_BAD : LAYOUT_GOOD); }
GIOChannel *g_at_mux_create_channel(GAtMux *mux) { GAtMuxChannel *mux_channel; GIOChannel *channel; int i; for (i = 0; i < MAX_CHANNELS; i++) { if (mux->dlcs[i] == NULL) break; } if (i == MAX_CHANNELS) return NULL; mux_channel = g_try_new0(GAtMuxChannel, 1); if (mux_channel == NULL) return NULL; if (mux->driver->open_dlc) mux->driver->open_dlc(mux, i+1); channel = (GIOChannel *) mux_channel; g_io_channel_init(channel); channel->close_on_unref = TRUE; channel->funcs = &channel_funcs; channel->is_seekable = FALSE; channel->is_readable = TRUE; channel->is_writeable = TRUE; channel->do_encode = FALSE; mux_channel->mux = mux; mux_channel->dlc = i+1; mux_channel->buffer = ring_buffer_new(MUX_CHANNEL_BUFFER_SIZE); mux_channel->throttled = FALSE; mux->dlcs[i] = mux_channel; debug(mux, "created channel %p, dlc: %d", channel, i+1); return channel; }
Qcow2Cache *qcow2_cache_create(BlockDriverState *bs, int num_tables) { BDRVQcowState *s = bs->opaque; Qcow2Cache *c; c = g_new0(Qcow2Cache, 1); c->size = num_tables; c->entries = g_try_new0(Qcow2CachedTable, num_tables); c->table_array = qemu_try_blockalign(bs->file, (size_t) num_tables * s->cluster_size); if (!c->entries || !c->table_array) { qemu_vfree(c->table_array); g_free(c->entries); g_free(c); c = NULL; } return c; }
LqrRetVal lqr_carver_rigmask_init(LqrCarver *r) { /* gint y, x; */ LQR_CATCH_CANC(r); LQR_CATCH_F(r->active); LQR_CATCH_MEM(r->rigidity_mask = g_try_new0(gfloat, r->w0 * r->h0)); #if 0 for (y = 0; y < r->h0; y++) { for (x = 0; x < r->w0; x++) { r->rigidity_mask[y * r->w0 + x] = 1; } } #endif return LQR_OK; }
extern "C" ut_Immediate* ut_Immediate_new(void* userdata, ut_ImmediateCallback* cb, GError** error) { ut_Immediate* self = g_try_new0(ut_Immediate, 1); if (G_UNLIKELY(!self)) { if (error) *error = gx_error_no_memory; return NULL; } self->userdata = userdata; self->cb = cb; TRAPD(errCode, self->ao = CImmediateAo::NewL(*self)); if (G_UNLIKELY(errCode)) { g_free(self); if (error) *error = make_error(errCode, "failed to create native immediate instance"); return NULL; } return self; }
GIsiClient *g_isi_client_create(GIsiModem *modem, uint8_t resource) { GIsiClient *client; if (modem == NULL) { errno = EINVAL; return NULL; } client = g_try_new0(GIsiClient, 1); if (client == NULL) { errno = ENOMEM; return NULL; } client->timeout = G_ISI_CLIENT_DEFAULT_TIMEOUT; client->resource = resource; client->modem = modem; return client; }
GAtMux *g_at_mux_new(GIOChannel *channel, const GAtMuxDriver *driver) { GAtMux *mux; if (channel == NULL) return NULL; mux = g_try_new0(GAtMux, 1); if (mux == NULL) return NULL; mux->ref_count = 1; mux->driver = driver; mux->shutdown = TRUE; mux->channel = channel; g_io_channel_ref(channel); g_io_channel_set_close_on_unref(channel, TRUE); return mux; }
GivImage *giv_image_new_full(GivImageType img_type, int width, int row_stride, int height, int frame_stride, int rank, int depth) { GivImage *img = g_new0(GivImage, 1); img->rank = rank; img->ref_count = 1; img->img_type = img_type; img->width = width; img->row_stride = row_stride; img->frame_stride = frame_stride; img->height= height; if (depth < 1) depth = 1; img->depth = depth; int buf_size = frame_stride * depth; // This should probably be aligned to be faster... img->buf.buf = (guint8*)g_try_new0(guint8, buf_size); if (!img->buf.buf) { g_free(img); return NULL; } img->attribute_map = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); // One bit is used for signalling one bit images. This should // eventually be moved into image type. By default it is off. img->one_bit = FALSE; return img; }
static mc_skin_color_t * mc_skin_color_get_from_ini_file (mc_skin_t * mc_skin, const gchar * group, const gchar * key) { gsize items_count; gchar **values; mc_skin_color_t *mc_skin_color, *tmp; values = mc_config_get_string_list (mc_skin->config, group, key, &items_count); if (values == NULL || values[0] == NULL) { g_strfreev (values); return NULL; } mc_skin_color = g_try_new0 (mc_skin_color_t, 1); if (mc_skin_color == NULL) { g_strfreev (values); return NULL; } tmp = mc_skin_color_get_with_defaults (group, "_default_"); mc_skin_color->fgcolor = (items_count > 0 && values[0][0]) ? g_strstrip (g_strdup (values[0])) : (tmp != NULL) ? g_strdup (tmp->fgcolor) : NULL; mc_skin_color->bgcolor = (items_count > 1 && values[1][0]) ? g_strstrip (g_strdup (values[1])) : (tmp != NULL) ? g_strdup (tmp->bgcolor) : NULL; mc_skin_color->attrs = (items_count > 2 && values[2][0]) ? g_strstrip (g_strdup (values[2])) : (tmp != NULL) ? g_strdup (tmp->attrs) : NULL; g_strfreev (values); mc_skin_color->pair_index = tty_try_alloc_color_pair2 (mc_skin_color->fgcolor, mc_skin_color->bgcolor, mc_skin_color->attrs, FALSE); return mc_skin_color; }
static bool view_main_wifi_insert_found_ap(wifi_device_info_t *wifi_device) { devpkr_gl_data_t *gdata = g_try_new0(devpkr_gl_data_t, 1); wifi_connection_state_e state; assertm_if(NULL == list, "list is NULL"); if (gdata == NULL) return false; gdata->dev_info = wifi_device; if (gdata->dev_info == NULL) { g_free(gdata); return true; } wifi_ap_get_connection_state(wifi_device->ap, &state); if (WIFI_CONNECTION_STATE_ASSOCIATION == state || WIFI_CONNECTION_STATE_CONFIGURATION == state) { gdata->connection_mode = ITEM_CONNECTION_MODE_CONNECTING; gdata->it = elm_genlist_item_append(list, &itc, gdata, NULL, ELM_GENLIST_ITEM_NONE, __gl_sel, gdata); view_main_state_set(ITEM_CONNECTION_MODE_CONNECTING); return true; } gdata->connection_mode = ITEM_CONNECTION_MODE_OFF; gdata->it = elm_genlist_item_append(list, &itc, gdata, NULL, ELM_GENLIST_ITEM_NONE, __gl_sel, gdata); return true; }
static GDBusProxy *proxy_new(GDBusClient *client, const char *path, const char *interface) { GDBusProxy *proxy; proxy = g_try_new0(GDBusProxy, 1); if (proxy == NULL) return NULL; proxy->client = client; proxy->obj_path = g_strdup(path); proxy->interface = g_strdup(interface); proxy->prop_list = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, prop_entry_free); proxy->watch = g_dbus_add_properties_watch(client->dbus_conn, client->service_name, proxy->obj_path, proxy->interface, properties_changed, proxy, NULL); return g_dbus_proxy_ref(proxy); }
static void swfdec_as_array_do_sort (SwfdecAsContext *cx, SwfdecAsObject *object, const SortOption *options, SwfdecAsFunction *custom_function, const char **fields, SwfdecAsValue *ret) { SortEntry *array; SortCollectData collect_data; SortCompareData compare_data; gint32 i, length; const char *var; SwfdecAsObject *target; SwfdecAsValue val; SortOption options_; gboolean descending; g_return_if_fail (SWFDEC_IS_AS_CONTEXT (cx)); g_return_if_fail (SWFDEC_IS_AS_OBJECT (object)); g_return_if_fail (options != NULL); g_return_if_fail (custom_function == NULL || SWFDEC_IS_AS_FUNCTION (custom_function)); g_return_if_fail (fields == NULL || fields[0] != NULL); length = swfdec_as_array_length (object); if (length == 0) { // special case for empty array, because g_try_new0 would return NULL SWFDEC_AS_VALUE_SET_OBJECT (ret, object); return; } if (!swfdec_as_context_try_use_mem (cx, sizeof (SortEntry) * length)) { SWFDEC_WARNING ("Array not sorted, too big (%i elements)", length); SWFDEC_AS_VALUE_SET_OBJECT (ret, object); return; } // FIXME: this should be different, but context's memory management is not // done properly yet array = g_try_new0 (SortEntry, length); if (!array) { SWFDEC_WARNING ("Array not sorted, too big (%i elements)", length); SWFDEC_AS_VALUE_SET_OBJECT (ret, object); goto done; } for (i = 0; i < length; i++) { array[i].index_ = i; } // collect values and indexes to the array collect_data.length = length; collect_data.array = array; swfdec_as_object_foreach (object, swfdec_as_array_foreach_sort_collect, &collect_data); // sort the array compare_data.context = cx; compare_data.fields = fields; compare_data.options = options; // if no fields, then we'll do descending here after the sort if (fields == NULL && options[0] & SORT_OPTION_DESCENDING) { descending = TRUE; options_ = options[0] & ~SORT_OPTION_DESCENDING; compare_data.options = &options_; } else { descending = FALSE; } compare_data.custom_function = custom_function; compare_data.equal_found = FALSE; swfdec_as_array_sort_array (array, length, swfdec_as_array_sort_compare, &compare_data); // check unique sort if (options[0] & SORT_OPTION_UNIQUESORT) { if (fields == NULL && custom_function != NULL) { // if we used custom_function for comparision, we shall now go trough the // sorted array and compare them using the default array sort comparision // and use that to decide if it's unique (no it doesn't make too much // sense) for (i = 0; i < length - 1; i++) { SwfdecAsValue *a = &array[i].value; SwfdecAsValue *b = &array[i + 1].value; if (swfdec_as_array_sort_compare_values (cx, a, b, 0, NULL) == 0) break; } if (i < length - 1) { SWFDEC_AS_VALUE_SET_INT (ret, 0); goto done; } } else if (compare_data.equal_found) { SWFDEC_AS_VALUE_SET_INT (ret, 0); goto done; } } if (options[0] & SORT_OPTION_RETURNINDEXEDARRAY) { target = swfdec_as_array_new (cx); if (!target) goto done; } else { target = object; } for (i = 0; i < length; i++) { SortEntry *entry = &array[i]; // set only the values that have new indexes if (!(options[0] & SORT_OPTION_RETURNINDEXEDARRAY) && entry->index_ == (descending ? length - i - 1 : i)) continue; var = swfdec_as_integer_to_string (cx, (descending ? length - i - 1 : i)); if (options[0] & SORT_OPTION_RETURNINDEXEDARRAY) { SWFDEC_AS_VALUE_SET_INT (&val, entry->index_); swfdec_as_object_set_variable (target, var, &val); } else { swfdec_as_object_set_variable (target, var, &entry->value); } } SWFDEC_AS_VALUE_SET_OBJECT (ret, target); done: g_free (array); swfdec_as_context_unuse_mem (cx, sizeof (SortEntry) * length); }
/** * Read QTH file and add data to list store. * @param liststore The GtkListStore where the data should be stored. * @param filename The full name of the qth file. * @return 1 if read is successful, 0 if an error occurs. * * The function uses the gtk-sat-data infrastructure to read the qth * data from the specified file. * * There is a little challenge here. First, we want to read the data from * the .qth files and store them in the list store. To do this we use a * qth_t structure, which can be populated using gtk_sat_data_read_qth. * Then, when the configuration is finished and the user presses "OK", we * want to write all the data back to the .qth files. To do that, we create * an up-to-date qth_t data structure and pass it to the gtk_sat_data_write_qth * function, which will take care of updating the GKeyFile data structure and * writing the contents to the .qth file. */ static guint read_qth_file(GtkListStore * liststore, gchar * filename) { GtkTreeIter item; /* new item added to the list store */ qth_t *qth; /* qth data structure */ gchar *defqth; gboolean is_default = FALSE; gchar *fname; gint dispalt; /* displayed altitude */ if ((qth = g_try_new0(qth_t, 1)) == NULL) { sat_log_log(SAT_LOG_LEVEL_ERROR, _("%s:%d: Failed to allocate memory!\n"), __FILE__, __LINE__); return FALSE; } /* read data from file */ if (!qth_data_read(filename, qth)) { g_free(qth); return FALSE; } /* calculate QRA locator */ gint retcode; qth->qra = g_malloc(7); retcode = longlat2locator(qth->lon, qth->lat, qth->qra, 3); if (retcode != RIG_OK) { sat_log_log(SAT_LOG_LEVEL_ERROR, _("%s:%d: Could not convert (%.2f,%.2f) to QRA."), __FILE__, __LINE__, qth->lat, qth->lon); qth->qra[0] = '\0'; } else { qth->qra[6] = '\0'; sat_log_log(SAT_LOG_LEVEL_DEBUG, _("%s:%d: QRA locator is %s"), __FILE__, __LINE__, qth->qra); } /* is this the default qth? */ defqth = sat_cfg_get_str(SAT_CFG_STR_DEF_QTH); if (g_str_has_suffix(filename, defqth)) { is_default = TRUE; sat_log_log(SAT_LOG_LEVEL_INFO, _("%s:%d: This appears to be the default QTH."), __FILE__, __LINE__); } g_free(defqth); /* check wehter we are using imperial or metric system; in case of imperial we have to convert altitude from meters to feet. note: the internat data are always kept in metric and only the displayed numbers are converted. Therefore, we use a dedicated var 'dispalt' */ /* NO, ONLY DISPLAY WIDGETS WILL BE AFFECTED BY THIS SETTING */ if (sat_cfg_get_bool(SAT_CFG_BOOL_USE_IMPERIAL)) { dispalt = (gint) M_TO_FT(qth->alt); } else { dispalt = (gint) qth->alt; } /* strip file name; we don't need the whole path */ fname = g_path_get_basename(filename); /* we now have all necessary data in the qth_t structure; add the data to the list store */ gtk_list_store_append(liststore, &item); gtk_list_store_set(liststore, &item, QTH_LIST_COL_NAME, qth->name, QTH_LIST_COL_LOC, qth->loc, QTH_LIST_COL_DESC, qth->desc, QTH_LIST_COL_LAT, qth->lat, QTH_LIST_COL_LON, qth->lon, QTH_LIST_COL_ALT, dispalt, QTH_LIST_COL_QRA, qth->qra, QTH_LIST_COL_WX, qth->wx, QTH_LIST_COL_DEF, is_default, QTH_LIST_COL_TYPE, qth->type, QTH_LIST_COL_GPSD_SERVER, qth->gpsd_server, QTH_LIST_COL_GPSD_PORT, qth->gpsd_port, -1); g_free(fname); /* we are finished with this qth, free it */ qth_data_free(qth); return TRUE; }
static void get_uid_reply(unsigned int uid, void *user_data, int err) { struct cb_data *cbd = user_data; connman_session_config_func_t cb = cbd->cb; struct policy_config *policy = cbd->data; const char *owner; struct passwd *pwd; struct group *grp; gid_t *groups = NULL; int nrgroups, i; DBG("session %p uid %d", policy->session, uid); if (err < 0) { cleanup_config(policy); goto err; } pwd = getpwuid((uid_t)uid); if (!pwd) { if (errno != 0) err = -errno; else err = -EINVAL; goto err; } policy->uid = g_strdup(pwd->pw_name); nrgroups = 0; getgrouplist(pwd->pw_name, pwd->pw_gid, NULL, &nrgroups); groups = g_try_new0(gid_t, nrgroups); if (!groups) { err = -ENOMEM; goto err; } err = getgrouplist(pwd->pw_name, pwd->pw_gid, groups, &nrgroups); if (err < 0) goto err; for (i = 0; i < nrgroups; i++) { grp = getgrgid(groups[i]); if (!grp) { if (errno != 0) err = -errno; else err = -EINVAL; goto err; } policy->gids = g_slist_prepend(policy->gids, g_strdup(grp->gr_name)); } g_free(groups); owner = connman_session_get_owner(policy->session); err = connman_dbus_get_selinux_context(connection, owner, selinux_context_reply, cbd); if (err == 0) { /* * We are able to ask for a SELinux context. Let's defer the * creation of the session config until we get the answer * from D-Bus. */ return; } finish_create(policy, cb, cbd->user_data); g_free(cbd); return; err: failed_create(NULL, cb, cbd->user_data, err); g_free(cbd); g_free(groups); }
GDBusClient *g_dbus_client_new_full(DBusConnection *connection, const char *service, const char *path, const char *root_path) { GDBusClient *client; unsigned int i; if (!connection || !service) return NULL; client = g_try_new0(GDBusClient, 1); if (client == NULL) return NULL; if (dbus_connection_add_filter(connection, message_filter, client, NULL) == FALSE) { g_free(client); return NULL; } client->dbus_conn = dbus_connection_ref(connection); client->service_name = g_strdup(service); client->base_path = g_strdup(path); client->root_path = g_strdup(root_path); client->connected = FALSE; client->match_rules = g_ptr_array_sized_new(1); g_ptr_array_set_free_func(client->match_rules, g_free); client->watch = g_dbus_add_service_watch(connection, service, service_connect, service_disconnect, client, NULL); if (!root_path) return g_dbus_client_ref(client); client->added_watch = g_dbus_add_signal_watch(connection, service, client->root_path, DBUS_INTERFACE_OBJECT_MANAGER, "InterfacesAdded", interfaces_added, client, NULL); client->removed_watch = g_dbus_add_signal_watch(connection, service, client->root_path, DBUS_INTERFACE_OBJECT_MANAGER, "InterfacesRemoved", interfaces_removed, client, NULL); g_ptr_array_add(client->match_rules, g_strdup_printf("type='signal'," "sender='%s',path_namespace='%s'", client->service_name, client->base_path)); for (i = 0; i < client->match_rules->len; i++) { modify_match(client->dbus_conn, "AddMatch", g_ptr_array_index(client->match_rules, i)); } return g_dbus_client_ref(client); }
/** \brief Read fresh TLE data into hash table. * \param dir The directory to read from. * \param fnam The name of the file to read from. * \param fresh_data Hash table where the data should be stored. * \return The number of satellites successfully read. * * This function will read fresh TLE data from local files into memory. * If there is a saetllite category (.cat file) with the same name as the * input file it will also update the satellites in that category. */ static gint read_fresh_tle (const gchar *dir, const gchar *fnam, GHashTable *data) { new_tle_t *ntle; tle_t tle; gchar *path; gchar tle_str[3][80]; gchar tle_working[3][80]; gchar linetmp[80]; guint linesneeded = 3; gchar catstr[6]; gchar idstr[7]="\0\0\0\0\0\0\0",idyearstr[3]; gchar *b; FILE *fp; gint retcode = 0; guint catnr,i,idyear; guint *key = NULL; /* category sync related */ gchar *catname, *catpath, *buff, **buffv; FILE *catfile; gchar category[80]; gboolean catsync = FALSE; /* whether .cat file should be synced */ /* Normal cases to check 1. 3 line tle file as in amatuer.txt from celestrak 2. 2 line tle file as in .... from celestrak corner cases to check 1. 3 line tle with something at the end. (nasa.all from amsat) 2. 2 line tle with only one in the file 3. 2 line tle file reading the last one. */ path = g_strconcat (dir, G_DIR_SEPARATOR_S, fnam, NULL); fp = g_fopen (path, "r"); if (fp != NULL) { /* Prepare .cat file for sync while we read data */ buffv = g_strsplit (fnam, ".", 0); catname = g_strconcat (buffv[0], ".cat", NULL); g_strfreev (buffv); catpath = sat_file_name (catname); g_free (catname); /* read category name for catfile */ catfile = g_fopen (catpath, "r"); if (catfile!=NULL) { b = fgets (category, 80, catfile); if (b == NULL) { sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s:%s: There is no category in %s"), __FILE__, __FUNCTION__, catpath); } fclose (catfile); catsync = TRUE; } else { /* There is no category with this name (could be update from custom file) */ sat_log_log (SAT_LOG_LEVEL_INFO, _("%s:%s: There is no category called %s"), __FILE__, __FUNCTION__, fnam); } /* reopen a new catfile and write category name */ if (catsync) { catfile = g_fopen (catpath, "w"); if (catfile != NULL) { fputs (category, catfile); } else { catsync = FALSE; sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s:%s: Could not reopen .cat file while reading TLE from %s"), __FILE__, __FUNCTION__, fnam); } /* .cat file now contains the category name; satellite catnums will be added during update in the while loop */ } /* set b to non-null as a flag */ b = path; /* read lines from tle file */ while (fgets (linetmp, 80, fp)) { /*read in the number of lines needed to potentially get to a new tle*/ switch (linesneeded) { case 3: strncpy(tle_working[0],linetmp,80); /* b is being used a flag here if b==NULL then we only have one line read in and there is no way we have a full tle as there is only one line in the buffer. A TLE must be two or three lines. */ b = fgets (tle_working[1], 80, fp); if (b==NULL) { /* make sure there is no junk in tle_working[1] */ tle_working[1][0]='\0'; break; } /* make sure there is no junk in tle_working[2] */ if (fgets (tle_working[2], 80, fp)==NULL) { tle_working[2][0]='\0'; } break; case 2: strncpy(tle_working[0],tle_working[2],80); strncpy(tle_working[1],linetmp,80); /* make sure there is no junk in tle_working[2] */ if (fgets (tle_working[2], 80, fp)==NULL) { tle_working[2][0]='\0'; } break; case 1: strncpy(tle_working[0],tle_working[1],80); strncpy(tle_working[1],tle_working[2],80); strncpy(tle_working[2],linetmp,80); break; default: sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s:%s: Something wrote linesneeded to an illegal value %d"), __FILE__, __FUNCTION__, linesneeded); break; } /* b can only be null if there is only one line in the buffer*/ /* a tle must be two or three */ if (b == NULL) { break; } /* remove leading and trailing whitespace to be more forgiving */ g_strstrip(tle_working[0]); g_strstrip(tle_working[1]); g_strstrip(tle_working[2]); /* there are three possibilities at this point */ /* first is that line 0 is a name and normal text for three line element and that lines 1 and 2 are the corresponding tle */ /* second is that line 0 and line 1 are a tle for a bare tle */ /* third is that neither of these is true and we are consuming either text at the top of the file or a text file that happens to be in the update directory */ if ((tle_working[1][0] == '1') && (tle_working[2][0] == '2') && Checksum_Good(tle_working[1]) && Checksum_Good(tle_working[2])) { sat_log_log (SAT_LOG_LEVEL_DEBUG, _("%s:%s: Processing a three line TLE"), __FILE__, __FUNCTION__); /* it appears that the first line may be a name followed by a tle */ strncpy(tle_str[0],tle_working[0],80); strncpy(tle_str[1],tle_working[1],80); strncpy(tle_str[2],tle_working[2],80); /* we consumed three lines so we need three lines */ linesneeded = 3; } else if ((tle_working[0][0] == '1') && (tle_working[1][0] == '2') && Checksum_Good(tle_working[0]) && Checksum_Good(tle_working[1])) { sat_log_log (SAT_LOG_LEVEL_DEBUG, _("%s:%s: Processing a bare two line TLE"), __FILE__, __FUNCTION__); /* first line appears to belong to the start of bare TLE */ /* put in a dummy name of form yyyy-nnaa base on international id */ /* this special form will be overwritten if a three line tle ever has another name */ strncpy(idstr,&tle_working[0][11],6); g_strstrip(idstr); strncpy(idyearstr,&tle_working[0][9],2); idstr[6]= '\0'; idyearstr[2]= '\0'; idyear = g_ascii_strtod(idyearstr,NULL); /* there is a two digit year field that started around sputnik */ if (idyear >= 57) idyear += 1900; else idyear += 2000; snprintf(tle_str[0],79,"%d-%s",idyear,idstr); strncpy(tle_str[1],tle_working[0],80); strncpy(tle_str[2],tle_working[1],80); /* we consumed two lines so we need two lines */ linesneeded = 2; } else { /* we appear to have junk read another line in and do nothing else */ linesneeded = 1; /* skip back to beginning of loop */ continue; } tle_str[1][69] = '\0'; tle_str[2][69] = '\0'; /* copy catnum and convert to integer */ for (i = 2; i < 7; i++) { catstr[i-2] = tle_str[1][i]; } catstr[5] = '\0'; catnr = (guint) g_ascii_strtod (catstr, NULL); if (Get_Next_Tle_Set (tle_str, &tle) != 1) { /* TLE data not good */ sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s:%s: Invalid data for %d"), __FILE__, __FUNCTION__, catnr); } else { if (catsync) { /* store catalog number in catfile */ buff = g_strdup_printf ("%d\n", catnr); fputs (buff, catfile); g_free (buff); } /* add data to hash table */ key = g_try_new0 (guint, 1); *key = catnr; ntle = g_hash_table_lookup (data, key); /* check if satellite already in hash table */ if ( ntle == NULL) { /* create new_tle structure */ ntle = g_try_new (new_tle_t, 1); ntle->catnum = catnr; ntle->epoch = tle.epoch; ntle->status = tle.status; ntle->satname = g_strdup (tle.sat_name); ntle->line1 = g_strdup (tle_str[1]); ntle->line2 = g_strdup (tle_str[2]); ntle->srcfile = g_strdup (fnam); ntle->isnew = TRUE; /* flag will be reset when using data */ g_hash_table_insert (data, key, ntle); retcode++; } else { /* satellite is already in hash */ /* apply various merge routines */ /* time merge */ if (ntle->epoch == tle.epoch) { /* if satellite epoch has the same time, merge status as appropriate */ if (ntle->status != tle.status) { /* log if there is something funny about the data coming in */ sat_log_log (SAT_LOG_LEVEL_WARN, _("%s:%s: Two different statuses for %d (%s) at the same time."), __FILE__, __FUNCTION__, ntle->catnum, ntle->satname); if ( tle.status != OP_STAT_UNKNOWN ) ntle->status = tle.status; } } else if ( ntle->epoch < tle.epoch ) { /* if the satellite in the hash is older than the one just loaded, copy the values over. */ ntle->catnum = catnr; ntle->epoch = tle.epoch; ntle->status = tle.status; g_free (ntle->line1); ntle->line1 = g_strdup (tle_str[1]); g_free (ntle->line2); ntle->line2 = g_strdup (tle_str[2]); g_free (ntle->srcfile); ntle->srcfile = g_strdup (fnam); ntle->isnew = TRUE; /* flag will be reset when using data */ } /* merge based on name */ if (is_computer_generated_name (ntle->satname) && !is_computer_generated_name(tle_str[0])) { g_free (ntle->satname); ntle->satname = g_strdup (tle.sat_name); } /* free the key since we do not commit it to the cache */ g_free (key); } } } if (catsync) { /* close category file */ fclose (catfile); } g_free (catpath); /* close input TLE file */ fclose (fp); } else { sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s:%s: Failed to open %s"), __FILE__, __FUNCTION__, path); } g_free (path); return retcode; }
GDHCPServer *g_dhcp_server_new(GDHCPType type, int ifindex, GDHCPServerError *error) { GDHCPServer *dhcp_server = NULL; if (ifindex < 0) { *error = G_DHCP_SERVER_ERROR_INVALID_INDEX; return NULL; } dhcp_server = g_try_new0(GDHCPServer, 1); if (!dhcp_server) { *error = G_DHCP_SERVER_ERROR_NOMEM; return NULL; } dhcp_server->interface = get_interface_name(ifindex); if (!dhcp_server->interface) { *error = G_DHCP_SERVER_ERROR_INTERFACE_UNAVAILABLE; goto error; } if (!interface_is_up(ifindex)) { *error = G_DHCP_SERVER_ERROR_INTERFACE_DOWN; goto error; } dhcp_server->server_nip = get_interface_address(ifindex); if (dhcp_server->server_nip == 0) { *error = G_DHCP_SERVER_ERROR_IP_ADDRESS_INVALID; goto error; } dhcp_server->nip_lease_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL); dhcp_server->option_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL); dhcp_server->started = FALSE; /* All the leases have the same fixed lease time, * do not support DHCP_LEASE_TIME option from client. */ dhcp_server->lease_seconds = DEFAULT_DHCP_LEASE_SEC; dhcp_server->type = type; dhcp_server->ref_count = 1; dhcp_server->ifindex = ifindex; dhcp_server->listener_sockfd = -1; dhcp_server->listener_watch = -1; dhcp_server->listener_channel = NULL; dhcp_server->save_lease_func = NULL; dhcp_server->save_ack_lease_func = NULL; dhcp_server->debug_func = NULL; dhcp_server->debug_data = NULL; *error = G_DHCP_SERVER_ERROR_NONE; return dhcp_server; error: g_free(dhcp_server->interface); g_free(dhcp_server); return NULL; }
void *validate_value(gint value_id, gint input_type, void *value) { // Local variables guint base_type; guint capabilities; gboolean capability_check; gchar *conversion_buffer = NULL; // Used when converting between unicode character types gchar *decimal_point; GString *error_string; gchar input_char; gunichar input_char_unicode; gchar *input_ptr; struct lconv *locale_info; gboolean match_found; gint output_gint; gint *output_gint_ptr; gfloat output_gfloat; gfloat *output_gfloat_ptr; GString *output_gstring; guint output_guint; guint *output_guint_ptr; guint string_counter; gint string_length; gint string_max; guint string_min; gfloat value_max; gfloat value_min; // Initialise various things base_type = get_valid_fields_base_type(value_id); capabilities = get_valid_fields_capabilities(value_id); input_ptr = (gchar *) value; output_gstring = g_string_new(NULL); locale_info = localeconv(); decimal_point = locale_info->decimal_point; switch (base_type) { case V_CHAR: // * We're validating a char or string * // We can only validate string input for this type of value if (V_CHAR != input_type) { return NULL; } // Get the length of the input string string_max = get_valid_fields_max_value(value_id); string_min = get_valid_fields_min_value(value_id); string_length = g_utf8_strlen(input_ptr, -1); // If the length of the string isn't in the acceptable range, return NULL if (string_length < string_min) return NULL; if ((string_length > string_max) && (-1 != string_max)) // -1 for string_max means "no maximum limit" return NULL; if (0 == string_length) { // 0 length string, so we just return it return output_gstring; } // Sanitise each character of the input string for (string_counter = 0; string_counter < string_length; string_counter++) { // Get the next character input_char_unicode = g_utf8_get_char_validated(input_ptr, -1); if ((gunichar)-1 == input_char_unicode) { // The returned character was not a valid unicode character, so we indicate failure return NULL; } if ((gunichar)-2 == input_char_unicode) { // The returned character was not a valid unicode character, so we indicate failure return NULL; } // Convert the character to UTF-8 so we can process it conversion_buffer = g_ucs4_to_utf8(&input_char_unicode, 1, NULL, NULL, NULL); // Determine which character we're examining if (TRUE == g_unichar_isalnum(input_char_unicode)) { // It's a standard unicode alphanumeric character, so we accept it as is g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); } else { // * The input wasn't a standard alphanumic character, so check if it * // * is one of the characters in the capabilities list for this field * match_found = FALSE; capability_check = V_ANY_UNICHAR & capabilities; if (FALSE != capability_check) { // This field is allowed to have any valid unicode character if (TRUE == g_unichar_validate(input_char_unicode)) { // Yes, this is a valid unicode character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_SPACES & capabilities; if (FALSE != capability_check) { // This field is allowed to have spaces if (0 == g_strcmp0(" ", conversion_buffer)) { // Yes, this is a space character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_FULL_STOP & capabilities; if (FALSE != capability_check) { // This field is allowed to have full stops if (0 == g_strcmp0(".", conversion_buffer)) { // Yes, this is a full stop character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_HYPENS & capabilities; if (FALSE != capability_check) { // This field is allowed to have hypens if (0 == g_strcmp0("-", conversion_buffer)) { // Yes, this is a hypen character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_UNDERSCORES & capabilities; if (FALSE != capability_check) { // This field is allowed to have underscores if (0 == g_strcmp0("_", conversion_buffer)) { // Yes, this is an underscore character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_PATH_SEP & capabilities; if (FALSE != capability_check) { // This field is allowed to have path separator characters ('/', '\') if ((0 == g_strcmp0("/", conversion_buffer)) || (0 == g_strcmp0("\\", conversion_buffer))) { // Yes, this is a path separator character match_found = TRUE; output_gstring = g_string_append_c(output_gstring, G_DIR_SEPARATOR); // Output the OS correct version input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_EQUALS & capabilities; if (FALSE != capability_check) { // This field is allowed to have equals signs if (0 == g_strcmp0("=", conversion_buffer)) { // Yes, this is an equals sign character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_FORWARD_SLASHES & capabilities; if (FALSE != capability_check) { // This field is allowed to have forward slashes if (0 == g_strcmp0("/", conversion_buffer)) { // Yes, this is a forward slash character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_NEW_LINES & capabilities; if (FALSE != capability_check) { // This field is allowed to have new line characters if (0 == g_strcmp0("\n", conversion_buffer)) { // Yes, this is a new line character match_found = TRUE; output_gstring = g_string_append_c(output_gstring, '\n'); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_PLUSES & capabilities; if (FALSE != capability_check) { // This field is allowed to have pluses if (0 == g_strcmp0("+", conversion_buffer)) { // Yes, this is a plus character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_PERCENT & capabilities; if (FALSE != capability_check) { // This field is allowed to have the percent sign if (0 == g_strcmp0("%", conversion_buffer)) { // Yes, this is a percent sign match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_COLON & capabilities; if (FALSE != capability_check) { // This field is allowed to have colons if (0 == g_strcmp0(":", conversion_buffer)) { // Yes, this is a colon character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_AT & capabilities; if (FALSE != capability_check) { // This field is allowed to have the at symbol if (0 == g_strcmp0("@", conversion_buffer)) { // Yes, this is an at character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_QUESTION & capabilities; if (FALSE != capability_check) { // This field is allowed to have the question mark if (0 == g_strcmp0("?", conversion_buffer)) { // Yes, this is a question mark character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } capability_check = V_AMPERSAND & capabilities; if (FALSE != capability_check) { // This field is allowed to have the ampersand character if (0 == g_strcmp0("&", conversion_buffer)) { // Yes, this is an ampersand character match_found = TRUE; g_string_append_printf(output_gstring, "%s", conversion_buffer); input_ptr = g_utf8_find_next_char(input_ptr, NULL); continue; } } // The character we are checking is not in the list of valid inputs for this field if (FALSE == match_found) { g_free(conversion_buffer); g_string_free(output_gstring, TRUE); return NULL; } } } // Remove any leading and/or trailing white space output_gstring->str = g_strstrip(output_gstring->str); output_gstring->len = strlen(output_gstring->str); // Recheck the length of the output string if (output_gstring->len < string_min) { g_free(conversion_buffer); g_string_free(output_gstring, TRUE); return NULL; } // Free the memory used so far if (0 != string_length) { g_free(conversion_buffer); } // The string seems to be valid, so return it for use return output_gstring; break; case V_FLOAT_UNSIGNED: // * We're validating an unsigned float * // If we're working with string input, we need to convert it to a float first if (V_CHAR == input_type) { // * We're working with string input * // Get the length of the input string string_length = strlen((gchar *) value); // Sanitise each character of the input string for (string_counter = 0; string_counter < string_length; string_counter++) { input_char = ((gchar *) value)[string_counter]; // Check for decimal digits if (TRUE == g_ascii_isdigit(input_char)) { output_gstring = g_string_append_c(output_gstring, input_char); } else { // This field is allowed to have full stops. Is this character a full stop? if (0 == g_ascii_strncasecmp(".", &input_char, 1)) { // Yes, this is a full stop character output_gstring = g_string_append_c(output_gstring, *decimal_point); match_found = TRUE; continue; } // This field is allowed to have commas (equiv to full stop in some locales). Is this character a comma? if (0 == g_ascii_strncasecmp(",", &input_char, 1)) { // Yes, this is a comma character output_gstring = g_string_append_c(output_gstring, *decimal_point); match_found = TRUE; continue; } // The character we are checking is not in the list of valid inputs for this field if (FALSE == match_found) { g_string_free(output_gstring, TRUE); return NULL; } } } // Convert the string to a float output_gfloat = (gfloat) g_strtod(output_gstring->str, NULL); } else { // We're working with a float input, so just copy the value directly output_gfloat = *((gfloat *) value); } // Is the float value within the defined bounds? value_max = get_valid_fields_max_value(value_id); value_min = get_valid_fields_min_value(value_id); if ((output_gfloat < value_min) || (output_gfloat > value_max)) { // Value is out of bounds, so fail g_string_free(output_gstring, TRUE); return NULL; } // The value looks ok, so we copy it to newly allocated memory, to pass it back output_gfloat_ptr = g_try_new0(gfloat, 1); if (NULL == output_gfloat_ptr) { // Unable to allocate memory for the new value, so fail g_string_free(output_gstring, TRUE); return NULL; } *output_gfloat_ptr = output_gfloat; // Free the string memory allocated in this function g_string_free(output_gstring, TRUE); return output_gfloat_ptr; case V_INT_UNSIGNED: // * We're validating an unsigned integer * // If we're working with string input, we need to convert it to an integer first if (V_CHAR == input_type) { // * We're working with string input * // Get the length of the input string string_length = strlen((gchar *) value); // Sanitise each character of the input string for (string_counter = 0; string_counter < string_length; string_counter++) { input_char = ((gchar *) value)[string_counter]; // Check for decimal digits if (TRUE == g_ascii_isdigit(input_char)) { output_gstring = g_string_append_c(output_gstring, input_char); } else { // This wasn't a valid character g_string_free(output_gstring, TRUE); return NULL; } } // Convert the string to an integer output_guint = atoi(output_gstring->str); } else { // We're working with integer input, so just copy the value directly output_guint = *((guint *) value); } // Is the integer value within the defined bounds? value_max = get_valid_fields_max_value(value_id); value_min = get_valid_fields_min_value(value_id); if ((output_guint < value_min) || (output_guint > value_max)) { // Value is out of bounds, so fail g_string_free(output_gstring, TRUE); return NULL; } // The value looks ok, so we copy it to newly allocated memory, to pass it back output_guint_ptr = g_try_new0(guint, 1); if (NULL == output_guint_ptr) { // Unable to allocate memory for the new value, so fail g_string_free(output_gstring, TRUE); return NULL; } *output_guint_ptr = output_guint; // Free the string memory allocated in this function g_string_free(output_gstring, TRUE); return output_guint_ptr; case V_INT_SIGNED: // * We're validating a signed integer * // If we're working with string input, we need to convert it to an integer first if (V_CHAR == input_type) { // * We're working with string input * // Get the length of the input string string_length = strlen((gchar *) value); // Sanitise each character of the input string for (string_counter = 0; string_counter < string_length; string_counter++) { input_char = ((gchar *) value)[string_counter]; // Check for decimal digits if (TRUE == g_ascii_isdigit(input_char)) { output_gstring = g_string_append_c(output_gstring, input_char); } else { // * The input wasn't a standard digit character, so check if it * // * is one of the characters in the capabilities list for this field * match_found = FALSE; capability_check = V_HYPENS & capabilities; if (FALSE != capability_check) { // This field is allowed to have hypens if (0 == g_ascii_strncasecmp("-", &input_char, 1)) { // Yes, this is a hypen character match_found = TRUE; g_string_append_printf(output_gstring, "%s", "-"); } } // The character we are checking is not in the list of valid inputs for this field if (FALSE == match_found) { g_string_free(output_gstring, TRUE); return NULL; } } } // Convert the string to an integer output_gint = atoi(output_gstring->str); } else { // We're working with integer input, so just copy the value directly output_gint = *((gint *) value); } // Is the integer value within the defined bounds? value_max = get_valid_fields_max_value(value_id); value_min = get_valid_fields_min_value(value_id); if ((output_gint < value_min) || (output_gint > value_max)) { // Value is out of bounds, so fail g_string_free(output_gstring, TRUE); return NULL; } // The value looks ok, so we copy it to newly allocated memory, to pass it back output_gint_ptr = g_try_new0(gint, 1); if (NULL == output_gint_ptr) { // Unable to allocate memory for the new value, so fail g_string_free(output_gstring, TRUE); return NULL; } *output_gint_ptr = output_gint; // Free the string memory allocated in this function g_string_free(output_gstring, TRUE); return output_gint_ptr; case V_RESOLUTION: // * We're working with a resolution (text string) input. i.e. '1920x1200 pixels' * // Get the length of the input string string_length = strlen((gchar *) value); string_max = get_valid_fields_max_value(value_id); string_min = get_valid_fields_min_value(value_id); // If the length of the string isn't in the acceptable range, return NULL if ((string_length < string_min) || (string_length > string_max)) return NULL; // Sanitise each character of the input string for (string_counter = 0; string_counter < string_length; string_counter++) { input_char = ((gchar *) value)[string_counter]; // Check for decimal digits if (TRUE == g_ascii_isdigit(input_char)) { output_gstring = g_string_append_c(output_gstring, input_char); } else { match_found = FALSE; // This field is allowed to have the ' ' and 'x' characters . Is this character one of those? if (0 == g_ascii_strncasecmp(" ", &input_char, 1)) { // Yes, this is a space character, so we've already collected the required resolution // info and we can just return the resolution part of the string so far // Remove any leading and/or trailing white space output_gstring->str = g_strstrip(output_gstring->str); output_gstring->len = strlen(output_gstring->str); // Recheck the length of the output string if ((string_length < string_min) || (string_length > string_max)) return NULL; // The string seems to be valid, so return it for use return output_gstring; } if (0 == g_ascii_strncasecmp("x", &input_char, 1)) { // Yes, this is a 'x' character output_gstring = g_string_append_c(output_gstring, 'x'); match_found = TRUE; continue; } if (FALSE == match_found) { // This wasn't a valid character g_string_free(output_gstring, TRUE); return NULL; } } } // Remove any leading and/or trailing white space output_gstring->str = g_strstrip(output_gstring->str); output_gstring->len = strlen(output_gstring->str); // Recheck the length of the output string if ((string_length < string_min) || (string_length > string_max)) return NULL; // The string seems to be valid, so return it for use return output_gstring; case V_ZOOM: // * We're working with a zoom level. i.e. "100%" or "Fit to width" * // Get the length of the input string string_length = g_utf8_strlen((gchar *) value, -1); string_max = get_valid_fields_max_value(value_id); string_min = get_valid_fields_min_value(value_id); // If the length of the string isn't in the acceptable range, return NULL if ((string_length < string_min) || (string_length > string_max)) return NULL; // If the string is "Fit to width" or a localised version of it if ((0 == g_strcmp0("Fit to width", (gchar *) value)) || (0 == g_strcmp0(_("Fit to width"), (gchar *) value))) { // Yes, this is the "Fit to width" value output_gstring = g_string_assign(output_gstring, value); return output_gstring; } // * The incoming string isn't the "Fit to width" value, * // * so should only consist of decimal characters and '%' * // Sanitise each character of the input string for (string_counter = 0; string_counter < string_length; string_counter++) { input_char = ((gchar *) value)[string_counter]; // Check for decimal digits if (TRUE == g_ascii_isdigit(input_char)) { output_gstring = g_string_append_c(output_gstring, input_char); continue; } // Check for '%' character if (0 == g_ascii_strncasecmp("%", &input_char, 1)) { // Yes, this is a '%' character output_gstring = g_string_append_c(output_gstring, '%'); continue; } // This wasn't a valid character g_string_free(output_gstring, TRUE); return NULL; } return output_gstring; default: // Unknown value type, we should never get here error_string = g_string_new(NULL); g_string_printf(error_string, "%s ED119: %s - '%s'", _("Error"), _("Unknown value passed to validation function"), get_valid_fields_name(value_id)); display_warning(error_string->str); g_string_free(error_string, TRUE); return NULL; } // If we get here, then something went wrong! return NULL; }
/** \brief Update TLE data in a file. * \param ldname Directory name for gpredict tle files. * \param fname The name of the TLE file. * \param data The hash table containing the fresh data. * \param sat_upd OUT: number of sats updated. * \param sat_ski OUT: number of sats skipped. * \param sat_nod OUT: number of sats for which no data found * \param sat_tot OUT: total number of sats * * For each satellite in the TLE file ldname/fnam, this function * checks whether there is any newer data available in the hash table. * If yes, the function writes the fresh data to temp_file, if no, the * old data is copied to temp_file. * When all sats have been copied ldname/fnam is deleted and temp_file * is renamed to ldname/fnam. */ static void update_tle_in_file (const gchar *ldname, const gchar *fname, GHashTable *data, guint *sat_upd, guint *sat_ski, guint *sat_nod, guint *sat_tot) { gchar *path; guint updated = 0; /* number of updated sats */ guint nodata = 0; /* no sats for which no fresh data available */ guint skipped = 0; /* no. sats where fresh data is older */ guint total = 0; /* total no. of sats in gpredict tle file */ gchar **catstr; guint catnr; guint *key = NULL; tle_t tle; new_tle_t *ntle; op_stat_t status; GError *error = NULL; GKeyFile *satdata; gchar *tlestr1, *tlestr2, *rawtle, *satname, *satnickname; gboolean updateddata; /* get catalog number for this satellite */ catstr = g_strsplit (fname, ".sat", 0); catnr = (guint) g_ascii_strtod (catstr[0], NULL); /* see if we have new data for this satellite */ key = g_try_new0 (guint, 1); *key = catnr; ntle = (new_tle_t *) g_hash_table_lookup (data, key); g_free (key); if (ntle == NULL) { /* no new data found for this sat => obsolete */ nodata++; /* check if obsolete sats should be deleted */ /**** FIXME: This is dangereous, so we omit it */ sat_log_log (SAT_LOG_LEVEL_INFO, _("%s: No new TLE data found for %d. Satellite might be obsolete."), __FUNCTION__, catnr); } else { /* open input file (file containing old tle) */ path = g_strconcat (ldname, G_DIR_SEPARATOR_S, fname, NULL); satdata = g_key_file_new (); if (!g_key_file_load_from_file (satdata, path, G_KEY_FILE_KEEP_COMMENTS, &error)) { sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s: Error loading %s (%s)"), __FUNCTION__, path, error->message); g_clear_error (&error); skipped++; } else { /* This satellite is not new */ ntle->isnew = FALSE; /* get TLE data */ tlestr1 = g_key_file_get_string (satdata, "Satellite", "TLE1", NULL); if (error != NULL) { sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s: Error reading TLE line 2 from %s (%s)"), __FUNCTION__, path, error->message); g_clear_error (&error); } tlestr2 = g_key_file_get_string (satdata, "Satellite", "TLE2", NULL); if (error != NULL) { sat_log_log (SAT_LOG_LEVEL_ERROR, _("%s: Error reading TLE line 2 from %s (%s)"), __FUNCTION__, path, error->message); g_clear_error (&error); } /* get name data */ satname = g_key_file_get_string (satdata, "Satellite", "NAME", NULL); satnickname = g_key_file_get_string (satdata, "Satellite", "NICKNAME", NULL); /* get status data */ if (g_key_file_has_key(satdata,"Satellite","STATUS", NULL)) { status = g_key_file_get_integer (satdata, "Satellite", "STATUS", NULL); } else { status = OP_STAT_UNKNOWN; } rawtle = g_strconcat (tlestr1, tlestr2, NULL); if (!Good_Elements (rawtle)) { sat_log_log (SAT_LOG_LEVEL_WARN, _("%s: Current TLE data for %d appears to be bad"), __FUNCTION__, catnr); /* set epoch to zero so it gets overwritten */ tle.epoch = 0; } else { Convert_Satellite_Data (rawtle, &tle); } g_free (tlestr1); g_free (tlestr2); g_free (rawtle); /* Initialize flag for update */ updateddata = FALSE; if (ntle->satname != NULL) { /* when a satellite first appears in the elements it is sometimes refered to by the international designator which is awkward after it is given a name */ if (!is_computer_generated_name(ntle->satname)) { if (is_computer_generated_name (satname)) { sat_log_log (SAT_LOG_LEVEL_INFO, _("%s: Data for %d updated for name."), __FUNCTION__, catnr); g_key_file_set_string (satdata, "Satellite", "NAME", ntle->satname); updateddata = TRUE; } /* FIXME what to do about nickname Possibilities: */ /* clobber with name */ /* clobber if nickname and name were same before */ /* clobber if international designator */ if ( is_computer_generated_name (satnickname) ) { sat_log_log (SAT_LOG_LEVEL_INFO, _("%s: Data for %d updated for nickname."), __FUNCTION__, catnr); g_key_file_set_string (satdata, "Satellite", "NICKNAME", ntle->satname); updateddata = TRUE; } } } g_free(satname); g_free(satnickname); if (tle.epoch < ntle->epoch) { /* new data is newer than what we already have */ /* store new data */ sat_log_log (SAT_LOG_LEVEL_INFO, _("%s: Data for %d updated for tle."), __FUNCTION__, catnr); g_key_file_set_string (satdata, "Satellite", "TLE1", ntle->line1); g_key_file_set_string (satdata, "Satellite", "TLE2", ntle->line2); g_key_file_set_integer (satdata, "Satellite", "STATUS", ntle->status); updateddata = TRUE; } else if (tle.epoch == ntle->epoch) { if ((status != ntle->status) && (ntle->status != OP_STAT_UNKNOWN)){ sat_log_log (SAT_LOG_LEVEL_INFO, _("%s: Data for %d updated for operational status."), __FUNCTION__, catnr); g_key_file_set_integer (satdata, "Satellite", "STATUS", ntle->status); updateddata = TRUE; } } if (updateddata ==TRUE) { if (gpredict_save_key_file(satdata, path)) { skipped++; } else { updated++; } } else { skipped++; } } g_key_file_free (satdata); g_free (path); } g_strfreev (catstr); /* update out parameters */ *sat_upd = updated; *sat_ski = skipped; *sat_nod = nodata; *sat_tot = total; }