bool SessionManager::checkInvitationQueue() { // The user is currently busy with an action. Defer invitation processing // until the user is free. int x, y; Gdk::ModifierType mt; Gdk::Display::get_default()->get_pointer(x, y, mt); if (mt & GDK_BUTTON1_MASK) return true; if (invitations.size() > 0) { // There's an invitation to process; process it. Invitation invitation = invitations.front(); Glib::ustring from = invitation.first; Glib::ustring sessionId = invitation.second; Glib::ustring primary = "<span weight=\"bold\" size=\"larger\">" + String::ucompose(_("<b>%1</b> has invited you to a whiteboard session."), from) + "</span>\n\n" + String::ucompose(_("Do you wish to accept <b>%1</b>'s whiteboard session invitation?"), from); InvitationConfirmDialog dialog(primary); dialog.add_button(_("Accept invitation"), Dialog::ACCEPT_INVITATION); dialog.add_button(_("Decline invitation"), Dialog::DECLINE_INVITATION); Dialog::DialogReply reply = static_cast< Dialog::DialogReply >(dialog.run()); SPDocument* doc = makeInkboardDocument(g_quark_from_static_string("xml"), "svg:svg", State::WHITEBOARD_PEER, from); InkboardDocument* inkdoc = dynamic_cast< InkboardDocument* >(doc->rdoc); if(inkdoc == NULL) return true; inkdoc->handleState(State::INITIAL,State::CONNECTING); inkdoc->setSessionId(sessionId); addSession(WhiteboardRecord(sessionId, inkdoc)); switch (reply) { case Dialog::ACCEPT_INVITATION:{ inkdoc->send(from, Message::PROTOCOL,Message::ACCEPT_INVITATION); makeInkboardDesktop(doc); break; } case Dialog::DECLINE_INVITATION: default: { inkdoc->send(from, Message::PROTOCOL,Message::DECLINE_INVITATION); terminateSession(sessionId); break; } } invitations.pop_front(); } return true; }
SessionPtr WebUserManager::authenticate(const string& aUserName, const string& aPassword, bool aIsSecure, uint64_t aMaxInactivityMinutes, bool aUserSession) noexcept { auto u = getUser(aUserName); if (!u) { return nullptr; } if (u->getPassword() != aPassword) { return nullptr; } u->setLastLogin(GET_TIME()); u->addSession(); fire(WebUserManagerListener::UserUpdated(), u); auto uuid = boost::uuids::random_generator()(); auto session = std::make_shared<Session>(u, boost::uuids::to_string(uuid), aIsSecure, server, aMaxInactivityMinutes, aUserSession); { WLock l(cs); sessionsRemoteId.emplace(session->getAuthToken(), session); sessionsLocalId.emplace(session->getId(), session); } if (aUserSession) { ActivityManager::getInstance()->updateActivity(); } return session; }
/** * popuplate the side bar with all sessions inside the current window. Information * is gathered from the tab control, which remains active (but invisible) when the * switch bar is in use. * * This is needed when the user switches from tabs to a switchbar layout while a * window is open. */ void CSideBar::populateAll() { HWND hwndTab = ::GetDlgItem(m_pContainer->hwnd, IDC_MSGTABS); if (hwndTab == NULL) return; int iItems = (int)TabCtrl_GetItemCount(hwndTab); TCITEM item = { 0 }; item.mask = TCIF_PARAM; m_iTopButtons = 0; for (int i = 0; i < iItems; i++) { TabCtrl_GetItem(hwndTab, i, &item); if (item.lParam == 0 || !IsWindow((HWND)item.lParam)) continue; TWindowData *dat = (TWindowData*)::GetWindowLongPtr((HWND)item.lParam, GWLP_USERDATA); if (dat == NULL) continue; CSideBarButton *b_item = findSession(dat); if (b_item == NULL) addSession(dat, i); else { b_item->setLayout(m_currentLayout); if (m_dwFlags & SIDEBARLAYOUT_VERTICALORIENTATION) { b_item->measureItem(); m_topHeight += b_item->getHeight() + 1; } else m_topHeight += m_elementHeight + 1; } } }
bool Beacon::StartActiveSession(const IpAddr &remoteAddr, const IpAddr &localAddr) { Session *session = NULL; LogAssert(m_scheduler->IsMainThread()); session = findInSourceMap(remoteAddr, localAddr); if (session) { if (session->IsActiveSession()) return true; if (!session->UpgradeToActiveSession()) { LogOptional(Log::Session, "Failed to upgrade Session id=%u for %s to %s is to an active session.", session->GetId(), localAddr.ToString(), remoteAddr.ToString() ); return false; } LogOptional(Log::Session, "Session id=%u for %s to %s is now an active session.", session->GetId(), localAddr.ToString(), remoteAddr.ToString() ); return true; } else { session = addSession(remoteAddr, localAddr); if (!session) return false; LogOptional(Log::Session, "Manually added new session for %s to %s id=%u.", localAddr.ToString(), remoteAddr.ToString(), session->GetId()); if (!session->StartActiveSession(remoteAddr, localAddr)) { LogOptional(Log::Session, "Failed to start active session id=%u for %s to %s.", session->GetId(), localAddr.ToString(), remoteAddr.ToString() ); return false; } LogOptional(Log::Session, "Session id=%u for %s to %s is started as an active session.", session->GetId(), localAddr.ToString(), remoteAddr.ToString() ); return true; } }
void ObexManagerPrivate::interfacesAdded(const QDBusObjectPath &objectPath, const QVariantMapMap &interfaces) { const QString &path = objectPath.path(); QVariantMapMap::const_iterator it; for (it = interfaces.constBegin(); it != interfaces.constEnd(); ++it) { if (it.key() == Strings::orgBluezObexSession1()) { addSession(path, it.value()); } } }
void SessionTreeControl::addAudioSessionEvent( wxCommandEvent& evt ) { wxTextEntryDialog dialog( this, _("Enter session in format address/port"), _("Add New Audio Session") ); if ( dialog.ShowModal() == wxID_OK ) { std::string address( dialog.GetValue().char_str() ); addSession( address, true, false ); } }
__private_extern__ void server_init() { serverSessionRef mySession; CFRunLoopSourceRef rls; char *service_name; mach_port_t service_port = MACH_PORT_NULL; kern_return_t status; service_name = getenv("SCD_SERVER"); if (!service_name) { service_name = SCD_SERVER; } /* Check "configd" server status */ status = bootstrap_check_in(bootstrap_port, service_name, &service_port); switch (status) { case BOOTSTRAP_SUCCESS : /* if we are being [re-]started by launchd */ break; case BOOTSTRAP_NOT_PRIVILEGED : /* if another instance of the server is starting */ SCLog(TRUE, LOG_ERR, CFSTR("'%s' server already starting"), service_name); exit (EX_UNAVAILABLE); case BOOTSTRAP_SERVICE_ACTIVE : /* if another instance of the server is active */ SCLog(TRUE, LOG_ERR, CFSTR("'%s' server already active"), service_name); exit (EX_UNAVAILABLE); default : SCLog(TRUE, LOG_ERR, CFSTR("server_init bootstrap_check_in(..., '%s', ...) failed: %s"), service_name, bootstrap_strerror(status)); exit (EX_UNAVAILABLE); } /* Create the primary / new connection port and backing session */ mySession = addSession(service_port, serverMPCopyDescription); configd_port = mySession->serverPort; /* * Create and add a run loop source for the port and add this source * to the default run loop mode. */ rls = CFMachPortCreateRunLoopSource(NULL, configd_port, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode); CFRelease(rls); return; }
void TcpServerDispatcher::onPost(ec::Data &data) { ec::TcpServerDispatcher::NewSessionData sessionData = data.get<ec::TcpServerDispatcher::NewSessionData>(); TcpSessionPtr session(new TcpSession(this, sessionData.id)); session->attach(sessionData.sock); if (!session->isInited()) { return; } addSession(session); getServer()->onNewSession(session.get()); }
static PSPAMResult_t handleOpenRequest(char *msgBuf) { char user[USERNAME_LEN], rhost[HOSTNAME_LEN]; pid_t pid, sid; struct passwd *spasswd; User_t *pamUser; PSPAMResult_t res = PSPAM_RES_DENY; char *ptr = msgBuf; /* ensure we use the same byteorder as the PAM module */ bool byteOrder = setByteOrder(true); /* get ssh pid */ getPid(&ptr, &pid); /* get ssh sid */ getPid(&ptr, &sid); /* get pam username */ getString(&ptr, user, sizeof(user)); /* get pam rhost */ getString(&ptr, rhost, sizeof(rhost)); /* reset psserial's byteorder */ setByteOrder(byteOrder); mdbg(PSPAM_LOG_DEBUG, "%s: got pam request user: '******' pid: %i sid: %i" " rhost: '%s'\n", __func__, user, pid, sid, rhost); errno = 0; spasswd = getpwnam(user); if (!spasswd && errno) mwarn(errno, "%s: getpwnam(%s)", __func__, user); pamUser = findUser(user, NULL); /* Determine user's allowance */ if (spasswd && isPSAdminUser(spasswd->pw_uid, spasswd->pw_gid)) { res = PSPAM_RES_ADMIN_USER; } else if (pamUser) { if (pamUser->state == PSPAM_STATE_PROLOGUE) { res = PSPAM_RES_PROLOG; } else { res = PSPAM_RES_BATCH; addSession(user, rhost, pid, sid); } } mdbg(PSPAM_LOG_DEBUG, "%s: reply to user '%s' rhost '%s': %i\n", __func__, user, rhost, res); return res; }
void MainWindow::setupClassViewer() { tbtnAdd_class->setAction(actionAdd_class, true); tbtnAdd_class->setText(tr("Add")); tbtnAdd_class->setIconSize(QSize(16, 16)); tbtnDelete_class->setAction(actionDelete_class, true); tbtnDelete_class->setText(tr("Delete")); tbtnDelete_class->setIconSize(QSize(16, 16)); tbtnAdd_student->setAction(actionAdd_student, true); tbtnAdd_student->setText(tr("Add")); tbtnAdd_student->setIconSize(QSize(16, 16)); tbtnDelete_student->setAction(actionDelete_student, true); tbtnDelete_student->setText(tr("Delete")); tbtnDelete_student->setIconSize(QSize(16, 16)); tbtnAdd_session->setAction(actionAdd_session, true); tbtnAdd_session->setText(tr("Add")); tbtnAdd_session->setIconSize(QSize(16, 16)); tbtnDelete_session->setAction(actionDelete_session, true); tbtnDelete_session->setText(tr("Delete")); tbtnDelete_session->setIconSize(QSize(16, 16)); QObject::connect(actionAdd_class, SIGNAL(triggered()), this, SLOT(addClass())); QObject::connect(actionDelete_class, SIGNAL(triggered()), this, SLOT(deleteClass())); QObject::connect(actionPrint_class_summary, SIGNAL(triggered()), this, SLOT(printClassSummary())); QObject::connect(actionAdd_student, SIGNAL(triggered()), this, SLOT(addStudent())); QObject::connect(actionDelete_student, SIGNAL(triggered()), this, SLOT(deleteStudent())); QObject::connect(actionAdd_session, SIGNAL(triggered()), this, SLOT(addSession())); QObject::connect(actionDelete_session, SIGNAL(triggered()), this, SLOT(deleteSession())); QObject::connect(CLSCFirstYearSpinBox, SIGNAL(valueChanged(int)), CLSCLastYearSpinBox, SLOT(setMinimum(int))); QObject::connect(CLLCListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(setCurrentClass(QListWidgetItem *))); QObject::connect(CLLSListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(setCurrentClassMember(QListWidgetItem *))); QObject::connect(CLLSSListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(viewSession(QListWidgetItem *))); QObject::connect(CLLSSListWidget, SIGNAL(currentIndexAvailabilityChanged(bool)), actionDelete_session, SLOT(setEnabled(bool))); QObject::connect(CLLSSListWidget, SIGNAL(currentTextChanged(QString)), this, SLOT(toggleAddSessionToMemberEnabled())); QObject::connect(CLSSResultsTableWidget, SIGNAL(currentIndexAvailabilityChanged(bool)), tbtnRemoveSession, SLOT(setEnabled(bool))); QObject::connect(CLSSResultsTableWidget, SIGNAL(itemDoubleClicked(QTableWidgetItem *)), this, SLOT(viewSessionAndStudent(QTableWidgetItem *))); QObject::connect(CLLCSearchLineEdit, SIGNAL(textChanged(QLineEdit *, const QString &)), CLLCListWidget, SLOT(filterItems(QLineEdit *, const QString &))); QObject::connect(CLLSSearchLineEdit, SIGNAL(textChanged(QLineEdit *, const QString &)), CLLSListWidget, SLOT(filterItems(QLineEdit *, const QString &))); QObject::connect(CLLSSSearchLineEdit, SIGNAL(textChanged(QLineEdit *, const QString &)), CLLSSListWidget, SLOT(filterItems(QLineEdit *, const QString &))); QObject::connect(tbtnApplyClassChanges, SIGNAL(released()), this, SLOT(updateClassProperties())); QObject::connect(tbtnSaveMemberName, SIGNAL(released()), this, SLOT(updateClassMemberName())); QObject::connect(tbtnAddSession, SIGNAL(released()), this, SLOT(addSessionToMember())); QObject::connect(tbtnRemoveSession, SIGNAL(released()), this, SLOT(removeSessionFromMember())); CLLCListWidget->setSortingEnabled(true); CLLSSListWidget->setSortingEnabled(true); CLSSResultsTableWidget->horizontalHeader()->setResizeMode(QHeaderView::Stretch); CLSSResultsTableWidget->verticalHeader()->hide(); CLSSResultsTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); setCLSCEnabled(false); }
LLUUID LLIMMgr::addP2PSession(const std::string& name, const LLUUID& other_participant_id, const std::string& voice_session_handle, const std::string& caller_uri) { LLUUID session_id = addSession(name, IM_NOTHING_SPECIAL, other_participant_id); LLFloaterIMPanel* floater = findFloaterBySession(session_id); if(floater) { LLVoiceChannelP2P* voice_channelp = (LLVoiceChannelP2P*)floater->getVoiceChannel(); voice_channelp->setSessionHandle(voice_session_handle, caller_uri); } return session_id; }
// // Joins the indicated file on behalf of the default procid. Joining a file // means that any file-scoped patterns for this procid are updated to // contain this file. It also means we have to indicated to procids in // other sessions that this procid is interested in messages addressed to // this file. This is done by storing the session for this procid in a // persistent property on this file. The details of that are in // _Tt_file::add_joined_file. Another responsibility of this method is to // process any queued messages that are destined for any ptype declared // by p. This client/server division in the way file-scope queued // messages are implemented reflects a goal of offloading any // computation from the server to its clients. This is specially true // of any computation that involves communicating with the database // servers. // // XXX: it's misleading to have a _Tt_procid_ptr input arg here when // in fact the default procid joins the file, not the specified // procid. Either figure out how to join the specified procid or // remove the parameter. // Tt_status _Tt_c_file::c_join( _Tt_procid_ptr & ) { Tt_status status; Tt_status rs; _Tt_db_results dbStatus; _Tt_file_join_args args; _Tt_session_ptr d_session; _Tt_c_procid *sp; sp = (_Tt_c_procid *)_tt_c_mp->default_procid().c_pointer(); args.procid = _tt_c_mp->default_procid(); args.path = getNetworkPath(); d_session = sp->default_session(); rs = d_session->call(TT_RPC_JOIN_FILE, (xdrproc_t)tt_xdr_file_join_args, (char *)&args, (xdrproc_t)xdr_int, (char *)&status); if (status == TT_WRN_NOTFOUND) { // No file patterns updated on the server side. status = TT_OK; } else { sp->add_joined_file(getNetworkPath()); // add our session to the list of sessions // interested in this file. if (status == TT_WRN_STALE_OBJID) { dbStatus = addSession(d_session->process_tree_id()); status = _tt_get_api_error( dbStatus, _TT_API_FILE ); if (status == TT_ERR_INTERNAL) { _tt_syslog( 0, LOG_WARNING, "_Tt_db_file::addSession(): %d", dbStatus ); } } if (status != TT_OK) { return status; } // process any queued messages on this file // for any of the ptypes we've declared. process_message_queue(); } return((rs == TT_OK) ? status : rs); }
void TEDemo::newSession(int i) { char* shell = getenv("SHELL"); if (shell == NULL || *shell == '\0') shell = "/bin/sh"; KSimpleConfig* co = no2command.find(i); if (!co) return; // oops assert( se ); //FIXME: careful here. QString cmd = co->readEntry("Exec"); // not null QString nam = co->readEntry("Name"); // not null QString emu = co->readEntry("Term"); QString sch = co->readEntry("Schema"); QString txt = co->readEntry("Comment"); // not null int fno = QMIN(co->readUnsignedNumEntry("Font",se->fontNo()),7); ColorSchema* schema = sch.isEmpty() ? (ColorSchema*)NULL : ColorSchema::find(sch); //FIXME: schema names here are absolut. Wrt. loadAllSchemas, // relative pathes should be allowed, too. int schmno = schema?schema->numb:se->schemaNo(); if (emu.isEmpty()) emu = se->emuName(); QStrList args; args.append(shell); args.append("-c"); args.append(cmd); TESession* s = new TESession(this,te,args,emu.data(),0); s->setFontNo(fno); s->setSchemaNo(schmno); s->setTitle(txt.data()); addSession(s); runSession(s); // activate and run }
void ObexManagerPrivate::getManagedObjectsFinished(QDBusPendingCallWatcher *watcher) { const QDBusPendingReply<DBusManagerStruct> &reply = *watcher; watcher->deleteLater(); if (reply.isError()) { Q_EMIT initError(reply.error().message()); return; } DBusManagerStruct::const_iterator it; const DBusManagerStruct &managedObjects = reply.value(); for (it = managedObjects.constBegin(); it != managedObjects.constEnd(); ++it) { const QString &path = it.key().path(); const QVariantMapMap &interfaces = it.value(); if (interfaces.contains(Strings::orgBluezObexSession1())) { addSession(path, interfaces.value(Strings::orgBluezObexSession1())); } else if (interfaces.contains(Strings::orgBluezObexClient1()) && interfaces.contains(Strings::orgBluezObexAgentManager1())) { m_obexClient = new ObexClient(Strings::orgBluezObex(), path, DBusConnection::orgBluezObex(), this); m_obexAgentManager = new ObexAgentManager(Strings::orgBluezObex(), path, DBusConnection::orgBluezObex(), this); } } if (!m_obexClient) { Q_EMIT initError(QStringLiteral("Cannot find org.bluez.obex.Client1 object!")); return; } if (!m_obexAgentManager) { Q_EMIT initError(QStringLiteral("Cannot find org.bluez.obex.AgentManager1 object!")); return; } m_loaded = true; m_initialized = true; Q_EMIT q->operationalChanged(true); Q_EMIT initFinished(); }
/** * Initiates a shared session with a user or conference room. * * \param to The recipient to which this desktop will be linked, specified as a JID. * \param type Type of the session; i.e. private message or group chat. */ void SessionManager::initialiseSession(Glib::ustring const& to, State::SessionType type) { SPDocument* doc = makeInkboardDocument(g_quark_from_static_string("xml"), "svg:svg", type, to); InkboardDocument* inkdoc = dynamic_cast< InkboardDocument* >(doc->rdoc); if(inkdoc == NULL) return; if(type == State::WHITEBOARD_PEER) { ChooseDesktop dialog; int result = dialog.run(); if(result == Gtk::RESPONSE_OK) { SPDesktop *desktop = dialog.getDesktop(); if(desktop != NULL) { Inkscape::XML::Document *old_doc = sp_desktop_document(desktop)->rdoc; inkdoc->root()->mergeFrom(old_doc->root(),"id"); } }else { return; } } char * sessionId = createSessionId(10); inkdoc->setSessionId(sessionId); makeInkboardDesktop(doc); addSession(WhiteboardRecord(sessionId, inkdoc)); inkdoc->startSessionNegotiation(); }
// ----------------------------------------- // entry point // ----------------------------------------- int main(int argc, char** argv) { #if AUDIO_STREAM StreamReplicator* audio_replicator = NULL; #endif // default parameters const char *dev_name = "/dev/video1"; int format = V4L2_PIX_FMT_H264; int width = 1280; int height = 720; int queueSize = 10; int fps = 30; int isp_fps = 30; int bitrate = 1024; //(Kbps) int mjpeg_qp = 120; int m2m_en = 1; int gop = fps; unsigned short rtpPortNum = 20000; unsigned short rtcpPortNum = rtpPortNum+1; unsigned char ttl = 5; struct in_addr destinationAddress; unsigned short rtspPort = 554; unsigned short rtspOverHTTPPort = 0; bool multicast = false; int verbose = 0; std::string outputFile; //bool useMmap = true; std::string url = "unicast"; std::string murl = "multicast"; bool useThread = true; in_addr_t maddr = INADDR_NONE; bool audio_en = false; // decode parameters int c = 0; //while ((c = getopt (argc, argv, "hW:H:Q:P:F:v::O:T:m:u:rsM:")) != -1) #if AUDIO_STREAM while ((c = getopt (argc, argv, "hb:W:H:g:Q:P:F:i:O:T:m:u:M:aj:")) != -1) #else while ((c = getopt (argc, argv, "hb:W:H:g:Q:P:F:i:O:T:m:u:M:j:")) != -1) #endif { switch (c) { case 'O': outputFile = optarg; break; //case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'm': multicast = true; if (optarg) murl = optarg; break; case 'M': multicast = true; if (optarg) maddr = inet_addr(optarg); break; case 'g': gop = atoi(optarg); break; case 'b': bitrate = atoi(optarg); break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'Q': queueSize = atoi(optarg); break; case 'P': rtspPort = atoi(optarg); break; case 'T': rtspOverHTTPPort = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'i': isp_fps = atoi(optarg); break; //case 'r': useMmap = false; break; //case 's': useThread = false; break; case 'u': url = optarg; break; #if AUDIO_STREAM case 'a': audio_en = true; break; #endif case 'j': format = V4L2_PIX_FMT_MJPEG; mjpeg_qp = atoi(optarg);break; case 'h': default: { std::cout << argv[0] << "Version:" << SNX_RTSP_SERVER_VERSION << std::endl; std::cout << "Usage :" << std::endl; std::cout << "\t " << argv[0] << " [-a] [-j mjpeg_qp] [-m] [-P RTSP port][-T RTSP/HTTP port][-Q queueSize] [-M groupaddress] [-b bitrate] [-W width] [-H height] [-F fps] [-i isp_fps] [device]" << std::endl; std::cout << "\t -Q length: Number of frame queue (default "<< queueSize << ")" << std::endl; std::cout << "\t RTSP options :" << std::endl; std::cout << "\t -u url : unicast url (default " << url << ")" << std::endl; std::cout << "\t -m url : multicast url (default " << murl << ")" << std::endl; std::cout << "\t -M addr : multicast group (default is a random address)" << std::endl; std::cout << "\t -P port : RTSP port (default "<< rtspPort << ")" << std::endl; std::cout << "\t -T port : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")" << std::endl; std::cout << "\t V4L2 options :" << std::endl; //std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; //std::cout << "\t -s : V4L2 capture using live555 mainloop (default use a separated reading thread)" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -i isp_fps : ISP capture framerate (default "<< isp_fps << ")" << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height : V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t V4L2 H264 options :" << std::endl; std::cout << "\t -b bitrate : V4L2 capture bitrate kbps(default "<< bitrate << " kbps)" << std::endl; std::cout << "\t -g gop : V4L2 capture gop (default "<< gop << " )" << std::endl; std::cout << "\t device : V4L2 capture device (default "<< dev_name << ")" << std::endl; std::cout << "\t V4L2 MJPEG options :" << std::endl; std::cout << "\t -j mjpeg_qp : MJPEG streaming and qp (default is 60)" << std::endl; #if AUDIO_STREAM std::cout << "\t -a : enable A-law pcm streaming " << std::endl; std::cout << "\t H264 example : "<< argv[0] << " -a -Q 5 -u media/stream1 -P 554" << std::endl; #else std::cout << "\t H264 example : "<< argv[0] << " -Q 5 -u media/stream1 -P 554" << std::endl; #endif std::cout << "\t MJPEG example : "<< argv[0] << " -W 640 -H 480 -j 120 -Q 5 -u media/stream1 -P 554" << std::endl; exit(0); } } } if (optind<argc) { dev_name = argv[optind]; } // create live555 environment scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); // create RTSP server rtspServer = RTSPServer::createNew(*env, rtspPort); if (rtspServer == NULL) { //LOG(ERROR) << "Failed to create RTSP server: " << env->getResultMsg(); fprintf(stderr, "Failed to create RTSP server: %s \n", env->getResultMsg()); } else { // set http tunneling if (rtspOverHTTPPort) { rtspServer->setUpTunnelingOverHTTP(rtspOverHTTPPort); } // Init capture //LOG(NOTICE) << "Create V4L2 Source..." << dev_name; fprintf(stderr, "create Video source = %s \n", dev_name); V4L2DeviceParameters param(dev_name,format,width,height,fps, isp_fps, verbose, bitrate, m2m_en, gop, mjpeg_qp, queueSize ); videoCapture = createVideoCapure(param); #if AUDIO_STREAM if (audio_en) { audioCapture = createAudioCapure(); } #endif if (videoCapture) { int outputFd = -1; //int outputFd = createOutput(outputFile, videoCapture->getFd()); //LOG(NOTICE) << "Start V4L2 Capture..." << dev_name; fprintf(stderr, "Start V4L2 Capture... %s \n", dev_name); //videoCapture->captureStart(); snx98600_video_start(videoCapture); printf("\n\n------- V4L2 Infomation -------- \n"); printf("m2m_en: %d\n", videoCapture->m2m->m2m); printf("codec_dev: %s\n", videoCapture->m2m->codec_dev); printf("codec_fps: %d\n", videoCapture->m2m->codec_fps); if(videoCapture->m2m->m2m) printf("isp_fps: %d\n", videoCapture->m2m->isp_fps); printf("width: %d\n", videoCapture->m2m->width); printf("height: %d\n", videoCapture->m2m->height); printf("scale: %d\n", videoCapture->m2m->scale); printf("bit_rate: %d\n", videoCapture->m2m->bit_rate); printf("dyn_fps_en: %d\n", videoCapture->m2m->dyn_fps_en); if(videoCapture->m2m->dyn_fps_en) { printf("framerate: %d\n", videoCapture->rate_ctl->framerate); } printf("GOP: %d\n", videoCapture->rate_ctl->gop); printf("ds_font_num: %d\n", videoCapture->m2m->ds_font_num); printf("\n----------------------------- \n\n"); #if AUDIO_STREAM /* Start Audio Device */ if (audio_en) { int rc; if (audioCapture) { if ((rc = snx98600_record_audio_start(audioCapture))) { fprintf(stderr, "failed to start audio source: %s\n", strerror(rc)); } } } #endif /* Determind which Class to use */ if (format == V4L2_PIX_FMT_H264) videoES = H264_V4L2DeviceSource::createNew(*env, param, outputFd, useThread); else { videoES = V4L2DeviceSource::createNew(*env, param, outputFd, useThread); } /* check if create a Device source success */ if (videoES == NULL) { //LOG(FATAL) << "Unable to create source for device " << dev_name; fprintf(stderr, "Unable to create source for device %s \n", dev_name); } else { videoCapture->devicesource = videoES; // Setup the outpacket size; if (m2m_en) { //OutPacketBuffer::maxSize = (unsigned int)videoCapture->m2m->isp_buffers->length; OutPacketBuffer::maxSize = bitrate << 8; //2X Bitrate as the max packet size fprintf(stderr, "isp buffers: %u , outpack maxsize : %u\n", (unsigned int)videoCapture->m2m->isp_buffers->length, OutPacketBuffer::maxSize ); }else { OutPacketBuffer::maxSize = width * height * 3 / 2; } #if AUDIO_STREAM /* create Alsa Device source Class */ if (audio_en && audioCapture) { audioES = AlsaDeviceSource::createNew(*env, -1, queueSize, useThread); if (audioES == NULL) { fprintf(stderr, "Unable to create audio devicesource \n"); } else { audioCapture->devicesource = audioES; } } #endif replicator = StreamReplicator::createNew(*env, videoES, false); #if AUDIO_STREAM if (audio_en && audioCapture) audio_replicator = StreamReplicator::createNew(*env, audioES, false); #endif // Create Server Multicast Session if (multicast) { ServerMediaSubsession * multicast_video_subSession = NULL; ServerMediaSubsession * multicast_audio_subSession = NULL; if (maddr == INADDR_NONE) maddr = chooseRandomIPv4SSMAddress(*env); destinationAddress.s_addr = maddr; //LOG(NOTICE) << "Mutlicast address " << inet_ntoa(destinationAddress); fprintf(stderr, "Mutlicast address %s \n", inet_ntoa(destinationAddress)); multicast_video_subSession = MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, replicator,format,param); #if AUDIO_STREAM if (audio_en && audioCapture) multicast_audio_subSession = MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, audio_replicator,WA_PCMA,param); #endif addSession(rtspServer, murl.c_str(), multicast_video_subSession, multicast_audio_subSession); } ServerMediaSubsession * video_subSession = NULL; ServerMediaSubsession * audio_subSession = NULL; video_subSession = UnicastServerMediaSubsession::createNew(*env,replicator,format, param); #if AUDIO_STREAM if (audio_en && audioCapture) audio_subSession = UnicastServerMediaSubsession::createNew(*env,audio_replicator,WA_PCMA, param); #endif // Create Server Unicast Session addSession(rtspServer, url.c_str(), video_subSession, audio_subSession); // main loop signal(SIGINT,sighandler); env->taskScheduler().doEventLoop(&quit); fprintf(stderr, "Exiting.... \n"); #if AUDIO_STREAM if (audioES) { Medium::close(audioES); } #endif Medium::close(videoES); } #if AUDIO_STREAM if (audio_en && audioCapture) closeAudioCapure(audioCapture); #endif if (videoCapture) closeVideoCapure(videoCapture); //delete videoCapture; if (outputFd != -1) { close(outputFd); } } Medium::close(rtspServer); } env->reclaim(); delete scheduler; return 0; }
// ----------------------------------------- // entry point // ----------------------------------------- int main(int argc, char** argv) { // default parameters const char *dev_name = "/dev/video0"; int format = V4L2_PIX_FMT_H264; int width = 640; int height = 480; int queueSize = 10; int fps = 25; unsigned short rtpPortNum = 20000; unsigned short rtcpPortNum = rtpPortNum+1; unsigned char ttl = 5; struct in_addr destinationAddress; unsigned short rtspPort = 8554; unsigned short rtspOverHTTPPort = 0; bool multicast = false; int verbose = 0; std::string outputFile; bool useMmap = false; // decode parameters int c = 0; while ((c = getopt (argc, argv, "hW:H:Q:P:F:v::O:T:mM")) != -1) { switch (c) { case 'O': outputFile = optarg; break; case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'm': multicast = true; break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'Q': queueSize = atoi(optarg); break; case 'P': rtspPort = atoi(optarg); break; case 'T': rtspOverHTTPPort = atoi(optarg); break; case 'F': fps = atoi(optarg); break; case 'M': useMmap = true; break; case 'h': { std::cout << argv[0] << " [-v[v]][-m] [-P RTSP port][-P RTSP/HTTP port][-Q queueSize] [-M] [-W width] [-H height] [-F fps] [-O file] [device]" << std::endl; std::cout << "\t -v : verbose " << std::endl; std::cout << "\t -v v : very verbose " << std::endl; std::cout << "\t -Q length: Number of frame queue (default "<< queueSize << ")" << std::endl; std::cout << "\t -O file : Dump capture to a file" << std::endl; std::cout << "\t RTSP options :" << std::endl; std::cout << "\t -m : Enable multicast output" << std::endl; std::cout << "\t -P port : RTSP port (default "<< rtspPort << ")" << std::endl; std::cout << "\t -H port : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")" << std::endl; std::cout << "\t V4L2 options :" << std::endl; std::cout << "\t -M : V4L2 capture using memory mapped buffers (default use read interface)" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height: V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t device : V4L2 capture device (default "<< dev_name << ")" << std::endl; exit(0); } } } if (optind<argc) { dev_name = argv[optind]; } // create live555 environment TaskScheduler* scheduler = BasicTaskScheduler::createNew(); UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler); // create RTSP server RTSPServer* rtspServer = RTSPServer::createNew(*env, rtspPort); if (rtspServer == NULL) { *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n"; } else { // set http tunneling if (rtspOverHTTPPort) { rtspServer->setUpTunnelingOverHTTP(rtspOverHTTPPort); } // Init capture *env << "Create V4L2 Source..." << dev_name << "\n"; V4L2DeviceParameters param(dev_name,format,width,height,fps,verbose); V4L2Device* videoCapture = NULL; if (useMmap) { videoCapture = V4L2MMAPDeviceSource::createNew(param); } else { videoCapture = V4L2READDeviceSource::createNew(param); } V4L2DeviceSource* videoES = V4L2DeviceSource::createNew(*env, param, videoCapture, outputFile, queueSize, verbose); if (videoES == NULL) { *env << "Unable to create source for device " << dev_name << "\n"; } else { destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env); OutPacketBuffer::maxSize = videoCapture->getBufferSize(); StreamReplicator* replicator = StreamReplicator::createNew(*env, videoES, false); // Create Server Multicast Session if (multicast) { addSession(rtspServer, "multicast", MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, 96, replicator,format)); } // Create Server Unicast Session addSession(rtspServer, "unicast", UnicastServerMediaSubsession::createNew(*env,replicator,format)); // main loop signal(SIGINT,sighandler); env->taskScheduler().doEventLoop(&quit); *env << "Exiting..\n"; } Medium::close(videoES); delete videoCapture; Medium::close(rtspServer); } env->reclaim(); delete scheduler; return 0; }
/* FIXME: implement Call Group ts offsets for soft changing of call groups */ void AmMediaProcessor::changeCallgroup(AmMediaSession* s, const string& new_callgroup) { removeFromProcessor(s, SoftRemoveSession); addSession(s, new_callgroup); }
// ----------------------------------------- // entry point // ----------------------------------------- int main(int argc, char** argv) { // default parameters const char *dev_name = "/dev/video0"; int format = V4L2_PIX_FMT_H264; int width = 640; int height = 480; int queueSize = 10; int fps = 25; unsigned short rtspPort = 8554; unsigned short rtspOverHTTPPort = 0; bool multicast = false; int verbose = 0; std::string outputFile; bool useMmap = true; std::string url = "unicast"; std::string murl = "multicast"; bool useThread = true; std::string maddr; bool repeatConfig = true; int timeout = 65; // decode parameters int c = 0; while ((c = getopt (argc, argv, "v::Q:O:" "I:P:T:m:u:M:ct:" "rsfF:W:H:" "h")) != -1) { switch (c) { case 'v': verbose = 1; if (optarg && *optarg=='v') verbose++; break; case 'Q': queueSize = atoi(optarg); break; case 'O': outputFile = optarg; break; // RTSP/RTP case 'I': ReceivingInterfaceAddr = inet_addr(optarg); break; case 'P': rtspPort = atoi(optarg); break; case 'T': rtspOverHTTPPort = atoi(optarg); break; case 'u': url = optarg; break; case 'm': multicast = true; murl = optarg; break; case 'M': multicast = true; maddr = optarg; break; case 'c': repeatConfig = false; break; case 't': timeout = atoi(optarg); break; // V4L2 case 'r': useMmap = false; break; case 's': useThread = false; break; case 'f': format = 0; break; case 'F': fps = atoi(optarg); break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case 'h': default: { std::cout << argv[0] << " [-v[v]] [-Q queueSize] [-O file]" << std::endl; std::cout << "\t [-I interface] [-P RTSP port] [-T RTSP/HTTP port] [-m multicast url] [-u unicast url] [-M multicast addr] [-c] [-t timeout]" << std::endl; std::cout << "\t [-r] [-s] [-W width] [-H height] [-F fps] [device] [device]" << std::endl; std::cout << "\t -v : verbose" << std::endl; std::cout << "\t -vv : very verbose" << std::endl; std::cout << "\t -Q length: Number of frame queue (default "<< queueSize << ")" << std::endl; std::cout << "\t -O output: Copy captured frame to a file or a V4L2 device" << std::endl; std::cout << "\t RTSP options :" << std::endl; std::cout << "\t -I addr : RTSP interface (default autodetect)" << std::endl; std::cout << "\t -P port : RTSP port (default "<< rtspPort << ")" << std::endl; std::cout << "\t -T port : RTSP over HTTP port (default "<< rtspOverHTTPPort << ")" << std::endl; std::cout << "\t -u url : unicast url (default " << url << ")" << std::endl; std::cout << "\t -m url : multicast url (default " << murl << ")" << std::endl; std::cout << "\t -M addr : multicast group:port (default is random_address:20000)" << std::endl; std::cout << "\t -c : don't repeat config (default repeat config before IDR frame)" << std::endl; std::cout << "\t -t secs : RTCP expiration timeout (default " << timeout << ")" << std::endl; std::cout << "\t V4L2 options :" << std::endl; std::cout << "\t -r : V4L2 capture using read interface (default use memory mapped buffers)" << std::endl; std::cout << "\t -s : V4L2 capture using live555 mainloop (default use a reader thread)" << std::endl; std::cout << "\t -f : V4L2 capture using current format (-W,-H,-F are ignore)" << std::endl; std::cout << "\t -W width : V4L2 capture width (default "<< width << ")" << std::endl; std::cout << "\t -H height: V4L2 capture height (default "<< height << ")" << std::endl; std::cout << "\t -F fps : V4L2 capture framerate (default "<< fps << ")" << std::endl; std::cout << "\t device : V4L2 capture device (default "<< dev_name << ")" << std::endl; exit(0); } } } std::list<std::string> devList; while (optind<argc) { devList.push_back(argv[optind]); optind++; } if (devList.empty()) { devList.push_back(dev_name); } // init logger initLogger(verbose); // create live555 environment TaskScheduler* scheduler = BasicTaskScheduler::createNew(); UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler); // split multicast info std::istringstream is(maddr); std::string ip; getline(is, ip, ':'); struct in_addr destinationAddress; destinationAddress.s_addr = chooseRandomIPv4SSMAddress(*env); if (!ip.empty()) { destinationAddress.s_addr = inet_addr(ip.c_str()); } std::string port; getline(is, port, ':'); unsigned short rtpPortNum = 20000; if (!port.empty()) { rtpPortNum = atoi(port.c_str()); } unsigned short rtcpPortNum = rtpPortNum+1; unsigned char ttl = 5; // create RTSP server RTSPServer* rtspServer = createRTSPServer(*env, rtspPort, rtspOverHTTPPort, timeout); if (rtspServer == NULL) { LOG(ERROR) << "Failed to create RTSP server: " << env->getResultMsg(); } else { int nbSource = 0; std::list<std::string>::iterator devIt; for ( devIt=devList.begin() ; devIt!=devList.end() ; ++devIt) { std::string deviceName(*devIt); // Init capture LOG(NOTICE) << "Create V4L2 Source..." << deviceName; V4L2DeviceParameters param(deviceName.c_str(),format,width,height,fps, verbose); V4l2Capture* videoCapture = V4l2DeviceFactory::CreateVideoCapure(param, useMmap); if (videoCapture) { nbSource++; format = videoCapture->getFormat(); int outfd = -1; V4l2Output* out = NULL; if (!outputFile.empty()) { V4L2DeviceParameters outparam(outputFile.c_str(), videoCapture->getFormat(), videoCapture->getWidth(), videoCapture->getHeight(), 0,verbose); V4l2Output* out = V4l2DeviceFactory::CreateVideoOutput(outparam, useMmap); if (out != NULL) { outfd = out->getFd(); } } LOG(NOTICE) << "Start V4L2 Capture..." << deviceName; if (!videoCapture->captureStart()) { LOG(NOTICE) << "Cannot start V4L2 Capture for:" << deviceName; } V4L2DeviceSource* videoES = NULL; if (format == V4L2_PIX_FMT_H264) { videoES = H264_V4L2DeviceSource::createNew(*env, param, videoCapture, outfd, queueSize, useThread, repeatConfig); } else { videoES = V4L2DeviceSource::createNew(*env, param, videoCapture, outfd, queueSize, useThread); } if (videoES == NULL) { LOG(FATAL) << "Unable to create source for device " << deviceName; delete videoCapture; } else { // extend buffer size if needed if (videoCapture->getBufferSize() > OutPacketBuffer::maxSize) { OutPacketBuffer::maxSize = videoCapture->getBufferSize(); } StreamReplicator* replicator = StreamReplicator::createNew(*env, videoES, false); std::string baseUrl; if (devList.size() > 1) { baseUrl = basename(deviceName.c_str()); baseUrl.append("/"); } // Create Multicast Session if (multicast) { LOG(NOTICE) << "RTP address " << inet_ntoa(destinationAddress) << ":" << rtpPortNum; LOG(NOTICE) << "RTCP address " << inet_ntoa(destinationAddress) << ":" << rtcpPortNum; addSession(rtspServer, baseUrl+murl, MulticastServerMediaSubsession::createNew(*env,destinationAddress, Port(rtpPortNum), Port(rtcpPortNum), ttl, replicator,format)); // increment ports for next sessions rtpPortNum+=2; rtcpPortNum+=2; } // Create Unicast Session addSession(rtspServer, baseUrl+url, UnicastServerMediaSubsession::createNew(*env,replicator,format)); } if (out) { delete out; } } } if (nbSource>0) { // main loop signal(SIGINT,sighandler); env->taskScheduler().doEventLoop(&quit); LOG(NOTICE) << "Exiting...."; } Medium::close(rtspServer); } env->reclaim(); delete scheduler; return 0; }
__private_extern__ kern_return_t _configopen(mach_port_t server, xmlData_t nameRef, /* raw XML bytes */ mach_msg_type_number_t nameLen, xmlData_t optionsRef, /* raw XML bytes */ mach_msg_type_number_t optionsLen, mach_port_t *newServer, int *sc_status, audit_token_t audit_token) { CFDictionaryRef info; serverSessionRef mySession; CFStringRef name = NULL; /* name (un-serialized) */ CFMutableDictionaryRef newInfo; mach_port_t oldNotify; CFDictionaryRef options = NULL; /* options (un-serialized) */ CFStringRef sessionKey; kern_return_t status; SCDynamicStorePrivateRef storePrivate; CFBooleanRef useSessionKeys = NULL; *sc_status = kSCStatusOK; /* un-serialize the name */ if (!_SCUnserializeString(&name, NULL, (void *)nameRef, nameLen)) { *sc_status = kSCStatusFailed; } if ((optionsRef != NULL) && (optionsLen > 0)) { /* un-serialize the [session] options */ if (!_SCUnserialize((CFPropertyListRef *)&options, NULL, (void *)optionsRef, optionsLen)) { *sc_status = kSCStatusFailed; } } if (*sc_status != kSCStatusOK) { goto done; } if (!isA_CFString(name)) { *sc_status = kSCStatusInvalidArgument; goto done; } if (options != NULL) { if (!isA_CFDictionary(options)) { *sc_status = kSCStatusInvalidArgument; goto done; } /* * [pre-]process any provided options */ useSessionKeys = CFDictionaryGetValue(options, kSCDynamicStoreUseSessionKeys); if (useSessionKeys != NULL) { if (!isA_CFBoolean(useSessionKeys)) { *sc_status = kSCStatusInvalidArgument; goto done; } } } /* * establish the new session */ mySession = addSession(server, openMPCopyDescription); if (mySession == NULL) { #ifdef DEBUG SCLog(TRUE, LOG_DEBUG, CFSTR("_configopen(): session is already open.")); #endif /* DEBUG */ *sc_status = kSCStatusFailed; /* you can't re-open an "open" session */ goto done; } *newServer = mySession->key; __MACH_PORT_DEBUG(TRUE, "*** _configopen (after addSession)", *newServer); /* save the audit_token in case we need to check the callers credentials */ mySession->auditToken = audit_token; /* Create and add a run loop source for the port */ mySession->serverRunLoopSource = CFMachPortCreateRunLoopSource(NULL, mySession->serverPort, 0); CFRunLoopAddSource(CFRunLoopGetCurrent(), mySession->serverRunLoopSource, kCFRunLoopDefaultMode); if (_configd_trace) { SCTrace(TRUE, _configd_trace, CFSTR("open : %5d : %@\n"), *newServer, name); } *sc_status = __SCDynamicStoreOpen(&mySession->store, name); storePrivate = (SCDynamicStorePrivateRef)mySession->store; /* * Make the server port accessible to the framework routines. * ... and be sure to clear before calling CFRelease(store) */ storePrivate->server = *newServer; /* * Process any provided [session] options */ if (useSessionKeys != NULL) { storePrivate->useSessionKeys = CFBooleanGetValue(useSessionKeys); } /* Request a notification when/if the client dies */ status = mach_port_request_notification(mach_task_self(), *newServer, MACH_NOTIFY_NO_SENDERS, 1, *newServer, MACH_MSG_TYPE_MAKE_SEND_ONCE, &oldNotify); if (status != KERN_SUCCESS) { SCLog(TRUE, LOG_ERR, CFSTR("_configopen() mach_port_request_notification() failed: %s"), mach_error_string(status)); cleanupSession(*newServer); *newServer = MACH_PORT_NULL; *sc_status = kSCStatusFailed; goto done; } __MACH_PORT_DEBUG(TRUE, "*** _configopen (after mach_port_request_notification)", *newServer); if (oldNotify != MACH_PORT_NULL) { SCLog(TRUE, LOG_ERR, CFSTR("_configopen(): oldNotify != MACH_PORT_NULL")); } /* * Save the name of the calling application / plug-in with the session data. */ sessionKey = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), *newServer); info = CFDictionaryGetValue(sessionData, sessionKey); if (info != NULL) { newInfo = CFDictionaryCreateMutableCopy(NULL, 0, info); } else { newInfo = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } CFDictionarySetValue(newInfo, kSCDName, name); CFDictionarySetValue(sessionData, sessionKey, newInfo); CFRelease(newInfo); CFRelease(sessionKey); /* * Note: at this time we should be holding ONE send right and * ONE receive right to the server. The send right is * moved to the caller. */ done : if (name != NULL) CFRelease(name); if (options != NULL) CFRelease(options); return KERN_SUCCESS; }
void Beacon::handleListenSocket(Socket &socket) { SockAddr sourceAddr; IpAddr destIpAddr, sourceIpAddr; uint8_t ttl; BfdPacket packet; bool found; Session *session = NULL; if (!m_packet.DoRecvMsg(socket)) { gLog.ErrnoError(m_packet.GetLastError(), "Error receiving on BFD listen socket"); return; } sourceAddr = m_packet.GetSrcAddress(); if (!LogVerify(sourceAddr.IsValid())) return; sourceIpAddr = IpAddr(sourceAddr); destIpAddr = m_packet.GetDestAddress(); if (!destIpAddr.IsValid()) { gLog.LogError("Could not get destination address for packet from %s.", sourceAddr.ToString()); return; } ttl = m_packet.GetTTLorHops(&found); if (!found) { gLog.LogError("Could not get ttl for packet from %s.", sourceAddr.ToString()); return; } LogOptional(Log::Packet, "Received bfd packet %zu bytes from %s to %s", m_packet.GetDataSize(), sourceAddr.ToString(), destIpAddr.ToString()); // // Check ip specific stuff. See draft-ietf-bfd-v4v6-1hop-11.txt // // Port if (m_strictPorts) { if (sourceAddr.Port() < bfd::MinSourcePort) // max port is max value, so no need to check { LogOptional(Log::Discard, "Discard packet: bad source port %s to %s", sourceAddr.ToString(), destIpAddr.ToString()); return; } } // TTL assumes that all control packets are from neighbors. if (ttl != 255) { gLog.Optional(Log::Discard, "Discard packet: bad ttl/hops %hhu", ttl); return; } if (!Session::InitialProcessControlPacket(m_packet.GetData(), m_packet.GetDataSize(), packet)) { gLog.Optional(Log::Discard, "Discard packet"); return; } // We have a (partially) valid packet ... now find the correct session. if (packet.header.yourDisc != 0) { DiscMapIt found = m_discMap.find(packet.header.yourDisc); if (found == m_discMap.end()) { if (gLog.LogTypeEnabled(Log::DiscardDetail)) Session::LogPacketContents(packet, false, true, sourceAddr, destIpAddr); gLog.Optional(Log::Discard, "Discard packet: no session found for yourDisc <%u>.", packet.header.yourDisc); return; } session = found->second; if (session->GetRemoteAddress() != sourceIpAddr) { if (gLog.LogTypeEnabled(Log::DiscardDetail)) Session::LogPacketContents(packet, false, true, sourceAddr, destIpAddr); LogOptional(Log::Discard, "Discard packet: mismatched yourDisc <%u> and ip <from %s to %s>.", packet.header.yourDisc, sourceAddr.ToString(), destIpAddr.ToString()); return; } } else { // No discriminator session = findInSourceMap(sourceIpAddr, destIpAddr); if (NULL == session) { // No session yet .. create one !? if (!m_allowAnyPassiveIP && m_allowedPassiveIP.find(sourceIpAddr) == m_allowedPassiveIP.end()) { if (gLog.LogTypeEnabled(Log::DiscardDetail)) Session::LogPacketContents(packet, false, true, sourceAddr, destIpAddr); LogOptional(Log::Discard, "Ignoring unauthorized bfd packets from %s", sourceAddr.ToString()); return; } session = addSession(sourceIpAddr, destIpAddr); if (!session) return; if (!session->StartPassiveSession(sourceAddr, destIpAddr)) { gLog.LogError("Failed to add new session for local %s to remote %s id=%d.", destIpAddr.ToString(), sourceAddr.ToString(), session->GetId()); KillSession(session); } LogOptional(Log::Session, "Added new session for local %s to remote %s id=%d.", destIpAddr.ToString(), sourceAddr.ToString(), session->GetId()); } } // // We have a session that can handle the rest. // session->ProcessControlPacket(packet, sourceAddr.Port()); }
string AmSessionContainer::startSessionUAC(const AmSipRequest& req, string& app_name, AmArg* session_params) { auto_ptr<AmSession> session; try { session.reset(createSession(req, app_name, session_params)); if(session.get() != 0) { session->dlg->initFromLocalRequest(req); session->setCallgroup(req.from_tag); switch(addSession(req.from_tag,session.get())) { case AmSessionContainer::Inserted: // successful case break; case AmSessionContainer::ShutDown: throw AmSession::Exception(AmConfig::ShutdownModeErrCode, AmConfig::ShutdownModeErrReason); case AmSessionContainer::AlreadyExist: throw AmSession::Exception(482, SIP_REPLY_LOOP_DETECTED); default: ERROR("adding session to session container\n"); throw string(SIP_REPLY_SERVER_INTERNAL_ERROR); } MONITORING_LOG5(req.from_tag, "app", app_name.c_str(), "dir", "out", "from", req.from.c_str(), "to", req.to.c_str(), "ruri", req.r_uri.c_str()); if (int err = session->sendInvite(req.hdrs)) { ERROR("INVITE could not be sent: error code = %d.\n", err); AmEventDispatcher::instance()->delEventQueue(req.from_tag); MONITORING_MARK_FINISHED(req.from_tag.c_str()); return ""; } if (AmConfig::LogSessions) { INFO("Starting UAC session %s app %s\n", req.from_tag.c_str(), app_name.c_str()); } try { session->start(); } catch (...) { AmEventDispatcher::instance()->delEventQueue(req.from_tag); throw; } } } catch(const AmSession::Exception& e){ ERROR("%i %s\n",e.code,e.reason.c_str()); return ""; } catch(const string& err){ ERROR("startSession: %s\n",err.c_str()); return ""; } catch(...){ ERROR("unexpected exception\n"); return ""; } session.release(); return req.from_tag; }
void AmSessionContainer::startSessionUAS(AmSipRequest& req) { try { // Call-ID and From-Tag are unknown: it's a new session auto_ptr<AmSession> session; string app_name; session.reset(createSession(req,app_name)); if(session.get() != 0){ // update session's local tag (ID) if not already set session->setLocalTag(); const string& local_tag = session->getLocalTag(); // by default each session is in its own callgroup session->setCallgroup(local_tag); if (AmConfig::LogSessions) { INFO("Starting UAS session %s\n", local_tag.c_str()); } switch(addSession(req.callid,req.from_tag,local_tag, req.via_branch,session.get())) { case AmSessionContainer::Inserted: // successful case break; case AmSessionContainer::ShutDown: throw AmSession::Exception(AmConfig::ShutdownModeErrCode, AmConfig::ShutdownModeErrReason); case AmSessionContainer::AlreadyExist: throw AmSession::Exception(482, SIP_REPLY_LOOP_DETECTED); default: ERROR("adding session to session container\n"); throw string(SIP_REPLY_SERVER_INTERNAL_ERROR); } MONITORING_LOG4(local_tag.c_str(), "dir", "in", "from", req.from.c_str(), "to", req.to.c_str(), "ruri", req.r_uri.c_str()); try { session->start(); } catch (...) { AmEventDispatcher::instance()-> delEventQueue(local_tag); throw; } session->postEvent(new AmSipRequestEvent(req)); session.release(); } } catch(const AmSession::Exception& e){ ERROR("%i %s %s\n",e.code,e.reason.c_str(), e.hdrs.c_str()); AmSipDialog::reply_error(req,e.code,e.reason, e.hdrs); } catch(const string& err){ ERROR("startSession: %s\n",err.c_str()); AmSipDialog::reply_error(req,500,err); } catch(...){ ERROR("unexpected exception\n"); AmSipDialog::reply_error(req,500,"unexpected exception"); } }
void MainWindow::newSession() { //QString title = tr("Shell n.")+QString::number(_sessionCount+1); QString title = tr("Shell"); addSession(title.toLatin1().constData()); }
TEDemo::TEDemo(char* name, QStrList & _args, int login_shell) : KTMainWindow(name), args(_args) { se = 0L; menubar = menuBar(); setMinimumSize(200,100); // session management setUnsavedData( true ); // terminals cannot store their contents // create terminal emulation framework //////////////////////////////////// te = new TEWidget(this); te->setMinimumSize(150,70); // allow resizing, cause resize in TEWidget // create applications ///////////////////////////////////////////////////// setView(te,FALSE); makeMenu(); makeStatusbar(); // Init DnD: Set up drop zone and drop handler ///////////////////////////// dropZone = new KDNDDropZone( this, DndURL ); connect( dropZone, SIGNAL( dropAction( KDNDDropZone* )), SLOT( onDrop( KDNDDropZone*))); // load session commands /////////////////////////////////////////////////// loadSessionCommands(); m_file->insertSeparator(); m_file->insertItem( i18n("E&xit"), kapp, SLOT(quit())); // load schema ///////////////////////////////////////////////////////////// curr_schema = 0; ColorSchema::loadAllSchemas(); for (int i = 0; i < ColorSchema::count(); i++) { ColorSchema* s = ColorSchema::find(i); assert( s ); m_schema->insertItem(s->title.data(),s->numb); } //FIXME: we should build a complete session before running it. // construct initial session /////////////////////////////////////////////// TESession* initial = new TESession(this,te,args,"xterm",login_shell); title = (args.count() && !strcmp(kapp->getCaption(),PACKAGE)) ? args.at(0) // program executed in the title bar : kapp->getCaption(); // `konsole' or -caption initial->setTitle(title); addSession(initial); // read and apply default values /////////////////////////////////////////// readProperties(kapp->getConfig()); // activate and run first session ////////////////////////////////////////// runSession(initial); }
void ConfigStorage::checkFile() { if (m_cfg_file >= 0) return; char* cfg_file_name = m_sharedMemory->getHeader()->cfg_file_name; if (!(*cfg_file_name)) { fb_assert(m_sharedMemory->getHeader()->cnt_uses == 0); char dir[MAXPATHLEN]; iscPrefixLock(dir, "", true); PathName filename = TempFile::create("fb_trace_", dir); filename.copyTo(cfg_file_name, sizeof(m_sharedMemory->getHeader()->cfg_file_name)); m_cfg_file = os_utils::openCreateSharedFile(cfg_file_name, O_BINARY); } else { m_cfg_file = ::open(cfg_file_name, O_RDWR | O_BINARY); if (m_cfg_file < 0) checkFileError(cfg_file_name, "open", isc_io_open_err); } // put default (audit) trace file contents into storage if (m_sharedMemory->getHeader()->change_number == 0) { FILE* cfgFile = NULL; try { PathName configFileName(Config::getAuditTraceConfigFile()); // remove quotes around path if present { // scope const FB_SIZE_T pathLen = configFileName.length(); if (pathLen > 1 && configFileName[0] == '"' && configFileName[pathLen - 1] == '"') { configFileName.erase(0, 1); configFileName.erase(pathLen - 2, 1); } } if (configFileName.empty()) return; if (PathUtils::isRelative(configFileName)) { PathName root(Config::getRootDirectory()); PathUtils::ensureSeparator(root); configFileName.insert(0, root); } cfgFile = fopen(configFileName.c_str(), "rb"); if (!cfgFile) { checkFileError(configFileName.c_str(), "fopen", isc_io_open_err); } TraceSession session(*getDefaultMemoryPool()); fseek(cfgFile, 0, SEEK_END); const long len = ftell(cfgFile); if (len) { fseek(cfgFile, 0, SEEK_SET); char* p = session.ses_config.getBuffer(len + 1); if (fread(p, 1, len, cfgFile) != size_t(len)) { checkFileError(configFileName.c_str(), "fread", isc_io_read_err); } p[len] = 0; } else { gds__log("Audit configuration file \"%s\" is empty", configFileName.c_str()); } session.ses_user = SYSDBA_USER_NAME; session.ses_name = "Firebird Audit"; session.ses_flags = trs_admin | trs_system; addSession(session); } catch(const Exception& ex) { ISC_STATUS_ARRAY temp; ex.stuff_exception(temp); iscLogStatus("Cannot open audit configuration file", temp); } if (cfgFile) { fclose(cfgFile); } } }
Session * SessionManager::newSession() { std::string id = generateNewId(); Session * ses = new Session(id); addSession(ses); return ses; }
void AbstractChatWidget::addSessions(const ChatSessionList &sessions) { foreach(ChatSessionImpl *s,sessions) addSession(s); }