static void test_write_fail(void) { int status; pid_t pid; ThriftSocket *tsocket = NULL; ThriftTransport *transport = NULL; int port = 51198; guchar buf[10] = TEST_DATA; /* a buffer */ /* SIGPIPE when send to disconnected socket */ signal(SIGPIPE, SIG_IGN); pid = fork (); assert ( pid >= 0 ); if ( pid == 0 ) { /* child listens */ ThriftServerTransport *transport = NULL; ThriftTransport *client = NULL; ThriftServerSocket *tsocket = g_object_new (THRIFT_TYPE_SERVER_SOCKET, "port", port, NULL); transport = THRIFT_SERVER_TRANSPORT (tsocket); thrift_server_transport_listen (transport, NULL); /* wrap the client in a BufferedTransport */ client = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, "transport", thrift_server_transport_accept (transport, NULL), "r_buf_size", 5, NULL); assert (client != NULL); /* just close socket */ thrift_buffered_transport_close (client, NULL); g_object_unref (client); g_object_unref (tsocket); exit (0); } else { /* parent connects, wait a bit for the socket to be created */ sleep (1); tsocket = g_object_new (THRIFT_TYPE_SOCKET, "hostname", "localhost", "port", port, NULL); transport = g_object_new (THRIFT_TYPE_BUFFERED_TRANSPORT, "transport", THRIFT_TRANSPORT (tsocket), "w_buf_size", 4, NULL); assert (thrift_buffered_transport_open (transport, NULL) == TRUE); assert (thrift_buffered_transport_is_open (transport)); /* recognize disconnection */ sleep(1); assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == TRUE); assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == FALSE); /* write and overflow buffer */ assert (thrift_buffered_transport_write (transport, buf, 10, NULL) == FALSE); /* write 1 and flush */ assert (thrift_buffered_transport_write (transport, buf, 1, NULL) == TRUE); assert (thrift_buffered_transport_flush (transport, NULL) == FALSE); thrift_buffered_transport_close (transport, NULL); g_object_unref (transport); g_object_unref (tsocket); assert ( wait (&status) == pid ); assert ( status == 0 ); } }
int main(int argc, char **argv) { signal(SIGCHLD, SIG_IGN); signal(SIGSEGV, terminationHandler); fl_init_locale_support("eworkpanel", PREFIX"/share/locale"); fl_init_images_lib(); int X=0,Y=0,W=Fl::w(),H=Fl::h(); int substract; // Get current workarea Fl_WM::get_workarea(X,Y,W,H); //printf("Free area: %d %d %d %d\n", X,Y,W,H); // We expect that other docks are moving away from panel :) mPanelWindow = new Fl_Update_Window(X, Y+H-30, W, 30, "Workpanel"); mPanelWindow->layout_spacing(0); // Panel is type DOCK mPanelWindow->window_type(Fl_WM::DOCK); mPanelWindow->setAutoHide(0); // Read config bool doShowDesktop; pGlobalConfig.get("Panel", "ShowDesktop", doShowDesktop, false); bool doWorkspaces; pGlobalConfig.get("Panel", "Workspaces", doWorkspaces, true); bool doRunBrowser; pGlobalConfig.get("Panel", "RunBrowser", doRunBrowser, true); bool doSoundMixer; pGlobalConfig.get("Panel", "SoundMixer", doSoundMixer, true); bool doCpuMonitor; pGlobalConfig.get("Panel", "CPUMonitor", doCpuMonitor, true); // Group that holds everything.. Fl_Group *g = new Fl_Group(0,0,0,0); g->box(FL_DIV_UP_BOX); g->layout_spacing(2); g->layout_align(FL_ALIGN_CLIENT); g->begin(); mSystemMenu = new MainMenu(); Fl_VertDivider *v = new Fl_VertDivider(0, 0, 5, 18, ""); v->layout_align(FL_ALIGN_LEFT); substract = 5; if ((doShowDesktop) || (doWorkspaces)) { //this is ugly: int size; if ((doShowDesktop) && (doWorkspaces)) { size=48; } else { size=24; } Fl_Group *g2 = new Fl_Group(0,0,size,22); g2->box(FL_FLAT_BOX); g2->layout_spacing(0); g2->layout_align(FL_ALIGN_LEFT); // Show desktop button if (doShowDesktop) { PanelButton *mShowDesktop; mShowDesktop = new PanelButton(0, 0, 24, 22, FL_NO_BOX, FL_DOWN_BOX, "ShowDesktop"); mShowDesktop->layout_align(FL_ALIGN_LEFT); mShowDesktop->label_type(FL_NO_LABEL); mShowDesktop->align(FL_ALIGN_INSIDE|FL_ALIGN_CENTER); mShowDesktop->image(showdesktop_pix); mShowDesktop->tooltip(_("Show desktop")); mShowDesktop->callback( (Fl_Callback*)cb_showdesktop); mShowDesktop->show(); substract += 26; } // Workspaces panel if (doWorkspaces) { mWorkspace = new PanelMenu(0, 0, 24, 22, FL_NO_BOX, FL_DOWN_BOX, "WSMenu"); mWorkspace->layout_align(FL_ALIGN_LEFT); mWorkspace->label_type(FL_NO_LABEL); mWorkspace->align(FL_ALIGN_INSIDE|FL_ALIGN_CENTER); mWorkspace->image(desktop_pix); mWorkspace->tooltip(_("Workspaces")); mWorkspace->end(); substract += 26; } g2->end(); g2->show(); g2->resizable(); v = new Fl_VertDivider(0, 0, 5, 18, ""); v->layout_align(FL_ALIGN_LEFT); substract += 5; } // Run browser if (doRunBrowser) { runBrowser = new Fl_Input_Browser("",100,FL_ALIGN_LEFT,30); //runBrowser->image(run_pix); //runBrowser->box(FL_THIN_DOWN_BOX); // Added _ALWAYS so callback is in case: // 1) select old command from input browser // 2) press enter to execute. (this won't work w/o _ALWAYS) // runBrowser->input()->when(FL_WHEN_ENTER_KEY_ALWAYS | FL_WHEN_RELEASE_ALWAYS); // Vedran: HOWEVER, with _ALWAYS cb_run_app will be called way // too many times, causing fork-attack runBrowser->input()->when(FL_WHEN_ENTER_KEY); runBrowser->input()->callback((Fl_Callback*)cb_run_app); runBrowser->callback((Fl_Callback*)cb_run_app2); v = new Fl_VertDivider(0, 0, 5, 18, ""); v->layout_align(FL_ALIGN_LEFT); substract += 105; } // Popup menu for the whole taskbar Fl_Menu_Button *mPopupPanelProp = new Fl_Menu_Button( 0, 0, W, 28 ); mPopupPanelProp->type( Fl_Menu_Button::POPUP3 ); mPopupPanelProp->anim_flags(Fl_Menu_::LEFT_TO_RIGHT); mPopupPanelProp->anim_speed(0.8); mPopupPanelProp->begin(); Fl_Item *mPanelSettings = new Fl_Item(_("Settings")); mPanelSettings->x_offset(12); mPanelSettings->callback( (Fl_Callback*)runUtility, (void*)"epanelconf" ); new Fl_Divider(10, 5); Fl_Item *mAboutItem = new Fl_Item(_("About EDE...")); mAboutItem->x_offset(12); mAboutItem->callback( (Fl_Callback *)AboutDialog ); mPopupPanelProp->end(); // Subgroup to properly align everything /* Fl_Group *subgroup; { subgroup = new Fl_Group(0, 0, W-substract, 18); subgroup->box(FL_FLAT_BOX); subgroup->layout_align(FL_ALIGN_RIGHT); subgroup->show(); subgroup->begin(); */ // Taskbar... tasks = new TaskBar(); dock = new Dock(); v = new Fl_VertDivider(0, 0, 5, 18, ""); v->layout_align(FL_ALIGN_RIGHT); /* subgroup->end(); }*/ { // MODEM mModemLeds = new Fl_Group(0, 0, 25, 18); mModemLeds->box(FL_FLAT_BOX); mModemLeds->hide(); mLedIn = new Fl_Box(2, 5, 10, 10); mLedIn->box( FL_OVAL_BOX ); mLedIn->color( (Fl_Color)968701184); mLedOut = new Fl_Box(12, 5, 10, 10); mLedOut->box( FL_OVAL_BOX); mLedOut->color( (Fl_Color)968701184); mModemLeds->end(); } { // KEYBOARD SELECT mKbdSelect = new KeyboardChooser(0, 0, 20, 18, FL_NO_BOX, FL_DOWN_BOX, "us"); mKbdSelect->hide(); mKbdSelect->anim_speed(4); mKbdSelect->label_font(mKbdSelect->label_font()->bold()); mKbdSelect->highlight_color(mKbdSelect->selection_color()); mKbdSelect->highlight_label_color( mKbdSelect->selection_text_color()); } { // CLOCK mClockBox = new Fl_Button(0, 0, 50, 20); mClockBox->align(FL_ALIGN_INSIDE|FL_ALIGN_LEFT); mClockBox->hide(); mClockBox->box(FL_FLAT_BOX); mClockBox->callback( (Fl_Callback*)startUtility, (void*)"Time and date"); } dock->add_to_tray(mClockBox); dock->add_to_tray(mKbdSelect); // SOUND applet if (doSoundMixer) { Fl_Button *mSoundMixer; mSoundMixer = new Fl_Button(0, 0, 20, 18); mSoundMixer->hide(); mSoundMixer->box(FL_NO_BOX); mSoundMixer->focus_box(FL_NO_BOX); mSoundMixer->image(sound_pix); mSoundMixer->tooltip(_("Volume control")); mSoundMixer->align(FL_ALIGN_INSIDE); mSoundMixer->callback( (Fl_Callback*)startUtility, (void*)"Volume Control" ); dock->add_to_tray(mSoundMixer); } // CPU monitor if (doCpuMonitor) { CPUMonitor *cpumon; cpumon = new CPUMonitor(); cpumon->hide(); dock->add_to_tray(cpumon); } Fl::focus(mSystemMenu); mPanelWindow->end(); mPanelWindow->show(argc, argv); Fl_WM::callback(FL_WM_handler, 0, Fl_WM::DESKTOP_COUNT | Fl_WM::DESKTOP_NAMES | Fl_WM::DESKTOP_CHANGED| Fl_WM::WINDOW_LIST| Fl_WM::WINDOW_DESKTOP| Fl_WM::WINDOW_ACTIVE| Fl_WM::WINDOW_NAME| Fl_WM::WINDOW_ICONNAME); updateWorkspaces(0,0); Fl::add_timeout(0, clockRefresh); Fl::add_timeout(0, updateStats); while(mPanelWindow->shown()) Fl::wait(); }
int lurk() { wav_file in, out; int quit; int16_t *buffer; int buffer_length, buffer_bytes, read_length; uint64_t total_length, cut_length, peak_length; int recording; char *output_path, *output_temp_path; double rms; const char progress[] = {'|', '/', '-', '\\'}; uint64_t progress_temp, progress_position; quit = 0; terminate_signal = 0; output_path = NULL; output_temp_path = NULL; progress_position = 0; printf("Reading header from %s\n", (input == NULL ? "stdin" : input)); if(wav_open_read(input, &in) == -1) { fprintf(stderr, "Failed to open %s for input\n", input); return -1; } if(!(in.format.audio_format == 1 && /* 1 = PCM */ in.format.bits_per_sample == 16 && in.format.num_channels == 1)) { fprintf(stderr, "Wrong audio format, i want 16 bit mono PCM audio\n"); return -1; } printf("Output: %s\n", output); printf("Recording append: %s\n", recording_append); printf("Threshold: %g\n", threshold); printf("Runlength: %g seconds\n", runlength); if(short_filter != 0) printf("Short filter: %g seconds\n", short_filter); buffer_length = in.format.sample_rate / slice_divisor; buffer_bytes = buffer_length * in.format.block_align; buffer = malloc(buffer_bytes); if(buffer == NULL) { fprintf(stderr, "lurk: malloc audio buffer failed\n"); return -1; } total_length = 0; cut_length = 0; peak_length = 0; recording = 0; if(time_start != 0) { char s[256]; strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", localtime(&time_start)); printf("Start time: %s\n", s); } printf("Sample rate: %d Hz\n", in.format.sample_rate); printf("Slice divisor: %g\n", slice_divisor); printf("\n"); printf("Starting to lurk...\n"); signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); while(quit == 0) { read_length = riff_read_wave_16(in.stream, buffer, buffer_length); if(read_length < 1) { if(read_length == 0) { if(recording == 1) quit = 1; /* run loop one last time */ else break; } else { fprintf(stderr, "Error reading input file\n"); if(recording == 1) { message("Trying to close output file nicely\n"); wav_close_write(&out); rename(output_temp_path, output_path); } break; } } if(terminate_signal == 1) quit = 1; rms = root_mean_square(buffer, read_length); total_length += read_length; if(recording == 1) { if((double)peak_length / in.format.sample_rate > runlength || quit == 1) { /* stop recording to file */ recording = 0; /* remove runlength seconds of silence at end of recording */ cut_length -= runlength * in.format.sample_rate; /* adjust file */ wav_truncate(&out, cut_length * out.format.block_align); if(wav_close_write(&out) == -1) fprintf(stderr, "lurk: failed to close output file %s\n", output_temp_path); if(short_filter != 0 && (double)cut_length / in.format.sample_rate < short_filter) { if(unlink(output_temp_path) == -1) fprintf(stderr, "lurk: faild to unlink %s\n", output_temp_path); message("Recording removed, short filter\n"); } else { if(rename(output_temp_path, output_path) == -1) fprintf(stderr, "lurk: faild to rename %s to %s\n", output_temp_path, output_path); message("Recording stopped, %d minutes %d seconds recorded\n", (int)(cut_length / in.format.sample_rate) / 60, /* (int)(ceil(cut_length / in.format.sample_rate)) % 60 */ (int)(cut_length / in.format.sample_rate) % 60 ); } free(output_path); free(output_temp_path); output_path = NULL; output_temp_path = NULL; cut_length = 0; peak_length = 0; } else { cut_length += read_length; peak_length += read_length; if(rms > threshold) peak_length = 0; } } else { if(rms > threshold) { time_t t; char *s, *d; char expanded[PATH_MAX]; /* start recording to file */ recording = 1; /* fancy print output path (non-absolute path etc) */ if(time_start != 0) t = time_start + total_length / in.format.sample_rate; else time(&t); strftime(expanded, sizeof(expanded), output, localtime(&t)); message("Recording started to %s\n", expanded); if(asprintf(&output_path, "%s%s", (output[0] == '/' ? "" : current_dir), /* make absolute if relative */ expanded ) == -1) { fprintf(stderr, "lurk: asprintf failed: output_path\n"); return -1; } if(asprintf(&output_temp_path, "%s%s", output_path, recording_append ) == -1) { fprintf(stderr, "lurk: asprintf failed: output_temp_path\n"); return -1; } s = strdup(output_path); if(s == NULL) { fprintf(stderr, "lurk: strdup failed: output_path\n"); return -1; } d = dirname(s); if(mkdirp(d) == -1) { fprintf(stderr, "lurk: mkdirp failed: %s\n", d); return -1; } free(s); out.riff.size = INT32_MAX; /* as big as possible, wav_close_write will fix them */ out.data.size = INT32_MAX; out.format.audio_format = 1; /* PCM */ out.format.num_channels = 1; /* mono */ out.format.sample_rate = in.format.sample_rate; out.format.byte_rate = in.format.byte_rate; out.format.block_align = in.format.block_align; out.format.bits_per_sample = in.format.bits_per_sample; if(wav_open_write(output_temp_path, &out) == -1) { fprintf(stderr, "lurk: failed to open temp output file %s\n", output_temp_path); return -1; } } } /* progress_temp = total_length / in.format.sample_rate; if(progress_temp > progress_position) { progress_position = progress_temp; message("%s %c", (recording == 1 ? "Recording" : "Lurking"), progress[progress_position % sizeof(progress)] ); fflush(stdout); } */ /* bloated fancy status featuring cut length, volume-meter and more! */ { int p, l; char b[21]; progress_position = total_length / in.format.sample_rate; l = sizeof(b) * rms; for(p = 0; p < sizeof(b) - 1; p++) b[p] = (p < l ? '=' : ' '); b[sizeof(b) - 1] = '\0'; message("%s %c [t:%.1f c:%.1f p:%.1f] [%s]", (recording == 1 ? "Recording" : "Lurking"), progress[progress_position % sizeof(progress)], (double)total_length / in.format.sample_rate, (double)cut_length / in.format.sample_rate, (double)peak_length / in.format.sample_rate, b ); fflush(stdout); } if(recording == 1) { /* write audio to file */ if(riff_write_wave_16(out.stream, buffer, read_length) == -1) { fprintf(stderr, "lurk: riff_write_wave_16 failed\n"); return -1; } } } wav_close_read(&in); free(buffer); if(output_path != NULL) free(output_path); if(output_temp_path != NULL) free(output_temp_path); message("Stopped\n"); return 0; }
int main(int argc, char **argv) { struct pk_manager *m; unsigned int tmp_uint; int gotargs = 0; int verbosity = 0; int use_ipv4 = 1; #ifdef HAVE_IPV6 int use_ipv6 = 1; #endif int use_evil = 0; int use_watchdog = 0; int max_conns = 25; int lport; int ac; SSL_CTX* ssl_ctx; /* FIXME: Is this too lame? */ srand(time(0) ^ getpid()); pks_global_init(PK_LOG_NORMAL); while (-1 != (ac = getopt(argc, argv, "46a:c:B:E:qvWZ"))) { switch (ac) { case '4': use_ipv4 = 0; break; case '6': #ifdef HAVE_IPV6 use_ipv6 = 0; #endif break; case 'v': verbosity++; break; case 'q': verbosity--; break; case 'W': use_watchdog = 1; break; case 'Z': use_evil = 1; break; case 'B': gotargs++; if (1 == sscanf(optarg, "%u", &pk_state.bail_on_errors)) break; usage(EXIT_ERR_USAGE); case 'c': gotargs++; if (1 == sscanf(optarg, "%d", &max_conns)) break; usage(EXIT_ERR_USAGE); case 'E': gotargs++; if (1 == sscanf(optarg, "%u", &tmp_uint)) { pk_state.conn_eviction_idle_s = tmp_uint; break; } usage(EXIT_ERR_USAGE); default: usage(EXIT_ERR_USAGE); } gotargs++; } if ((argc-1-gotargs) < 5 || ((argc-1-gotargs) % 5) != 0) { usage(EXIT_ERR_USAGE); } signal(SIGUSR1, &raise_log_level); pk_state.log_mask = ((verbosity < 0) ? PK_LOG_ERRORS : ((verbosity < 1) ? PK_LOG_NORMAL : ((verbosity < 2) ? PK_LOG_DEBUG : PK_LOG_ALL))); PKS_SSL_INIT(ssl_ctx); if (NULL == (m = pkm_manager_init(NULL, 0, NULL, 0, PAGEKITE_NET_CLIENT_MAX, max_conns, NULL, ssl_ctx))) { pk_perror(argv[0]); exit(EXIT_ERR_MANAGER_INIT); } if (use_evil) { m->housekeeping_interval_min = 5; m->housekeeping_interval_max = 20; m->check_world_interval = 30; } if (use_watchdog) m->enable_watchdog = 1; for (ac = gotargs; ac < argc; ac += 1) { if (1 == sscanf(argv[ac+1], "%d", &lport)) { if (use_ipv4) if (NULL == (pkr_add_listener(m, lport))) { pk_perror(argv[0]); exit(EXIT_ERR_ADD_LPORT); } #ifdef HAVE_IPV6 if (use_ipv6) if (NULL == (pkr_add_listener_v6(m, lport))) { pk_perror(argv[0]); exit(EXIT_ERR_ADD_LPORT); } #endif } else { break; } } for (; ac+2 < argc; ac += 2) { if (NULL == (pkm_add_kite(m, NULL, argv[ac+1], 0, argv[ac+2], NULL, 0))) { pk_perror(argv[0]); exit(EXIT_ERR_ADD_KITE); } } if (0 > pkm_run_in_thread(m)) { pk_perror(argv[0]); exit(EXIT_ERR_START_THREAD); } pkm_wait_thread(m); return 0; }
int main(int argc, char *argv[]) { int ch; time_t secs = 0, t; char *cp; long nsecs = 0; struct timespec rqtp; int i; if (pledge("stdio", NULL) == -1) err(1, "pledge"); signal(SIGALRM, alarmh); while ((ch = getopt(argc, argv, "")) != -1) switch(ch) { default: usage(); } argc -= optind; argv += optind; if (argc != 1) usage(); cp = *argv; while ((*cp != '\0') && (*cp != '.')) { if (!isdigit((unsigned char)*cp)) usage(); t = (secs * 10) + (*cp++ - '0'); if (t / 10 != secs) /* oflow */ return (EINVAL); secs = t; } /* Handle fractions of a second */ if (*cp == '.') { cp++; for (i = 100000000; i > 0; i /= 10) { if (*cp == '\0') break; if (!isdigit((unsigned char)*cp)) usage(); nsecs += (*cp++ - '0') * i; } /* * We parse all the way down to nanoseconds * in the above for loop. Be pedantic about * checking the rest of the argument. */ while (*cp != '\0') { if (!isdigit((unsigned char)*cp++)) usage(); } } rqtp.tv_sec = secs; rqtp.tv_nsec = nsecs; if ((secs > 0) || (nsecs > 0)) if (nanosleep(&rqtp, NULL)) err(1, NULL); return (0); }
/* main -- dnsproxy main function */ int main(int argc, char *argv[]) { int ch; struct passwd *pw = NULL; struct sockaddr_in addr; struct event evq, eva; const char *config = "/etc/dnsproxy.conf"; int daemonize = 0; /* Process commandline arguments */ while ((ch = getopt(argc, argv, "c:dhV")) != -1) { switch (ch) { case 'c': config = optarg; break; case 'd': daemonize = 1; break; case 'V': fprintf(stderr, PACKAGE_STRING "\n"); exit(0); /* FALLTHROUGH */ case 'h': default: fprintf(stderr, "usage: dnsproxy [-c file] [-dhV]\n" \ "\t-c file Read configuration from file\n" \ "\t-d Detach and run as a daemon\n" \ "\t-h This help text\n" \ "\t-V Show version information\n"); exit(1); } } /* Parse configuration and check required parameters */ if (!parse(config)) fatal("unable to parse configuration"); if (!authoritative || !recursive) fatal("No authoritative or recursive server defined"); if (!listenat) listenat = strdup("0.0.0.0"); /* Create and bind query socket */ if ((sock_query = socket(AF_INET, SOCK_DGRAM, 0)) == -1) fatal("unable to create socket: %s", strerror(errno)); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_addr.s_addr = inet_addr(listenat); addr.sin_port = htons(port); addr.sin_family = AF_INET; if (bind(sock_query, (struct sockaddr *)&addr, sizeof(addr)) != 0) fatal("unable to bind socket: %s", strerror(errno)); /* Create and bind answer socket */ if ((sock_answer = socket(AF_INET, SOCK_DGRAM, 0)) == -1) fatal("unable to create socket: %s", strerror(errno)); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; if (bind(sock_answer, (struct sockaddr *)&addr, sizeof(addr)) != 0) fatal("unable to bind socket: %s", strerror(errno)); /* Fill sockaddr_in structs for both servers */ memset(&authoritative_addr, 0, sizeof(struct sockaddr_in)); authoritative_addr.sin_addr.s_addr = inet_addr(authoritative); authoritative_addr.sin_port = htons(authoritative_port); authoritative_addr.sin_family = AF_INET; memset(&recursive_addr, 0, sizeof(struct sockaddr_in)); recursive_addr.sin_addr.s_addr = inet_addr(recursive); recursive_addr.sin_port = htons(recursive_port); recursive_addr.sin_family = AF_INET; /* Daemonize if requested and switch to syslog */ if (daemonize) { if (daemon(0, 0) == -1) fatal("unable to daemonize"); log_syslog("dnsproxy"); } /* Find less privileged user */ if (user) { pw = getpwnam(user); if (!pw) fatal("unable to find user %s", user); } /* Do a chroot if requested */ if (chrootdir) { if (chdir(chrootdir) || chroot(chrootdir)) fatal("unable to chroot to %s", chrootdir); chdir("/"); } /* Drop privileges */ if (user) { if (setgroups(1, &pw->pw_gid) < 0) fatal("setgroups: %s", strerror(errno)); #if defined(HAVE_SETRESGID) if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) < 0) fatal("setresgid: %s", strerror(errno)); #elif defined(HAVE_SETREGID) if (setregid(pw->pw_gid, pw->pw_gid) < 0) fatal("setregid: %s", strerror(errno)); #else if (setegid(pw->pw_gid) < 0) fatal("setegid: %s", strerror(errno)); if (setgid(pw->pw_gid) < 0) fatal("setgid: %s", strerror(errno)); #endif #if defined(HAVE_SETRESUID) if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) < 0) fatal("setresuid: %s", strerror(errno)); #elif defined(HAVE_SETREUID) if (setreuid(pw->pw_uid, pw->pw_uid) < 0) fatal("setreuid: %s", strerror(errno)); #else if (seteuid(pw->pw_uid) < 0) fatal("seteuid: %s", strerror(errno)); if (setuid(pw->pw_uid) < 0) fatal("setuid: %s", strerror(errno)); #endif } /* Init event handling */ event_init(); event_set(&evq, sock_query, EV_READ, do_query, &evq); event_add(&evq, NULL); event_set(&eva, sock_answer, EV_READ, do_answer, &eva); event_add(&eva, NULL); /* Zero counters and start statistics timer */ statistics_start(); /* Take care of signals */ if (signal(SIGINT, signal_handler) == SIG_ERR) fatal("unable to mask signal SIGINT: %s", strerror(errno)); if (signal(SIGTERM, signal_handler) == SIG_ERR) fatal("unable to mask signal SIGTERM: %s", strerror(errno)); if (signal(SIGHUP, SIG_IGN) == SIG_ERR) fatal("unable to mask signal SIGHUP: %s", strerror(errno)); event_sigcb = signal_event; /* Start libevent main loop */ event_dispatch(); return 0; }
int main(int argc, char **argv) { int c; char *scan; /* the + on the front tells GNU getopt not to rearrange argv */ const char *optlist = "+F:f:v:W;m:D"; int stopped_early = FALSE; int old_optind; extern int optind; extern int opterr; extern char *optarg; int i; int stdio_problem = FALSE; /* do these checks early */ if (getenv("TIDYMEM") != NULL) do_tidy_mem = TRUE; if (getenv("WHINY_USERS") != NULL) whiny_users = TRUE; #ifdef HAVE_MCHECK_H if (do_tidy_mem) mtrace(); #endif /* HAVE_MCHECK_H */ #if defined(LC_CTYPE) setlocale(LC_CTYPE, ""); #endif #if defined(LC_COLLATE) setlocale(LC_COLLATE, ""); #endif #if defined(LC_MESSAGES) setlocale(LC_MESSAGES, ""); #endif #if defined(LC_NUMERIC) /* * Force the issue here. According to POSIX 2001, decimal * point is used for parsing source code and for command-line * assignments and the locale value for processing input, * number to string conversion, and printing output. */ setlocale(LC_NUMERIC, "C"); #endif #if defined(LC_TIME) setlocale(LC_TIME, ""); #endif #ifdef MBS_SUPPORT /* * In glibc, MB_CUR_MAX is actually a function. This value is * tested *a lot* in many speed-critical places in gawk. Caching * this value once makes a speed difference. */ gawk_mb_cur_max = MB_CUR_MAX; /* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */ #endif (void) bindtextdomain(PACKAGE, LOCALEDIR); (void) textdomain(PACKAGE); (void) signal(SIGFPE, catchsig); (void) signal(SIGSEGV, catchsig); #ifdef SIGBUS (void) signal(SIGBUS, catchsig); #endif myname = gawk_name(argv[0]); argv[0] = (char *) myname; os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */ /* remove sccs gunk */ if (strncmp(version_string, "@(#)", 4) == 0) version_string += 4; if (argc < 2) usage(1, stderr); /* Robustness: check that file descriptors 0, 1, 2 are open */ init_fds(); /* init array handling. */ array_init(); /* we do error messages ourselves on invalid options */ opterr = FALSE; /* option processing. ready, set, go! */ for (optopt = 0, old_optind = 1; (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF; optopt = 0, old_optind = optind) { if (do_posix) opterr = TRUE; switch (c) { case 'F': preassigns_add(PRE_ASSIGN_FS, optarg); break; case 'S': disallow_var_assigns = TRUE; /* fall through */ case 'f': /* * a la MKS awk, allow multiple -f options. * this makes function libraries real easy. * most of the magic is in the scanner. * * The following is to allow for whitespace at the end * of a #! /bin/gawk line in an executable file */ scan = optarg; if (argv[optind-1] != optarg) while (ISSPACE(*scan)) scan++; srcfiles_add(SOURCEFILE, (*scan == '\0' ? argv[optind++] : optarg)); break; case 'v': preassigns_add(PRE_ASSIGN, optarg); break; case 'm': /* * Research awk extension. * -mf nnn set # fields, gawk ignores * -mr nnn set record length, ditto */ if (do_lint) lintwarn(_("`-m[fr]' option irrelevant in gawk")); if (optarg[0] != 'r' && optarg[0] != 'f') warning(_("-m option usage: `-m[fr] nnn'")); /* * Set fixed length records for Tandem, * ignored on other platforms (see io.c:get_a_record). */ if (optarg[0] == 'r') { if (ISDIGIT(optarg[1])) MRL = atoi(optarg+1); else { MRL = atoi(argv[optind]); optind++; } } else if (optarg[1] == '\0') optind++; break; case 'W': /* gawk specific options - now in getopt_long */ fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"), argv[0], optarg); break; /* These can only come from long form options */ case 'C': copyleft(); break; case 'd': do_dump_vars = TRUE; if (optarg != NULL && optarg[0] != '\0') varfile = optarg; break; case 'l': #ifndef NO_LINT do_lint = LINT_ALL; if (optarg != NULL) { if (strcmp(optarg, "fatal") == 0) lintfunc = r_fatal; else if (strcmp(optarg, "invalid") == 0) do_lint = LINT_INVALID; } #endif break; case 'p': do_profiling = TRUE; if (optarg != NULL) set_prof_file(optarg); else set_prof_file(DEFAULT_PROFILE); break; case 's': if (optarg[0] == '\0') warning(_("empty argument to `--source' ignored")); else srcfiles_add(CMDLINE, optarg); break; case 'u': usage(0, stdout); /* per coding stds */ break; case 'V': version(); break; case 0: /* * getopt_long found an option that sets a variable * instead of returning a letter. Do nothing, just * cycle around for the next one. */ break; case 'D': #ifdef GAWKDEBUG yydebug = 2; break; #endif /* if not debugging, fall through */ case '?': default: /* * New behavior. If not posix, an unrecognized * option stops argument processing so that it can * go into ARGV for the awk program to see. This * makes use of ``#! /bin/gawk -f'' easier. * * However, it's never simple. If optopt is set, * an option that requires an argument didn't get the * argument. We care because if opterr is 0, then * getopt_long won't print the error message for us. */ if (! do_posix && (optopt == '\0' || strchr(optlist, optopt) == NULL)) { /* * can't just do optind--. In case of an * option with >= 2 letters, getopt_long * won't have incremented optind. */ optind = old_optind; stopped_early = TRUE; goto out; } else if (optopt != '\0') /* Use 1003.2 required message format */ fprintf(stderr, _("%s: option requires an argument -- %c\n"), myname, optopt); /* else let getopt print error message for us */ break; } if (c == 'S') /* --exec ends option processing */ break; } out: if (do_nostalgia) nostalgia(); /* check for POSIXLY_CORRECT environment variable */ if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) { do_posix = TRUE; if (do_lint) lintwarn( _("environment variable `POSIXLY_CORRECT' set: turning on `--posix'")); } if (do_posix) { if (do_traditional) /* both on command line */ warning(_("`--posix' overrides `--traditional'")); else do_traditional = TRUE; /* * POSIX compliance also implies * no GNU extensions either. */ } if (do_traditional && do_non_decimal_data) { do_non_decimal_data = FALSE; warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'")); } if (do_lint && os_is_setuid()) warning(_("running %s setuid root may be a security problem"), myname); /* * Force profiling if this is pgawk. * Don't bother if the command line already set profiling up. */ if (! do_profiling) init_profiling(& do_profiling, DEFAULT_PROFILE); /* load group set */ init_groupset(); /* initialize the null string */ Nnull_string = make_string("", 0); Nnull_string->numbr = 0.0; Nnull_string->type = Node_val; Nnull_string->flags = (PERM|STRCUR|STRING|NUMCUR|NUMBER); /* * Tell the regex routines how they should work. * Do this before initializing variables, since * they could want to do a regexp compile. */ resetup(); /* Set up the special variables */ init_vars(); /* Set up the field variables */ init_fields(); /* Now process the pre-assignments */ for (i = 0; i <= numassigns; i++) if (preassigns[i].stype == PRE_ASSIGN) (void) arg_assign(preassigns[i].val, TRUE); else /* PRE_ASSIGN_FS */ cmdline_fs(preassigns[i].val); free(preassigns); if ((BINMODE & 1) != 0) if (os_setbinmode(fileno(stdin), O_BINARY) == -1) fatal(_("can't set binary mode on stdin (%s)"), strerror(errno)); if ((BINMODE & 2) != 0) { if (os_setbinmode(fileno(stdout), O_BINARY) == -1) fatal(_("can't set binary mode on stdout (%s)"), strerror(errno)); if (os_setbinmode(fileno(stderr), O_BINARY) == -1) fatal(_("can't set binary mode on stderr (%s)"), strerror(errno)); } #ifdef GAWKDEBUG setbuf(stdout, (char *) NULL); /* make debugging easier */ #endif if (isatty(fileno(stdout))) output_is_tty = TRUE; /* No -f or --source options, use next arg */ if (numfiles == -1) { if (optind > argc - 1 || stopped_early) /* no args left or no program */ usage(1, stderr); srcfiles_add(CMDLINE, argv[optind]); optind++; } init_args(optind, argc, (char *) myname, argv); (void) tokexpand(); #if defined(LC_NUMERIC) /* * FRAGILE! CAREFUL! * Pre-initing the variables with arg_assign() can change the * locale. Force it to C before parsing the program. */ setlocale(LC_NUMERIC, "C"); #endif /* Read in the program */ if (yyparse() != 0 || errcount != 0) exit(1); free(srcfiles); if (do_intl) exit(0); if (do_lint && begin_block == NULL && expression_value == NULL && end_block == NULL) lintwarn(_("no program text at all!")); if (do_lint) shadow_funcs(); init_profiling_signals(); #if defined(LC_NUMERIC) /* See comment above. */ setlocale(LC_NUMERIC, ""); #endif #if defined(HAVE_LOCALE_H) loc = *localeconv(); /* Make a local copy of locale numeric info */ #endif /* Whew. Finally, run the program. */ if (begin_block != NULL) { in_begin_rule = TRUE; (void) interpret(begin_block); } in_begin_rule = FALSE; if (! exiting && (expression_value != NULL || end_block != NULL)) do_input(); if (end_block != NULL) { in_end_rule = TRUE; (void) interpret(end_block); } in_end_rule = FALSE; /* * This used to be: * * if (close_io() != 0 && ! exiting && exit_val == 0) * exit_val = 1; * * Other awks don't care about problems closing open files * and pipes, in that it doesn't affect their exit status. * So we no longer do either. */ (void) close_io(& stdio_problem); /* * However, we do want to exit non-zero if there was a problem * with stdout/stderr, so we reinstate a slightly different * version of the above: */ if (stdio_problem && ! exiting && exit_val == 0) exit_val = 1; if (do_profiling) { dump_prog(begin_block, expression_value, end_block); dump_funcs(); } if (do_dump_vars) dump_vars(varfile); if (do_tidy_mem) release_all_vars(); exit(exit_val); /* more portable */ return exit_val; /* to suppress warnings */ }
/*********************************************************************** * Procedure: * main - start of afterstep ************************************************************************/ int main (int argc, char **argv, char **envp) { register int i ; int start_viewport_x = 0 ; int start_viewport_y = 0 ; int start_desk = 0 ; #ifdef LOCAL_DEBUG #if 0 LOCAL_DEBUG_OUT( "calibrating sleep_a_millisec : %s","" ); for( i = 0 ; i < 500 ; ++i ) sleep_a_millisec( 10 ); LOCAL_DEBUG_OUT( "500 sliip_a_millisec(10) completed%s","" ); for( i = 0 ; i < 50 ; ++i ) sleep_a_millisec( 100 ); LOCAL_DEBUG_OUT( "50 sliip_a_millisec(100) completed%s","" ); for( i = 0 ; i < 10 ; ++i ) sleep_a_millisec( 300 ); LOCAL_DEBUG_OUT( "10 sliip_a_millisec(300) completed%s","" ); #endif #endif _as_grab_screen_func = GrabEm; _as_ungrab_screen_func = UngrabEm; original_DISPLAY_string = getenv("DISPLAY"); if (original_DISPLAY_string) original_DISPLAY_string = mystrdup(original_DISPLAY_string); #ifdef DEBUG_TRACE_X trace_window_id2name_hook = &window_id2name; #endif set_DeadPipe_handler(DeadPipe); #if !HAVE_DECL_ENVIRON override_environ( envp ); #endif InitMyApp( CLASS_AFTERSTEP, argc, argv, NULL, AfterStep_usage, 0); LinkAfterStepConfig(); AfterStepState = MyArgs.flags ; clear_flags( AfterStepState, ASS_NormalOperation ); set_flags( AfterStepState, ASS_SuppressDeskBack ); #ifdef __CYGWIN__ CloseOnExec = ASCloseOnExec ; #endif #if defined(LOG_FONT_CALLS) fprintf (stderr, "logging font calls now\n"); #endif /* These signals are mandatory : */ signal (SIGUSR1, Restart); /* These signals we would like to handle only if those are not handled already (by debugger): */ IgnoreSignal(SIGINT); IgnoreSignal(SIGHUP); IgnoreSignal(SIGQUIT); IgnoreSignal(SIGTERM); if( ConnectX( ASDefaultScr, AS_ROOT_EVENT_MASK ) < 0 ) { show_error( "Hostile X server encountered - unable to proceed :-("); return 1;/* failed to accure window management selection - other wm is running */ } ASDBus_fd = asdbus_init(); XSetWindowBackground( dpy, Scr.Root, Scr.asv->black_pixel ); Scr.Look.desktop_animation_tint = get_random_tint_color(); cover_desktop(); if( get_flags( AfterStepState, ASS_Restarting )) { show_progress( "AfterStep v.%s is restarting ...", VERSION ); display_progress( True, "AfterStep v.%s is restarting ...", VERSION ); }else { show_progress( "AfterStep v.%s is starting up ...", VERSION ); display_progress( True, "AfterStep v.%s is starting up ...", VERSION ); } if (ASDBus_fd>=0) { show_progress ("Successfuly accured System DBus connection."); asdbus_RegisterSMClient(SMClientID_string); } SHOW_CHECKPOINT; InitSession(); SHOW_CHECKPOINT; XSync (dpy, 0); SHOW_CHECKPOINT; set_parent_hints_func( afterstep_parent_hints_func ); /* callback for collect_hints() */ SHOW_CHECKPOINT; SetupModules(); SHOW_CHECKPOINT; SetupScreen(); SHOW_CHECKPOINT; event_setup( True /*Bool local*/ ); SHOW_CHECKPOINT; /* * Lets init each and every screen separately : */ for (i = 0; i < Scr.NumberOfScreens; i++) { show_progress( "Initializing screen %d ...", i ); display_progress( True, "Initializing screen %d ...", i ); if (i != Scr.screen) { if( !get_flags(MyArgs.flags, ASS_SingleScreen) ) { int pid = spawn_child( MyName, (i<MAX_USER_SINGLETONS_NUM)?i:-1, i, NULL, None, C_NO_CONTEXT, True, True, NULL ); if( pid >= 0 ) show_progress( "\t instance of afterstep spawned with pid %d.", pid ); else show_error( "failed to launch instance of afterstep to handle screen #%d", i ); } }else { make_screen_envvars(ASDefaultScr); putenv (Scr.rdisplay_string); putenv (Scr.display_string); if( is_output_level_under_threshold( OUTPUT_LEVEL_PROGRESS ) ) { show_progress( "\t screen[%d].size = %ux%u", Scr.screen, Scr.MyDisplayWidth, Scr.MyDisplayHeight ); display_progress( True, " screen[%d].size = %ux%u", Scr.screen, Scr.MyDisplayWidth, Scr.MyDisplayHeight ); show_progress( "\t screen[%d].root = %lX", Scr.screen, Scr.Root ); show_progress( "\t screen[%d].color_depth = %d", Scr.screen, Scr.asv->true_depth ); display_progress( True, " screen[%d].color_depth = %d", Scr.screen, Scr.asv->true_depth ); show_progress( "\t screen[%d].colormap = 0x%lX", Scr.screen, Scr.asv->colormap ); show_progress( "\t screen[%d].visual.id = %X", Scr.screen, Scr.asv->visual_info.visualid ); display_progress( True, " screen[%d].visual.id = %X", Scr.screen, Scr.asv->visual_info.visualid ); show_progress( "\t screen[%d].visual.class = %d", Scr.screen, Scr.asv->visual_info.class ); display_progress( True, " screen[%d].visual.class = %d", Scr.screen, Scr.asv->visual_info.class ); show_progress( "\t screen[%d].visual.red_mask = 0x%8.8lX", Scr.screen, Scr.asv->visual_info.red_mask ); show_progress( "\t screen[%d].visual.green_mask = 0x%8.8lX", Scr.screen, Scr.asv->visual_info.green_mask ); show_progress( "\t screen[%d].visual.blue_mask = 0x%8.8lX", Scr.screen, Scr.asv->visual_info.blue_mask ); show_progress( "\t screen[%d].rdisplay_string = \"%s\"", Scr.screen, Scr.rdisplay_string ); show_progress( "\t screen[%d].display_string = \"%s\"", Scr.screen, Scr.display_string ); display_progress( True, " screen[%d].display_string = \"%s\"", Scr.screen, Scr.display_string ); } } } /* make sure we're on the right desk, and the _WIN_DESK property is set */ Scr.CurrentDesk = INVALID_DESK ; if( get_flags( Scr.wmprops->set_props, WMC_ASDesks ) ) { start_desk = Scr.wmprops->as_current_desk ; }else if( get_flags( Scr.wmprops->set_props, WMC_DesktopCurrent ) ) { int curr = Scr.wmprops->desktop_current ; start_desk = curr; if( get_flags( Scr.wmprops->set_props, WMC_DesktopViewport ) && curr < Scr.wmprops->desktop_viewports_num ) { /* we have to do that prior to capturing any window so that they'll get in * correct position and will not end up outside of the screen */ start_viewport_x = Scr.wmprops->desktop_viewport[curr<<1] ; start_viewport_y = Scr.wmprops->desktop_viewport[(curr<<1)+1] ; } } if( get_flags( Scr.wmprops->set_props, WMC_ASViewport ) ) { start_viewport_x = Scr.wmprops->as_current_vx ; start_viewport_y = Scr.wmprops->as_current_vy ; } /* temporarily setting up desktop 0 */ ChangeDesks(0); /* Load config ... */ /* read config file, set up menus, colors, fonts */ LoadASConfig (0, PARSE_EVERYTHING); /* Reparent all the windows and setup pan frames : */ XSync (dpy, 0); /***********************************************************/ #ifndef DONT_GRAB_SERVER /* grabbed !!!!!*/ grab_server(); /* grabbed !!!!!*/ #endif /* grabbed !!!!!*/ init_screen_panframes(ASDefaultScr); /* grabbed !!!!!*/ display_progress( True, "Capturing all windows ..." ); CaptureAllWindows (ASDefaultScr); /* grabbed !!!!!*/ display_progress( False, "Done." ); check_screen_panframes(ASDefaultScr); /* grabbed !!!!!*/ ASSync( False ); #ifndef DONT_GRAB_SERVER /* grabbed !!!!!*/ ungrab_server(); /* UnGrabbed !!!!!*/ #endif /* UnGrabbed !!!!!*/ /**********************************************************/ XDefineCursor (dpy, Scr.Root, Scr.Feel.cursors[ASCUR_Default]); display_progress( True, "Seting initial viewport to %+d%+d ...", Scr.wmprops->as_current_vx, Scr.wmprops->as_current_vy ); SetupFunctionHandlers(); display_progress( True, "Processing all pending events ..." ); ConfigureNotifyLoop(); display_progress( True, "All done." ); remove_desktop_cover(); if( !get_flags(AfterStepStartupFlags, ASSF_BypassAutoexec)) DoAutoexec(get_flags( AfterStepState, ASS_Restarting)); /* once all the windows are swallowed and placed in its proper desks - we cas restore proper desktop/viewport : */ clear_flags( AfterStepState, ASS_SuppressDeskBack ); ChangeDeskAndViewport ( start_desk, start_viewport_x, start_viewport_y, False); /* all system Go! we are completely Operational! */ set_flags( AfterStepState, ASS_NormalOperation); #if (defined(LOCAL_DEBUG)||defined(DEBUG)) && defined(DEBUG_ALLOCS) LOCAL_DEBUG_OUT( "printing memory%s",""); spool_unfreed_mem( "afterstep.allocs.startup", NULL ); #endif LOCAL_DEBUG_OUT( "entering main loop%s",""); HandleEvents (); return (0); }
/*********************************************************************** * our signal handlers : ************************************************************************/ void IgnoreSignal (int sig) { if (signal (sig, SIG_IGN) != SIG_IGN) signal (sig, SigDone); }
int main(int argc, char **argv) { int force = 0, lsock, csock, one = 0, jeden = 1, local_port; int detach = 1, sa_len, conn_limit = 0, optc; char *username = NULL, *bind_host = NULL; struct sockaddr *sa; struct sockaddr_in laddr, caddr; struct sockaddr_in6 laddr6; unsigned int caddrlen = sizeof(caddr); struct passwd *pw = NULL; while ((optc = getopt(argc, argv, "1dv46fHs:l:I:i:hu:m:L:A:p:")) != -1) { switch (optc) { case '1': one = 1; break; case 'd': detach = 0; break; case 'v': verbose = 1; break; case '4': break; case '6': remote_hint = AF_INET; local_hint = AF_INET6; break; case 's': source_host = xstrdup(optarg); break; case 'l': bind_host = xstrdup(optarg); break; case 'r': force = 1; break; case 'i': ircpass = xstrdup(optarg); clear_argv(argv[optind - 1]); break; case 'I': ircsendpass = xstrdup(optarg); clear_argv(argv[optind - 1]); break; case 'h': hexdump = 1; break; case 'u': username = xstrdup(optarg); break; case 'm': map_file = xstrdup(optarg); break; case 'L': conn_limit = atoi(optarg); break; case 'p': pid_file = xstrdup(optarg); break; case 'H': hint_optional = 1; break; default: return 1; } } if (hexdump) verbose = 1; if (verbose) detach = 0; if (detach) verbose = 0; if (argc - optind < 2) { usage(argv[0]); exit(1); } if (username && !(pw = getpwnam(username))) { fprintf(stderr, "%s: unknown user %s\n", argv[0], username); exit(1); } if (map_file) map_read(); local_port = atoi(argv[optind++]); remote_host = argv[optind++]; remote_port = (argc == optind) ? local_port : atoi(argv[optind]); debug("resolving %s\n", remote_host); if (!(sa = resolve_host(remote_host, remote_hint)) && !force) { fprintf(stderr, "%s: unable to resolve host %s\n", argv[0], remote_host); exit(1); } free(sa); sa = NULL; if (bind_host) { debug("resolving %s\n", bind_host); if (!(sa = resolve_host(bind_host, local_hint))) { fprintf(stderr, "%s: unable to resolve host %s\n", argv[0], remote_host); exit(1); } } debug("local: %s,%d; ", (bind_host) ? bind_host : "default", local_port); debug("remote: %s,%d; ", remote_host, remote_port); if (map_file) debug("source: mapped\n"); else debug("source: %s\n", (source_host) ? source_host : "default"); if (local_hint == AF_INET) { lsock = socket(PF_INET, SOCK_STREAM, 0); memset(&laddr, 0, (sa_len = sizeof(laddr))); laddr.sin_family = AF_INET; laddr.sin_port = htons(local_port); if (sa) { memcpy(&laddr.sin_addr, &((struct sockaddr_in*) sa)->sin_addr, sizeof(struct in_addr)); free(sa); } sa = (struct sockaddr*) &laddr; } else { lsock = socket(PF_INET6, SOCK_STREAM, 0); memset(&laddr6, 0, (sa_len = sizeof(laddr6))); laddr6.sin6_family = AF_INET6; laddr6.sin6_port = htons(local_port); if (sa) { memcpy(&laddr6.sin6_addr, &((struct sockaddr_in6*) sa)->sin6_addr, sizeof(struct in6_addr)); free(sa); } sa = (struct sockaddr*) &laddr6; } if (setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &jeden, sizeof(jeden)) == -1) { perror("setsockopt"); exit(1); } if (bind(lsock, sa, sa_len)) { perror("bind"); exit(1); } if (listen(lsock, 100)) { perror("listen"); exit(1); } if (detach) { int i, ret; signal(SIGHUP, sighup); for (i = 0; i < 3; i++) close(i); ret = fork(); if (ret == -1) { perror("fork"); exit(1); } if (ret) exit(0); } if (pid_file) { FILE *f = fopen(pid_file, "w"); if (!f) debug("warning: cannot write to pidfile (%s)\n", strerror(errno)); else { fprintf(f, "%d", getpid()); fclose(f); } } if (username && ((setgid(pw->pw_gid) == -1) || (setuid(pw->pw_uid) == -1))) { perror("setuid/setgid"); exit(1); } setsid(); signal(SIGCHLD, sigchld); signal(SIGTERM, sigterm); signal(SIGINT, sigterm); signal(SIGHUP, sighup); for (;;) { int ret; fd_set rds; FD_ZERO(&rds); FD_SET(lsock, &rds); if (select(lsock + 1, &rds, NULL, NULL, NULL) == -1) { if (errno == EINTR) continue; perror("select"); break; } if ((csock = accept(lsock, (struct sockaddr*) &caddr, &caddrlen)) == -1) { perror("accept"); break; } inet_ntop(caddr.sin_family, (caddr.sin_family == AF_INET) ? &caddr.sin_addr : (void*) &(((struct sockaddr_in6*)&caddr)->sin6_addr), remote, sizeof(remote)); debug("<%d> connection from %s,%d", csock, remote, ntohs(caddr.sin_port)); if (conn_limit && (conn_count >= conn_limit)) { debug(" -- rejected due to limit.\n"); shutdown(csock, 2); close(csock); continue; } if (conn_limit) { conn_count++; debug(" (no. %d)", conn_count); } fflush(stdout); if ((ret = fork()) == -1) { debug(" -- fork() failed.\n"); shutdown(csock, 2); close(csock); continue; } if (!ret) { signal(SIGHUP, SIG_IGN); close(lsock); debug("\n"); make_tunnel(csock, remote); debug("<%d> connection closed\n", csock); exit(0); } close(csock); if (one) { shutdown(lsock, 2); close(lsock); exit(0); } } close(lsock); exit(1); }
int main(int argc, char *argv[]) { int interactive; int warning_displayed = 0; int c; int daemonize = 0; const char *global = NULL; if (os_program_init()) return -1; for (;;) { c = getopt(argc, argv, "a:Bg:hi:p:P:v"); if (c < 0) break; switch (c) { case 'a': action_file = optarg; break; case 'B': daemonize = 1; break; case 'g': global = optarg; break; case 'h': usage(); return 0; case 'v': printf("%s\n", wpa_cli_version); return 0; case 'i': ctrl_ifname = strdup(optarg); break; case 'p': ctrl_iface_dir = optarg; break; case 'P': pid_file = optarg; break; default: usage(); return -1; } } interactive = (argc == optind) && (action_file == NULL); if (interactive) printf("%s\n\n%s\n\n", wpa_cli_version, wpa_cli_license); if (global) { ctrl_conn = wpa_ctrl_open(global); if (ctrl_conn == NULL) { perror("Failed to connect to wpa_supplicant - " "wpa_ctrl_open"); return -1; } } for (; !global;) { #ifndef CONFIG_CTRL_IFACE_UDP if (ctrl_ifname == NULL) { struct dirent *dent; DIR *dir = opendir(ctrl_iface_dir); if (dir) { while ((dent = readdir(dir))) { #ifdef _DIRENT_HAVE_D_TYPE /* Skip the file if it is not a socket. * Also accept DT_UNKNOWN (0) in case * the C library or underlying file * system does not support d_type. */ if (dent->d_type != DT_SOCK && dent->d_type != DT_UNKNOWN) continue; #endif /* _DIRENT_HAVE_D_TYPE */ if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) continue; printf("Selected interface '%s'\n", dent->d_name); ctrl_ifname = strdup(dent->d_name); break; } closedir(dir); } } #endif /* CONFIG_CTRL_IFACE_UDP */ ctrl_conn = wpa_cli_open_connection(ctrl_ifname); if (ctrl_conn) { if (warning_displayed) printf("Connection established.\n"); break; } if (!interactive) { perror("Failed to connect to wpa_supplicant - " "wpa_ctrl_open"); return -1; } if (!warning_displayed) { printf("Could not connect to wpa_supplicant - " "re-trying\n"); warning_displayed = 1; } os_sleep(1, 0); continue; } #ifndef _WIN32_WCE signal(SIGINT, wpa_cli_terminate); signal(SIGTERM, wpa_cli_terminate); #endif /* _WIN32_WCE */ #ifndef CONFIG_NATIVE_WINDOWS signal(SIGALRM, wpa_cli_alarm); #endif /* CONFIG_NATIVE_WINDOWS */ if (interactive || action_file) { if (wpa_ctrl_attach(ctrl_conn) == 0) { wpa_cli_attached = 1; } else { printf("Warning: Failed to attach to " "wpa_supplicant.\n"); if (!interactive) return -1; } } if (daemonize && os_daemonize(pid_file)) return -1; if (interactive) wpa_cli_interactive(); else if (action_file) wpa_cli_action(ctrl_conn); else wpa_request(ctrl_conn, argc - optind, &argv[optind]); free(ctrl_ifname); wpa_cli_cleanup(); return 0; }
void * xmalloc_large_ext (size_t sz) { #if !defined(__MTA__)&&defined(USE_MMAP_LARGE_EXT) char extname[4096+1]; char *tmppath; void *out; int fd, which; if (getenv ("TMPDIR")) tmppath = getenv ("TMPDIR"); else if (getenv ("TEMPDIR")) tmppath = getenv ("TEMPDIR"); else tmppath = "/tmp"; sprintf (extname, "%s/graph500-ext-XXXXXX", tmppath); which = n_large_alloc++; if (n_large_alloc > MAX_LARGE) { fprintf (stderr, "Out of large allocations.\n"); abort (); } large_alloc[which].p = 0; large_alloc[which].fd = -1; fd = mkstemp (extname); if (fd < 0) { perror ("xmalloc_large_ext failed to make a file"); abort (); } if (unlink (extname)) { perror ("UNLINK FAILED!"); goto errout; } #if _XOPEN_SOURCE >= 500 if (pwrite (fd, &fd, sizeof (fd), sz - sizeof(fd)) != sizeof (fd)) { perror ("resizing pwrite failed"); goto errout; } #else if (lseek (fd, sz - sizeof(fd), SEEK_SET) < 0) { perror ("lseek failed"); goto errout; } if (write (fd, &fd, sizeof(fd)) != sizeof (fd)) { perror ("resizing write failed"); goto errout; } #endif fcntl (fd, F_SETFD, O_ASYNC); out = mmap (NULL, sz, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE|MAP_NOSYNC, fd, 0); if (MAP_FAILED == out || !out) { perror ("mmap ext failed"); goto errout; } if (!installed_handler) { installed_handler = 1; if (atexit (exit_handler)) { perror ("failed to install exit handler"); goto errout; } old_abort_handler = signal (SIGABRT, abort_handler); if (SIG_ERR == old_abort_handler) { perror ("failed to install cleanup handler"); goto errout; } } large_alloc[which].p = out; large_alloc[which].sz = sz; large_alloc[which].fd = fd; return out; errout: if (fd >= 0) close (fd); abort (); #else return xmalloc_large (sz); #endif }
/* * ########################## * Main Function * ########################## */ int main(int argc, char *argv[]) { /* program setup variable */ struct mosquitto *mosq = NULL; struct mqtt_userdata *ud = NULL; bool clean_session = true; bool debug = false; char buf[MQTT_BUFSIZE]; char err[MQTT_ERR_BUFSIZE]; /* client id */ char id[MQTT_ID_LEN]; char id_prefix[MQTT_ID_LEN]; char hostname[MQTT_HOSTNAME_BUFSIZE]; /* broker variable */ char host[MQTT_IP_LEN] = "127.0.0.1"; int port = 1883; int keepalive = 3600; /* will information */ char *will_topic = NULL; long will_payloadlen = 0; char *will_payload = NULL; int will_qos = 0; bool will_retain = false; /* temp variable */ int i; int rc; /* initialized program and user data structure */ ud = malloc(sizeof(struct mqtt_userdata)); memset(ud, 0, sizeof(struct mqtt_userdata)); memset(id, '\0', sizeof(id)); memset(id_prefix, '\0', sizeof(id_prefix)); ud->topic_qos = 2; /* get option */ for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i==argc-1){ fprintf(stderr, "Error: -p argument given but no port specified.\n\n"); mqtt_print_usage(); return 1; }else{ port = atoi(argv[i+1]); if(port<1 || port>65535){ fprintf(stderr, "Error: Invalid port given: %d\n", port); mqtt_print_usage(); return 1; } } i++; }else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){ clean_session = false; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){ debug = true; }else if(!strcmp(argv[i], "--help")){ mqtt_print_usage(); return 0; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){ if(i==argc-1){ fprintf(stderr, "Error: -h argument given but no host specified.\n\n"); mqtt_print_usage(); return 1; }else{ if (strlen(argv[i+1]) >= MQTT_IP_LEN) { fprintf(stderr, "Error: max length of ip is %d.\n\n", MQTT_IP_LEN); mqtt_print_usage(); } else { memset(host, '\0', sizeof(host)); strcpy(host, argv[i+1]); } } i++; }else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){ if(strlen(id_prefix) != 0){ fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n"); mqtt_print_usage(); return 1; } if(i==argc-1){ fprintf(stderr, "Error: -i argument given but no id specified.\n\n"); mqtt_print_usage(); return 1; }else{ if (strlen(argv[i+1]) >= MOSQ_MQTT_ID_MAX_LENGTH) { fprintf(stderr, "Error: max length of client id is %d.\n\n", MOSQ_MQTT_ID_MAX_LENGTH); mqtt_print_usage(); } else { strcpy(id, argv[i+1]); } } i++; }else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){ if(strlen(id) != 0){ fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n"); mqtt_print_usage(); return 1; } if(i==argc-1){ fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n"); mqtt_print_usage(); return 1; }else{ if (strlen(argv[i+1]) >= MOSQ_MQTT_ID_MAX_LENGTH) { fprintf(stderr, "Error: max length of client id is %d.\n\n", MOSQ_MQTT_ID_MAX_LENGTH); mqtt_print_usage(); } else { strcpy(id_prefix, argv[i+1]); } } i++; }else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){ if(i==argc-1){ fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n"); mqtt_print_usage(); return 1; }else{ keepalive = atoi(argv[i+1]); if(keepalive>65535){ fprintf(stderr, "Error: Invalid keepalive given: %d\n", keepalive); mqtt_print_usage(); return 1; } } i++; }else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){ if(i==argc-1){ fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n"); mqtt_print_usage(); return 1; }else{ ud->topic_qos = atoi(argv[i+1]); if(ud->topic_qos<0 || ud->topic_qos>2){ fprintf(stderr, "Error: Invalid QoS given: %d\n", ud->topic_qos); mqtt_print_usage(); return 1; } } i++; }else if(!strcmp(argv[i], "--quiet")){ ud->quiet = true; }else if(!strcmp(argv[i], "-R")){ ud->no_retain = true; }else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){ if(i==argc-1){ fprintf(stderr, "Error: -t argument given but no topic specified.\n\n"); mqtt_print_usage(); return 1; }else{ ud->topic_count++; ud->topics = realloc(ud->topics, ud->topic_count*sizeof(char *)); ud->topics[ud->topic_count-1] = argv[i+1]; } i++; }else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){ if(i==argc-1){ fprintf(stderr, "Error: -u argument given but no username specified.\n\n"); mqtt_print_usage(); return 1; }else{ ud->username = argv[i+1]; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ ud->verbose = 1; }else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){ if(i==argc-1){ fprintf(stderr, "Error: -P argument given but no password specified.\n\n"); mqtt_print_usage(); return 1; }else{ ud->password = argv[i+1]; } i++; }else if(!strcmp(argv[i], "--will-payload")){ if(i==argc-1){ fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n"); mqtt_print_usage(); return 1; }else{ will_payload = argv[i+1]; will_payloadlen = strlen(will_payload); } i++; }else if(!strcmp(argv[i], "--will-qos")){ if(i==argc-1){ fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n"); mqtt_print_usage(); return 1; }else{ will_qos = atoi(argv[i+1]); if(will_qos < 0 || will_qos > 2){ fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos); return 1; } } i++; }else if(!strcmp(argv[i], "--will-retain")){ will_retain = true; }else if(!strcmp(argv[i], "--will-topic")){ if(i==argc-1){ fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n"); mqtt_print_usage(); return 1; }else{ will_topic = argv[i+1]; } i++; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); mqtt_print_usage(); return 1; } } /* verify necessary variable */ if(clean_session == false && ((strlen(id_prefix) != 0) || (strlen(id) == 0))){ if(!ud->quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n"); return 1; } if(ud->topic_count == 0){ fprintf(stderr, "Error: You must specify a topic to subscribe to.\n"); mqtt_print_usage(); return 1; } if(will_payload && !will_topic){ fprintf(stderr, "Error: Will payload given, but no will topic given.\n"); mqtt_print_usage(); return 1; } if(will_retain && !will_topic){ fprintf(stderr, "Error: Will retain given, but no will topic given.\n"); mqtt_print_usage(); return 1; } if(ud->password && !ud->username){ if(!ud->quiet) fprintf(stderr, "Warning: Not using password since username not set.\n"); } /* setup signal handler */ signal(SIGINT, mqtt_signal_handler); signal(SIGTERM, mqtt_signal_handler); /* init mosquitto library */ mosquitto_lib_init(); /* setup client id */ if(strlen(id_prefix) != 0){ snprintf(id, sizeof(id), "%s%d", id_prefix, getpid()); }else if(strlen(id) == 0){ memset(hostname, '\0', sizeof(hostname)); gethostname(hostname, sizeof(hostname)); snprintf(id, sizeof(id), "mosqsub/%d-%s", getpid(), hostname); } if(strlen(id) > MOSQ_MQTT_ID_MAX_LENGTH){ /* Enforce maximum client id length of 23 characters */ id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0'; } /* start mosquitto */ mosq = mosquitto_new(id, clean_session, ud); if(!mosq){ if(!ud->quiet) fprintf(stderr, "Error: %s\n", strerror(errno)); mosquitto_lib_cleanup(); return 1; } /* setup mosquitto */ if(debug){ mosquitto_log_callback_set(mosq, mqtt_log_callback); } if(will_topic && mosquitto_will_set(mosq, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){ if(!ud->quiet) fprintf(stderr, "Error: Problem setting will.\n"); mosquitto_lib_cleanup(); return 1; } if(ud->username && mosquitto_username_pw_set(mosq, ud->username, ud->password)){ if(!ud->quiet) fprintf(stderr, "Error: Problem setting username and password.\n"); mosquitto_lib_cleanup(); return 1; } mosquitto_connect_callback_set(mosq, mqtt_connect_callback); mosquitto_message_callback_set(mosq, mqtt_message_callback); if(debug){ mosquitto_subscribe_callback_set(mosq, mqtt_subscribe_callback); } /* connect mosquitto */ rc = mosquitto_connect(mosq, host, port, keepalive); if(rc){ if(!ud->quiet){ if(rc == MOSQ_ERR_ERRNO){ #ifndef WIN32 strerror_r(errno, err, sizeof(err)); #else FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, sizeof(err), NULL); #endif fprintf(stderr, "Error: %s\n", err); }else{ fprintf(stderr, "Unable to connect (%d: %s).\n", rc, mosquitto_strerror(rc)); } } mosquitto_lib_cleanup(); return rc; } mosquitto_loop_start(mosq); /* * loop mosquitto, * it use select() to call back the callback-function which defined before. */ do{ if (fgets(buf, sizeof(buf), stdin)) { buf[strlen(buf)-1] = '\0'; rc = mosquitto_publish(mosq, &ud->mid_sent, "simon", strlen(buf), buf, 0, 0); if (rc) { if (!ud->quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc); mosquitto_disconnect(mosq); } } } while (rc == MOSQ_ERR_SUCCESS); mosquitto_loop_stop(mosq, false); /* free mosquitto */ mosquitto_destroy(mosq); mosquitto_lib_cleanup(); mqtt_userdata_free(ud); return 0; }
void posix_death_signal(int signum) { memento(); signal(signum, SIG_DFL); exit(3); }
int main(int argc, char *argv[]) { /* Make sure we received two arguments, a hostname and a port number. */ if (argc < 2) { printf("Simple TCP/IP uptime server.\n"); printf("Usage: %s <port>\n", argv[0]); return 1; } port = atoi(argv[1]); /* Create the listener socket. This socket will queue incoming connections. */ listener = socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if (listener < 0) { printf("Unable to create a listener socket: %s\n", strerror(errno)); return 1; } /* Now bind the listener to a local address. This uses the same sockaddr_in structure as connect. */ sa_len = sizeof(sa); memset(&sa, 0, sa_len); sa.sin_family = AF_INET; sa.sin_port = htons(port); sa.sin_addr.s_addr = htonl(INADDR_ANY); /* Listen on all interfaces. */ if (bind(listener, &sa, sa_len) < 0) { printf("Unable to bind to port %i: %s\n", port, strerror(errno)); return 1; } /* Let the networking system know we're accepting connections on this socket. Ask for a connection queue of five clients. (If more than five clients try to connect before we call accept, some will be denied.) */ if (listen(listener, 5) < 0) { printf("Unable to listen: %s\n", strerror(errno)); return 1; } /* Ready! Now accept connections until the user presses Control-C. */ signal(SIGINT, signal_handler); for (;;) { char sendbuf[1024]; int sent, length; FILE *uptime; client = accept(listener, &sa, &sa_len); if (client < 0) { printf("Unable to accept: %s\n", strerror(errno)); close(listener); return 1; } /* We now have a live client. Print information about it and then send something over the wire. */ inet_ntop(AF_INET, &sa.sin_addr, dotted_ip, 15); printf("Received connection from %s.\n", dotted_ip); /* Use popen to retrieve the output of the uptime command. This is a bit of a hack, but it's portable and it works fairly well. popen opens a pipe to a program (that is, it executes the program and redirects its I/O to a file handle). */ uptime = popen("/usr/bin/uptime", "r"); if (uptime == NULL) { strcpy(sendbuf, "Unable to read system's uptime.\n"); } else { sendbuf[0] = '\0'; fgets(sendbuf, 1023, uptime); pclose(uptime); } /* Figure out how much data we need to send. */ length = strlen(sendbuf); sent = 0; /* Repeatedly call write until the entire buffer is sent. */ while (sent < length) { int amt; amt = write(client, sendbuf+sent, length-sent); if (amt <= 0) { /* Zero-byte writes are OK if they are caused by signals (EINTR). Otherwise they mean the socket has been closed. */ if (errno == EINTR) continue; else { printf("Send error: %s\n", strerror(errno)); break; } } /* Update our position by the number of bytes that were sent. */ sent += amt; } close(client); } return 0; }
void handle_sigint(int signum){ logd("Caught sigint %i\n", signum); should_close = true; signal(SIGINT, NULL); // next time just quit. }
int main(int argc, char **argv) { //Register signal and signal handler signal(SIGINT, signal_callback_handler); //Init UDP with callbacks and pointer to run status initUDP( &UDP_Command_Handler, &UDP_Control_Handler, &Running ); print("Eddie starting...\r\n"); initIdentity(); double EncoderPos[2] = {0}; initEncoders( 183, 46, 45, 44 ); print("Encoders activated.\r\n"); imuinit(); print("IMU Started.\r\n"); float kalmanAngle; InitKalman(); #ifndef DISABLE_MOTORS print( "Starting motor driver (and resetting wireless) please be patient..\r\n" ); if ( motor_driver_enable() < 1 ) { print("Startup Failed; Error starting motor driver.\r\n"); motor_driver_disable(); return -1; } print("Motor Driver Started.\r\n"); #endif print("Eddie is starting the UDP network thread..\r\n"); pthread_create( &udplistenerThread, NULL, &udplistener_Thread, NULL ); print( "Eddie is Starting PID controllers\r\n" ); /*Set default PID values and init pitchPID controllers*/ pidP_P_GAIN = PIDP_P_GAIN; pidP_I_GAIN = PIDP_I_GAIN; pidP_D_GAIN = PIDP_D_GAIN; pidP_I_LIMIT = PIDP_I_LIMIT; pidP_EMA_SAMPLES = PIDP_EMA_SAMPLES; PIDinit( &pitchPID[0], &pidP_P_GAIN, &pidP_I_GAIN, &pidP_D_GAIN, &pidP_I_LIMIT, &pidP_EMA_SAMPLES ); PIDinit( &pitchPID[1], &pidP_P_GAIN, &pidP_I_GAIN, &pidP_D_GAIN, &pidP_I_LIMIT, &pidP_EMA_SAMPLES ); /*Set default values and init speedPID controllers*/ pidS_P_GAIN = PIDS_P_GAIN; pidS_I_GAIN = PIDS_I_GAIN; pidS_D_GAIN = PIDS_D_GAIN; pidS_I_LIMIT = PIDS_I_LIMIT; pidS_EMA_SAMPLES = PIDS_EMA_SAMPLES; PIDinit( &speedPID[0], &pidS_P_GAIN, &pidS_I_GAIN, &pidS_D_GAIN, &pidS_I_LIMIT, &pidS_EMA_SAMPLES ); PIDinit( &speedPID[1], &pidS_P_GAIN, &pidS_I_GAIN, &pidS_D_GAIN, &pidS_I_LIMIT, &pidS_EMA_SAMPLES ); //Get estimate of starting angle and specify complementary filter and kalman filter start angles getOrientation(); kalmanAngle = filteredPitch = i2cPitch; setkalmanangle( filteredPitch ); filteredRoll = i2cRoll; print( "Eddie startup complete. Hold me upright to begin\r\n" ); double gy_scale = 0.01; last_PID_ms = last_gy_ms = current_milliseconds(); while(Running) { GetEncoders( EncoderPos ); if( fabs(GetEncoder()) > 2000 && !inRunAwayState ) { print( "Help! I'm running and not moving.\r\n"); ResetEncoders(); inRunAwayState=1; } /*Read IMU and calculate rough angle estimates*/ getOrientation(); /*Calculate time since last IMU reading and determine gyro scale (dt)*/ gy_scale = ( current_milliseconds() - last_gy_ms ) / 1000.0f; last_gy_ms = current_milliseconds(); /*Complementary filters to smooth rough pitch and roll estimates*/ filteredPitch = 0.995 * ( filteredPitch + ( gy * gy_scale ) ) + ( 0.005 * i2cPitch ); filteredRoll = 0.98 * ( filteredRoll + ( gx * gy_scale ) ) + ( 0.02 * i2cRoll ); /*Kalman filter for most accurate pitch estimates*/ kalmanAngle = -getkalmanangle(filteredPitch, gy, gy_scale /*dt*/); /* Monitor angles to determine if Eddie has fallen too far... or if Eddie has been returned upright*/ if ( ( inRunAwayState || ( fabs( kalmanAngle ) > 50 || fabs( filteredRoll ) > 45 ) ) && !inFalloverState ) { #ifndef DISABLE_MOTORS motor_driver_standby(1); #endif inFalloverState = 1; print( "Help! I've fallen over and I can't get up =)\r\n"); } else if ( fabs( kalmanAngle ) < 10 && inFalloverState && fabs( filteredRoll ) < 20 ) { if ( ++inSteadyState == 100 ) { inRunAwayState = 0; inSteadyState = 0; #ifndef DISABLE_MOTORS motor_driver_standby(0); #endif inFalloverState = 0; print( "Thank you!\r\n" ); } } else { inSteadyState = 0; } if ( !inFalloverState ) { /* Drive operations */ smoothedDriveTrim = ( 0.99 * smoothedDriveTrim ) + ( 0.01 * driveTrim ); if( smoothedDriveTrim != 0 ) { EncoderAddPos(smoothedDriveTrim); //Alter encoder position to generate movement } /* Turn operations */ if( turnTrim != 0 ) { EncoderAddPos2( turnTrim, -turnTrim ); //Alter encoder positions to turn } double timenow = current_milliseconds(); speedPIDoutput[0] = PIDUpdate( 0, EncoderPos[0], timenow - last_PID_ms, &speedPID[0] );//Wheel Speed PIDs speedPIDoutput[1] = PIDUpdate( 0, EncoderPos[1], timenow - last_PID_ms, &speedPID[1] );//Wheel Speed PIDs pitchPIDoutput[0] = PIDUpdate( speedPIDoutput[0], kalmanAngle, timenow - last_PID_ms, &pitchPID[0] );//Pitch Angle PIDs pitchPIDoutput[1] = PIDUpdate( speedPIDoutput[1], kalmanAngle, timenow - last_PID_ms, &pitchPID[1] );//Pitch Angle PIDs last_PID_ms = timenow; //Limit PID output to +/-100 to match 100% motor throttle if ( pitchPIDoutput[0] > 100.0 ) pitchPIDoutput[0] = 100.0; if ( pitchPIDoutput[1] > 100.0 ) pitchPIDoutput[1] = 100.0; if ( pitchPIDoutput[0] < -100.0 ) pitchPIDoutput[0] = -100.0; if ( pitchPIDoutput[1] < -100.0 ) pitchPIDoutput[1] = -100.0; } else //We are inFalloverState { ResetEncoders(); pitchPID[0].accumulatedError = 0; pitchPID[1].accumulatedError = 0; speedPID[0].accumulatedError = 0; speedPID[1].accumulatedError = 0; driveTrim = 0; turnTrim = 0; } #ifndef DISABLE_MOTORS set_motor_speed_right( pitchPIDoutput[0] ); set_motor_speed_left( pitchPIDoutput[1] ); #endif if ( (!inFalloverState || outputto == UDP) && StreamData ) { print( "PIDout: %0.2f,%0.2f\tcompPitch: %6.2f kalPitch: %6.2f\tPe: %0.3f\tIe: %0.3f\tDe: %0.3f\tPe: %0.3f\tIe: %0.3f\tDe: %0.3f\r\n", speedPIDoutput[0], pitchPIDoutput[0], filteredPitch, kalmanAngle, pitchPID[0].error, pitchPID[0].accumulatedError, pitchPID[0].differentialError, speedPID[0].error, speedPID[0].accumulatedError, speedPID[0].differentialError ); } } //--while(Running) print( "Eddie is cleaning up...\r\n" ); CloseEncoder(); pthread_join(udplistenerThread, NULL); print( "UDP Thread Joined..\r\n" ); #ifndef DISABLE_MOTORS motor_driver_disable(); print( "Motor Driver Disabled..\r\n" ); #endif print( "Eddie cleanup complete. Good Bye!\r\n" ); return 0; }
void ipmi_start_daemon(struct ipmi_intf *intf) { pid_t pid; int fd; #ifdef SIGHUP sigset_t sighup; #endif #ifdef SIGHUP sigemptyset(&sighup); sigaddset(&sighup, SIGHUP); if (sigprocmask(SIG_UNBLOCK, &sighup, NULL) < 0) fprintf(stderr, "ERROR: could not unblock SIGHUP signal\n"); signal(SIGHUP, SIG_IGN); #endif #ifdef SIGTTOU signal(SIGTTOU, SIG_IGN); #endif #ifdef SIGTTIN signal(SIGTTIN, SIG_IGN); #endif #ifdef SIGQUIT signal(SIGQUIT, SIG_IGN); #endif #ifdef SIGTSTP signal(SIGTSTP, SIG_IGN); #endif pid = (pid_t) fork(); if (pid < 0 || pid > 0) exit(0); #if defined(SIGTSTP) && defined(TIOCNOTTY) if (setpgid(0, getpid()) == -1) exit(1); if ((fd = open(_PATH_TTY, O_RDWR)) >= 0) { ioctl(fd, TIOCNOTTY, NULL); close(fd); } #else if (setpgid(0, 0) == -1) exit(1); pid = (pid_t) fork(); if (pid < 0 || pid > 0) exit(0); #endif chdir("/"); umask(0); for (fd=0; fd<64; fd++) { if (fd != intf->fd) close(fd); } fd = open("/dev/null", O_RDWR); assert(0 == fd); dup(fd); dup(fd); }
int main(int argc, char *argv[]) { int fd = 0; char *currentfile, old_dir[PATH_MAX]; playlist *pl = NULL; struct id3_file *id3struct = NULL; struct id3_tag *id3tag = NULL; buffer playbuf; struct mad_decoder decoder; old_dir[0] = '\0'; playbuf.pl = pl = new_playlist(); if (!pl) { fprintf(stderr, "malloc failed at startup!\n"); exit(1); } options.volume = MAD_F_ONE; status = MPG321_PLAYING; /* Get the command line options */ parse_options(argc, argv, pl); /* If there were no files and no playlist specified just print the usage */ if (!playlist_file && optind == argc) { usage(argv[0]); exit(0); } if (playlist_file) load_playlist(pl, playlist_file); add_cmdline_files(pl, argv); if (shuffle_play) shuffle_files(pl); ao_initialize(); check_default_play_device(); if (!(options.opt & MPG321_REMOTE_PLAY)) { handle_signals(-1); /* initialize signal handler */ remote_input_buf[0] = '\0'; } if (!(options.opt & MPG321_QUIET_PLAY)) mpg123_boilerplate(); if (options.opt & MPG321_REMOTE_PLAY) { printf ("@R MPG123\n"); } /* Play the mpeg files or zip it! */ while((currentfile = get_next_file(pl, &playbuf))) { if (quit_now) break; signal(SIGINT, SIG_DFL); playbuf.buf = NULL; playbuf.fd = -1; playbuf.length = 0; playbuf.done = 0; playbuf.num_frames = 0; playbuf.max_frames = -1; strncpy(playbuf.filename,currentfile, PATH_MAX); playbuf.filename[PATH_MAX-1] = '\0'; if (status == MPG321_PLAYING) file_change = 1; mad_timer_reset(&playbuf.duration); mad_timer_reset(¤t_time); if (!(options.opt & MPG321_QUIET_PLAY) && file_change) { id3struct = id3_file_open (currentfile, ID3_FILE_MODE_READONLY); if (id3struct) { id3tag = id3_file_tag (id3struct); if (id3tag) { show_id3 (id3tag); } id3_file_close (id3struct); } } if (options.opt & MPG321_REMOTE_PLAY && file_change) { id3struct = id3_file_open (currentfile, ID3_FILE_MODE_READONLY); if (id3struct) { id3tag = id3_file_tag (id3struct); if (id3tag) { if (!show_id3(id3tag)) { /* This shouldn't be necessary, but it appears that libid3tag doesn't necessarily know if there are no id3 tags on a given mp3 */ char * basec = strdup(currentfile); char * basen = basename(basec); char * dot = strrchr(basen, '.'); if (dot) *dot = '\0'; printf("@I %s\n", basen); free(basec); } } else { fprintf(stderr, "Allocation error"); exit(1); } id3_file_close (id3struct); } else { char * basec = strdup(currentfile); char * basen = basename(basec); char * dot = strrchr(basen, '.'); if (dot) *dot = '\0'; printf("@I %s\n", basen); free(basec); } } /* Create the MPEG stream */ /* Check if source is on the network */ if((fd = raw_open(currentfile)) != 0 || (fd = http_open(currentfile)) != 0 || (fd = ftp_open(currentfile)) != 0) { playbuf.fd = fd; playbuf.buf = malloc(BUF_SIZE); playbuf.length = BUF_SIZE; mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0, output, /*error*/0, /* message */ 0); } /* Check if we are to use stdin for input */ else if(strcmp(currentfile, "-") == 0) { playbuf.fd = fileno(stdin); playbuf.buf = malloc(BUF_SIZE); playbuf.length = BUF_SIZE; mad_decoder_init(&decoder, &playbuf, read_from_fd, read_header, /*filter*/0, output, /*error*/0, /* message */ 0); } /* currentfile is a local file (presumably.) mmap() it */ else { struct stat stat; if((fd = open(currentfile, O_RDONLY)) == -1) { mpg321_error(currentfile); /* mpg123 stops immediately if it can't open a file */ break; } if(fstat(fd, &stat) == -1) { close(fd); mpg321_error(currentfile); continue; } if (!S_ISREG(stat.st_mode)) { close(fd); continue; } calc_length(currentfile, &playbuf); if ((options.maxframes != -1) && (options.maxframes <= playbuf.num_frames)) { playbuf.max_frames = options.maxframes; } playbuf.frames = malloc((playbuf.num_frames + 1) * sizeof(void*)); playbuf.times = malloc((playbuf.num_frames + 1) * sizeof(mad_timer_t)); if((playbuf.buf = mmap(0, playbuf.length, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) { close(fd); mpg321_error(currentfile); continue; } close(fd); playbuf.frames[0] = playbuf.buf; mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0, output, /*error*/0, /* message */ 0); } if(!(options.opt & MPG321_QUIET_PLAY))/*zip it!!!*/ { /* Because dirname might modify the argument */ char * dirc = strdup(currentfile); char * basec = strdup(currentfile); char * basen = basename(basec); char * dirn = dirname(dirc); /* make sure that the file has a pathname; otherwise don't print out a Directory: listing */ if(strchr(currentfile, '/') && strncmp(old_dir, dirn, PATH_MAX) != 0) { /* Print information about the file */ fprintf(stderr, "\n"); fprintf(stderr,"Directory: %s/\n", dirn); strncpy(old_dir, dirn, PATH_MAX); old_dir[PATH_MAX-1] = '\0'; } /* print a newline between different songs only, not after Directory: listing */ else { fprintf(stderr, "\n"); } fprintf(stderr,"Playing MPEG stream from %s ...\n", basen); free(dirc); free(basec); } signal(SIGINT, handle_signals); /* Every time the user gets us to rewind, we exit decoding, reinitialize it, and re-start it */ while (1) { mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC); /* if we're rewinding on an mmap()ed stream */ if(status == MPG321_REWINDING && playbuf.fd == -1) { mad_decoder_init(&decoder, &playbuf, read_from_mmap, read_header, /*filter*/0, output, /*error*/0, /* message */ 0); } else break; } if (!(options.opt & MPG321_QUIET_PLAY)) { char time_formatted[11]; mad_timer_string(current_time, time_formatted, "%.1u:%.2u", MAD_UNITS_MINUTES, MAD_UNITS_SECONDS, 0); fprintf(stderr, "\n[%s] Decoding of %s finished.\n",time_formatted, basename(currentfile)); } if (options.opt & MPG321_REMOTE_PLAY && status == MPG321_STOPPED) { clear_remote_file(pl); } mad_decoder_finish(&decoder); if (quit_now) break; if (playbuf.frames) free(playbuf.frames); if (playbuf.times) free(playbuf.times); if (playbuf.fd == -1) { munmap(playbuf.buf, playbuf.length); } else { free(playbuf.buf); if (playbuf.fd != fileno(stdin)) close(playbuf.fd); } } if(playdevice) ao_close(playdevice); ao_shutdown(); #if defined(RAW_SUPPORT) || defined(HTTP_SUPPORT) || defined(FTP_SUPPORT) if(fd) close(fd); #endif return(0); }
//====================================== Main===========================================// int main(int argc, char **argv) { int sd; struct sockaddr saddr; int r, i, j, m, n; struct sockaddr inaddr; unsigned int inlen; unsigned int conn; int child_id; reservation newRes; char buffer[BSIZE]; struct timeval stop; //Defining signal handlers signal(SIGCHLD,sig_chld); signal(SIGINT,sig_int); //Shared memory creation sh_mem_id=shmget((key_t)SH_MEM_NAME,(size_t) sizeof(data),(int) (0600|IPC_CREAT)); if(sh_mem_id<0) { printf("Failed to create shared memory.\n"); exit(1); } //Attach server to shared memory sh_mem=(data*)shmat(sh_mem_id,NULL,0); if(sh_mem==(data*)-1) { printf("Failed to attach server to shared memory.\n"); exit(1); } //Initialize shared data. We use the arguments defined in Myheader.h. init_data(NUMBER_OF_OPERATORS, NUMBER_OF_TERMINALS, A_SEATS, B_SEATS, C_SEATS, D_SEATS); /*/////////////////////////////////////////////////////////////////////////////////////////////// THEATER CHECK -PROCESS After next line we create a new process that it continously checks,if all class get empty. When this happen it set 'theater status' into full. In the end, it prints several information about the reservations, such as a foreground of the theater. This process runs simultaneously with its parent. //////////////////////////////////////////////////////////////////////////////////////////////*/ if ( fork() == 0 ) { //Only Child process hets in here. //Child gets shared memory handler sh_mem_id=shmget((key_t)SH_MEM_NAME,sizeof(data),0600); if(sh_mem_id<0) { printf("Child failed to retrieve shared memory handler.\n"); exit(1); } //Child is attached to shared memory. sh_mem=(data*)shmat(sh_mem_id,NULL,0); if(sh_mem==(data*)-1) { printf("Failed to attach child to shared memory.\n"); exit(1); } //Infinite loop used to check if theater gets Full. while(1){ /*Check every class if they are empty*/ if(sh_mem->Theater[1]==0 && sh_mem->Theater[2]==0 && sh_mem->Theater[3]==0 && sh_mem->Theater[4]==0 ){ sh_mem->Theater[0]=1; //If all classes are empty, set 'theater status' full. sleep(2); // 2 secands delay. } /*Check if theater is full*/ if(sh_mem->Theater[0]==1){ printf("==================================================================="); printf("\nTheater got FULL. \nTheater server will now close.\n"); int a=((double)sh_mem->com/(sh_mem->com+sh_mem->incom))*100; int b=((double)sh_mem->incom/(sh_mem->com+sh_mem->incom))*100; printf("\n---Completed Reservations:%d Incompleted:%d \n",sh_mem->com,sh_mem->incom); printf("Percent of completed reservations: %d%% \n",a); printf("Percent of incompleted reservations: %d%% \n",b); printf("Theater Income=%d E.\n",sh_mem->Theater_account); printf("--Theater reservations's foreground-- \n"); /*--------Printing the foreground of Class A ------*/ printf("-Class A: \n"); //checking every reservation for(m=0; m< NUM_RES; m++){ //Checking if this reservation is about Class A && //if this reservation is done. if(sh_mem->reservations[m].info[0]==0 && sh_mem->reservations[m].info[5]==1){ //Printing the reservation's number: one time per seat for (i=0; i<=sh_mem->reservations[m].info[1]; i++);{ printf("[%d]",m); } } } /*--------Printing the foreground of Class B ------*/ printf("\n-Class B: \n"); //checking every reservation for(m=0; m< NUM_RES; m++){ //Checking if this reservation is about Class A && //if this reservation is done. if(sh_mem->reservations[m].info[0]==1 && sh_mem->reservations[m].info[5]==1){ //Printing the reservation's number: one time per seat for (n=0; n<=sh_mem->reservations[m].info[1]; n++);{ printf("[%d]",m); } } } /*--------Printing the foreground of Class C ------*/ printf("\n-Class C: \n"); //checking every reservation for(m=0; m< NUM_RES; m++){ //Checking if this reservation is about Class A && //if this reservation is done. if(sh_mem->reservations[m].info[0]==2 && sh_mem->reservations[m].info[5]==1){ //Printing the reservation's number: one time per seat for (i=0; i<=sh_mem->reservations[m].info[1]; i++);{ printf("[%d]",m); } } } /*--------Printing the foreground of Class D ------*/ printf("\n-Class D: \n"); //checking every reservation for(m=0; m< NUM_RES; m++){ //Checking if this reservation is about Class A && //if this reservation is done. if(sh_mem->reservations[m].info[0]==3 && sh_mem->reservations[m].info[5]==1){ //Printing the reservation's number: one time per seat for (i=0; i<=sh_mem->reservations[m].info[1]; i++);{ printf("[%d]",m); } } } printf("\n"); printf(" Press ctrl-c to close server...."); break; //breaking while } } exit(0); //End of process } /*/////////////////////////////////////////////////////////////////////////////////////////////// TRANSFER MONEY -PROCESS After next line we create a new process that is transfering the income of the reservations. from Company_account to Theater_account. This process runs simultaneously with its parent. //////////////////////////////////////////////////////////////////////////////////////////////*/ if ( fork() == 0 ) { //Only Child process hets in here. //Child gets shared memory handler sh_mem_id=shmget((key_t)SH_MEM_NAME,sizeof(data),0600); if(sh_mem_id<0) { printf("Child failed to retrieve shared memory handler.\n"); exit(1); } //Child is attached to shared memory. sh_mem=(data*)shmat(sh_mem_id,NULL,0); if(sh_mem==(data*)-1) { printf("Failed to attach child to shared memory.\n"); exit(1); } //Infinite loop used to keep the process opened. while(1){ if(sh_mem->Theater[0]==0){ sleep(TRANSFER_TIME); // <TRANSFER_TIME> between each transfer. sem_wait(sh_mem->res_sem); //locking res_sem to make the transfer //printf("\n***********************************\n"); //printf("Funds transfered to Theater account: %d E",sh_mem->Company_account); sh_mem->Theater_account=sh_mem->Theater_account+sh_mem->Company_account; //transfer sh_mem->Company_account=0; //Initializing company's account //printf("\n***********************************\n"); sem_post(sh_mem->res_sem); //leaving res_sem } else if(sh_mem->Theater[0]==1){ break; // If theater got full, break 'while' and end the process. } } exit(0); //End of process } //---------------------------------------------------------------------------------------OPERATORS /*/////////////////////////////////////////////////////////////////////////////////////////////// OPERATORS -PROCESS We create <NUM_OF_OPERATORS> new processes, which act like the operators of our company. These processes run simultaneously with their parent. //////////////////////////////////////////////////////////////////////////////////////////////*/ for (i=0; i<sh_mem->operators; i++) { //Only Child process hets in here. child_id=fork(); if(child_id==0) { /*Child gets shared memory handler*/ sh_mem_id=shmget((key_t)SH_MEM_NAME,sizeof(data),0600); if(sh_mem_id<0) { printf("Child failed to retrieve shared memory handler.\n"); exit(1); } /*Child is attached to shared memory.*/ sh_mem=(data*)shmat(sh_mem_id,NULL,0); if(sh_mem==(data*)-1) { printf("Failed to attach child to shared memory.\n"); exit(1); } //--------------------------------------------------------------------------------- //Infinite loop. //If there are reservations, serve them. while(1) { sem_wait(sh_mem->oper_sem); //Locking oper_sem /*Only one process gets in here each time*/ if(sh_mem->res_head < sh_mem->res_tail && sh_mem->reservations[sh_mem->res_head].info[4]!=3 ) { int head = sh_mem->res_head; //From now on use "head" as the process's ID //Inform the qeue of reservations ,which reservation is first in line. sh_mem->res_head++; //Set in terminal's qeue,this process ID sh_mem->term_tail++; sem_post(sh_mem->oper_sem); //Leaving oper_sem //From now on use "seatsClass" as the current reservation's class int seatsClass = sh_mem->reservations[head].info[0]; //From now on use "seatsNum" as the current reservation's Number of seats int seatsNum = sh_mem->reservations[head].info[1]; //printf("Checking number of available seats...\n"); //Check if 'A' is our current reservation's class if (sh_mem->reservations[head].info[0]==0){ //Check if available seats in Class A are enough for current reservation if(sh_mem->reservations[head].info[1] >sh_mem->Theater[1]){ //printf ("No seat available in Class A\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } } //Check if 'B' is our current reservation's class if (sh_mem->reservations[head].info[0]==1){ //Check if available seats in Class B are enough for current reservation if(sh_mem->reservations[head].info[1] >sh_mem->Theater[2]){ //printf ("No seat available in Class B\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } } //Check if 'C' is our current reservation's class if (sh_mem->reservations[head].info[0]==2){ //Check if available seats in Class C are enough for current reservation if(sh_mem->reservations[head].info[1] >sh_mem->Theater[3]){ //printf ("No seat available in Class C\n"); //If available seats aren't enough sh_mem->reservations[head].info[5]=3; //(info[5]=3)=No available seats in this Class. } } //Check if 'D' is our current reservation's class if (sh_mem->reservations[head].info[0]==3){ //Check if available seats in Class D are enough for current reservation if(sh_mem->reservations[head].info[1] >sh_mem->Theater[4]){ //printf ("No seat available in Class D\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } } // "Checking for Seats" sleep(SEATFIND_TIME); // <SEATFIND_TIME> delay /*----At this point seats are ckecked---------*/ /*Cheking if we have any 'asnwer' from the Bank (terminals*/ while(1){ if(sh_mem->reservations[head].info[4]==2){ //(info[5]=3)=Checked for available seats and Consumer's bank account. break; } } /*-------------At this point seats and client's account are ckecked-----------------------*/ /*Checking the value of info[5]. -If its 2,then: wrong card_ID/Insufficient account's balance. -If its 3,then there are not enough seats in this Class. If none of these happen,we can continue in reserving the seats. */ if(sh_mem->reservations[head].info[5] != 2 && sh_mem->reservations[head].info[5] != 3){ //dhladh entaksei me thn karta kai me theseis //---------------Check if 'A' is our current reservation's class if (sh_mem->reservations[head].info[0]==0){ sem_wait(sh_mem->seat_sem); //Locking seat_sem //SECOND check if available seats in Class A are enough for current reservation. if(sh_mem->reservations[head].info[1] >sh_mem->Theater[1]){ //printf ("Seats taken in A class by another Operator.\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } else{ //Bring up to date Class's variable -> Theater[1]=Class A sh_mem->Theater[1]=sh_mem->Theater[1]-seatsNum; //Counting the tickets's cost and saving it. //info[3]=Cost sh_mem->reservations[head].info[3]=sh_mem->reservations[head].info[1]*50; sh_mem->reservations[head].info[5]=1;//(info[5]=1)=Done. ->Current reservation is completed. } sem_post(sh_mem->seat_sem); //Leaving seat_sem } //---------------Check if 'B' is our current reservation's class if (sh_mem->reservations[head].info[0]==1){ sem_wait(sh_mem->seat_sem); //Locking seat_sem //SECOND check if available seats in Class B are enough for current reservation. if(sh_mem->reservations[head].info[1] >sh_mem->Theater[2]){ //printf ("Seats taken in B class by another Operator.\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } else{ //Bring up to date Class's variable -> Theater[2]=Class B sh_mem->Theater[2]=sh_mem->Theater[2]-seatsNum; //Counting the tickets's cost and saving it. //info[3]=Cost sh_mem->reservations[head].info[3]=sh_mem->reservations[head].info[1]*40; sh_mem->reservations[head].info[5]=1;//(info[5]=1)=Done. ->Current reservation is completed. } sem_post(sh_mem->seat_sem); //Leaving seat_sem } //---------------Check if 'C' is our current reservation's class if (sh_mem->reservations[head].info[0]==2){ sem_wait(sh_mem->seat_sem); //Locking seat_sem //SECOND check if available seats in Class C are enough for current reservation. if(sh_mem->reservations[head].info[1] >sh_mem->Theater[3]){ //printf ("Seats taken in C class by another Operator.\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } else{ //Bring up to date Class's variable -> Theater[3]=Class C sh_mem->Theater[3]=sh_mem->Theater[3]-seatsNum; //Counting the tickets's cost and saving it. //info[3]=Cost sh_mem->reservations[head].info[3]=sh_mem->reservations[head].info[1]*35; sh_mem->reservations[head].info[5]=1;//(info[5]=1)=Done. ->Current reservation is completed. } sem_post(sh_mem->seat_sem); //Leaving seat_sem } //---------------Check if 'D' is our current reservation's class if (sh_mem->reservations[head].info[0]==3){ sem_wait(sh_mem->seat_sem); //Locking seat_sem //SECOND check if available seats in Class D are enough for current reservation. if(sh_mem->reservations[head].info[1] >sh_mem->Theater[4]){ //printf ("Seats taken in D class by another Operator.\n"); sh_mem->reservations[head].info[5]=3;//(info[5]=3)=No available seats in this Class. } else{ //Bring up to date Class's variable -> Theater[4]=Class D sh_mem->Theater[4]=sh_mem->Theater[4]-seatsNum; //Counting the tickets's cost and saving it. //info[3]=Cost sh_mem->reservations[head].info[3]=sh_mem->reservations[head].info[1]*30; sh_mem->reservations[head].info[5]=1;//(info[5]=1)=Done. ->Current reservation is completed. } sem_post(sh_mem->seat_sem); //Leaving seat_sem } /*At this point, seats are saved.*/ sh_mem->reservations[head].info[4]=3;//(info[4]=3)=Reservation process ended. if(sh_mem->reservations[head].info[5]==3){ //if there weren't enough available seats in the class we wanted (info[5]=3) //print a message in our screen //printf("Reservation %d Incompleted:\nNot enough seats.(Seats taken by another Operator.\n",head); } else if(sh_mem->reservations[head].info[5]==1){ //our reservations is completed //(info[5]=1)=Done. gettimeofday(&stop, NULL); //Printing all the information we want to know about our current reservation printf("Reservation %d Completed!, %d seats of class %d %f msec\n", head, seatsNum, seatsClass, (float) (stop.tv_sec-sh_mem->reservations[head].reserveTime.tv_sec) * 1000000 + (stop.tv_usec-sh_mem->reservations[head].reserveTime.tv_usec)); } //Printing Current available theater seats. //printf("\nCurrent available theater seats: A:%d B:%d C:%d D:%d \n",sh_mem->Theater[1],sh_mem->Theater[2],sh_mem->Theater[3],sh_mem->Theater[4]); } else{ //In our first check there weren't enough seats printf("Reservation %d Incompleted:\nNot enough seats or insufficient account's balance/inaccurate cardID. \n",head); sh_mem->reservations[head].info[4]=3;//(info[4]=3)=Reservation process ended. } } else { sem_post(sh_mem->oper_sem);//Leaving oper_sem //Everytime there is no reservation in our qeue, leave oper_sem and wait to check again. } } exit(0); } } // --------------------------------------------------------------------------------------TERMINALS /*/////////////////////////////////////////////////////////////////////////////////////////////// OPERATORS -PROCESS We create <NUM_OF_TERMINALS> new processes, which act like the terminals of the bank. These processes run simultaneously with their parent. //////////////////////////////////////////////////////////////////////////////////////////////*/ for (j=0; j<sh_mem->terminals; j++) { child_id=fork(); if(child_id==0){ //Child gets shared memory handler sh_mem_id=shmget((key_t)SH_MEM_NAME,sizeof(data),0600); if(sh_mem_id<0) { printf("Child failed to retrieve shared memory handler.\n"); exit(1); } //Child is attached to shared memory. sh_mem=(data*)shmat(sh_mem_id,NULL,0); if(sh_mem==(data*)-1) { printf("Failed to attach child to shared memory.\n"); exit(1); } /*read queue, if there is work do it */ while(1) { sem_wait(sh_mem->term_sem); //elegxos an yparxei diathesimo terminal if(sh_mem->term_head < sh_mem->term_tail) { int head = sh_mem->term_head;//!!!!!!!!!!!!!!!! sh_mem->term_head++; sem_post(sh_mem->term_sem); //printf("Checking cardID and account's balance...\n"); //periptwsh apotyxias if (percent_value(head)==7){ sh_mem->reservations[head].info[5] = 2; } ////////////////////////////// sleep(CARDCHECK_TIME); /////////////////////////// sh_mem->reservations[head].info[4]=2; // CHECKED } else { sem_post(sh_mem->term_sem); } } exit(0); } } ////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------SOCKETS-----------------------------------------------// /*Getting a socket handler*/ sd=socket(AF_UNIX,SOCK_STREAM,0); if(sd<0) { printf("Error in creating socket.\n"); exit(1); } /*Delete socket file if already exists*/ unlink(SOCKET_NAME); // "MySock" /*Specify socket address details*/ saddr.sa_family = AF_UNIX; strcpy(saddr.sa_data,SOCKET_NAME); /*Bind socket*/ r=bind(sd,&saddr,sizeof(saddr)); if(r<0) { printf("Error in binding socket.\n"); exit(1); } /*Listen to socket*/ r=listen(sd,1); /*size of listening queue is 1*/ if(r<0) { printf("Error in listening.\n"); exit(1); } while(1) // { inlen=sizeof(inaddr); /*Wait for connection attempt*/ conn=accept(sd,&inaddr,&inlen); if(conn<0) { printf("Connection attempt failed.\n"); continue; } /*Connection established, spawn a child to serve it*/ child_id=fork(); if(child_id==0) { signal(SIGUSR1,sig_res); /*Child gets shared memory handler*/ sh_mem_id=shmget((key_t)SH_MEM_NAME,sizeof(data),0600); if(sh_mem_id<0) { printf("Child failed to retrieve shared memory handler.\n"); exit(1); } /*Child is attached to shared memory.*/ sh_mem=(data*)shmat(sh_mem_id,NULL,0); if(sh_mem==(data*)-1) { printf("Failed to attach child to shared memory.\n"); exit(1); } /*read user reservation*/ read(conn,&newRes,sizeof(reservation)); //printf("-------------------------------------------------------------\n"); /*TODO:add reservation to queue*/ /*TODO:add pid to queue*/ sem_wait(sh_mem->res_sem); // trying to get res_sem opened int resNum = sh_mem->res_tail; sh_mem->reservations[sh_mem->res_tail].info[0] = newRes.info[0]; //CLASS sh_mem->reservations[sh_mem->res_tail].info[1] = newRes.info[1]; //NUMBER sh_mem->reservations[sh_mem->res_tail].info[2] = newRes.info[2]; //CARD_ID sh_mem->reservations[sh_mem->res_tail].info[4] = 1; //STATUS -diavasthke if(sh_mem->Theater[0]==1){ //If Theater is full set Curretnt reservation's status: //(info[4]=3)-Reservation process ended sh_mem->reservations[resNum].info[4]=3; } sh_mem->reservations[sh_mem->res_tail].procNumber = getpid(); gettimeofday(&(sh_mem->reservations[sh_mem->res_tail].reserveTime), NULL); sh_mem->res_tail++; sem_post(sh_mem->res_sem); // leaving the oper_sem if(sh_mem->Theater[0]==0){ while(1){ //Checking current reservation's status if(sh_mem->reservations[resNum].info[4]==3){ break; } } } else{ sh_mem->reservations[resNum].info[5]=4; //printf("Current reservation incompleted!\nTheater if FULL.\n No further reservations can be accepted. \n"); } switch (sh_mem->reservations[resNum].info[5]) { case 1: sprintf(buffer, "Reservation %d completed !\nClass: %d\nSeats Number: %d\ncard_ID: %d \nCost: %d E",resNum, sh_mem->reservations[resNum].info[0], sh_mem->reservations[resNum].info[1], sh_mem->reservations[resNum].info[2],sh_mem->reservations[resNum].info[3]); sem_wait(sh_mem->res_sem); sh_mem->Company_account=sh_mem->Company_account+sh_mem->reservations[resNum].info[3]; sh_mem->com++; sem_post(sh_mem->res_sem); break; case 2: sprintf(buffer, "Reservation %d incompleted !\nInaccurate cardID or insufficient account's balance.",resNum); sem_wait(sh_mem->res_sem); sh_mem->incom++; sem_post(sh_mem->res_sem); break; case 3: sprintf(buffer,"Reservation %d incompleted !\nNo seats available in this Class.",resNum); sem_wait(sh_mem->res_sem); sh_mem->incom++; sem_post(sh_mem->res_sem); break; case 4: sprintf(buffer, "Reservation %d incompleted !\nTheater is FULL.",resNum); sem_wait(sh_mem->res_sem); sh_mem->incom++; sem_post(sh_mem->res_sem); break; default: sprintf(buffer, "Kati paixthke me th diergasia %d",resNum); } write(conn,buffer,BSIZE); semaphores_close(); /*deattach child from shared memory*/ r=shmdt(sh_mem); if(r<0) { printf("Failed to deattach child from shared memory.\n"); exit(1); } exit(0); } close(conn); } exit(0); //!!!!!!!!!!! }
int main(int argc, char **argv) { char *temp, *s; char* displayName = NULL; commands=NULL; /* Save the program name for error messages and config parsing */ temp = argv[0]; s=strrchr(argv[0], '/'); if (s != NULL) temp = s + 1; Module=temp; if((argc != 6)&&(argc != 7)) { fprintf(stderr,"%s Version %s should only be executed by fvwm!\n",Module, VERSION); exit(1); } Fvwm_fd[0] = atoi(argv[1]); Fvwm_fd[1] = atoi(argv[2]); /* Grab the X display information now. */ dpy = XOpenDisplay(displayName); if (!dpy) { fprintf(stderr, "%s: unable to open display '%s'\n", Module, XDisplayName (displayName)); exit (2); } screen = DefaultScreen(dpy); root = RootWindow(dpy, screen); /* Open a log file if necessary */ # ifdef LOGFILE logFile = fopen(LOGFILE,"a"); fprintf(logFile,"Initialising FvwmBacker\n"); # endif signal (SIGPIPE, DeadPipe); /* Parse the config file */ ParseConfig(); fd_width = GetFdWidth(); SetMessageMask(Fvwm_fd,M_NEW_DESK|M_CONFIG_INFO|M_END_CONFIG_INFO); /* ** we really only want the current desk, and window list sends it */ SendInfo(Fvwm_fd,"Send_WindowList",0); /* Recieve all messages from Fvwm */ EndLessLoop(); /* Should never get here! */ return 1; }
int main(int argc, char ** argv) { int fdm, fds, status; char *slavename; pid_t pid; test_init(argc, argv); fdm = open("/dev/ptmx", O_RDWR); if (fdm == -1) { err("Can't open a master pseudoterminal"); return 1; } grantpt(fdm); unlockpt(fdm); slavename = ptsname(fdm); pid = test_fork(); if (pid < 0) { err("fork() failed"); return 1; } if (pid == 0) { close(fdm); signal(SIGHUP, sighup_handler); if (setsid() == -1) return 1; /* set up a controlling terminal */ fds = open(slavename, O_RDWR); if (fds == -1) { err("Can't open a slave pseudoterminal %s", slavename); return 1; } if (ioctl(fdm, TIOCSCTTY, 1) < 0) { err("Can't setup a controlling terminal"); return 1; } close(fds); test_waitsig(); if (sighup) return 0; return 1; } test_daemon(); test_waitsig(); close(fdm); if (kill(pid, SIGTERM) == -1) { err("kill failed"); return 1; } pid = waitpid(pid, &status, 0); if (pid < 0) return 1; if (WIFEXITED(status)) { if (WEXITSTATUS(status)) { fail("The child returned %d", WEXITSTATUS(status)); return 1; } } else err("The child has been killed by %d", WTERMSIG(status)); pass(); return 0; }
int64 io_waituntil2(int64 milliseconds) { #ifndef __MINGW32__ struct pollfd* p; #endif long i,j,r; if (!io_wanted_fds) return 0; #ifdef HAVE_EPOLL if (io_waitmode==EPOLL) { int n; struct epoll_event y[50]; if ((n=epoll_wait(io_master,y,50,milliseconds))==-1) return -1; int first_new = -1; int last_new = -1; for (i=n-1; i>=0; --i) { io_entry* e=array_get(&io_fds,sizeof(io_entry),y[i].data.fd); if (e) { if (y[i].events&(EPOLLERR|EPOLLHUP)) { /* error; signal whatever app is looking for */ if (e->wantread) y[i].events|=EPOLLIN; if (e->wantwrite) y[i].events|=EPOLLOUT; } #ifdef EPOLLRDNORM if (y[i].data.fd == io_master && !e->canread && (y[i].events&(EPOLLIN|EPOLLPRI|EPOLLRDNORM|EPOLLRDBAND))) { #else if (y[i].data.fd == io_master && !e->canread && (y[i].events&(EPOLLIN|EPOLLPRI))) { #endif e->canread=1; e->next_read=first_new; if(first_new == -1) last_new = y[i].data.fd; first_new=y[i].data.fd; } } } //if(n > 1) printf("n: %d\n", n); for (i=n-1; i>=0; --i) { //for (i=0; i < n; i++) { io_entry* e=array_get(&io_fds,sizeof(io_entry),y[i].data.fd); if (e) { #ifdef EPOLLRDNORM if (!e->canread && (y[i].events&(EPOLLIN|EPOLLPRI|EPOLLRDNORM|EPOLLRDBAND))) { #else if (!e->canread && (y[i].events&(EPOLLIN|EPOLLPRI))) { #endif e->canread=1; e->next_read=first_readable; first_readable=y[i].data.fd; } if (!e->canwrite && (y[i].events&EPOLLOUT)) { e->canwrite=-1; e->next_write=first_writeable; first_writeable=y[i].data.fd; } } else { epoll_ctl(io_master,EPOLL_CTL_DEL,y[i].data.fd,y+i); } } // if there are new connections, put them first... if(last_new != -1) { if(first_readable != -1) { io_entry* e=array_get(&io_fds,sizeof(io_entry),last_new); e->next_read=first_readable; } first_readable = first_new; } return n; } #endif #ifdef HAVE_KQUEUE if (io_waitmode==KQUEUE) { struct kevent y[100]; int n; struct timespec ts; ts.tv_sec=milliseconds/1000; ts.tv_nsec=(milliseconds%1000)*1000000; if ((n=kevent(io_master,0,0,y,100,milliseconds!=-1?&ts:0))==-1) return -1; for (i=n-1; i>=0; --i) { io_entry* e=array_get(&io_fds,sizeof(io_entry),y[--n].ident); #ifdef DEBUG if (!e) { e=e; } #endif if (e) { if (y[n].flags&EV_ERROR) { /* error; signal whatever app is looking for */ if (e->wantread) y[n].filter=EVFILT_READ; else if (e->wantwrite) y[n].filter=EVFILT_WRITE; } if (!e->canread && (y[n].filter==EVFILT_READ)) { e->canread=1; e->next_read=first_readable; first_readable=y[n].ident; } if (!e->canwrite && (y[n].filter==EVFILT_WRITE)) { e->canwrite=1; e->next_write=first_writeable; first_writeable=y[i].ident; } #ifdef DEBUG } else { fprintf(stderr,"got kevent on fd#%d, which is not in array!\n",y[n].ident); #endif } } return n; } #endif #ifdef HAVE_DEVPOLL if (io_waitmode==DEVPOLL) { dvpoll_t timeout; struct pollfd y[100]; int n; timeout.dp_timeout=milliseconds; timeout.dp_nfds=100; timeout.dp_fds=y; if ((n=ioctl(io_master,DP_POLL,&timeout))==-1) return -1; for (i=n-1; i>=0; --i) { io_entry* e=array_get(&io_fds,sizeof(io_entry),y[--n].fd); if (e) { if (y[n].revents&(POLLERR|POLLHUP|POLLNVAL)) { /* error; signal whatever app is looking for */ if (e->wantread) y[n].revents=POLLIN; if (e->wantwrite) y[n].revents=POLLOUT; } if (!e->canread && (y[n].revents&POLLIN)) { e->canread=1; if (e->next_read==-1) { e->next_read=first_readable; first_readable=y[n].fd; } } if (!e->canwrite && (y[n].revents&POLLOUT)) { e->canwrite=1; if (e->next_write==-1) { e->next_write=first_writeable; first_writeable=y[i].fd; } } #ifdef DEBUG } else { fprintf(stderr,"got kevent on fd#%d, which is not in array!\n",y[n].fd); #endif } } return n; } #endif #ifdef HAVE_SIGIO if (io_waitmode==_SIGIO) { siginfo_t info; struct timespec ts; int r; io_entry* e; if (alt_firstread>=0 && (e=array_get(&io_fds,sizeof(io_entry),alt_firstread)) && e->canread) return 1; if (alt_firstwrite>=0 && (e=array_get(&io_fds,sizeof(io_entry),alt_firstwrite)) && e->canwrite) return 1; if (milliseconds==-1) r=sigwaitinfo(&io_ss,&info); else { ts.tv_sec=milliseconds/1000; ts.tv_nsec=(milliseconds%1000)*1000000; r=sigtimedwait(&io_ss,&info,&ts); } switch (r) { case SIGIO: /* signal queue overflow */ signal(io_signum,SIG_DFL); goto dopoll; default: if (r==io_signum) { io_entry* e=array_get(&io_fds,sizeof(io_entry),info.si_fd); if (e) { if (info.si_band&(POLLERR|POLLHUP)) { /* error; signal whatever app is looking for */ if (e->wantread) info.si_band|=POLLIN; if (e->wantwrite) info.si_band|=POLLOUT; } if (info.si_band&POLLIN && !e->canread) { debug_printf(("io_waituntil2: enqueueing %ld in normal read queue before %ld\n",info.si_fd,first_readable)); e->canread=1; e->next_read=first_readable; first_readable=info.si_fd; } if (info.si_band&POLLOUT && !e->canwrite) { debug_printf(("io_waituntil2: enqueueing %ld in normal write queue before %ld\n",info.si_fd,first_writeable)); e->canwrite=1; e->next_write=first_writeable; first_writeable=info.si_fd; } #ifdef DEBUG } else { fprintf(stderr,"got kevent on fd#%d, which is not in array!\n",info.si_fd); #endif } } } return 1; } dopoll: #endif #ifdef __MINGW32__ DWORD numberofbytes; ULONG_PTR x; LPOVERLAPPED o; if (first_readable!=-1 || first_writeable!=-1) { fprintf(stderr,"io_waituntil2() returning immediately because first_readable(%p) or first_writeable(%p) are set\n",first_readable,first_writeable); return; } fprintf(stderr,"Calling GetQueuedCompletionStatus %p...",io_comport); if (GetQueuedCompletionStatus(io_comport,&numberofbytes,&x,&o,milliseconds==-1?milliseconds:INFINITE)) { io_entry* e=array_get(&io_fds,sizeof(io_entry),x); fprintf(stderr," OK. Got %x, e=%p\n",x,e); if (!e) return 0; e->errorcode=0; fprintf(stderr,"o=%p, e->or=%p, e->ow=%p, e->os=%p\n",o,&e->or,&e->ow,&e->os); fprintf(stderr,"e->readqueued=%d, e->writequeued=%d, e->acceptqueued=%d, e->connectqueued=%d, e->sendfilequeued=%d\n", e->readqueued,e->writequeued,e->acceptqueued,e->connectqueued,e->sendfilequeued); if (o==&e->or && e->readqueued==1) { e->readqueued=2; e->canread=1; e->bytes_read=numberofbytes; e->next_read=first_readable; first_readable=x; // printf("read %lu bytes on fd %lu: %p\n",numberofbytes,x,e); } else if (o==&e->ow && e->writequeued==1) { e->writequeued=2; e->canwrite=1; e->bytes_written=numberofbytes; e->next_write=first_writeable; first_writeable=x; } else if (o==&e->or && e->acceptqueued==1) { e->acceptqueued=2; e->canread=1; e->next_read=first_readable; first_readable=x; } else if (o==&e->ow && e->connectqueued==1) { e->connectqueued=2; e->canwrite=1; e->next_write=first_writeable; first_writeable=x; } else if (o==&e->os && e->sendfilequeued==1) { e->sendfilequeued=2; e->canwrite=1; e->bytes_written=numberofbytes; e->next_write=first_writeable; first_writeable=x; } return 1; } else { /* either the overlapped I/O request failed or we timed out */ DWORD err; io_entry* e; fprintf(stderr," failure, o=%p.\n",o); if (!o) return 0; /* timeout */ /* we got a completion packet for a failed I/O operation */ err=GetLastError(); if (err==WAIT_TIMEOUT) return 0; /* or maybe not */ e=array_get(&io_fds,sizeof(io_entry),x); if (!e) return 0; /* WTF?! */ e->errorcode=err; if (o==&e->or && (e->readqueued || e->acceptqueued)) { if (e->readqueued) e->readqueued=2; else if (e->acceptqueued) e->acceptqueued=2; e->canread=1; e->bytes_read=-1; e->next_read=first_readable; first_readable=x; } else if ((o==&e->ow || o==&e->os) && (e->writequeued || e->connectqueued || e->sendfilequeued)) { if (o==&e->ow) { if (e->writequeued) e->writequeued=2; else if (e->connectqueued) e->connectqueued=2; } else if (o==&e->os) e->sendfilequeued=2; e->canwrite=1; e->bytes_written=-1; e->next_write=first_writeable; first_writeable=x; } return 1; } #else for (i=r=0; i<array_length(&io_fds,sizeof(io_entry)); ++i) { io_entry* e=array_get(&io_fds,sizeof(io_entry),i); if (!e) return -1; e->canread=e->canwrite=0; if (e->wantread || e->wantwrite) { struct pollfd* p; if ((p=array_allocate(&io_pollfds,sizeof(struct pollfd),r))) { p->fd=i; p->events=(e->wantread?POLLIN:0) + (e->wantwrite?POLLOUT:0); ++r; } else return -1; } } p=array_start(&io_pollfds); if ((i=poll(array_start(&io_pollfds),r,milliseconds))<1) return -1; for (j=r-1; j>=0; --j) { io_entry* e=array_get(&io_fds,sizeof(io_entry),p->fd); if (p->revents&(POLLERR|POLLHUP|POLLNVAL)) { /* error; signal whatever app is looking for */ if (e->wantread) p->revents|=POLLIN; if (e->wantwrite) p->revents|=POLLOUT; } if (!e->canread && (p->revents&POLLIN)) { e->canread=1; e->next_read=first_readable; first_readable=p->fd; } if (!e->canwrite && (p->revents&POLLOUT)) { e->canwrite=1; e->next_write=first_writeable; first_writeable=p->fd; } p++; } return i; #endif }
gint main (gint argc, gchar **argv) { setlocale (LC_ALL, ""); GOptionContext *context = g_option_context_new ("- ibus daemon"); g_option_context_add_main_entries (context, entries, "ibus-daemon"); g_argv = g_strdupv (argv); GError *error = NULL; if (!g_option_context_parse (context, &argc, &argv, &error)) { g_printerr ("Option parsing failed: %s\n", error->message); g_error_free (error); exit (-1); } if (g_gdbus_timeout < -1) { g_printerr ("Bad timeout (must be >= -1): %d\n", g_gdbus_timeout); exit (-1); } if (g_mempro) { g_mem_set_vtable (glib_mem_profiler_table); signal (SIGUSR2, _sig_usr2_handler); } /* check uid */ { const gchar *username = ibus_get_user_name (); uid_t uid = getuid (); struct passwd *pwd = getpwuid (uid); if (pwd == NULL || g_strcmp0 (pwd->pw_name, username) != 0) { g_printerr ("Please run ibus-daemon with login user! Do not run ibus-daemon with sudo or su.\n"); exit (-1); } } /* daemonize process */ if (daemonize) { if (daemon (1, 0) != 0) { g_printerr ("Can not daemonize ibus.\n"); exit (-1); } } /* create a new process group. this is important to kill all of its children by SIGTERM at a time in bus_ibus_impl_destroy. */ setpgid (0, 0); ibus_init (); ibus_set_log_handler (g_verbose); /* check if ibus-daemon is running in this session */ if (ibus_get_address () != NULL) { IBusBus *bus = ibus_bus_new (); if (ibus_bus_is_connected (bus)) { if (!replace) { g_printerr ("current session already has an ibus-daemon.\n"); exit (-1); } ibus_bus_exit (bus, FALSE); while (ibus_bus_is_connected (bus)) { g_main_context_iteration (NULL, TRUE); } } g_object_unref (bus); } bus_server_init (); if (!single) { /* execute config component */ if (g_strcmp0 (config, "default") == 0) { BusComponent *component; component = bus_ibus_impl_lookup_component_by_name ( BUS_DEFAULT_IBUS, IBUS_SERVICE_CONFIG); if (component) { bus_component_set_restart (component, restart); } if (component == NULL || !bus_component_start (component, g_verbose)) { g_printerr ("Can not execute default config program\n"); exit (-1); } } else if (g_strcmp0 (config, "disable") != 0 && g_strcmp0 (config, "") != 0) { if (!execute_cmdline (config)) exit (-1); } /* execute panel component */ if (g_strcmp0 (panel, "default") == 0) { BusComponent *component; component = bus_ibus_impl_lookup_component_by_name ( BUS_DEFAULT_IBUS, IBUS_SERVICE_PANEL); if (component) { bus_component_set_restart (component, restart); } if (component == NULL || !bus_component_start (component, g_verbose)) { g_printerr ("Can not execute default panel program\n"); exit (-1); } } else if (g_strcmp0 (panel, "disable") != 0 && g_strcmp0 (panel, "") != 0) { if (!execute_cmdline (panel)) exit (-1); } } /* execute ibus xim server */ if (xim) { if (!execute_cmdline (LIBEXECDIR "/ibus-x11 --kill-daemon")) exit (-1); } bus_server_run (); return 0; }
int dacq_start(int boot, int testmode, char *tracker_type, char *dacq_server, char *trakdev) { int shmid, ii; /* init the internal timestamper, in case it's needed later */ timestamp(1); if ((shmid = shmget((key_t)SHMKEY, sizeof(DACQINFO), 0666 | IPC_CREAT)) < 0) { if (errno == EINVAL) { fprintf(stderr, "dacq_start: Shared memory buffer's changed sizes!\n"); fprintf(stderr, " Run pypekill, then try pype again.\n"); return(0); } else { perror("shmget"); fprintf(stderr, "dacq_start: %d kernel compiled with SHM/IPC?\n", errno); return(0); } } if ((dacq_data = shmat(shmid, NULL, 0)) == NULL) { perror("shmat"); fprintf(stderr, "dacq_start: kernel compiled with SHM/IPC?\n"); return(0); } if ((semid = psem_init(SEMKEY)) < 0) { perror("psem_init"); fprintf(stderr, "dacq_start: can't init semaphore\n"); return(0); } else { /* start semaphore off at value of 1 */ if (psem_set(semid, 1) < 0) { perror("psem_init"); return(-1); } } /* don't need to LOCK/UNLOCK until child processes are * running ... so don't bother here.. */ if (boot) { int i; for (i = 0; i < NDIGIN; i++) { dacq_data->din[i] = 0; dacq_data->din_changes[i] = 0; dacq_data->din_intmask[i] = 0; } for (i = 0; i < NDIGOUT; i++) { dacq_data->dout[i] = 0; } dacq_data->dout_strobe = 0; for (i = 0; i < NADC; i++) { dacq_data->adc[i] = 0; } dacq_data->eye_xgain = 1.0; dacq_data->eye_ygain = 1.0; dacq_data->eye_xoff = 0; dacq_data->eye_yoff = 0; for (i = 0; i < NFIXWIN; i++) { dacq_data->fixwin[i].active = 0; dacq_data->fixwin[i].genint = 0; } for (i = 0; i < NJOYBUT; i++) { dacq_data->js[i] = 0; } dacq_data->js_x = 0; dacq_data->js_y = 0; dacq_data->js_enabled = 0; dacq_data->adbuf_on = 0; dacq_data->adbuf_ptr = 0; dacq_data->adbuf_overflow = 0; for (i = 0; i < ADBUFLEN; i++) { dacq_data->adbuf_t[i] = 0; dacq_data->adbuf_x[i] = 0; dacq_data->adbuf_y[i] = 0; for (ii=0; ii < NADC; ii++) { dacq_data->adbufs[ii][i] = 0; } } for (i = 0; i < NDAC; i++) { dacq_data->dac[i] = 0; } dacq_data->dac_strobe = 0; dacq_data->timestamp = 0; dacq_data->terminate = 0; dacq_data->das_ready = 0; dacq_data->eye_smooth = 0; dacq_data->eye_x = 0; dacq_data->eye_y = 0; dacq_data->dacq_pri = 0; dacq_data->fixbreak_tau = 5; /* alarm timer (same units as timestamp); 0 for no alarm */ dacq_data->alarm_time = 0; if (testmode) { dacq_data->din[2] = 1; dacq_data->din[3] = 1; fprintf(stderr, "dacq: testmode = 1 (no sub process!)\n"); } else { signal(SIGCHLD, dacq_sigchld_handler); fprintf(stderr, "dacq: testmode = 0\n"); fprintf(stderr, "dacq: tracker_type = %s\n", tracker_type); fprintf(stderr, "dacq: dacq_server = %s\n", dacq_server); if ((dacq_server_pid = fork()) == 0) { /* child process execs the dacq_server */ if (strcmp(tracker_type, "ISCAN") == 0) { //fprintf(stderr, "dacqmodule: starting iscan\n"); execlp(dacq_server, dacq_server, "-iscan", trakdev, NULL); } else if (strcmp(tracker_type, "EYELINK") == 0) { //fprintf(stderr, "dacqmodule: starting eyelink\n"); execlp(dacq_server, dacq_server, "-eyelink", trakdev, NULL); } else if (strcmp(tracker_type, "ANALOG") == 0) { //fprintf(stderr, "dacqmodule: starting analog\n"); execlp(dacq_server, dacq_server, NULL); } else if (strcmp(tracker_type, "EYEJOY") == 0) { //fprintf(stderr, "dacqmodule: starting eyelink\n"); execlp(dacq_server, dacq_server, "-eyejoy", NULL); } else if (strcmp(tracker_type, "NONE") == 0) { //fprintf(stderr, "dacqmodule: starting w/o tracker\n"); execlp(dacq_server, dacq_server, "-notracker", NULL); } perror(dacq_server); exit(1); } else { /* parent waits for server to become ready */ do { LOCK(semid); i = dacq_data->das_ready; UNLOCK(semid); usleep(100); } while (i == 0); } } } return(1); }
int telnet_main(int argc, char **argv) { char *host; int port; int len; #ifdef USE_POLL struct pollfd ufds[2]; #else fd_set readfds; int maxfd; #endif INIT_G(); #if ENABLE_FEATURE_AUTOWIDTH get_terminal_width_height(0, &G.win_width, &G.win_height); #endif #if ENABLE_FEATURE_TELNET_TTYPE G.ttype = getenv("TERM"); #endif if (tcgetattr(0, &G.termios_def) >= 0) { G.do_termios = 1; G.termios_raw = G.termios_def; cfmakeraw(&G.termios_raw); } if (argc < 2) bb_show_usage(); #if ENABLE_FEATURE_TELNET_AUTOLOGIN if (1 & getopt32(argv, "al:", &G.autologin)) G.autologin = getenv("USER"); argv += optind; #else argv++; #endif if (!*argv) bb_show_usage(); host = *argv++; port = bb_lookup_port(*argv ? *argv++ : "telnet", "tcp", 23); if (*argv) /* extra params?? */ bb_show_usage(); G.netfd = create_and_connect_stream_or_die(host, port); setsockopt(G.netfd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1)); signal(SIGINT, fgotsig); #ifdef USE_POLL ufds[0].fd = 0; ufds[1].fd = G.netfd; ufds[0].events = ufds[1].events = POLLIN; #else FD_ZERO(&readfds); FD_SET(0, &readfds); FD_SET(G.netfd, &readfds); maxfd = G.netfd + 1; #endif while (1) { #ifndef USE_POLL fd_set rfds = readfds; switch (select(maxfd, &rfds, NULL, NULL, NULL)) #else switch (poll(ufds, 2, -1)) #endif { case 0: /* timeout */ case -1: /* error, ignore and/or log something, bay go to loop */ if (G.gotsig) conescape(); else sleep(1); break; default: #ifdef USE_POLL if (ufds[0].revents) /* well, should check POLLIN, but ... */ #else if (FD_ISSET(0, &rfds)) #endif { len = read(0, G.buf, DATABUFSIZE); if (len <= 0) doexit(0); TRACE(0, ("Read con: %d\n", len)); handlenetoutput(len); } #ifdef USE_POLL if (ufds[1].revents) /* well, should check POLLIN, but ... */ #else if (FD_ISSET(G.netfd, &rfds)) #endif { len = read(G.netfd, G.buf, DATABUFSIZE); if (len <= 0) { write_str(1, "Connection closed by foreign host\r\n"); doexit(1); } TRACE(0, ("Read netfd (%d): %d\n", G.netfd, len)); handlenetinput(len); } } } }
static void initCrashCatch() { for (auto sig : s_fatal_signals) { signal(sig, signalHandler); } }
void Scene1200::sub9DAD6(int indx) { _object1.sub9EE22(R2_GLOBALS._v56AA2, R2_GLOBALS._v56AA4); switch (indx) { case 0: if ( ((_object1.sub51AF8(Common::Point(200, 50)) > 36) || (_object1.sub51AF8(Common::Point(200, 88)) > 36)) && ( ((R2_GLOBALS._v56AA2 == 3) && (R2_GLOBALS._v56AA4 == 33) && (_field418 != 4)) || ((R2_GLOBALS._v56AA2 == 13) && (R2_GLOBALS._v56AA4 == 21) && (_field418 != 2)) || ((R2_GLOBALS._v56AA2 == 29) && (R2_GLOBALS._v56AA4 == 17) && (_field418 != 1)) || ((R2_GLOBALS._v56AA2 == 33) && (R2_GLOBALS._v56AA4 == 41)) ) ) { R2_GLOBALS._player.disableControl(); _sceneMode = 1200; setAction(&_sequenceManager, this, 1200, &_actor1, NULL); } else if (_object1.sub51AF8(Common::Point(200, 69)) == 36) { switch (_field412 - 1) { case 0: if (R2_GLOBALS._player._visage == 3155) _sceneMode = 15; else _sceneMode = 10; break; case 1: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 76; else _sceneMode = 75; break; case 2: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 101; else _sceneMode = 100; break; case 3: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 111; else _sceneMode = 110; break; default: break; } R2_GLOBALS._player.disableControl(); _field412 = 1; signal(); } break; case 1: if ( ((_object1.sub51AF8(Common::Point(120, 50)) > 36) || (_object1.sub51AF8(Common::Point(120, 88)) > 36)) && ( ((R2_GLOBALS._v56AA2 == 7) && (R2_GLOBALS._v56AA4 == 33) && (_field418 != 4)) || ((R2_GLOBALS._v56AA2 == 17) && (R2_GLOBALS._v56AA4 == 21) && (_field418 != 2)) || ((R2_GLOBALS._v56AA2 == 33) && (R2_GLOBALS._v56AA4 == 17) && (_field418 != 1)) || ((R2_GLOBALS._v56AA2 == 5) && (R2_GLOBALS._v56AA4 == 5)) ) ) { R2_GLOBALS._player.disableControl(); _sceneMode = 1201; setAction(&_sequenceManager, this, 1201, &_actor1, NULL); } else if (_object1.sub51AF8(Common::Point(120, 69)) == 36) { switch (_field412 - 1) { case 0: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 56; else _sceneMode = 55; break; case 1: if (R2_GLOBALS._player._visage == 3155) _sceneMode = 25; else _sceneMode = 20; break; case 2: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 91; else _sceneMode = 90; break; case 3: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 121; else _sceneMode = 120; break; default: break; } R2_GLOBALS._player.disableControl(); _field412 = 2; signal(); } break; case 2: if ( ((_object1.sub51AF8(Common::Point(140, 110)) > 36) || (_object1.sub51AF8(Common::Point(178, 110)) > 36)) && ( ((R2_GLOBALS._v56AA2 == 17) && (R2_GLOBALS._v56AA4 == 5) && (_field418 != 3)) || ((R2_GLOBALS._v56AA2 == 41) && (R2_GLOBALS._v56AA4 == 21)) ) ) { R2_GLOBALS._player.disableControl(); _sceneMode = 1203; setAction(&_sequenceManager, this, 1203, &_actor1, NULL); } else if (_object1.sub51AF8(Common::Point(160, 110)) == 36) { switch (_field412 - 1) { case 0: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 51; else _sceneMode = 50; break; case 1: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 81; else _sceneMode = 80; break; case 2: if (R2_GLOBALS._player._visage == 3155) _sceneMode = 35; else _sceneMode = 30; break; case 3: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 116; else _sceneMode = 115; break; default: break; } R2_GLOBALS._player.disableControl(); _field412 = 3; signal(); } break; case 3: if ( ((_object1.sub51AF8(Common::Point(140, 30)) > 36) || (_object1.sub51AF8(Common::Point(178, 30)) > 36)) && ( ((R2_GLOBALS._v56AA2 == 17) && (R2_GLOBALS._v56AA4 == 9) && (_field418 != 3)) || ((R2_GLOBALS._v56AA2 == 35) && (R2_GLOBALS._v56AA4 == 17)) ) ) { R2_GLOBALS._player.disableControl(); _sceneMode = 1202; setAction(&_sequenceManager, this, 1202, &_actor1, NULL); } else if (_object1.sub51AF8(Common::Point(160, 30)) == 36) { switch (_field412 - 1) { case 0: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 61; else _sceneMode = 60; break; case 1: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 71; else _sceneMode = 70; break; case 2: if (R2_GLOBALS._player._visage == 3156) _sceneMode = 96; else _sceneMode = 95; break; case 3: if (R2_GLOBALS._player._visage == 3155) _sceneMode = 45; else _sceneMode = 40; break; default: _sceneMode = 1; R2_GLOBALS._player.setup(3156, 4, 6); break; } R2_GLOBALS._player.disableControl(); _field412 = 4; signal(); } break; default: break; } }
int main() { /// Sets up exception handling signal(SIGFPE, FPE_ExceptionHandler); bool gaugeUnification = true, ewsbBCscale = false; /// Do we include 2-loop RGEs of *all* scalar masses and A-terms, or only the /// scalar mass Higgs parameters? (Other quantities all 2-loop anyway): the /// default in SOFTSUSY 3 is to include all 2-loop terms, except for RPV, /// which is already slow and calculated to less accuracy than the R-parity /// conserving version INCLUDE_2_LOOP_SCALAR_CORRECTIONS = false; /// Sets format of output: 6 decimal places outputCharacteristics(6); /// Header cerr << "SOFTSUSY" << SOFTSUSY_VERSION << " Ben Allanach, Markus Bernhardt 2009\n"; cerr << "If you use SOFTSUSY, please refer to B.C. Allanach, "; cerr << "Comput. Phys. Commun. 143 (2002) 305, hep-ph/0104145;\n"; cerr << "For RPV aspects, B.C. Allanach and M.A. Bernhardt, "; cerr << "Comp. Phys. Commun. 181 (2010) 232, "; cerr << "arXiv:0903.1805.\n"; /// "try" catches errors in main program and prints them out try { /// Contains default quark and lepton masses and gauge coupling /// information QedQcd oneset; ///< See "lowe.h" for default parameter definitions oneset.toMz(); ///< Runs SM fermion masses to MZ /// Print out the Standard Model data being used, as well as quark mixing /// assumption and the numerical accuracy of the solution cerr << "Low energy data in SOFTSUSY: MIXING=" << MIXING << " TOLERANCE=" << TOLERANCE << endl << oneset << endl; /// set parameters double tanb = 10.; int sgnMu = 1; double mgutGuess = 2.e16; double a0 = 0.0, m12 = 500.0, m0 = 125.0; /// number of points for scan const int numPoints = 20; /// parameter region double Start = 0. , End = 0.4; DoubleVector pars(3); /// set basic entries in pars pars(1) = m0; pars(2) = m12; pars(3) = a0; cout << "# l''_{323}(M_X) m_stop_R # Problem flag" << endl; /// loop over parameter space region int ii; for (ii=0; ii<=numPoints; ii++){ double lambda = Start + ((End - Start) / double(numPoints) * double(ii)); /// define rpvSoftsusy object RpvSoftsusy kw; /// set lambda coupling at mgut kw.setLamPrimePrime(3, 2, 3, lambda); /// output parameters into double vector pars used by lowOrg kw.rpvDisplay(pars); /// generate spectrum in RpvSoftsusy object kw kw.lowOrg(rpvSugraBcs, mgutGuess, pars, sgnMu, tanb, oneset, gaugeUnification, ewsbBCscale); /// outputs for this scan cout << lambda << " " << kw.displayPhys().mu(2, 3) << " # " << kw.displayProblem() << endl; } } catch(const string & a) { cout << a; return -1; } catch(const char *a) { printf("%s", a); return -1; } return 0; }
int main(int argc, char *argv[]) { #ifdef __FreeBSD__ FILE *fpid = NULL; #endif fd_set *fdsr = NULL, *fdsw = NULL; struct sockaddr_in sin; struct sockaddr_in lin; int ch, s, s2, conflisten = 0, syncfd = 0, i, omax = 0, one = 1; socklen_t sinlen; u_short port; struct servent *ent; struct rlimit rlp; char *bind_address = NULL; const char *errstr; char *sync_iface = NULL; char *sync_baddr = NULL; tzset(); openlog_r("spamd", LOG_PID | LOG_NDELAY, LOG_DAEMON, &sdata); if ((ent = getservbyname("spamd", "tcp")) == NULL) errx(1, "Can't find service \"spamd\" in /etc/services"); port = ntohs(ent->s_port); if ((ent = getservbyname("spamd-cfg", "tcp")) == NULL) errx(1, "Can't find service \"spamd-cfg\" in /etc/services"); cfg_port = ntohs(ent->s_port); if ((ent = getservbyname("spamd-sync", "udp")) == NULL) errx(1, "Can't find service \"spamd-sync\" in /etc/services"); sync_port = ntohs(ent->s_port); if (gethostname(hostname, sizeof hostname) == -1) err(1, "gethostname"); maxfiles = get_maxfiles(); if (maxcon > maxfiles) maxcon = maxfiles; if (maxblack > maxfiles) maxblack = maxfiles; while ((ch = #ifndef __FreeBSD__ getopt(argc, argv, "45l:c:B:p:bdG:h:s:S:M:n:vw:y:Y:")) != -1) { #else getopt(argc, argv, "45l:c:B:p:bdG:h:s:S:M:n:vw:y:Y:t:m:")) != -1) { #endif switch (ch) { case '4': nreply = "450"; break; case '5': nreply = "550"; break; case 'l': bind_address = optarg; break; case 'B': i = atoi(optarg); maxblack = i; break; case 'c': i = atoi(optarg); if (i > maxfiles) { fprintf(stderr, "%d > system max of %d connections\n", i, maxfiles); usage(); } maxcon = i; break; case 'p': i = atoi(optarg); port = i; break; case 'd': debug = 1; break; case 'b': greylist = 0; break; case 'G': if (sscanf(optarg, "%d:%d:%d", &passtime, &greyexp, &whiteexp) != 3) usage(); /* convert to seconds from minutes */ passtime *= 60; /* convert to seconds from hours */ whiteexp *= (60 * 60); /* convert to seconds from hours */ greyexp *= (60 * 60); break; case 'h': bzero(&hostname, sizeof(hostname)); if (strlcpy(hostname, optarg, sizeof(hostname)) >= sizeof(hostname)) errx(1, "-h arg too long"); break; case 's': i = atoi(optarg); if (i < 0 || i > 10) usage(); stutter = i; break; case 'S': /* * strtonum is aviable with FreeBSD 6.1, * for older versions we have to fallback */ i = strtonum(optarg, 0, 90, &errstr); if (errstr) usage(); grey_stutter = i; break; case 'M': low_prio_mx_ip = optarg; break; case 'n': spamd = optarg; break; case 'v': verbose = 1; break; case 'w': window = atoi(optarg); if (window <= 0) usage(); break; case 'Y': if (sync_addhost(optarg, sync_port) != 0) sync_iface = optarg; syncsend++; break; case 'y': sync_baddr = optarg; syncrecv++; break; #ifdef __FreeBSD__ case 't': ipfw_tabno = atoi(optarg); break; case 'm': if (strcmp(optarg, "ipfw") == 0) use_pf=0; break; #endif default: usage(); break; } } setproctitle("[priv]%s%s", greylist ? " (greylist)" : "", (syncrecv || syncsend) ? " (sync)" : ""); if (!greylist) maxblack = maxcon; else if (maxblack > maxcon) usage(); rlp.rlim_cur = rlp.rlim_max = maxcon + 15; if (setrlimit(RLIMIT_NOFILE, &rlp) == -1) err(1, "setrlimit"); con = calloc(maxcon, sizeof(*con)); if (con == NULL) err(1, "calloc"); con->obuf = malloc(8192); if (con->obuf == NULL) err(1, "malloc"); con->osize = 8192; for (i = 0; i < maxcon; i++) con[i].fd = -1; signal(SIGPIPE, SIG_IGN); s = socket(AF_INET, SOCK_STREAM, 0); if (s == -1) err(1, "socket"); if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) return (-1); conflisten = socket(AF_INET, SOCK_STREAM, 0); if (conflisten == -1) err(1, "socket"); if (setsockopt(conflisten, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) return (-1); memset(&sin, 0, sizeof sin); sin.sin_len = sizeof(sin); if (bind_address) { if (inet_pton(AF_INET, bind_address, &sin.sin_addr) != 1) err(1, "inet_pton"); } else sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_family = AF_INET; sin.sin_port = htons(port); if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1) err(1, "bind"); memset(&lin, 0, sizeof sin); lin.sin_len = sizeof(sin); lin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); lin.sin_family = AF_INET; lin.sin_port = htons(cfg_port); if (bind(conflisten, (struct sockaddr *)&lin, sizeof lin) == -1) err(1, "bind local"); if (syncsend || syncrecv) { syncfd = sync_init(sync_iface, sync_baddr, sync_port); if (syncfd == -1) err(1, "sync init"); } pw = getpwnam("_spamd"); if (!pw) pw = getpwnam("nobody"); #ifdef __FreeBSD__ /* open the pid file just before daemon */ fpid = fopen(pid_file, "w"); if (fpid == NULL) { syslog(LOG_ERR, "exiting (couldn't create pid file %s)", pid_file); err(1, "couldn't create pid file \"%s\"", pid_file); } #endif if (debug == 0) { if (daemon(1, 1) == -1) err(1, "daemon"); } if (greylist) { #ifdef __FreeBSD__ if(use_pf){ #endif pfdev = open("/dev/pf", O_RDWR); if (pfdev == -1) { syslog_r(LOG_ERR, &sdata, "open /dev/pf: %m"); exit(1); } #ifdef __FreeBSD__ } #endif maxblack = (maxblack >= maxcon) ? maxcon - 100 : maxblack; if (maxblack < 0) maxblack = 0; /* open pipe to talk to greylister */ if (pipe(greypipe) == -1) { syslog(LOG_ERR, "pipe (%m)"); exit(1); } /* open pipe to recieve spamtrap configs */ if (pipe(trappipe) == -1) { syslog(LOG_ERR, "pipe (%m)"); exit(1); } jail_pid = fork(); switch (jail_pid) { case -1: syslog(LOG_ERR, "fork (%m)"); exit(1); case 0: /* child - continue */ signal(SIGPIPE, SIG_IGN); grey = fdopen(greypipe[1], "w"); if (grey == NULL) { syslog(LOG_ERR, "fdopen (%m)"); _exit(1); } close(greypipe[0]); trapfd = trappipe[0]; trapcfg = fdopen(trappipe[0], "r"); if (trapcfg == NULL) { syslog(LOG_ERR, "fdopen (%m)"); _exit(1); } close(trappipe[1]); goto jail; } /* parent - run greylister */ grey = fdopen(greypipe[0], "r"); if (grey == NULL) { syslog(LOG_ERR, "fdopen (%m)"); exit(1); } close(greypipe[1]); trapcfg = fdopen(trappipe[1], "w"); if (trapcfg == NULL) { syslog(LOG_ERR, "fdopen (%m)"); exit(1); } close(trappipe[0]); return (greywatcher()); /* NOTREACHED */ } jail: #ifdef __FreeBSD__ /* after switch user and daemon write and close the pid file */ if (fpid) { fprintf(fpid, "%ld\n", (long) getpid()); if (fclose(fpid) == EOF) { syslog(LOG_ERR, "exiting (couldn't close pid file %s)", pid_file); exit(1); } } #endif if (chroot("/var/empty") == -1 || chdir("/") == -1) { syslog(LOG_ERR, "cannot chdir to /var/empty."); exit(1); } if (pw) if (setgroups(1, &pw->pw_gid) || setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) || setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) err(1, "failed to drop privs"); if (listen(s, 10) == -1) err(1, "listen"); if (listen(conflisten, 10) == -1) err(1, "listen"); if (debug != 0) printf("listening for incoming connections.\n"); syslog_r(LOG_WARNING, &sdata, "listening for incoming connections."); while (1) { struct timeval tv, *tvp; int max, n; int writers; max = MAX(s, conflisten); if (syncrecv) max = MAX(max, syncfd); max = MAX(max, conffd); max = MAX(max, trapfd); time(&t); for (i = 0; i < maxcon; i++) if (con[i].fd != -1) max = MAX(max, con[i].fd); if (max > omax) { free(fdsr); fdsr = NULL; free(fdsw); fdsw = NULL; fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS), sizeof(fd_mask)); if (fdsr == NULL) err(1, "calloc"); fdsw = (fd_set *)calloc(howmany(max+1, NFDBITS), sizeof(fd_mask)); if (fdsw == NULL) err(1, "calloc"); omax = max; } else { memset(fdsr, 0, howmany(max+1, NFDBITS) * sizeof(fd_mask)); memset(fdsw, 0, howmany(max+1, NFDBITS) * sizeof(fd_mask)); } writers = 0; for (i = 0; i < maxcon; i++) { if (con[i].fd != -1 && con[i].r) { if (con[i].r + MAXTIME <= t) { closecon(&con[i]); continue; } FD_SET(con[i].fd, fdsr); } if (con[i].fd != -1 && con[i].w) { if (con[i].w + MAXTIME <= t) { closecon(&con[i]); continue; } if (con[i].w <= t) FD_SET(con[i].fd, fdsw); writers = 1; } } FD_SET(s, fdsr); /* only one active config conn at a time */ if (conffd == -1) FD_SET(conflisten, fdsr); else FD_SET(conffd, fdsr); if (trapfd != -1) FD_SET(trapfd, fdsr); if (syncrecv) FD_SET(syncfd, fdsr); if (writers == 0) { tvp = NULL; } else { tv.tv_sec = 1; tv.tv_usec = 0; tvp = &tv; } n = select(max+1, fdsr, fdsw, NULL, tvp); if (n == -1) { if (errno != EINTR) err(1, "select"); continue; } if (n == 0) continue; for (i = 0; i < maxcon; i++) { if (con[i].fd != -1 && FD_ISSET(con[i].fd, fdsr)) handler(&con[i]); if (con[i].fd != -1 && FD_ISSET(con[i].fd, fdsw)) handlew(&con[i], clients + 5 < maxcon); } if (FD_ISSET(s, fdsr)) { sinlen = sizeof(sin); s2 = accept(s, (struct sockaddr *)&sin, &sinlen); if (s2 == -1) /* accept failed, they may try again */ continue; for (i = 0; i < maxcon; i++) if (con[i].fd == -1) break; if (i == maxcon) close(s2); else { initcon(&con[i], s2, (struct sockaddr *)&sin); syslog_r(LOG_INFO, &sdata, "%s: connected (%d/%d)%s%s", con[i].addr, clients, blackcount, ((con[i].lists == NULL) ? "" : ", lists:"), ((con[i].lists == NULL) ? "": con[i].lists)); } } if (FD_ISSET(conflisten, fdsr)) { sinlen = sizeof(lin); conffd = accept(conflisten, (struct sockaddr *)&lin, &sinlen); if (conffd == -1) /* accept failed, they may try again */ continue; else if (ntohs(lin.sin_port) >= IPPORT_RESERVED) { close(conffd); conffd = -1; } } if (conffd != -1 && FD_ISSET(conffd, fdsr)) do_config(); if (trapfd != -1 && FD_ISSET(trapfd, fdsr)) read_configline(trapcfg); if (syncrecv && FD_ISSET(syncfd, fdsr)) sync_recv(); } exit(1); }